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
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
//! Recursive-descent parser: `lexer` tokens → PHP AST (`ast::Stmt`).
use crate::ast::*;
use crate::lexer::{self, Spanned, Tok};
use std::collections::{HashMap, HashSet};
/// The words PHP's scanner turns into keyword tokens rather than identifiers, in
/// the canonical spelling a syntax error echoes back — lowercase for ordinary
/// keywords, uppercase for the magic constants, and `die` folded onto `exit`,
/// which is the token it produces. Matched case-insensitively.
///
/// `true`, `false`, `null`, `self`, `parent`, `enum` and the scalar type names are
/// deliberately absent: the scanner leaves them as identifiers, and PHP reports
/// them as `identifier "…"`.
const RESERVED_WORDS: &[&str] = &[
"abstract",
"and",
"array",
"as",
"break",
"callable",
"case",
"catch",
"class",
"clone",
"const",
"continue",
"declare",
"default",
"do",
"echo",
"else",
"elseif",
"empty",
"enddeclare",
"endfor",
"endforeach",
"endif",
"endswitch",
"endwhile",
"eval",
"exit",
"extends",
"final",
"finally",
"fn",
"for",
"foreach",
"function",
"global",
"goto",
"if",
"implements",
"include",
"include_once",
"instanceof",
"insteadof",
"interface",
"isset",
"list",
"match",
"namespace",
"new",
"or",
"print",
"private",
"protected",
"public",
"readonly",
"require",
"require_once",
"return",
"static",
"switch",
"throw",
"trait",
"try",
"unset",
"use",
"var",
"while",
"xor",
"yield",
"__CLASS__",
"__DIR__",
"__FILE__",
"__FUNCTION__",
"__LINE__",
"__METHOD__",
"__NAMESPACE__",
];
/// The canonical keyword spelling for `word`, or `None` if the scanner would
/// leave it an identifier.
fn reserved_spelling(word: &str) -> Option<&'static str> {
// `die` is an alias the scanner folds onto the `exit` token, so a syntax
// error on `die` reports `token "exit"`.
if word.eq_ignore_ascii_case("die") {
return Some("exit");
}
RESERVED_WORDS
.iter()
.find(|k| k.eq_ignore_ascii_case(word))
.copied()
}
/// PHP's magic constants, in the uppercase spelling they are written in. Matched
/// case-insensitively, as the scanner does — `__line__` is the same token.
const MAGIC_CONSTS: &[&str] = &[
"__LINE__",
"__FILE__",
"__DIR__",
"__FUNCTION__",
"__CLASS__",
"__METHOD__",
"__NAMESPACE__",
"__TRAIT__",
];
/// The canonical spelling of the magic constant `word` names, or `None` when it
/// is an ordinary identifier.
fn magic_const_spelling(word: &str) -> Option<&'static str> {
MAGIC_CONSTS
.iter()
.find(|k| k.eq_ignore_ascii_case(word))
.copied()
}
/// Whether `e` is the `variable` PHP's grammar requires either side of a
/// `++`/`--`: a plain `$v`, an array or string element, an instance or static
/// property. Everything else — a literal, a call result, a parenthesised
/// expression — is a syntax error at the operator, not a runtime failure.
fn is_incdec_target(e: &Expr) -> bool {
matches!(
e,
Expr::Var(_) | Expr::Index(..) | Expr::PropGet(..) | Expr::StaticProp(..)
)
}
/// Whether `e` may stand to the left of a `::` as a run-time class reference.
///
/// PHP's grammar allows only a *dereferenceable* expression there — a variable,
/// an element, a member, a call result, a `new`. A bare number is a syntax
/// error at the `::` itself (`1::K`), not a run-time "class name must be an
/// object or a string", so the two must be told apart here rather than later.
fn is_dyn_class_operand(e: &Expr) -> bool {
matches!(
e,
Expr::Var(_)
| Expr::Index(..)
| Expr::PropGet(..)
| Expr::NullsafePropGet(..)
| Expr::StaticProp(..)
| Expr::StaticGet(..)
| Expr::Call(..)
| Expr::CallValue(..)
| Expr::MethodCall(..)
| Expr::NullsafeMethodCall(..)
| Expr::StaticCall(..)
| Expr::New(..)
| Expr::NewDyn(..)
| Expr::NewAnon { .. }
)
}
/// Whether `e` is a form `isset()` accepts: a variable, a variable variable, an
/// index, a property fetch (arrow or nullsafe) or a static property. Only the
/// OUTERMOST node matters — the reference reads `isset(f()->p)` and
/// `isset(f()[0])` happily, and rejects `isset(f())`, `isset(C::K)`,
/// `isset(NAME)`, `isset(new C)` and `isset(1 + 1)`.
fn is_isset_operand(e: &Expr) -> bool {
matches!(
e,
Expr::Var(_)
| Expr::VarVar(_)
| Expr::Index(..)
| Expr::PropGet(..)
| Expr::NullsafePropGet(..)
| Expr::StaticProp(..)
)
}
/// Map a `(type)` cast keyword to the conversion function it desugars to.
///
/// `(array)` and `(object)` have no PHP-callable equivalent, so they lower to
/// the internal `__cast_array`/`__cast_object` builtins. `(unset)` was removed
/// in PHP 8 → `None`.
fn cast_fn(t: &str) -> Option<&'static str> {
match t.to_ascii_lowercase().as_str() {
"int" | "integer" => Some("intval"),
"float" | "double" | "real" => Some("floatval"),
"string" => Some("strval"),
"bool" | "boolean" => Some("boolval"),
"array" => Some("__cast_array"),
"object" => Some("__cast_object"),
_ => None,
}
}
/// A parse failure, carrying the SEVERITY PHP prints it under.
///
/// Almost every failure is a `Parse error`, but the `declare(strict_types=…)`
/// constraints are rejected as a `Fatal error` — a different word, a stack trace
/// after it, and the same "nothing ran" outcome. The distinction is only visible
/// on stdout, which is exactly what the parity harness compares.
#[derive(Debug, Clone)]
pub struct ParseFail {
/// `"Parse error"` or `"Fatal error"`.
pub severity: &'static str,
pub message: String,
}
/// What the parse learned about the compilation unit as a whole, beyond its
/// statements.
#[derive(Debug, Clone, Default)]
pub struct ParseMeta {
/// `declare(strict_types=1)` was in force for this file.
pub strict_types: bool,
/// `(line, message)` for each `declare` warning, to be issued before the run.
pub declare_warnings: Vec<(u32, String)>,
}
/// Parse a PHP source string into a statement list. Inline `rust { ... }` FFI
/// blocks are desugared to `__rust_compile(...)` calls before lexing.
pub fn parse(src: &str) -> Result<Vec<Stmt>, String> {
parse_meta(src).map(|(s, _)| s).map_err(|e| e.message)
}
/// [`parse`], keeping the severity of a failure and the file-level facts a plain
/// statement list cannot carry. The CLI uses this so a `declare` violation prints
/// under the word PHP prints it under.
pub fn parse_meta(src: &str) -> Result<(Vec<Stmt>, ParseMeta), ParseFail> {
let src = crate::rust_ffi::desugar(src);
lexer::clear_diags();
let toks = lexer::lex(&src).map_err(|e| ParseFail {
severity: "Parse error",
message: e,
})?;
let eof_line = src.bytes().filter(|b| *b == b'\n').count() as u32 + 1;
let mut p = Parser {
toks,
pos: 0,
eof_line,
pending_attrs: Vec::new(),
pending_deprecated: None,
last_deprecated: None,
doc_used: 0,
last_attrs: Vec::new(),
pending_attr_specs: Vec::new(),
top_level: true,
only_declares_so_far: true,
strict_types: false,
coalesce_temps: 0,
ns_seen: false,
deferred_fatal: None,
foreach_targets: Vec::new(),
declare_warnings: Vec::new(),
magic: MagicCtx::file_scope(),
imports: Imports::default(),
seen_classes: HashSet::new(),
};
let mut stmts = Vec::new();
while !p.at_end() {
let was_declare = p.at_kw("declare");
let stmt = p.statement().map_err(|e| p.classify(e))?;
// A `declare` does not close the window `strict_types` must appear in;
// every other statement does, inline HTML in front of `<?php` included.
if !was_declare {
p.only_declares_so_far = false;
}
stmts.push(stmt);
}
if let Some(fatal) = p.deferred_fatal.take() {
return Err(p.classify(fatal));
}
let meta = ParseMeta {
strict_types: p.strict_types,
declare_warnings: std::mem::take(&mut p.declare_warnings),
};
Ok((stmts, meta))
}
/// The marker `Parser::fatal_at` wraps a message in so `Parser::classify` can tell
/// a `Fatal error` apart from an ordinary syntax error on the way back out. It is
/// a control character, so no source text can forge one.
const FATAL_MARK: char = '\u{1}';
/// Turn the lexer's string segments into parsed ones: a bare `$name` becomes the
/// expression that reads it, and a [`StrPart::Raw`] — `{$expr}`, `$a->p`, `$a[k]`
/// — is lexed and parsed on its own, since each is a self-contained PHP
/// expression. Anything left over after it means the recorded source was not one.
fn resolve_interp_parts(
parts: Vec<StrPart>,
namespace: &str,
imports: &Imports,
) -> Result<Vec<InterpPart>, String> {
parts
.into_iter()
.map(|p| match p {
StrPart::Lit(s) => Ok(InterpPart::Lit(s)),
StrPart::Var(n) => Ok(InterpPart::Expr(Box::new(Expr::Var(n)))),
StrPart::Raw(src) => {
let toks = lexer::lex(&format!("<?php {src};"))?;
let mut inner = Parser {
toks,
pos: 0,
// A one-line synthetic source: the interpolated expression
// is spliced onto a single line, so end of input is line 1.
eof_line: 1,
pending_attrs: Vec::new(),
pending_deprecated: None,
last_deprecated: None,
doc_used: 0,
last_attrs: Vec::new(),
pending_attr_specs: Vec::new(),
// An interpolation is a bare expression, never a statement,
// so no declaration can appear in it and the value is moot.
top_level: false,
only_declares_so_far: false,
strict_types: false,
coalesce_temps: 0,
ns_seen: false,
deferred_fatal: None,
foreach_targets: Vec::new(),
declare_warnings: Vec::new(),
// An interpolation holds no declaration, so no magic
// constant it could contain would read anything but the
// file scope this starts at — save the namespace, which
// (with the imports) is what the names in it resolve in.
magic: MagicCtx {
namespace: namespace.to_string(),
..MagicCtx::file_scope()
},
imports: imports.clone(),
seen_classes: HashSet::new(),
};
let e = inner.expression()?;
if !inner.at_punct(";") {
return Err(format!("unparsed interpolation `{{{src}}}`"));
}
Ok(InterpPart::Expr(Box::new(e)))
}
})
.collect()
}
struct Parser {
toks: Vec<Spanned>,
pos: usize,
/// The line END OF INPUT falls on: one past the last newline in the source.
///
/// This is NOT the last token's line, which is where a diagnostic about the
/// end of the file used to be reported. The reference counts the file's
/// lines, so a source whose final statement sits on line 2 and ends with a
/// newline reports `unexpected end of file` on line 3.
eof_line: u32,
/// Attribute names read at the head of the statement being parsed, waiting
/// for the declaration that follows to claim them. Cleared by whoever takes
/// them, so a `#[Attr] class A {} class B {}` cannot leak onto `B`.
pending_attrs: Vec<String>,
/// The `#[\Deprecated]` among `pending_attrs`, for the function declaration
/// that follows.
pending_deprecated: Option<Deprecation>,
/// The `#[\Deprecated]` the latest `attributes()` call read, if any.
last_deprecated: Option<Deprecation>,
/// The number of the last doc comment a declaration took — see
/// [`Parser::take_doc`].
doc_used: u32,
/// The attributes, with their arguments, the latest `attributes()` call
/// read.
last_attrs: Vec<Attr>,
/// The statement-level attributes waiting for the declaration that
/// follows, as `pending_attrs` holds their names.
pending_attr_specs: Vec<Attr>,
/// Whether the statement about to be parsed sits at TOP level — file scope,
/// or directly inside a `namespace Name { }` body, which upstream's grammar
/// treats the same way. False anywhere inside a function body, an `if`, a
/// loop, or any other brace-delimited block.
///
/// Whether every statement parsed so far was a `declare`. `strict_types` is
/// legal only while this holds: PHP requires it to be the very first statement
/// but does NOT count a preceding `declare` of any directive against it.
only_declares_so_far: bool,
/// How many temporaries the `??=` desugaring has minted, for their names.
coalesce_temps: usize,
/// Whether a namespace declaration has been parsed.
ns_seen: bool,
/// A compile-time fatal the grammar accepts, held until the whole file has
/// parsed so that a later syntax error takes precedence, as in the reference.
deferred_fatal: Option<String>,
/// `(temporary, target)` pairs the `foreach` being parsed bound to targets that
/// are not plain variables.
foreach_targets: Vec<(String, Expr)>,
/// Whether `declare(strict_types=1)` was seen, i.e. whether this compilation
/// unit runs in strict mode.
strict_types: bool,
/// `(line, message)` for each `declare` PHP warns about — its full text, since
/// the two warned-about directives do not share one wording.
declare_warnings: Vec<(u32, String)>,
/// Only the `const` declaration reads this: it is a top-level statement
/// upstream, so `if (x) { const A = 1; }` is a syntax error there and must
/// be one here.
top_level: bool,
/// The declaration the cursor is inside, as PHP's magic constants report it.
/// Saved and restored around every construct that opens a new one.
magic: MagicCtx,
/// The `use` imports in force, which every `namespace` declaration resets.
imports: Imports,
/// The lowercased fully qualified names of the classes this file declared
/// so far — what an import of the same name collides with
/// (`CG(file_context).seen_symbols`).
seen_classes: HashSet<String>,
}
/// The `use` imports in force (`FC(imports)`, `FC(imports_function)`,
/// `FC(imports_const)`).
#[derive(Default, Clone)]
struct Imports {
/// Lowercased alias → fully qualified class (or namespace) name.
class: HashMap<String, String>,
/// Lowercased alias → fully qualified function name.
function: HashMap<String, String>,
/// Alias → fully qualified constant name. Case-sensitive, as constant names are.
constant: HashMap<String, String>,
}
/// How a name was written, which decides how it resolves.
#[derive(Clone, Copy, PartialEq, Eq)]
enum NameKind {
/// `Foo` — imports first, then the current namespace (and, for a function
/// or constant, the global one at run time).
Unqualified,
/// `A\Foo` — the first segment may be an imported alias.
Qualified,
/// `\A\Foo` — exactly as written.
FullyQualified,
/// `namespace\Foo` — the current namespace, never an import.
Relative,
}
/// Which table a `use` import binds into.
#[derive(Clone, Copy, PartialEq, Eq)]
enum ImportKind {
Class,
Function,
Const,
}
/// A name as written, without its leading `\` or `namespace\`.
struct RawName {
text: String,
kind: NameKind,
}
/// The type names a declaration reads as built-in types rather than classes
/// when written unqualified (`zend_lookup_builtin_type_by_name`, plus the
/// three class-relative names).
fn is_reserved_type_name(name: &str) -> bool {
[
"int", "float", "bool", "string", "array", "callable", "iterable", "object", "mixed",
"void", "null", "never", "false", "true", "static", "self", "parent",
]
.iter()
.any(|t| name.eq_ignore_ascii_case(t))
}
/// `self`, `parent` and `static`, which no namespace or import ever qualifies.
fn is_class_relative_name(name: &str) -> bool {
["self", "parent", "static"]
.iter()
.any(|t| name.eq_ignore_ascii_case(t))
}
/// A name PHP's magic constants report, in the two shapes it can take.
#[derive(Clone)]
enum MagicName {
/// Settled by the parse.
Plain(String),
/// Built around something only the host knows — the script's name, or the
/// class the frame is running.
Dynamic(MagicConst),
}
impl MagicName {
/// The name PHP gives a closure declared on `line` with `self` as its
/// enclosing scope: `{closure:<scope>:<line>}`. Nesting composes, so a
/// closure inside a closure reads `{closure:{closure:f():3}:4}`.
fn closure_at(&self, line: u32) -> MagicName {
match self {
MagicName::Plain(s) => MagicName::Plain(format!("{{closure:{s}:{line}}}")),
MagicName::Dynamic(m) => MagicName::Dynamic(m.wrap("{closure:", &format!(":{line}}}"))),
}
}
/// This name with `suffix` appended — how a method name is built from the
/// class that declares it.
fn then(&self, suffix: &str) -> MagicName {
match self {
MagicName::Plain(s) => MagicName::Plain(format!("{s}{suffix}")),
MagicName::Dynamic(m) => MagicName::Dynamic(m.wrap("", suffix)),
}
}
/// This name as the expression that produces it.
fn to_expr(&self) -> Expr {
match self {
MagicName::Plain(s) => Expr::Str(s.clone()),
MagicName::Dynamic(m) => Expr::Magic(m.clone()),
}
}
}
/// What each magic constant answers at the cursor's position.
#[derive(Clone)]
struct MagicCtx {
/// `__NAMESPACE__`.
namespace: String,
/// `__CLASS__`.
class: MagicName,
/// What `__METHOD__` prefixes a method name with. NOT always `class`: a
/// trait's methods report the trait, while `__CLASS__` in them reports the
/// class that used it.
owner: MagicName,
/// `__TRAIT__` — the enclosing `trait` declaration, empty everywhere else.
trait_name: String,
/// `__FUNCTION__`.
function: MagicName,
/// `__METHOD__`.
method: MagicName,
/// What a closure declared here names as its enclosing scope. At file scope
/// that is the script itself, which is why it is not simply `method`.
scope: MagicName,
}
impl MagicCtx {
/// File scope: every name empty, and a closure declared here is named after
/// the script.
fn file_scope() -> Self {
MagicCtx {
namespace: String::new(),
class: MagicName::Plain(String::new()),
owner: MagicName::Plain(String::new()),
trait_name: String::new(),
function: MagicName::Plain(String::new()),
method: MagicName::Plain(String::new()),
scope: MagicName::Dynamic(MagicConst::File {
prefix: String::new(),
suffix: String::new(),
}),
}
}
}
/// Which of PHP's class-like declarations is being parsed, and the modifiers on
/// it — the five flags `class_rest` used to take one after another, which is
/// what `clippy::too_many_arguments` refuses at 8 (`-D warnings` in CI).
///
/// `Default` is the anonymous-class case: `new class(args) … { … }` is a plain
/// class, so every flag is false.
#[derive(Default, Clone, Copy)]
struct ClassKind {
is_interface: bool,
is_trait: bool,
is_enum: bool,
is_abstract: bool,
/// `readonly class` — every property the body declares is readonly,
/// promoted constructor parameters included.
is_readonly_class: bool,
}
impl Parser {
// ── cursor ─────────────────────────────────────────────────────────────
fn at_end(&self) -> bool {
self.pos >= self.toks.len()
}
fn peek(&self) -> Option<&Tok> {
self.toks.get(self.pos).map(|s| &s.tok)
}
/// The INNERMOST bracket still open at end of input, and the line it was
/// opened on.
///
/// The reference reports an unterminated construct as `Unclosed '(' on line
/// N` rather than as a syntax error, and it names the innermost one: for a
/// function whose body opens a further `{`, the line reported is the inner
/// brace's. Reading it off the token stream needs no lexer state — a `${`
/// or `{$` inside a string never reaches the stream as punctuation, so the
/// only braces seen here are real ones.
fn unclosed_delim(&self) -> Option<(char, u32)> {
let mut open: Vec<(char, u32)> = Vec::new();
for sp in &self.toks {
let Tok::Punct(p) = &sp.tok else { continue };
match *p {
"(" | "[" | "{" => open.push((p.chars().next().unwrap_or('('), sp.line)),
")" | "]" | "}" => {
open.pop();
}
_ => {}
}
}
open.pop()
}
/// The scanner-level diagnostic for a closing bracket that does not pair with
/// the opener on top of the nesting stack, if the token stream has one at or
/// before `idx` — the point the reference's parser had read up to when it
/// stopped, which is the only reason the scanner would have seen it.
///
/// PHP's scanner keeps that stack itself and throws before the grammar is
/// consulted: `Unmatched ')'` with nothing open, and `Unclosed '(' does not
/// match ']'` otherwise, the latter adding `on line N` when the opener sits
/// on another line than the closer. It is independent of the parser tables,
/// so unlike the `expecting` lists it is reproduced exactly.
fn nesting_error_through(&self, idx: usize) -> Option<String> {
let mut open: Vec<(char, u32)> = Vec::new();
for sp in self.toks.iter().take(idx.saturating_add(1)) {
let Tok::Punct(p) = &sp.tok else { continue };
let closer = match *p {
"(" | "[" | "{" | "#[" => {
open.push((if *p == "#[" { '[' } else { p.chars().next()? }, sp.line));
continue;
}
")" => ')',
"]" => ']',
"}" => '}',
_ => continue,
};
let expected = match closer {
')' => '(',
']' => '[',
_ => '{',
};
let msg = match open.pop() {
None => format!("Unmatched '{closer}'"),
Some((c, _)) if c == expected => continue,
Some((c, line)) => {
let on = if line == sp.line {
String::new()
} else {
format!(" on line {line}")
};
format!("Unclosed '{c}'{on} does not match '{closer}'")
}
};
return Some(crate::host::with_host(|h| {
format!("{msg} in {} on line {}", h.script_name(), sp.line)
}));
}
None
}
/// The line of the token at the cursor. Past the end there is no such token,
/// so the last one's line stands in — PHP reports `unexpected end of file`
/// against the final line of the source, not line zero.
fn line(&self) -> u32 {
self.line_at(self.pos)
}
/// The line of the token at `idx`, or — past the end, where there is none —
/// the last token's, since PHP reports `unexpected end of file` against the
/// final line of the source rather than line zero.
fn line_at(&self, idx: usize) -> u32 {
self.toks
.get(idx)
.or_else(|| self.toks.last())
.map(|s| s.line)
.unwrap_or(1)
}
fn next(&mut self) -> Option<Tok> {
let t = self.toks.get(self.pos).map(|s| s.tok.clone());
self.pos += 1;
t
}
// ── magic constants ────────────────────────────────────────────────────
/// The expression the magic constant `name` — a canonical spelling from
/// [`MAGIC_CONSTS`] — evaluates to at the cursor. The keyword itself has
/// already been consumed, so `__LINE__` reads the token before the cursor.
fn magic_const(&self, name: &str) -> Expr {
match name {
"__LINE__" => Expr::Int(i64::from(self.line_at(self.pos - 1))),
"__FILE__" => Expr::Magic(MagicConst::File {
prefix: String::new(),
suffix: String::new(),
}),
"__DIR__" => Expr::Magic(MagicConst::Dir),
"__NAMESPACE__" => Expr::Str(self.magic.namespace.clone()),
"__TRAIT__" => Expr::Str(self.magic.trait_name.clone()),
"__CLASS__" => self.magic.class.to_expr(),
"__FUNCTION__" => self.magic.function.to_expr(),
"__METHOD__" => self.magic.method.to_expr(),
_ => unreachable!("not a magic constant: {name}"),
}
}
/// Enter a named function's body, returning the context to restore after it.
///
/// A named function is never inside a class as far as the magic constants are
/// concerned — declaring one inside a method body puts it in the global
/// function table, and `__CLASS__` in it is empty — so the class context is
/// dropped rather than inherited.
fn enter_function(&mut self, name: &str) -> MagicCtx {
let ctx = MagicCtx {
namespace: self.magic.namespace.clone(),
class: MagicName::Plain(String::new()),
owner: MagicName::Plain(String::new()),
trait_name: String::new(),
function: MagicName::Plain(name.to_string()),
// A free function's `__METHOD__` is just its name — there is no
// `::` half to prepend.
method: MagicName::Plain(name.to_string()),
scope: MagicName::Plain(format!("{name}()")),
};
std::mem::replace(&mut self.magic, ctx)
}
/// Enter a method body, returning the context to restore after it. The
/// declaring class or trait is whatever the surrounding class declaration put
/// in `owner`, so this needs only the method's own name.
fn enter_method(&mut self, name: &str) -> MagicCtx {
let method = self.magic.owner.then(&format!("::{name}"));
let ctx = MagicCtx {
namespace: self.magic.namespace.clone(),
class: self.magic.class.clone(),
owner: self.magic.owner.clone(),
trait_name: self.magic.trait_name.clone(),
function: MagicName::Plain(name.to_string()),
scope: method.then("()"),
method,
};
std::mem::replace(&mut self.magic, ctx)
}
/// Enter a closure or arrow function declared on `line`, returning the context
/// to restore after it. A closure has no name of its own, so PHP builds one
/// from the scope it was written in; the class context carries through, which
/// is why `__CLASS__` inside a closure in a method still names that class.
fn enter_closure(&mut self, line: u32) -> MagicCtx {
let name = self.magic.scope.closure_at(line);
let ctx = MagicCtx {
namespace: self.magic.namespace.clone(),
class: self.magic.class.clone(),
owner: self.magic.owner.clone(),
trait_name: self.magic.trait_name.clone(),
function: name.clone(),
method: name.clone(),
scope: name,
};
std::mem::replace(&mut self.magic, ctx)
}
fn at_punct(&self, p: &str) -> bool {
matches!(self.peek(), Some(Tok::Punct(x)) if *x == p)
}
/// Whether the token *after* the cursor is the punctuation `p` (used to spot
/// `??`, which the lexer emits as two `?` tokens).
fn peek2_is_punct(&self, p: &str) -> bool {
self.nth_is_punct(1, p)
}
/// Whether the token `n` positions ahead of the cursor is the punctuation `p`.
fn nth_is_punct(&self, n: usize, p: &str) -> bool {
matches!(self.toks.get(self.pos + n).map(|s| &s.tok), Some(Tok::Punct(x)) if *x == p)
}
fn eat_punct(&mut self, p: &str) -> bool {
if self.at_punct(p) {
self.pos += 1;
true
} else {
false
}
}
fn expect_punct(&mut self, p: &str) -> Result<(), String> {
if self.eat_punct(p) {
Ok(())
} else {
Err(self.syntax_error())
}
}
/// Consume the closing delimiter of a list (`)` or `]`) after its last
/// element. The grammar leaves only that token open at this point, so a
/// stray token here is reported as the reference does:
/// `unexpected integer "2", expecting ")"`. Contexts where the reference
/// prints no list (`if ($a $b)`) keep using [`expect_punct`](Self::expect_punct).
/// Whether the token just before the cursor is a member modifier keyword.
fn after_member_modifier(&self) -> bool {
self.pos > 0
&& matches!(
self.toks.get(self.pos - 1).map(|s| &s.tok),
Some(Tok::Ident(w)) if matches!(
w.to_ascii_lowercase().as_str(),
"public" | "protected" | "private" | "static" | "readonly" | "var" | "abstract" | "final"
)
)
}
fn expect_closer(&mut self, p: &str) -> Result<(), String> {
self.expect_listing(p, &format!("\"{p}\""))
}
/// [`expect_punct`](Self::expect_punct) for a position where the reference
/// names what it would have accepted: `listing` is that clause as it prints,
/// e.g. `"," or ";"`. Used only where the grammar reduces the preceding
/// construct to a nonterminal before the punctuation, which is what makes
/// the list short enough for the reference to print it.
fn expect_listing(&mut self, p: &str, listing: &str) -> Result<(), String> {
if self.eat_punct(p) {
Ok(())
} else {
Err(self.syntax_error_expecting(listing))
}
}
// ── syntax errors ──────────────────────────────────────────────────────
/// PHP's `syntax error, …` diagnostic for the token at the cursor, in the
/// display form the CLI prints (the `Parse error: ` severity and the leading
/// blank line are added by [`crate::host::PhpHost::fatal`]).
///
/// DIVERGENCE: the reference message often carries a `, expecting "X" or "Y"`
/// suffix listing the tokens its LALR state would have accepted. That set is a
/// property of PHP's generated parser tables, not of the grammar as written
/// here, so it is printed only at the sites whose list was measured against
/// the reference ([`expect_listing`](Self::expect_listing) and
/// [`expect_closer`](Self::expect_closer)) and omitted everywhere else — an
/// invented list would be wrong more often than no list.
///
/// Observed rather than assumed: whether a list appears at all is table-
/// dependent, not a property of how specific the expectation looks.
/// `for ($i=0; $i<3 {` says `expecting ";"`, but `if ($a {` — the same shape
/// of mistake, one token from a closing delimiter — says nothing at all. The
/// rule that fits every probe is that a list appears when the construct
/// reduces its operand to a nonterminal before the punctuation (an argument,
/// an `echo` list, a `for` expression list), and not when the punctuation
/// follows a bare `expr` (`if (expr)`, `while (expr)`, `$a = expr;`).
///
/// What does NOT depend on those tables is handled, in
/// [`syntax_error_at`](Self::syntax_error_at): an unterminated bracket is
/// reported as `Unclosed '(' on line N`, naming the innermost one still
/// open, and end of input is reported against the file's last line rather
/// than the last token's.
fn syntax_error(&self) -> String {
self.syntax_error_at(self.pos)
}
/// A COMPILE-time `Fatal error` at `line`, in PHP's rendering: the message,
/// the script and line it names, and the empty stack trace it carries (these
/// are `CompileError`s upstream, which is why one has a trace at all).
///
/// Marked so [`Parser::classify`] can recover the severity on the way out;
/// `parse` (which yields only a string) drops the marker with it.
fn fatal_at(&self, line: u32, msg: String) -> String {
let file = crate::host::with_host(|h| h.script_name().to_string());
format!("{FATAL_MARK}{msg} in {file} on line {line}\nStack trace:\n#0 {{main}}")
}
/// A COMPILE-time `Fatal error` raised by the grammar itself — a misplaced
/// modifier — which the reference prints with NO stack trace, unlike the
/// ones [`fatal_at`](Self::fatal_at) renders.
fn bare_fatal_at(&self, line: u32, msg: String) -> String {
let file = crate::host::with_host(|h| h.script_name().to_string());
format!("{FATAL_MARK}{msg} in {file} on line {line}")
}
/// Split a raised message back into the severity PHP prints it under.
fn classify(&self, e: String) -> ParseFail {
match e.strip_prefix(FATAL_MARK) {
Some(rest) => ParseFail {
severity: "Fatal error",
message: rest.to_string(),
},
None => ParseFail {
severity: "Parse error",
message: e,
},
}
}
/// [`syntax_error`](Self::syntax_error) for a token the caller has already
/// consumed — a `match self.next()` arm reports `self.pos - 1`, the token it
/// just took, not the one after it.
fn syntax_error_at(&self, idx: usize) -> String {
self.syntax_error_expecting_at(idx, None)
}
/// [`syntax_error`](Self::syntax_error) for a position where the grammar
/// leaves exactly one token open: the closing delimiter of a list whose
/// element has just been parsed. The reference appends `, expecting "X"` to
/// the message there — see [`expect_closer`](Self::expect_closer).
fn syntax_error_expecting(&self, expected: &str) -> String {
self.syntax_error_expecting_at(self.pos, Some(expected))
}
fn syntax_error_expecting_at(&self, idx: usize, expected: Option<&str>) -> String {
if let Some(nesting) = self.nesting_error_through(idx) {
return nesting;
}
// At END OF INPUT the reference says something else entirely when a
// bracket is still open: `Unclosed '{' on line N`, naming where the
// construct began rather than where the file stopped.
if idx >= self.toks.len() {
if let Some((c, line)) = self.unclosed_delim() {
// The `on line N` clause names where the construct OPENED, and
// the reference drops it when that is the line being reported
// anyway — a one-line `php -r 'function f($a'` says just
// `Unclosed '('`.
let opened = if line == self.eof_line {
String::new()
} else {
format!(" on line {line}")
};
return crate::host::with_host(|h| {
format!(
"Unclosed '{c}'{opened} in {} on line {}",
h.script_name(),
self.eof_line
)
});
}
}
crate::host::with_host(|h| {
format!(
"syntax error, unexpected {}{} in {} on line {}",
self.tok_desc_at(idx),
expected.map_or(String::new(), |e| format!(", expecting {e}")),
h.script_name(),
if idx >= self.toks.len() {
self.eof_line
} else {
self.line_at(idx)
}
)
})
}
/// The two halves of `$target ??= v`: the expression that READS the target and
/// the one that WRITES it. Every sub-expression of the target that is not a
/// plain variable or literal — `f()` in `$a[f()]`, the call in `g()->p` — is
/// evaluated once, into a temporary the read half assigns and the write half
/// reuses, as the reference evaluates the target once.
fn split_coalesce_target(&mut self, e: &Expr) -> (Expr, Expr) {
match e {
Expr::Index(base, key) => {
let (br, bw) = self.split_coalesce_target(base);
let (kr, kw) = self.hoist_once(key);
(
Expr::Index(Box::new(br), Box::new(kr)),
Expr::Index(Box::new(bw), Box::new(kw)),
)
}
Expr::PropGet(base, member) => {
let (br, bw) = self.split_coalesce_target(base);
let (mr, mw) = match member {
Member::Dyn(inner) => {
let (r, w) = self.hoist_once(inner);
(Member::Dyn(Box::new(r)), Member::Dyn(Box::new(w)))
}
named => (named.clone(), named.clone()),
};
(
Expr::PropGet(Box::new(br), mr),
Expr::PropGet(Box::new(bw), mw),
)
}
other => self.hoist_once(other),
}
}
/// `(read, write)` halves of one sub-expression: itself twice when it is a
/// variable or a literal, otherwise an assignment to a fresh temporary and
/// that temporary.
fn hoist_once(&mut self, e: &Expr) -> (Expr, Expr) {
let simple = matches!(
e,
Expr::Var(_)
| Expr::Int(_)
| Expr::Float(_)
| Expr::Str(_)
| Expr::Bool(_)
| Expr::Null
| Expr::ConstFetch(_)
| Expr::StaticProp(..)
);
if simple {
return (e.clone(), e.clone());
}
self.coalesce_temps += 1;
let tmp = format!("@coalesce{}", self.coalesce_temps);
(
Expr::Assign(Box::new(Expr::Var(tmp.clone())), None, Box::new(e.clone())),
Expr::Var(tmp),
)
}
/// Consume a PHP 8.4 write-visibility modifier — `public(set)`,
/// `protected(set)` or `private(set)` — and return its visibility, leaving the
/// cursor untouched when the tokens at it are anything else.
fn eat_set_visibility(&mut self) -> Option<Visibility> {
let vis = match self.toks.get(self.pos).map(|s| &s.tok) {
Some(Tok::Ident(k)) if k.eq_ignore_ascii_case("public") => Visibility::Public,
Some(Tok::Ident(k)) if k.eq_ignore_ascii_case("protected") => Visibility::Protected,
Some(Tok::Ident(k)) if k.eq_ignore_ascii_case("private") => Visibility::Private,
_ => return None,
};
let is_set = matches!(
self.toks.get(self.pos + 1).map(|s| &s.tok),
Some(Tok::Punct("("))
) && matches!(
self.toks.get(self.pos + 2).map(|s| &s.tok),
Some(Tok::Ident(k)) if k.eq_ignore_ascii_case("set")
) && matches!(
self.toks.get(self.pos + 3).map(|s| &s.tok),
Some(Tok::Punct(")"))
);
if !is_set {
return None;
}
self.pos += 4;
Some(vis)
}
/// Whether the `\` at the cursor continues a qualified name: nothing but the
/// name before it, and an identifier directly after it. `A \ B` is three
/// tokens to the reference and `A\B` is one, so the whitespace decides.
fn at_name_join(&self) -> bool {
matches!(self.toks.get(self.pos), Some(s) if s.tok == Tok::Punct("\\") && !s.space_before)
&& matches!(
self.toks.get(self.pos + 1),
Some(s) if matches!(s.tok, Tok::Ident(_)) && !s.space_before
)
}
/// Whether the `\` at the cursor anchors a fully qualified name (`\A\B`): it
/// is directly followed by an identifier.
fn at_name_anchor(&self) -> bool {
matches!(self.toks.get(self.pos), Some(s) if s.tok == Tok::Punct("\\"))
&& matches!(
self.toks.get(self.pos + 1),
Some(s) if matches!(s.tok, Tok::Ident(_)) && !s.space_before
)
}
/// Whether the cursor is at `namespace\Name`, the namespace-relative form.
fn at_relative_name(&self) -> bool {
matches!(self.peek(), Some(Tok::Ident(kw)) if kw.eq_ignore_ascii_case("namespace"))
&& matches!(self.toks.get(self.pos + 1), Some(s) if s.tok == Tok::Punct("\\") && !s.space_before)
&& matches!(
self.toks.get(self.pos + 2),
Some(s) if matches!(s.tok, Tok::Ident(_)) && !s.space_before
)
}
/// Read a name as written — `Foo`, `A\Foo`, `\A\Foo` or `namespace\Foo` —
/// without resolving it.
fn raw_name(&mut self) -> Result<RawName, String> {
let mut kind = NameKind::Unqualified;
if self.at_name_anchor() {
self.pos += 1;
kind = NameKind::FullyQualified;
} else if self.at_relative_name() {
self.pos += 2;
kind = NameKind::Relative;
}
let mut text = match self.next() {
Some(Tok::Ident(n)) => n,
_ => return Err(self.syntax_error_at(self.pos - 1)),
};
self.raw_name_rest(&mut text);
if kind == NameKind::Unqualified && text.contains('\\') {
kind = NameKind::Qualified;
}
Ok(RawName { text, kind })
}
/// Append the `\Segment`s that continue the name already in `text`.
fn raw_name_rest(&mut self, text: &mut String) {
while self.at_name_join() {
self.pos += 1;
if let Some(Tok::Ident(n)) = self.next() {
text.push('\\');
text.push_str(&n);
}
}
}
/// `name` inside the current namespace (`zend_prefix_with_ns`).
fn ns_prefixed(&self, name: &str) -> String {
if self.magic.namespace.is_empty() {
name.to_string()
} else {
format!("{}\\{name}", self.magic.namespace)
}
}
/// A qualified name whose FIRST segment is an imported class or namespace
/// alias, with the alias substituted; `None` when it is not one.
fn import_prefixed(&self, name: &str) -> Option<String> {
let (first, rest) = name.split_once('\\')?;
let target = self.imports.class.get(&first.to_ascii_lowercase())?;
Some(format!("{target}\\{rest}"))
}
/// The fully qualified class a written name refers to
/// (`zend_resolve_class_name`). `self`, `parent` and `static` are left alone.
fn resolve_class(&self, raw: &RawName) -> String {
match raw.kind {
NameKind::FullyQualified => raw.text.clone(),
NameKind::Relative => self.ns_prefixed(&raw.text),
NameKind::Unqualified if is_class_relative_name(&raw.text) => raw.text.clone(),
NameKind::Unqualified => match self.imports.class.get(&raw.text.to_ascii_lowercase()) {
Some(target) => target.clone(),
None => self.ns_prefixed(&raw.text),
},
NameKind::Qualified => self
.import_prefixed(&raw.text)
.unwrap_or_else(|| self.ns_prefixed(&raw.text)),
}
}
/// A type as a declaration names it: a built-in type stays itself, anything
/// else is a class name.
fn resolve_type_name(&self, raw: &RawName) -> String {
if raw.kind == NameKind::Unqualified && is_reserved_type_name(&raw.text) {
raw.text.clone()
} else {
self.resolve_class(raw)
}
}
/// The function or constant a written name refers to
/// (`zend_resolve_non_class_name`). An unqualified name that no import
/// claims inside a namespace comes back marked with [`ns_fallback`]: which
/// of the two it means is a run-time question.
fn resolve_non_class(&self, raw: &RawName, imported: Option<&String>) -> String {
match raw.kind {
NameKind::FullyQualified => raw.text.clone(),
NameKind::Relative => self.ns_prefixed(&raw.text),
NameKind::Unqualified => match imported {
Some(target) => target.clone(),
None if self.magic.namespace.is_empty() => raw.text.clone(),
None => ns_fallback(&self.ns_prefixed(&raw.text)),
},
NameKind::Qualified => self
.import_prefixed(&raw.text)
.unwrap_or_else(|| self.ns_prefixed(&raw.text)),
}
}
/// [`Self::resolve_non_class`] for a function name.
fn resolve_function(&self, raw: &RawName) -> String {
let imported = self.imports.function.get(&raw.text.to_ascii_lowercase());
self.resolve_non_class(raw, imported)
}
/// [`Self::resolve_non_class`] for a constant name.
fn resolve_constant(&self, raw: &RawName) -> String {
let imported = self.imports.constant.get(&raw.text);
self.resolve_non_class(raw, imported)
}
/// The qualified name starting at token `idx`, spelled as the reference
/// quotes it in a syntax error — `A\B`, or `\A\B` when `idx` is the anchoring
/// `\` — or `None` when the token is not one.
fn qualified_name_at(&self, idx: usize) -> Option<(bool, String)> {
let mut i = idx;
let mut out = String::new();
let fully = matches!(self.toks.get(i), Some(s) if s.tok == Tok::Punct("\\"));
if fully {
out.push('\\');
i += 1;
}
let mut segments = 0;
loop {
match self.toks.get(i) {
Some(Spanned {
tok: Tok::Ident(n),
space_before: false,
..
}) if segments == 0 || out.ends_with('\\') => {
out.push_str(n);
segments += 1;
i += 1;
}
Some(Spanned {
tok: Tok::Ident(n), ..
}) if segments == 0 && !fully => {
out.push_str(n);
segments += 1;
i += 1;
}
Some(Spanned {
tok: Tok::Punct("\\"),
space_before: false,
..
}) if segments > 0 && !out.ends_with('\\') => {
out.push('\\');
i += 1;
}
_ => break,
}
}
let qualified = if fully { segments > 0 } else { segments > 1 };
(qualified && !out.ends_with('\\')).then_some((fully, out))
}
/// Whether `( void )` — the PHP 8.5 discard cast — starts at token `idx`.
fn void_cast_at(&self, idx: usize) -> bool {
matches!(self.toks.get(idx).map(|s| &s.tok), Some(Tok::Punct("(")))
&& matches!(
self.toks.get(idx + 1).map(|s| &s.tok),
Some(Tok::Ident(k)) if k.eq_ignore_ascii_case("void")
)
&& matches!(
self.toks.get(idx + 2).map(|s| &s.tok),
Some(Tok::Punct(")"))
)
}
fn at_void_cast(&self) -> bool {
self.void_cast_at(self.pos)
}
/// How PHP names the token at the cursor inside a syntax error. Literals are
/// echoed back in their source spelling and named by kind; a reserved word and
/// every operator or delimiter are quoted as a bare `token "…"`.
fn tok_desc_at(&self, idx: usize) -> String {
let Some(sp) = self.toks.get(idx) else {
return "end of file".to_string();
};
if self.void_cast_at(idx) {
return "token \"(void)\"".to_string();
}
let raw = |fallback: String| -> String {
sp.raw.as_ref().map(|r| r.to_string()).unwrap_or(fallback)
};
let q = crate::lexer::quoted_token_text;
if matches!(sp.tok, Tok::Ident(_) | Tok::Punct("\\")) {
if let Some((fully, name)) = self.qualified_name_at(idx) {
let kind = if fully {
"fully qualified name"
} else {
"qualified name"
};
return format!("{kind} \"{}\"", q(&name));
}
}
match &sp.tok {
Tok::Int(n) => format!("integer \"{}\"", q(&raw(n.to_string()))),
Tok::Float(f) => format!("floating-point number \"{}\"", q(&raw(f.to_string()))),
Tok::Str(s) => format!("single-quoted string \"{}\"", q(s)),
Tok::Interp(parts) => {
// A double-quoted string with no interpolation is reported with
// its text; anything with an embedded expression has no single
// spelling, so only the kind is named.
match parts.as_slice() {
[StrPart::Lit(s)] => format!("double-quoted string \"{}\"", q(s)),
_ => "double-quoted string".to_string(),
}
}
Tok::Var(v) => format!("variable \"{}\"", q(&format!("${v}"))),
// `enum` is a token only where an enum declaration can start: before
// a name that is not `extends`/`implements`.
Tok::Ident(id)
if id.eq_ignore_ascii_case("enum")
&& matches!(
self.toks.get(idx + 1).map(|s| &s.tok),
Some(Tok::Ident(n))
if !n.eq_ignore_ascii_case("extends")
&& !n.eq_ignore_ascii_case("implements")
) =>
{
"token \"enum\"".to_string()
}
Tok::Ident(id) => match reserved_spelling(id) {
Some(kw) => format!("token \"{kw}\""),
None => format!("identifier \"{}\"", q(id)),
},
Tok::Punct(p) => format!("token \"{p}\""),
Tok::InlineHtml(_) => "inline HTML".to_string(),
Tok::OpenEcho => "token \"<?=\"".to_string(),
}
}
/// The optional numeric level of a `break`/`continue` (`break 2;`),
/// defaulting to 1. PHP only accepts a literal integer here. A literal that
/// is not a positive integer (`0`, `1.5`) reads as level 0, which the
/// compiler refuses with `'break' operator accepts only positive integers`.
/// The operand of `break` / `continue`, read after the keyword. A literal
/// integer is the level; a literal float truncates to 0; anything else that
/// parses as an expression is the reference's compile-time refusal.
fn break_level(&mut self, kw: &str) -> Result<u32, String> {
let level = match self.peek() {
Some(Tok::Int(n)) => (*n).clamp(0, u32::MAX as i64) as u32,
Some(Tok::Float(_) | Tok::Str(_) | Tok::Interp(_)) => 0,
None | Some(Tok::Punct(";")) => return Ok(1),
_ => {
let line = self.line();
self.expression()?;
return Err(self.fatal_at(
line,
format!("'{kw}' operator with non-integer operand is no longer supported"),
));
}
};
self.pos += 1;
Ok(level)
}
/// True if the next token is the keyword `kw` (case-insensitive, as PHP).
fn at_kw(&self, kw: &str) -> bool {
matches!(self.peek(), Some(Tok::Ident(s)) if s.eq_ignore_ascii_case(kw))
}
fn eat_kw(&mut self, kw: &str) -> bool {
if self.at_kw(kw) {
self.pos += 1;
true
} else {
false
}
}
// ── statements ─────────────────────────────────────────────────────────
fn statement(&mut self) -> Result<Stmt, String> {
// A declaration statement may be preceded by attribute groups. They are
// read here and handed to the declaration that follows through
// `pending_attrs`, since only that declaration can interpret them.
self.pending_attrs = self.attributes()?;
self.pending_attr_specs = std::mem::take(&mut self.last_attrs);
self.pending_deprecated = self.last_deprecated.take();
let line = self.line();
let kind = match self.peek() {
Some(Tok::InlineHtml(_)) => {
let Some(Tok::InlineHtml(s)) = self.next() else {
unreachable!()
};
StmtKind::InlineHtml(s)
}
Some(Tok::OpenEcho) => {
self.pos += 1;
let e = self.expression()?;
self.eat_punct(";");
StmtKind::Echo(vec![e])
}
Some(Tok::Punct(";")) => {
self.pos += 1;
StmtKind::Block(vec![])
}
Some(Tok::Punct("{")) => StmtKind::Block(self.block()?),
// `goto label;` and a `label:` statement. A label is an identifier the
// scanner leaves an identifier, followed by a single `:`.
_ if self.at_kw("goto") => {
self.pos += 1;
let name = match self.next() {
Some(Tok::Ident(n)) if reserved_spelling(&n).is_none() => n,
_ => {
return Err(self.syntax_error_expecting_at(self.pos - 1, Some("identifier")))
}
};
self.expect_listing(";", "\";\"")?;
StmtKind::Goto(name)
}
Some(Tok::Ident(n)) if reserved_spelling(n).is_none() && self.nth_is_punct(1, ":") => {
let Some(Tok::Ident(name)) = self.next() else {
unreachable!()
};
self.pos += 1;
StmtKind::Label(name)
}
_ if self.at_kw("echo") => {
self.pos += 1;
let mut args = vec![self.expression()?];
while self.eat_punct(",") {
args.push(self.expression()?);
}
self.expect_listing(";", "\",\" or \";\"")?;
StmtKind::Echo(args)
}
_ if self.at_kw("declare") => self.declare_stmt()?,
_ if self.at_kw("namespace") => self.namespace_stmt()?,
_ if self.at_kw("use") => self.use_import_stmt()?,
// `const NAME = expr, ...;` — the declaration spelling of a global
// constant. Three productions in this file read a `const` token and
// they do not overlap: `use const` is consumed inside
// `use_import_stmt` (which eats `use` first), the class-body form is
// read by `class_body`, and this one is only ever reached with
// `const` at the head of a statement.
_ if self.at_kw("const") => {
// Top-level only, as upstream. Inside a function body or any
// other block the reference reports the `const` token itself as
// unexpected, so the error is raised here rather than by
// falling through to the expression parser.
if !self.top_level {
return Err(self.syntax_error());
}
self.const_stmt()?
}
_ if self.at_kw("if") => self.if_stmt()?,
_ if self.at_kw("while") => self.while_stmt()?,
_ if self.at_kw("do") => self.do_while_stmt()?,
_ if self.at_kw("switch") => self.switch_stmt()?,
_ if self.at_kw("for") => self.for_stmt()?,
_ if self.at_kw("foreach") => self.foreach_stmt()?,
// A DECLARATION needs a name. `function (` (or `function &(`) is a
// closure, which is an expression, and PHP accepts one as a
// statement of its own -- so it falls through to the expression
// arm rather than being read as a nameless declaration.
_ if self.at_kw("function")
&& !self.nth_is_punct(1, "(")
&& !(self.nth_is_punct(1, "&") && self.nth_is_punct(2, "(")) =>
{
self.function_stmt()?
}
// `static $a = 1, $b;` — a static local declaration, distinguished
// from a `static::` late-static-binding expression or a `static
// function`/`static fn` closure by the `$variable` that follows.
_ if self.at_kw("static")
&& matches!(
self.toks.get(self.pos + 1).map(|s| &s.tok),
Some(Tok::Var(_))
) =>
{
self.pos += 1; // static
let mut decls = Vec::new();
loop {
if !matches!(self.peek(), Some(Tok::Var(_))) {
return Err(self.syntax_error_expecting("variable"));
}
let name = self.expect_var()?;
let default = if self.eat_punct("=") {
Some(self.expression()?)
} else {
None
};
decls.push((name, default));
if !self.eat_punct(",") {
break;
}
}
self.expect_listing(";", "\",\" or \";\"")?;
StmtKind::StaticLocal(decls)
}
// `global $a, $b;` — bind each name to the global variable of that
// name. Unlike `static`, there is no initializer form: PHP's grammar
// takes a bare variable list.
_ if self.at_kw("global") => {
self.pos += 1; // global
let mut names = Vec::new();
loop {
if !matches!(self.peek(), Some(Tok::Var(_))) {
return Err(self.syntax_error_expecting("variable or \"$\""));
}
names.push(self.expect_var()?);
if !self.eat_punct(",") {
break;
}
}
self.expect_listing(";", "\",\" or \";\"")?;
StmtKind::Global(names)
}
_ if self.at_kw("class")
|| self.at_kw("interface")
|| self.at_kw("trait")
|| self.at_kw("abstract")
|| self.at_kw("final")
|| (self.at_kw("readonly") && !self.nth_is_punct(1, "(")) =>
{
self.class_stmt()?
}
// `enum Name [: type] { ... }`. `enum` is not a reserved keyword: the lexer
// makes it a token only before a name that is not `extends`/`implements`,
// and from there the grammar owns the rest — so `enum E 1 {` is an enum
// declaration with a syntax error, not an expression statement.
_ if self.at_kw("enum")
&& matches!(
self.toks.get(self.pos + 1).map(|s| &s.tok),
Some(Tok::Ident(n))
if !n.eq_ignore_ascii_case("extends")
&& !n.eq_ignore_ascii_case("implements")
) =>
{
self.class_stmt()?
}
_ if self.at_kw("try") => self.try_stmt()?,
_ if self.at_kw("return") => {
self.pos += 1;
if self.at_void_cast() {
return Err(self.syntax_error_expecting("\";\""));
}
let e = if self.at_punct(";") {
None
} else {
Some(self.expression()?)
};
self.expect_listing(";", "\";\"")?;
StmtKind::Return(e)
}
_ if self.at_kw("break") => {
self.pos += 1;
let level = self.break_level("break")?;
self.expect_listing(";", "\";\"")?;
StmtKind::Break(level)
}
_ if self.at_kw("continue") => {
self.pos += 1;
let level = self.break_level("continue")?;
self.expect_listing(";", "\";\"")?;
StmtKind::Continue(level)
}
_ => {
// PHP 8.5 `(void) expr;` — evaluate and explicitly discard. It is a
// statement-level form only; inside an expression it is a syntax
// error (see `tok_desc_at`).
if self.at_void_cast() {
self.pos += 3;
}
let e = self.expression()?;
if matches!(e, Expr::Unset(_)) {
self.expect_listing(";", "\";\"")?;
} else {
self.expect_punct(";")?;
}
StmtKind::Expr(e)
}
};
Ok(Stmt { line, kind })
}
/// A `{ ... }` block.
fn block(&mut self) -> Result<Vec<Stmt>, String> {
self.braced_body(false)
}
/// A `namespace Name { ... }` body. It is the ONE brace-delimited block that
/// does not leave top level: a `const` declaration is as legal directly
/// inside it as it is at file scope.
fn namespace_block(&mut self) -> Result<Vec<Stmt>, String> {
self.braced_body(true)
}
fn braced_body(&mut self, top_level: bool) -> Result<Vec<Stmt>, String> {
let outer = self.top_level;
self.top_level = top_level;
self.expect_closer("{")?;
let mut body = Vec::new();
while !self.at_punct("}") && !self.at_end() {
body.push(self.statement()?);
}
let closed = self.expect_punct("}");
self.top_level = outer;
closed?;
Ok(body)
}
/// A braced block or a single statement (for brace-less control bodies).
fn body(&mut self) -> Result<Vec<Stmt>, String> {
if self.at_punct("{") {
self.block()
} else {
Ok(vec![self.statement()?])
}
}
/// The body of a control structure, in either spelling.
///
/// PHP writes every one of `if`/`while`/`for`/`foreach`/`switch`/`declare`
/// two ways: braced (or a single statement), and the ALTERNATIVE syntax
/// `: stmt... endif;` that templates use because it survives being cut in
/// half by `?> html <?php`. Both are the same grammar with a different
/// terminator, so both are read here: a `:` after the head opens the
/// alternative form, whose statements run until one of `ends` is at the head
/// — left UNCONSUMED, because `elseif`/`else` continue the same `if` and
/// only the caller knows which of them it accepts.
///
/// Returns `(body, is_alternative)`.
fn control_body(&mut self, ends: &[&str]) -> Result<(Vec<Stmt>, bool), String> {
if !self.eat_punct(":") {
return Ok((self.body()?, false));
}
let mut out = Vec::new();
while !self.at_end() && !ends.iter().any(|e| self.at_kw(e)) {
out.push(self.statement()?);
}
Ok((out, true))
}
/// Consume the `endif;` / `endwhile;` … that closes an alternative-syntax
/// body. A missing terminator is the same syntax error PHP raises.
fn expect_end_kw(&mut self, kw: &str) -> Result<(), String> {
if !self.eat_kw(kw) {
return Err(self.syntax_error());
}
// The `;` is required, exactly as it is after any statement — a closing
// `?>` stands in for it, which the scanner has already turned into one.
self.expect_punct(";")
}
fn if_stmt(&mut self) -> Result<StmtKind, String> {
self.pos += 1; // if
self.expect_closer("(")?;
let cond = self.expression()?;
self.expect_punct(")")?;
const IF_ENDS: &[&str] = &["elseif", "else", "endif"];
let (then, alt) = self.control_body(IF_ENDS)?;
let mut elifs = Vec::new();
let mut els = None;
loop {
if self.eat_kw("elseif") {
self.expect_closer("(")?;
let c = self.expression()?;
self.expect_punct(")")?;
elifs.push((c, self.control_body(IF_ENDS)?.0));
} else if self.at_kw("else") {
self.pos += 1;
// `else if` is two keywords; fold it into an elseif branch.
// NOTE: `else if` is NOT legal in the alternative syntax (PHP
// requires `elseif` there), but accepting it costs nothing and
// rejecting it would need a second error path.
if self.eat_kw("if") {
self.expect_closer("(")?;
let c = self.expression()?;
self.expect_punct(")")?;
elifs.push((c, self.control_body(IF_ENDS)?.0));
} else {
els = Some(self.control_body(IF_ENDS)?.0);
break;
}
} else {
break;
}
}
if alt {
self.expect_end_kw("endif")?;
}
Ok(StmtKind::If {
cond,
then,
elifs,
els,
})
}
fn while_stmt(&mut self) -> Result<StmtKind, String> {
self.pos += 1;
self.expect_closer("(")?;
let cond = self.expression()?;
self.expect_punct(")")?;
let (body, alt) = self.control_body(&["endwhile"])?;
if alt {
self.expect_end_kw("endwhile")?;
}
Ok(StmtKind::While { cond, body })
}
fn do_while_stmt(&mut self) -> Result<StmtKind, String> {
self.pos += 1; // do
let body = self.body()?;
if !self.eat_kw("while") {
return Err(self.syntax_error_expecting("\"while\""));
}
self.expect_closer("(")?;
let cond = self.expression()?;
self.expect_punct(")")?;
self.expect_listing(";", "\";\"")?;
Ok(StmtKind::DoWhile { cond, body })
}
fn switch_stmt(&mut self) -> Result<StmtKind, String> {
self.pos += 1; // switch
self.expect_closer("(")?;
let subj = self.expression()?;
self.expect_punct(")")?;
// `switch ($x):` opens the alternative form, closed by `endswitch;`
// instead of `}`. The case labels themselves are spelled identically.
let alt = self.eat_punct(":");
if !alt {
self.expect_listing("{", "\":\" or \"{\"")?;
}
let mut cases = Vec::new();
while !self.at_punct("}") && !self.at_kw("endswitch") && !self.at_end() {
// A `case EXPR:` or `default:` label (PHP also allows `;` for `:`).
let test = if self.eat_kw("case") {
let e = self.expression()?;
if !self.eat_punct(":") {
self.expect_punct(";")?;
}
Some(e)
} else if self.eat_kw("default") {
if !self.eat_punct(":") {
self.expect_listing(";", "\":\" or \";\"")?;
}
None
} else {
return Err(if alt {
self.syntax_error()
} else {
self.syntax_error_expecting("\"case\" or \"default\" or \"}\"")
});
};
// The case body runs until the next case/default or the closing brace.
let mut body = Vec::new();
while !self.at_kw("case")
&& !self.at_kw("default")
&& !self.at_punct("}")
&& !self.at_kw("endswitch")
&& !self.at_end()
{
body.push(self.statement()?);
}
cases.push(SwitchCase { test, body });
}
if alt {
self.expect_end_kw("endswitch")?;
} else {
self.expect_punct("}")?;
}
Ok(StmtKind::Switch { subj, cases })
}
fn for_stmt(&mut self) -> Result<StmtKind, String> {
self.pos += 1;
self.expect_closer("(")?;
let init = self.expr_list_until(";")?;
self.expect_listing(";", "\";\"")?;
let cond = if self.at_punct(";") {
None
} else {
Some(self.expression()?)
};
self.expect_listing(";", "\";\"")?;
let step = self.expr_list_until(")")?;
self.expect_closer(")")?;
let (body, alt) = self.control_body(&["endfor"])?;
if alt {
self.expect_end_kw("endfor")?;
}
Ok(StmtKind::For {
init,
cond,
step,
body,
})
}
/// A comma-separated expression list up to (but not consuming) `stop`.
fn expr_list_until(&mut self, stop: &str) -> Result<Vec<Expr>, String> {
let mut v = Vec::new();
if self.at_punct(stop) {
return Ok(v);
}
v.push(self.expression()?);
while self.eat_punct(",") {
v.push(self.expression()?);
}
Ok(v)
}
fn foreach_stmt(&mut self) -> Result<StmtKind, String> {
self.pos += 1;
self.expect_closer("(")?;
let arr = self.expression()?;
if !self.eat_kw("as") {
return Err(self.syntax_error());
}
// A `&` before the value var marks by-reference iteration (writes back).
let outer_targets = std::mem::take(&mut self.foreach_targets);
let ref1 = self.eat_punct("&");
let first = self.foreach_target()?;
let (key_var, val, by_ref) = if self.eat_punct("=>") {
// The key is always a plain variable. PHP rejects a pattern there
// ("Cannot use list as key element"), so `[$a] => $v` is an error
// rather than a second destructuring site.
let ForeachVal::Var(k) = first else {
return Err(self.syntax_error_at(self.pos - 1));
};
let ref2 = self.eat_punct("&");
(Some(k), self.foreach_target()?, ref2)
} else {
(None, first, ref1)
};
// `foreach ($a as &[$x, $y])` is a parse error in PHP: a pattern is not
// a place a reference can bind to. (An inner `[&$x, $y]` is a different
// construct and is not accepted here either — see `array_literal`.)
if by_ref && matches!(val, ForeachVal::Pattern(_)) {
return Err(self.syntax_error_at(self.pos - 1));
}
if matches!(val, ForeachVal::Var(_)) {
self.expect_listing(")", "\"->\" or \"?->\" or \"[\"")?;
} else {
self.expect_punct(")")?;
}
let mut assigns = std::mem::replace(&mut self.foreach_targets, outer_targets);
let (mut body, alt) = self.control_body(&["endforeach"])?;
if alt {
self.expect_end_kw("endforeach")?;
}
if !assigns.is_empty() {
let line = self.line();
let mut prefixed: Vec<Stmt> = assigns
.drain(..)
.map(|(tmp, target)| Stmt {
line,
kind: StmtKind::Expr(Expr::Assign(
Box::new(target),
None,
Box::new(Expr::Var(tmp)),
)),
})
.collect();
prefixed.append(&mut body);
body = prefixed;
}
Ok(StmtKind::Foreach {
arr,
key_var,
val,
by_ref,
body,
})
}
/// A `foreach` value target: a plain `$v`, or a destructuring pattern in
/// either spelling — `[$x, $y]` and `list($x, $y)` produce the same
/// `Expr::Array`, which is also what `[$x, $y] = …` produces, so the two
/// forms cannot drift apart.
fn foreach_target(&mut self) -> Result<ForeachVal, String> {
if self.eat_punct("[") {
return Ok(ForeachVal::Pattern(
self.array_literal("]", ArraySyntax::Short)?,
));
}
if self.at_kw("list") && self.nth_is_punct(1, "(") {
self.pos += 2; // `list` `(`
return Ok(ForeachVal::Pattern(
self.array_literal(")", ArraySyntax::List)?,
));
}
// `foreach ($a as $o->p)`, `as $arr['k']`, `as C::$s`: a write target that is
// not a plain variable. The loop binds a temporary and assigns it to the
// target before each pass of the body.
// A string literal can begin a dereferenceable variable (`'s'[0]`), so the
// reference accepts it here and only objects to what follows.
if matches!(self.peek(), Some(Tok::Str(_) | Tok::Interp(_))) {
self.pos += 1;
if !(self.at_punct("[") || self.at_punct("->") || self.at_punct("?->")) {
return Err(self.syntax_error_expecting("\"->\" or \"?->\" or \"[\""));
}
return Err(self.syntax_error_at(self.pos - 1));
}
let var_chain = matches!(self.peek(), Some(Tok::Var(_)))
&& (self.nth_is_punct(1, "->")
|| self.nth_is_punct(1, "?->")
|| self.nth_is_punct(1, "[")
|| self.nth_is_punct(1, "::"));
let static_prop = matches!(self.peek(), Some(Tok::Ident(_)))
&& self.nth_is_punct(1, "::")
&& matches!(
self.toks.get(self.pos + 2).map(|s| &s.tok),
Some(Tok::Var(_))
);
if var_chain || static_prop {
let target = self.postfix()?;
if !matches!(
target,
Expr::Index(..) | Expr::Append(_) | Expr::PropGet(..) | Expr::StaticProp(..)
) {
return Err(self.syntax_error_at(self.pos - 1));
}
self.coalesce_temps += 1;
let tmp = format!("@foreach{}", self.coalesce_temps);
self.foreach_targets.push((tmp.clone(), target));
return Ok(ForeachVal::Var(tmp));
}
Ok(ForeachVal::Var(self.expect_var()?))
}
/// The member after `->` / `?->`: a bare identifier, `$var`, or `{expr}`.
///
/// Only a simple variable follows the arrow directly: `$o->$n[0]` is
/// `($o->$n)[0]` under the uniform variable syntax, so the subscript is left
/// for the postfix loop. A brace holding nothing but a string literal is the
/// literal name, exactly as if it had been written bare.
fn object_member(&mut self) -> Result<Member, String> {
if let Some(Tok::Var(n)) = self.peek().cloned() {
self.pos += 1;
return Ok(Member::Dyn(Box::new(Expr::Var(n))));
}
if self.eat_punct("{") {
let e = self.expression()?;
self.expect_punct("}")?;
return Ok(match e {
Expr::Str(s) => Member::Name(s),
e => Member::Dyn(Box::new(e)),
});
}
match self.next() {
Some(Tok::Ident(n)) => Ok(Member::Name(n)),
_ => Err(self.syntax_error_expecting_at(
self.pos - 1,
Some("identifier or variable or \"{\" or \"$\""),
)),
}
}
/// A property / method / constant name after `->` or `::` (a bare identifier).
fn member_name(&mut self) -> Result<String, String> {
match self.next() {
Some(Tok::Ident(n)) => Ok(n),
_ => Err(self.syntax_error_at(self.pos - 1)),
}
}
/// The name after `Class::`: `$name`, or one computed — `$$n` takes the
/// value of `$n` (and `$$$n` that of `$$n`), `${expr}` that of `expr`.
fn static_prop_name(&mut self) -> Result<Member, String> {
if !self.eat_punct("$") {
return self.expect_var().map(Member::Name);
}
let name = if self.eat_punct("{") {
let e = self.expression()?;
self.expect_punct("}")?;
e
} else {
self.primary()?
};
Ok(Member::Dyn(Box::new(name)))
}
fn expect_var(&mut self) -> Result<String, String> {
match self.next() {
Some(Tok::Var(n)) => Ok(n),
_ => Err(self.syntax_error_at(self.pos - 1)),
}
}
/// The doc comment a declaration whose deciding token is at `at` reports:
/// the one pending there, unless an earlier declaration took it already
/// (`/** d */ public $a, $b;` gives it to `$a` only).
fn take_doc(&mut self, at: usize) -> Option<String> {
let doc = self.toks.get(at)?.doc.clone()?;
if doc.0 <= self.doc_used {
return None;
}
self.doc_used = doc.0;
Some(doc.1.to_string())
}
fn function_stmt(&mut self) -> Result<StmtKind, String> {
let doc = self.take_doc(self.pos);
let fn_line = self.line();
let attrs = std::mem::take(&mut self.pending_attr_specs);
self.pos += 1; // function
let deprecated = self.pending_deprecated.take();
let by_ref_return = self.eat_punct("&");
let name = match self.next() {
Some(Tok::Ident(n)) => n,
_ => return Err(self.syntax_error_expecting_at(self.pos - 1, Some("\"(\""))),
};
// A function declared in a namespace is that namespace's: `A\f`.
let name = self.ns_prefixed(&name);
let saved = self.enter_function(&name);
let params = self.param_list()?;
let ret = self.return_type()?;
let body = self.block()?;
self.magic = saved;
Ok(StmtKind::Function {
lines: (fn_line, self.line_at(self.pos - 1)),
name,
params,
body,
ret,
by_ref_return,
namespace: self.magic.namespace.clone(),
deprecated,
doc,
attrs,
})
}
/// `declare(directive=value);` or `declare(directive=value) { ... }`.
///
/// `strict_types` is the only directive with an effect here; it is also the only
/// one PHP constrains, and every constraint is a COMPILE-time one — the script
/// produces no output at all before the diagnostic, which is why these are
/// raised from the parser rather than emitted as a runtime fatal:
///
/// - it must be the very first statement, where a preceding `declare` of any
/// directive does NOT disqualify it but anything else — including the inline
/// HTML in front of a leading `<?php` — does;
/// - its value must be the literal `0` or `1`, and must be a literal at all;
/// - it must not use the block form, though `declare(ticks=1) { … }` may.
///
/// Every other directive (`ticks`, `encoding`) is accepted and ignored, and an
/// unknown one draws PHP's `Unsupported declare` warning. Ignoring `ticks` is
/// right rather than merely convenient: this engine registers no tick handler,
/// so a declared tick count has nothing to call.
fn declare_stmt(&mut self) -> Result<StmtKind, String> {
let kw_line = self.line();
self.pos += 1; // `declare`
self.expect_closer("(")?;
let mut body: Option<Vec<Stmt>> = None;
// Whether THIS `declare` names `strict_types` — the block-mode rule is
// about this statement, not about one that ran earlier in the file.
let mut here_strict = false;
loop {
let name = match self.next() {
Some(Tok::Ident(n)) => n,
_ => return Err(self.syntax_error_expecting_at(self.pos - 1, Some("identifier"))),
};
self.expect_closer("=")?;
if name.eq_ignore_ascii_case("strict_types") {
// The value is read BEFORE the position is judged, because PHP
// reports a bad value on a first-statement `declare` too — the
// checks are independent, and this is the order it applies them.
// Strictly a LITERAL: `-1` is a unary minus applied to one, which
// upstream rejects as "not a literal" rather than as a bad value.
let lit = match self.peek() {
Some(Tok::Int(v)) => {
let v = *v;
self.pos += 1;
Some(v)
}
_ => None,
};
let Some(v) = lit else {
return Err(self.fatal_at(
kw_line,
"declare(strict_types) value must be a literal".to_string(),
));
};
if v != 0 && v != 1 {
return Err(self.fatal_at(
kw_line,
"strict_types declaration must have 0 or 1 as its value".to_string(),
));
}
if !self.only_declares_so_far {
return Err(self.fatal_at(
kw_line,
"strict_types declaration must be the very first statement in the script"
.to_string(),
));
}
// A LATCH, not an assignment: once a file has turned strict typing on, a
// later `declare(strict_types=0)` does not turn it back off — measured both
// orders against the reference, and both stay strict.
self.strict_types |= v == 1;
here_strict = true;
} else {
// A non-`strict_types` directive: its value is an ordinary
// expression, evaluated for nothing and discarded.
self.expression()?;
// `ticks` is the one directive accepted in silence. `encoding` is
// recognised but always refused, because the reference is built
// without the Zend multibyte feature it would need — so it warns
// with its own text rather than the generic one. Anything else is
// unknown. All three are COMPILE-time, hence collected not emitted.
let w = if name.eq_ignore_ascii_case("ticks") {
None
} else if name.eq_ignore_ascii_case("encoding") {
Some("declare(encoding=...) ignored because Zend multibyte feature is turned off by settings".to_string())
} else {
Some(format!("Unsupported declare '{name}'"))
};
if let Some(w) = w {
self.declare_warnings.push((kw_line, w));
}
}
if !self.eat_punct(",") {
break;
}
}
self.expect_listing(")", "\",\" or \")\"")?;
// Both bodied spellings — `{ … }` and `: … enddeclare;` — are block
// mode, and the reference refuses `strict_types` in either.
if self.at_punct("{") || self.at_punct(":") {
if here_strict {
return Err(self.fatal_at(
kw_line,
"strict_types declaration must not use block mode".to_string(),
));
}
let (stmts, alt) = self.control_body(&["enddeclare"])?;
if alt {
self.expect_end_kw("enddeclare")?;
}
body = Some(stmts);
} else {
self.eat_punct(";");
}
Ok(StmtKind::Block(body.unwrap_or_default()))
}
/// `namespace Name;` or `namespace Name { ... }`. Every name the code after
/// it declares or refers to resolves inside `Name`, and the imports of the
/// namespace before it are dropped. The block form runs its body inline.
fn namespace_stmt(&mut self) -> Result<StmtKind, String> {
// The first namespace declaration must precede every statement but
// `declare`; later ones may follow code of the namespace before them.
if !self.only_declares_so_far && !self.ns_seen {
return Err(self.fatal_at(
self.line(),
"Namespace declaration statement has to be the very first statement or \
after any declare call in the script"
.to_string(),
));
}
self.ns_seen = true;
self.pos += 1; // namespace
let named = matches!(self.peek(), Some(Tok::Ident(_))) || self.at_punct("\\");
let mut ns = String::new();
if named {
self.eat_punct("\\");
ns = match self.next() {
Some(Tok::Ident(n)) => n,
_ => return Err(self.syntax_error_at(self.pos - 1)),
};
self.raw_name_rest(&mut ns);
}
// `namespace { }` is the global namespace.
self.magic.namespace = ns;
self.imports = Imports::default();
if self.at_punct("{") {
Ok(StmtKind::Block(self.namespace_block()?))
} else if !named {
// A bare `namespace;` has no name for the `;` to follow.
Err(self.syntax_error_expecting("\"{\""))
} else {
self.expect_listing(";", "\"{\"")?;
Ok(StmtKind::Block(Vec::new()))
}
}
/// `use A\B\C [as D];` (also `use function …` / `use const …`, and the
/// group form `use A\{B, function f, const K as L}`) — a namespace import.
/// It binds the alias (the last segment unless `as` names one) for the rest
/// of the namespace (`zend_compile_use`).
fn use_import_stmt(&mut self) -> Result<StmtKind, String> {
self.pos += 1; // use
let kind = if self.eat_kw("function") {
ImportKind::Function
} else if self.eat_kw("const") {
ImportKind::Const
} else {
ImportKind::Class
};
loop {
if kind != ImportKind::Class
&& !matches!(self.peek(), Some(Tok::Ident(_)))
&& !self.at_punct("\\")
{
return Err(self.syntax_error_expecting(
"identifier or fully qualified name or namespaced name",
));
}
let prefix = self.raw_name()?.text;
// `use A\B\{C, D as E, function f, const K};` — a group: the prefix
// ends in a separator that is followed by `{`.
if self.at_punct("\\") {
self.pos += 1;
self.expect_listing("{", "\"{\"")?;
let mut first = true;
loop {
if self.at_punct("}") {
if first {
return Err(self.syntax_error_expecting(
"identifier or namespaced name or \"function\" or \"const\"",
));
}
break;
}
first = false;
let member_kind = if self.eat_kw("function") {
ImportKind::Function
} else if self.eat_kw("const") {
ImportKind::Const
} else {
kind
};
let line = self.line();
let name = format!("{prefix}\\{}", self.raw_name()?.text);
let alias = self.import_alias()?;
self.add_import(member_kind, name, alias, line)?;
if !self.eat_punct(",") {
break;
}
}
self.expect_closer("}")?;
break;
}
let line = self.line();
let alias = self.import_alias()?;
self.add_import(kind, prefix, alias, line)?;
if !self.eat_punct(",") {
break;
}
}
self.expect_listing(";", "\",\" or \";\"")?;
Ok(StmtKind::Block(Vec::new()))
}
/// The `as Alias` after an imported name, if any. The alias is a plain
/// identifier: a reserved word there (`as static`) is a syntax error.
fn import_alias(&mut self) -> Result<Option<String>, String> {
if !self.eat_kw("as") {
return Ok(None);
}
match self.next() {
Some(Tok::Ident(a)) if reserved_spelling(&a).is_none() => Ok(Some(a)),
Some(Tok::Ident(_)) => {
Err(self.syntax_error_expecting_at(self.pos - 1, Some("identifier")))
}
_ => Ok(None),
}
}
/// Bind one import, refusing the clashes the reference refuses at compile
/// time: an alias already in use for the same kind of symbol, a class alias
/// that is a class-relative name, or one naming a class this file already
/// declared in the namespace.
fn add_import(
&mut self,
kind: ImportKind,
name: String,
alias: Option<String>,
line: u32,
) -> Result<(), String> {
let alias = alias.unwrap_or_else(|| name.rsplit('\\').next().unwrap_or(&name).to_string());
let (word, key) = match kind {
ImportKind::Class => ("", alias.to_ascii_lowercase()),
ImportKind::Function => ("function ", alias.to_ascii_lowercase()),
ImportKind::Const => ("const ", alias.clone()),
};
let in_use =
|| format!("Cannot use {word}{name} as {alias} because the name is already in use");
if kind == ImportKind::Class {
if is_class_relative_name(&alias) {
return Err(self.fatal_at(
line,
format!(
"Cannot use {name} as {alias} because '{alias}' is a special class name"
),
));
}
let local = self.ns_prefixed(&alias).to_ascii_lowercase();
if local != name.to_ascii_lowercase() && self.seen_classes.contains(&local) {
return Err(self.fatal_at(line, in_use()));
}
}
let table = match kind {
ImportKind::Class => &mut self.imports.class,
ImportKind::Function => &mut self.imports.function,
ImportKind::Const => &mut self.imports.constant,
};
if table.contains_key(&key) {
return Err(self.fatal_at(line, in_use()));
}
table.insert(key, name);
Ok(())
}
/// `const NAME = expr[, NAME2 = expr2]*;` — a global constant declaration.
///
/// The name is a BARE identifier, never a `$variable` and never qualified:
/// `const Foo\X = 1` is a syntax error upstream, because the declaration
/// takes its namespace from the enclosing `namespace`, not from the name.
fn const_stmt(&mut self) -> Result<StmtKind, String> {
self.pos += 1; // const
let mut decls = Vec::new();
loop {
let name = if matches!(self.peek(), Some(Tok::Ident(_))) {
self.member_name()?
} else {
return Err(self.syntax_error_expecting("identifier"));
};
self.expect_closer("=")?;
// Declared in the enclosing namespace: `namespace A; const K = 1;`
// defines `A\K`.
let name = self.ns_prefixed(&name);
decls.push((name, self.expression()?));
if !self.eat_punct(",") {
break;
}
}
self.expect_listing(";", "\",\" or \";\"")?;
Ok(StmtKind::ConstDecl(decls))
}
/// `try { body } catch (T1 | T2 [$e]) { ... } ... [finally { ... }]` — at
/// least one `catch` or a `finally` is required (PHP rule).
fn try_stmt(&mut self) -> Result<StmtKind, String> {
let try_idx = self.pos;
self.pos += 1; // try
let body = self.block()?;
let mut catches = Vec::new();
while self.at_kw("catch") {
self.pos += 1;
self.expect_closer("(")?;
// A `|`-separated union of class names.
let mut types = vec![self.expect_type_name()?];
while self.eat_punct("|") {
types.push(self.expect_type_name()?);
}
// The bound `$var` is optional (PHP 8 allows `catch (T) { }`).
let var = match self.peek() {
Some(Tok::Var(_)) => Some(self.expect_var()?),
_ => None,
};
self.expect_closer(")")?;
let cbody = self.block()?;
catches.push(CatchArm {
types,
var,
body: cbody,
});
}
let finally = if self.eat_kw("finally") {
Some(self.block()?)
} else {
None
};
if catches.is_empty() && finally.is_none() && self.deferred_fatal.is_none() {
// A grammar-valid `try` with no handler is refused by the COMPILER, so a
// syntax error further on is still the one reported.
self.deferred_fatal = Some(self.fatal_at(
self.line_at(try_idx),
"Cannot use try without catch or finally".to_string(),
));
}
Ok(StmtKind::Try {
body,
catches,
finally,
})
}
/// A class name — in a `catch`, `extends`, `implements`, a trait `use`,
/// `instanceof` — resolved against the current namespace and its imports.
fn expect_type_name(&mut self) -> Result<String, String> {
let raw = self.raw_name()?;
Ok(self.resolve_class(&raw))
}
/// Whether the token `n` positions ahead of the cursor begins a type NAME —
/// a bareword, or the `\` that anchors a qualified one.
fn nth_starts_type_name(&self, n: usize) -> bool {
matches!(
self.toks.get(self.pos + n).map(|s| &s.tok),
Some(Tok::Ident(_)) | Some(Tok::Punct("\\"))
)
}
/// One possibly-qualified type name: `int`, `Foo`, `\Foo\Bar`, `Foo\Bar`. A
/// built-in type written unqualified stays itself; any other name is a class,
/// resolved like every class reference.
fn qualified_type_name(&mut self) -> Result<String, String> {
if !self.at_name_anchor() && !matches!(self.peek(), Some(Tok::Ident(_))) {
return Err(self.syntax_error());
}
let raw = self.raw_name()?;
Ok(self.resolve_type_name(&raw))
}
/// Parse a type as written in a declaration, or `None` when none is present.
///
/// Handles the nullable shorthand (`?T`), unions (`A|B`), intersections (`A&B`)
/// and the PHP 8.2 DNF spelling (`(A&B)|C`). An intersection is kept as one
/// `&`-joined part, which the type check splits again.
///
/// In a parameter list `&` is ambiguous — `int &$x` is a by-reference marker,
/// `A&B $x` an intersection. It is read as an intersection only when a type NAME
/// follows it, which is the same rule PHP's own parser applies.
fn type_hint(&mut self) -> Result<Option<TypeHint>, String> {
let nullable = self.eat_punct("?");
let mut parts: Vec<String> = Vec::new();
loop {
if self.at_punct("(") {
// A DNF member: `(A&B)`. Its alternatives are joined back into the
// one part they came from, since an intersection is never enforced.
self.pos += 1;
let mut names = vec![self.qualified_type_name()?];
while self.eat_punct("&") {
names.push(self.qualified_type_name()?);
}
self.expect_punct(")")?;
parts.push(names.join("&"));
} else if self.nth_starts_type_name(0) {
parts.push(self.qualified_type_name()?);
} else {
break;
}
if self.eat_punct("|") {
continue;
}
if self.at_punct("&") && self.nth_starts_type_name(1) {
self.pos += 1;
let rhs = self.qualified_type_name()?;
if let Some(last) = parts.last_mut() {
last.push('&');
last.push_str(&rhs);
}
continue;
}
break;
}
if parts.is_empty() {
// A lone `?` with no type after it is not a type at all.
return if nullable {
Err(self.syntax_error())
} else {
Ok(None)
};
}
if nullable {
parts.push("null".to_string());
}
Ok(Some(TypeHint { parts }))
}
/// Parse an optional return-type hint (`: [?]type`).
fn return_type(&mut self) -> Result<Option<TypeHint>, String> {
if self.eat_punct(":") {
// After the `:` a type is mandatory; the reference reports the stray
// token itself, with no list of what could have followed.
match self.type_hint()? {
Some(t) => Ok(Some(t)),
None => Err(self.syntax_error()),
}
} else {
Ok(None)
}
}
/// Parse a `( ... )` formal parameter list. Before each `$var` it skips
/// modifiers and type hints — visibility keywords, `?` nullable, `&` by-ref,
/// and bareword type names — then reads an optional `...$rest` variadic marker,
/// the name, and an optional `= default` value. By-ref (`&`) and typed hints
/// are accepted but not enforced in the scaffold.
/// Consume any run of `#[Attr, Other(args)]` groups and return the attribute
/// names in source order, each resolved as a class name is — an attribute
/// IS a class, so `#[Deprecated]` inside `namespace A` names `A\Deprecated`.
///
/// The arguments are parsed as the call arguments they are (positional, then
/// named) and kept, with the names, in `last_attrs` for the declaration that
/// follows: nothing here executes, and reflection evaluates them on demand.
/// `#[\Deprecated]`'s literal `message`/`since` are read into
/// `last_deprecated`.
///
/// Every declaration form may carry attributes, so this is called at the head
/// of statements, class members, closures and parameters.
fn attributes(&mut self) -> Result<Vec<String>, String> {
let mut attrs: Vec<Attr> = Vec::new();
self.last_deprecated = None;
while self.eat_punct("#[") {
loop {
// `#[A, B,]`: a trailing comma closes the group.
if self.eat_punct("]") {
break;
}
let line = self.line();
let raw = self.raw_name()?;
let name = self.resolve_class(&raw);
let args = if self.eat_punct("(") {
self.arg_list()?
} else {
Vec::new()
};
attrs.push(Attr { name, args, line });
if !self.eat_punct(",") {
self.expect_punct("]")?;
break;
}
}
}
if let Some(dep) = attrs
.iter()
.find(|a| a.name.eq_ignore_ascii_case("Deprecated"))
{
self.last_deprecated = Some(deprecation_of(&dep.args));
}
let names = attrs.iter().map(|a| a.name.clone()).collect();
self.last_attrs = attrs;
Ok(names)
}
/// An attribute's class name as written — `anchored` when a `\` led it —
/// resolved against the namespace and imports.
fn param_list(&mut self) -> Result<Vec<Param>, String> {
self.expect_closer("(")?;
let mut params = Vec::new();
if !self.at_punct(")") {
loop {
// A parameter may be attributed (`function f(#[Attr] int $x)`).
self.attributes()?;
let param_attrs = std::mem::take(&mut self.last_attrs);
let pline = self.line();
// Skip a leading modifier/type-hint chain up to `...` or `$var`. A
// visibility/readonly keyword marks a promoted constructor property.
let mut promoted = false;
let mut readonly = false;
let mut by_ref = false;
let mut promoted_vis = Visibility::Public;
let mut promoted_set_vis: Option<Visibility> = None;
// Leading modifiers, which precede the type: `public int $x`.
while matches!(self.peek(), Some(Tok::Ident(_))) {
// `private(set)` and friends set the write visibility only.
if let Some(v) = self.eat_set_visibility() {
promoted = true;
promoted_set_vis = Some(v);
continue;
}
let Some(Tok::Ident(kw)) = self.peek() else {
break;
};
match kw.to_ascii_lowercase().as_str() {
"readonly" => {
promoted = true;
readonly = true;
}
"public" => promoted = true,
"protected" => {
promoted = true;
promoted_vis = Visibility::Protected;
}
"private" => {
promoted = true;
promoted_vis = Visibility::Private;
}
// Not a modifier — this identifier is the TYPE, which
// `type_hint` reads next.
_ => break,
}
self.pos += 1;
}
let ty = self.type_hint()?;
// `&` after the type is the by-reference marker; an intersection
// was already absorbed by `type_hint`.
if self.eat_punct("&") {
by_ref = true;
}
// `...$rest` collects all trailing arguments into an array.
let variadic = self.eat_punct("...");
if !matches!(self.peek(), Some(Tok::Var(_))) {
return Err(self.syntax_error_expecting("variable"));
}
let name = self.expect_var()?;
// A default value (`$x = expr`), applied when the caller omits it.
let default = if self.eat_punct("=") {
Some(self.expression()?)
} else {
None
};
params.push(Param {
name,
line: pline,
ty,
default,
variadic,
promoted,
promoted_vis,
promoted_set_vis,
readonly,
by_ref,
attrs: param_attrs,
});
// PHP 8.0+ allows a trailing comma in parameter lists too.
if !self.eat_punct(",") || self.at_punct(")") {
break;
}
}
}
self.expect_closer(")")?;
Ok(params)
}
/// Parse a call argument list up to and consuming the closing `)` (the opening
/// `(` is already eaten). Supports `...$arr` argument unpacking and PHP 8.0
/// named arguments (`name: value`).
fn arg_list(&mut self) -> Result<Vec<Expr>, String> {
self.arg_list_listing(Some("\")\""))
}
/// [`arg_list`](Self::arg_list) with the `expecting` clause a stray token
/// after the last argument is reported with — `None` for the constructs
/// whose operand sits directly before the `)` (`empty($a $b)`), where the
/// reference prints no list, and the chain tokens for `unset`.
fn arg_list_listing(&mut self, listing: Option<&str>) -> Result<Vec<Expr>, String> {
let mut args = Vec::new();
if !self.at_punct(")") {
loop {
if self.eat_punct("...") {
args.push(Expr::Spread(Box::new(self.expression()?)));
} else if let Some(name) = self.named_arg_label() {
args.push(Expr::NamedArg(name, Box::new(self.expression()?)));
} else {
args.push(self.expression()?);
}
// PHP 7.3+ allows a trailing comma before the `)`.
if !self.eat_punct(",") || self.at_punct(")") {
break;
}
}
}
match listing {
Some(l) => self.expect_listing(")", l)?,
None => self.expect_punct(")")?,
}
Ok(args)
}
/// The operand list of `unset( … )`. A number cannot begin a variable, so one
/// is refused where it stands — with no list after the first operand, and
/// with `expecting ")"` after a comma, where the grammar's trailing comma
/// leaves only the closing parenthesis.
fn unset_arg_list(&mut self) -> Result<Vec<Expr>, String> {
let mut args = Vec::new();
if !self.at_punct(")") {
loop {
if matches!(self.peek(), Some(Tok::Int(_) | Tok::Float(_))) {
return Err(if args.is_empty() {
self.syntax_error()
} else {
self.syntax_error_expecting("\")\"")
});
}
args.push(self.expression()?);
if !self.eat_punct(",") || self.at_punct(")") {
break;
}
}
}
self.expect_listing(")", "\"->\" or \"?->\" or \"[\"")?;
Ok(args)
}
/// A named-argument label `name:` — an identifier immediately followed by a
/// single `:` (a distinct token from `::`). Consumes `name :` and returns the
/// name; leaves the cursor untouched and returns `None` otherwise.
fn named_arg_label(&mut self) -> Option<String> {
if let Some(Tok::Ident(n)) = self.peek() {
if self.nth_is_punct(1, ":") {
let n = n.clone();
self.pos += 2; // identifier + ':'
return Some(n);
}
}
None
}
/// First-class callable syntax `callee(...)` (PHP 8.1). Called just after a
/// call's opening `(` is consumed: if the argument list is exactly `...`, this
/// consumes `... )` and returns the desugared closure
/// `fn(...$args) => call_user_func_array(<callable>, $args)` — a real
/// `Closure`. Returns `None` when it is not the first-class-callable form (the
/// caller then parses a normal argument list).
fn try_fcc(&mut self, callable: Expr, instance: bool) -> Result<Option<Expr>, String> {
if !(self.at_punct("...") && self.nth_is_punct(1, ")")) {
return Ok(None);
}
self.pos += 2; // consume `...` and `)`
Ok(Some(Expr::Fcc {
callable: Box::new(callable),
instance,
}))
}
/// `class Name [extends Parent] [implements ...] { members }`. Members are
/// consts, properties (with visibility/static/type modifiers), and methods.
/// A leading `abstract`/`final` class modifier is recorded; `final` is
/// enforced when a subclass links against it.
fn class_stmt(&mut self) -> Result<StmtKind, String> {
let attributes = std::mem::take(&mut self.pending_attrs);
let class_attrs = std::mem::take(&mut self.pending_attr_specs);
let is_interface = self.at_kw("interface");
let is_trait = self.at_kw("trait");
let is_enum = self.at_kw("enum");
// `abstract` marks the class un-instantiable, `final` forbids a
// subclass, and `readonly class C` (PHP 8.2) makes every declared
// property readonly. They may come in any order, each at most once.
let (mut is_abstract, mut is_final, mut is_readonly_class) = (false, false, false);
if !is_interface && !is_trait && !is_enum {
while !self.at_kw("class") {
let line = self.line();
let (flag, word) = if self.eat_kw("abstract") {
(&mut is_abstract, "abstract")
} else if self.eat_kw("final") {
(&mut is_final, "final")
} else if self.eat_kw("readonly") {
(&mut is_readonly_class, "readonly")
} else {
return Err(self.syntax_error_expecting(
"\"abstract\" or \"final\" or \"readonly\" or \"class\"",
));
};
if std::mem::replace(flag, true) {
return Err(self.bare_fatal_at(
line,
format!("Multiple {word} modifiers are not allowed"),
));
}
if is_abstract && is_final {
return Err(self.bare_fatal_at(
line,
"Cannot use the final modifier on an abstract class".to_string(),
));
}
}
}
let class_doc = self.take_doc(self.pos);
let class_line = self.line();
self.pos += 1; // class / interface / trait / enum
let name = match self.next() {
Some(Tok::Ident(n)) => n,
_ => return Err(self.syntax_error_expecting_at(self.pos - 1, Some("identifier"))),
};
// Declared in the enclosing namespace, unless an import already claims
// the short name for a different class (`zend_compile_class_decl`).
let short = name;
let name = self.ns_prefixed(&short);
if let Some(import) = self.imports.class.get(&short.to_ascii_lowercase()) {
if !import.eq_ignore_ascii_case(&name) {
return Err(self.fatal_at(
self.line(),
format!("Cannot redeclare class {name} (previously declared as local import)"),
));
}
}
self.seen_classes.insert(name.to_ascii_lowercase());
// A backed enum names its scalar backing type after `:` (`enum E: string`).
let mut enum_backing = None;
if is_enum && self.eat_punct(":") {
enum_backing = Some(self.raw_name()?.text);
}
// A trait's own name is not what `__CLASS__` answers inside it: its
// methods run as members of whichever class used the trait, so that half
// waits for run time while `__TRAIT__` is settled here.
let entered = MagicCtx {
class: if is_trait {
MagicName::Dynamic(MagicConst::Class {
prefix: String::new(),
suffix: String::new(),
})
} else {
MagicName::Plain(name.clone())
},
// `__METHOD__` names the DECLARING class or trait, so a trait's
// methods stay `T::m` even once flattened into the class that used it.
owner: MagicName::Plain(name.clone()),
trait_name: if is_trait {
name.clone()
} else {
String::new()
},
..self.magic.clone()
};
let saved = std::mem::replace(&mut self.magic, entered);
let decl = self.class_rest(
name,
ClassKind {
is_interface,
is_trait,
is_enum,
is_abstract,
is_readonly_class,
},
enum_backing,
);
self.magic = saved;
let mut decl = decl?;
if let Some(d) = class_doc {
decl.docs.insert(0, ("class".to_string(), d));
}
if !class_attrs.is_empty() {
decl.attrs.insert(0, ("class".to_string(), class_attrs));
}
Ok(StmtKind::Class(ClassDecl {
lines: (class_line, decl.lines.1),
attributes,
is_final,
namespace: self.magic.namespace.clone(),
..decl
}))
}
/// Everything of a class declaration after its name: the `extends` /
/// `implements` clauses and the `{ members }` body.
///
/// Split out of [`Parser::class_stmt`] because an anonymous class
/// (`new class(args) extends P implements I { … }`) is exactly this tail
/// with a generated name, so both forms must parse the same body grammar.
/// The returned declaration carries no attributes; the caller attaches them.
fn class_rest(
&mut self,
name: String,
kind: ClassKind,
enum_backing: Option<String>,
) -> Result<ClassDecl, String> {
let ClassKind {
is_interface,
is_trait,
is_enum,
is_abstract,
is_readonly_class,
} = kind;
let mut parent = None;
let mut implements = Vec::new();
// `extends`: one parent for a class; an interface may extend several. An
// enum has none, so the keyword is left for the `{` check to refuse.
if !is_enum && self.eat_kw("extends") {
loop {
let n = self.expect_type_name()?;
if is_interface {
implements.push(n);
if !self.eat_punct(",") {
break;
}
} else {
parent = Some(n);
break;
}
}
}
// `implements Iface, ...`.
if self.eat_kw("implements") {
loop {
implements.push(self.expect_type_name()?);
if !self.eat_punct(",") {
break;
}
}
}
self.expect_closer("{")?;
let mut consts = Vec::new();
let mut const_lines = Vec::new();
let mut const_pos = Vec::new();
let mut const_vis = Vec::new();
let mut final_consts = Vec::new();
let mut props = Vec::new();
let mut ctor_prop_slot = 0;
let mut methods = Vec::new();
let mut uses = Vec::new();
let mut trait_insteadof = Vec::new();
let mut trait_aliases = Vec::new();
let mut cases = Vec::new();
let mut docs = Vec::new();
let mut attrs: Vec<(String, Vec<Attr>)> = Vec::new();
while !self.at_punct("}") && !self.at_end() {
// Any member — const, property, method, enum case — may be attributed.
self.attributes()?;
let member_attrs = std::mem::take(&mut self.last_attrs);
let mut attach = |key: String| {
if !member_attrs.is_empty() {
attrs.push((key, member_attrs.clone()));
}
};
let member_deprecated = self.last_deprecated.take();
// `case Name [= value];` — an enum case (only meaningful inside `enum`).
if is_enum && self.at_kw("case") {
self.pos += 1;
if let Some(Tok::Ident(n)) = self.peek() {
attach(format!("case:{n}"));
}
if let (Some(d), Some(Tok::Ident(n))) = (self.take_doc(self.pos), self.peek()) {
docs.push((format!("case:{n}"), d));
}
let case_line = self.line();
let cname = match self.next() {
Some(Tok::Ident(n)) => n,
_ => return Err(self.syntax_error_at(self.pos - 1)),
};
let value = if self.eat_punct("=") {
Some(self.expression()?)
} else {
None
};
self.expect_listing(";", "\";\"")?;
cases.push(EnumCase {
name: cname,
value,
line: case_line,
});
continue;
}
// `use Trait1, Trait2;` — pull trait members into this class.
if self.at_kw("use") {
self.pos += 1;
loop {
uses.push(self.expect_type_name()?);
if !self.eat_punct(",") {
break;
}
}
// A `{ ... }` adaptation block resolves conflicts between the
// used traits (`insteadof`) and binds extra names or
// visibilities (`as`); otherwise a plain `;` terminates the use.
if self.at_punct("{") {
self.trait_adaptations(&mut trait_insteadof, &mut trait_aliases)?;
} else {
self.expect_listing(";", "\",\" or \";\" or \"{\"")?;
}
continue;
}
// Member modifiers: `static`, the visibility keyword, `readonly`,
// `abstract` and `final` are captured; `var` is accepted and ignored.
let mut m_abstract = false;
let mut m_final = false;
let mut is_static = false;
let mut readonly = is_readonly_class;
let mut visibility = Visibility::Public;
let mut set_visibility: Option<Visibility> = None;
// Each modifier may be written once (the three visibilities count as
// one); the reference rejects a repeat at the repeated word's line.
let (mut seen_vis, mut seen_set, mut seen_readonly) = (false, false, false);
let member_start = self.pos;
loop {
let line = self.line();
let (repeated, word) = if self.eat_kw("static") {
(std::mem::replace(&mut is_static, true), "static")
} else if let Some(v) = self.eat_set_visibility() {
set_visibility = Some(v);
(std::mem::replace(&mut seen_set, true), "access type")
} else if let Some(v) = [
("public", Visibility::Public),
("protected", Visibility::Protected),
("private", Visibility::Private),
]
.into_iter()
.find_map(|(kw, v)| self.eat_kw(kw).then_some(v))
{
visibility = v;
(std::mem::replace(&mut seen_vis, true), "access type")
} else if self.eat_kw("readonly") {
readonly = true;
(std::mem::replace(&mut seen_readonly, true), "readonly")
} else if self.eat_kw("abstract") {
(std::mem::replace(&mut m_abstract, true), "abstract")
} else if self.eat_kw("final") {
(std::mem::replace(&mut m_final, true), "final")
} else if self.eat_kw("var") {
(false, "var")
} else {
break;
};
if repeated {
return Err(self.bare_fatal_at(
line,
format!("Multiple {word} modifiers are not allowed"),
));
}
}
let const_line = self.line();
// A member that opens with no modifier can only be a constant or a
// method; anything else (`$a;`, `int $a;`, a stray literal) is
// refused where the reference refuses it, naming `function`.
if self.at_kw("case") && !is_enum {
return Err(
self.bare_fatal_at(self.line(), "Case can only be used in enums".to_string())
);
}
if self.pos == member_start && !self.at_kw("const") && !self.at_kw("function") {
return Err(self.syntax_error_expecting("\"function\""));
}
let set_word = |v: Visibility| match v {
Visibility::Public => "public(set)",
Visibility::Protected => "protected(set)",
Visibility::Private => "private(set)",
};
let misplaced = if self.at_kw("const") && set_visibility.is_some() {
set_visibility.map(|v| {
format!(
"Cannot use the {} modifier on a class constant",
set_word(v)
)
})
} else if self.at_kw("function") && set_visibility.is_some() {
set_visibility
.map(|v| format!("Cannot use the {} modifier on a method", set_word(v)))
} else if self.at_kw("const") {
// A constant takes a visibility and `final`, nothing else.
[
(m_abstract, "abstract"),
(is_static, "static"),
(seen_readonly, "readonly"),
]
.into_iter()
.find(|(set, _)| *set)
.map(|(_, word)| format!("Cannot use the {word} modifier on a class constant"))
} else if self.at_kw("function") && seen_readonly {
Some("Cannot use the readonly modifier on a method".to_string())
} else if self.at_kw("function") && m_abstract && m_final {
Some("Cannot use the final modifier on an abstract method".to_string())
} else {
None
};
if let Some(msg) = misplaced {
return Err(self.bare_fatal_at(const_line, msg));
}
if self.eat_kw("const") {
// PHP 8.3 typed constant, `const int X = 1;`: a type is present
// unless the first name is directly followed by `=`.
let untyped = matches!(self.peek(), Some(Tok::Ident(_)))
&& matches!(
self.toks.get(self.pos + 1).map(|s| &s.tok),
Some(Tok::Punct("="))
);
let const_ty = if untyped { None } else { self.type_hint()? };
let first_name_line = self.line();
loop {
const_lines.push(const_line);
const_pos.push(self.pos);
if let Some(Tok::Ident(n)) = self.peek() {
attach(format!("const:{n}"));
}
if let (Some(d), Some(Tok::Ident(n))) = (self.take_doc(self.pos), self.peek()) {
docs.push((format!("const:{n}"), d));
}
let cname = match self.next() {
Some(Tok::Ident(n)) => n,
_ => return Err(self.syntax_error_at(self.pos - 1)),
};
self.expect_closer("=")?;
if visibility != Visibility::Public {
const_vis.push((cname.clone(), visibility));
}
if m_final {
final_consts.push(cname.clone());
}
let value = self.expression()?;
if let Some(ty) = &const_ty {
if let Some(msg) =
const_type_error(ty, &name, parent.as_deref(), &cname, &value)
{
return Err(self.fatal_at(first_name_line, msg));
}
}
let value = match &const_ty {
Some(ty) => widen_int_literal(ty, value),
None => value,
};
consts.push((cname, value));
if !self.eat_punct(",") {
break;
}
}
self.expect_listing(";", "\",\" or \";\"")?;
} else if self.at_kw("function") {
let fn_line = self.line();
let method_doc = self.take_doc(self.pos);
self.pos += 1; // function
let by_ref_return = self.eat_punct("&"); // return-by-ref marker
let mname = match self.next() {
Some(Tok::Ident(n)) => n,
_ => return Err(self.syntax_error_at(self.pos - 1)),
};
if let Some(d) = method_doc {
docs.push((format!("method:{}", mname.to_ascii_lowercase()), d));
}
attach(format!("method:{}", mname.to_ascii_lowercase()));
// `zend_begin_method_decl`: a private method cannot be overridden, so
// `final` on one is pointless — except on a constructor, which a
// subclass constructor does not override.
if m_final
&& visibility == Visibility::Private
&& !mname.eq_ignore_ascii_case("__construct")
{
crate::lexer::push_diag(
"Warning",
crate::errlevel::E_COMPILE_WARNING,
fn_line,
"Private methods cannot be final as they are never overridden by other \
classes",
);
}
let saved = self.enter_method(&mname);
let params = self.param_list()?;
let ret = self.return_type()?;
// An abstract/interface method has no body, just `;`.
let has_body = !self.eat_punct(";");
if has_body && !self.at_punct("{") {
return Err(self.syntax_error_expecting("\";\" or \"{\""));
}
let body = if has_body { self.block()? } else { Vec::new() };
let end_line = self.line_at(self.pos - 1);
self.magic = saved;
if mname.eq_ignore_ascii_case("__construct") {
ctor_prop_slot = props.len();
}
methods.push(Method {
name: mname,
params,
body,
ret,
is_static,
visibility,
by_ref_return,
is_abstract: m_abstract || is_interface,
is_final: m_final,
has_body,
line: fn_line,
end_line,
deprecated: member_deprecated.clone(),
});
} else {
// Property declaration(s): an optional type precedes the $var, and
// applies to every name in a `public int $a, $b;` list.
let type_line = self.line();
let ty = self.type_hint()?;
loop {
let prop_line = self.line();
if let Some(Tok::Var(n)) = self.peek() {
attach(format!("prop:{n}"));
}
if let (Some(d), Some(Tok::Var(n))) = (self.take_doc(self.pos), self.peek()) {
docs.push((format!("prop:{n}"), d));
}
// After a modifier the reference expects a variable; at a member
// that starts with nothing recognisable it says `function`
// instead, which is not modelled, so no list is printed there.
let pname = if !matches!(self.peek(), Some(Tok::Var(_)))
&& (ty.is_some() || self.after_member_modifier())
{
return Err(self.syntax_error_expecting("variable"));
} else {
self.expect_var()?
};
let default = if self.eat_punct("=") {
Some(self.expression()?)
} else {
None
};
let default = match (&ty, default) {
(Some(t), Some(d)) => {
if let Some(msg) =
prop_default_error(t, &name, parent.as_deref(), &pname, &d)
{
return Err(self.fatal_at(type_line, msg));
}
Some(widen_int_literal(t, d))
}
(_, d) => d,
};
props.push(PropDecl {
name: pname,
default,
ty: ty.clone(),
is_static,
visibility,
set_visibility,
readonly,
is_final: m_final,
line: prop_line,
pos: self.pos,
});
if !self.eat_punct(",") {
break;
}
}
self.expect_listing(";", "\",\" or \";\"")?;
}
}
self.expect_punct("}")?;
let end_line = self.line_at(self.pos - 1);
// A backed enum implements `BackedEnum` (which extends `UnitEnum`); a pure
// enum implements `UnitEnum`. Added so `instanceof UnitEnum`/`BackedEnum`
// holds without the user declaring it.
if is_enum {
implements.push("UnitEnum".to_string());
if enum_backing.is_some() {
implements.push("BackedEnum".to_string());
}
}
Ok(ClassDecl {
// The caller knows where the declaration began.
lines: (0, end_line),
name,
parent,
implements,
uses,
trait_insteadof,
trait_aliases,
is_interface,
is_trait,
is_readonly: is_readonly_class,
is_abstract,
is_enum,
enum_backing,
cases,
consts,
const_lines,
const_pos,
const_vis,
final_consts,
props,
ctor_prop_slot,
methods,
attributes: Vec::new(),
namespace: String::new(),
is_final: false,
docs,
attrs,
})
}
/// The `{ … }` adaptation block of a `use Trait…` inside a class body:
///
/// ```text
/// A::m insteadof B, C; // keep A's m, drop B's and C's
/// A::m as alias; // bind A's m under a second name
/// A::m as protected alias; // …with a visibility of its own
/// m as protected; // change the visibility of the existing m
/// ```
///
/// The left-hand side may be qualified (`A::m`) or bare (`m`); a bare name
/// is only legal for `as`, and only when exactly one used trait declares it
/// — a check the compiler makes, because only it knows the traits' members.
fn trait_adaptations(
&mut self,
insteadof: &mut Vec<TraitInsteadof>,
aliases: &mut Vec<TraitAlias>,
) -> Result<(), String> {
self.expect_punct("{")?;
while !self.at_punct("}") && !self.at_end() {
let first = self.raw_name()?;
// `A::m` qualifies the method with its trait; a bare `m` does not.
let (from, method) = if self.eat_punct("::") {
let first = self.resolve_class(&first);
let m = match self.next() {
Some(Tok::Ident(n)) => n,
_ => return Err(self.syntax_error_at(self.pos - 1)),
};
(Some(first), m)
} else {
(None, first.text)
};
if self.eat_kw("insteadof") {
let mut losers = Vec::new();
loop {
losers.push(self.expect_type_name()?);
if !self.eat_punct(",") {
break;
}
}
// `insteadof` names which trait wins, so the left side must say
// which trait it is talking about.
let Some(winner) = from else {
return Err(self.syntax_error_at(self.pos - 1));
};
insteadof.push(TraitInsteadof {
winner,
method,
losers,
});
} else if self.eat_kw("as") {
let visibility = if self.eat_kw("public") {
Some(Visibility::Public)
} else if self.eat_kw("protected") {
Some(Visibility::Protected)
} else if self.eat_kw("private") {
Some(Visibility::Private)
} else {
None
};
// The new name is optional: `m as protected;` only re-marks the
// visibility of the binding the class already has.
let alias = match self.peek() {
Some(Tok::Ident(n)) => {
let n = n.clone();
self.pos += 1;
Some(n)
}
_ => None,
};
if visibility.is_none() && alias.is_none() {
return Err(self.syntax_error_at(self.pos));
}
aliases.push(TraitAlias {
from,
method,
alias,
visibility,
});
} else {
return Err(self.syntax_error_at(self.pos));
}
self.expect_punct(";")?;
}
self.expect_punct("}")?;
Ok(())
}
// ── expressions (precedence climbing) ──────────────────────────────────
fn expression(&mut self) -> Result<Expr, String> {
self.logical_word(0)
}
/// The three WORD logical operators, which sit BELOW assignment in PHP's
/// precedence table — that is the whole reason the language has them
/// alongside `&&`/`||`. `$x = a and b` assigns `a` and then ands the result
/// with `b`; folding them onto `&&`/`||` (which is where they used to be
/// read) made it assign `a and b` instead, and there was no `xor` at all.
///
/// Loosest first: `or` < `xor` < `and`, all left-associative.
fn logical_word(&mut self, min_bp: u8) -> Result<Expr, String> {
let mut lhs = self.assignment()?;
while let Some((word, bp)) = self.peek_logical_word() {
if bp < min_bp {
break;
}
self.pos += 1;
let rhs = self.logical_word(bp + 1)?;
lhs = match word {
"or" => Expr::Binary(BinOp::Or, Box::new(lhs), Box::new(rhs)),
"and" => Expr::Binary(BinOp::And, Box::new(lhs), Box::new(rhs)),
// `xor` has no short circuit — both sides always run — and its
// result is a bool, so it IS `(bool)a !== (bool)b`, evaluated
// left to right. Desugaring keeps it out of the opcode table.
_ => Expr::Binary(
BinOp::StrictNe,
Box::new(Expr::Call("boolval".to_string(), vec![lhs])),
Box::new(Expr::Call("boolval".to_string(), vec![rhs])),
),
};
}
Ok(lhs)
}
/// The word logical operator at the cursor and its binding power.
fn peek_logical_word(&self) -> Option<(&'static str, u8)> {
let Some(Tok::Ident(s)) = self.peek() else {
return None;
};
if s.eq_ignore_ascii_case("or") {
Some(("or", 0))
} else if s.eq_ignore_ascii_case("xor") {
Some(("xor", 2))
} else if s.eq_ignore_ascii_case("and") {
Some(("and", 4))
} else {
None
}
}
fn assignment(&mut self) -> Result<Expr, String> {
// `print` is an operator, not a statement: it binds looser than `=` and
// tighter than `yield`, so it is read here and takes everything to its
// right at assignment precedence (`print $x = 5` prints the assignment).
if self.at_kw("print") {
self.pos += 1;
let operand = self.assignment()?;
return Ok(Expr::Print(Box::new(operand)));
}
// `yield` binds looser than assignment, so it surfaces here (a statement
// `yield $v;` and an assignment RHS `$x = yield $v` both route through
// `assignment()`). `yield from EXPR` delegates; `yield K => V` carries a key;
// a bare `yield` (followed by a terminator) yields null.
if self.at_kw("yield") {
self.pos += 1;
if self.eat_kw("from") {
let src = self.ternary()?;
return Ok(Expr::YieldFrom(Box::new(src)));
}
// A bare `yield` with no operand (next token ends the expression).
if matches!(
self.peek(),
None | Some(Tok::Punct(";"))
| Some(Tok::Punct(")"))
| Some(Tok::Punct("]"))
| Some(Tok::Punct(","))
) {
return Ok(Expr::Yield {
key: None,
value: None,
});
}
let first = self.ternary()?;
if self.eat_punct("=>") {
let val = self.ternary()?;
return Ok(Expr::Yield {
key: Some(Box::new(first)),
value: Some(Box::new(val)),
});
}
return Ok(Expr::Yield {
key: None,
value: Some(Box::new(first)),
});
}
let lhs = self.ternary()?;
// `??=` — the lexer emits `? ? =`; ternary() leaves the `??` unconsumed
// when a `=` follows (see its lookahead). Desugar `$x ??= v` to
// `$x ?? ($x = v)`: the write happens only when the read found null, so a
// readonly or `private(set)` property, `__set` and `offsetSet` are not
// touched for a value that is already there.
if self.at_punct("?") && self.nth_is_punct(1, "?") && self.nth_is_punct(2, "=") {
self.pos += 3;
if matches!(lhs, Expr::Append(_)) {
return Err(self.fatal_at(self.line(), "Cannot use [] for reading".to_string()));
}
let rhs = self.assignment()?;
let (read, target) = self.split_coalesce_target(&lhs);
let write = Expr::Assign(Box::new(target), None, Box::new(rhs));
return Ok(Expr::Coalesce(Box::new(read), Box::new(write)));
}
let op = match self.peek() {
Some(Tok::Punct("=")) => Some(None),
Some(Tok::Punct("+=")) => Some(Some(BinOp::Add)),
Some(Tok::Punct("-=")) => Some(Some(BinOp::Sub)),
Some(Tok::Punct("*=")) => Some(Some(BinOp::Mul)),
Some(Tok::Punct("/=")) => Some(Some(BinOp::Div)),
Some(Tok::Punct("%=")) => Some(Some(BinOp::Mod)),
Some(Tok::Punct(".=")) => Some(Some(BinOp::Concat)),
Some(Tok::Punct("**=")) => Some(Some(BinOp::Pow)),
Some(Tok::Punct("&=")) => Some(Some(BinOp::BitAnd)),
Some(Tok::Punct("|=")) => Some(Some(BinOp::BitOr)),
Some(Tok::Punct("^=")) => Some(Some(BinOp::BitXor)),
Some(Tok::Punct("<<=")) => Some(Some(BinOp::Shl)),
Some(Tok::Punct(">>=")) => Some(Some(BinOp::Shr)),
_ => None,
};
if let Some(compound) = op {
self.pos += 1;
// `$b = &$a` — a reference binding rather than a value copy.
if compound.is_none() && self.at_punct("&") {
self.pos += 1;
if matches!(
self.peek(),
Some(Tok::Int(_) | Tok::Float(_) | Tok::Str(_) | Tok::Interp(_))
) {
return Err(self.syntax_error());
}
let rhs = self.assignment()?;
return Ok(Expr::RefAssign(Box::new(lhs), Box::new(rhs)));
}
let rhs = self.assignment()?; // right-associative
return Ok(Expr::Assign(Box::new(lhs), compound, Box::new(rhs)));
}
Ok(lhs)
}
fn ternary(&mut self) -> Result<Expr, String> {
let cond = self.binary(0)?;
// Null coalesce `a ?? b` (right-associative). The lexer has no `??`
// token, so it surfaces as two consecutive `?` tokens.
// A trailing `=` means this is `??=`, handled by `assignment()`; leave it.
if self.at_punct("?") && self.peek2_is_punct("?") && !self.nth_is_punct(2, "=") {
self.pos += 2;
let rhs = self.ternary()?;
return Ok(Expr::Coalesce(Box::new(cond), Box::new(rhs)));
}
// A `?` NOT followed by another `?` is the real ternary; `? ? …` here is
// a `??=` left for `assignment()` (the coalesce case was handled above).
if self.at_punct("?") && !self.peek2_is_punct("?") {
self.pos += 1;
// Short ternary / elvis `a ?: b`.
if self.eat_punct(":") {
let els = self.assignment()?;
return Ok(Expr::Elvis(Box::new(cond), Box::new(els)));
}
let then = self.expression()?;
self.expect_punct(":")?;
let els = self.assignment()?;
return Ok(Expr::Ternary(Box::new(cond), Box::new(then), Box::new(els)));
}
Ok(cond)
}
/// Precedence-climbing binary parser. Higher `min_bp` binds tighter.
fn binary(&mut self, min_bp: u8) -> Result<Expr, String> {
let mut lhs = self.unary()?;
loop {
// PHP 8.5 pipe: tighter than the relational operators, looser than
// `.`, left-associative. `a |> f` calls the callable `f` with `a`.
if self.at_punct("|>") {
if PIPE_BP.0 < min_bp {
break;
}
self.pos += 1;
let arrow = self.at_kw("fn")
|| (self.at_kw("static")
&& matches!(
self.toks.get(self.pos + 1).map(|s| &s.tok),
Some(Tok::Ident(k)) if k.eq_ignore_ascii_case("fn")
));
if arrow {
return Err(self.fatal_at(
self.line(),
"Arrow functions on the right hand side of |> must be parenthesized"
.to_string(),
));
}
let callee = self.binary(PIPE_BP.1)?;
lhs = Expr::CallValue(Box::new(callee), vec![lhs]);
continue;
}
let Some((op, lbp, rbp)) = self.peek_binop() else {
break;
};
if lbp < min_bp {
break;
}
self.pos += 1;
let rhs = self.binary(rbp)?;
lhs = Expr::Binary(op, Box::new(lhs), Box::new(rhs));
}
Ok(lhs)
}
/// The binary operator at the cursor, plus its left/right binding powers.
fn peek_binop(&self) -> Option<(BinOp, u8, u8)> {
let op = match self.peek() {
Some(Tok::Punct("||")) => BinOp::Or,
Some(Tok::Punct("&&")) => BinOp::And,
Some(Tok::Punct("==")) => BinOp::LooseEq,
Some(Tok::Punct("!=")) | Some(Tok::Punct("<>")) => BinOp::LooseNe,
Some(Tok::Punct("===")) => BinOp::StrictEq,
Some(Tok::Punct("!==")) => BinOp::StrictNe,
Some(Tok::Punct("<=>")) => BinOp::Spaceship,
Some(Tok::Punct("<")) => BinOp::Lt,
Some(Tok::Punct(">")) => BinOp::Gt,
Some(Tok::Punct("<=")) => BinOp::Le,
Some(Tok::Punct(">=")) => BinOp::Ge,
Some(Tok::Punct("<<")) => BinOp::Shl,
Some(Tok::Punct(">>")) => BinOp::Shr,
Some(Tok::Punct("&")) => BinOp::BitAnd,
Some(Tok::Punct("|")) => BinOp::BitOr,
Some(Tok::Punct("^")) => BinOp::BitXor,
Some(Tok::Punct("+")) => BinOp::Add,
Some(Tok::Punct("-")) => BinOp::Sub,
Some(Tok::Punct(".")) => BinOp::Concat,
Some(Tok::Punct("*")) => BinOp::Mul,
Some(Tok::Punct("/")) => BinOp::Div,
Some(Tok::Punct("%")) => BinOp::Mod,
// `**` is NOT handled here — it binds tighter than unary minus, so it
// is parsed in `power()` below the unary level, not as an infix op.
_ => return None,
};
// (left bp, right bp), following PHP operator precedence (loosest first):
// || < && < | < ^ < & < equality < relational < `.` < shift < additive <
// multiplicative. Right bp < left bp ⇒ right-associative. Since PHP 8 `.`
// binds looser than `+`/`-` and `<<`/`>>` (zend_language_parser.y), so
// `"a" . 1 + 2` is `"a" . 3`.
let (l, r) = match op {
BinOp::Or => (1, 2),
BinOp::And => (3, 4),
BinOp::BitOr => (5, 6),
BinOp::BitXor => (7, 8),
BinOp::BitAnd => (9, 10),
BinOp::LooseEq
| BinOp::LooseNe
| BinOp::StrictEq
| BinOp::StrictNe
| BinOp::Spaceship => (11, 12),
BinOp::Lt | BinOp::Gt | BinOp::Le | BinOp::Ge => (13, 14),
BinOp::Concat => (17, 18),
BinOp::Shl | BinOp::Shr => (19, 20),
BinOp::Add | BinOp::Sub => (21, 22),
BinOp::Mul | BinOp::Div | BinOp::Mod => (23, 24),
BinOp::Pow => (26, 25),
};
Some((op, l, r))
}
fn unary(&mut self) -> Result<Expr, String> {
// `(void)` is one token to the reference and no expression begins with it.
if self.at_void_cast() {
return Err(self.syntax_error());
}
// `include`/`require` and their `_once` forms are prefix operators that
// take everything to their right at assignment precedence, so
// `include "a" . ".php"` includes `a.php` — and, being expressions, they
// may stand wherever an operand may, `@include` included.
for (kw, kind) in [
("include", IncludeKind::Include),
("include_once", IncludeKind::IncludeOnce),
("require", IncludeKind::Require),
("require_once", IncludeKind::RequireOnce),
] {
if self.at_kw(kw) {
self.pos += 1;
let operand = self.assignment()?;
return Ok(Expr::Include(kind, Box::new(operand)));
}
}
// Type cast: `(int)`, `(float)`, `(string)`, `(bool)`, … — three tokens
// `( ident )` where the identifier names a cast target. Desugars to the
// matching conversion call so no new opcode is needed.
if self.at_punct("(") {
if let Some(Tok::Ident(t)) = self.toks.get(self.pos + 1).map(|s| &s.tok) {
if matches!(
self.toks.get(self.pos + 2).map(|s| &s.tok),
Some(Tok::Punct(")"))
) {
if let Some(fname) = cast_fn(t) {
self.pos += 3; // consume `( ident )`
let operand = self.unary()?;
return Ok(Expr::Call(fname.to_string(), vec![operand]));
}
}
}
}
// `@expr` — the error-suppression operator. Dynamic: it silences every
// diagnostic raised while the operand runs, including the ones raised
// from inside the library functions it calls, which have no opcode of
// their own to quieten.
if self.eat_punct("@") {
return Ok(Expr::Suppress(Box::new(self.unary()?)));
}
if self.eat_punct("!") {
return Ok(Expr::Unary(UnOp::Not, Box::new(self.unary()?)));
}
if self.eat_punct("~") {
return Ok(Expr::Unary(UnOp::BitNot, Box::new(self.unary()?)));
}
if self.eat_punct("-") {
return Ok(Expr::Unary(UnOp::Neg, Box::new(self.unary()?)));
}
if self.eat_punct("+") {
return Ok(Expr::Unary(UnOp::Pos, Box::new(self.unary()?)));
}
if self.eat_punct("++") {
return self.incdec_prefix(true);
}
if self.eat_punct("--") {
return self.incdec_prefix(false);
}
// `clone $o` binds tighter than every operator, `**` included, so its
// operand is a postfix expression: `clone $a->b` clones the property.
// It is NOT a `return` — `clone $a instanceof C` tests the clone, so
// the `instanceof` below still has to see it.
let e = if self.eat_kw("clone") {
match self.clone_call()? {
Some(call) => call,
None => Expr::Clone(Box::new(self.postfix()?)),
}
} else {
self.power()?
};
// `$x instanceof ClassName` (bareword class, optionally `\`-qualified).
if self.eat_kw("instanceof") {
if let Some(class) = self.new_dynamic_class()? {
return Ok(Expr::InstanceOfDyn(Box::new(e), Box::new(class)));
}
let cls = self.expect_type_name()?;
return Ok(Expr::InstanceOf(Box::new(e), cls));
}
Ok(e)
}
/// The PHP 8.5 function form of `clone`, after the keyword: `clone($o, [...])`,
/// `clone($o,)` or `clone(object: $o, withProperties: [...])`. It is the
/// function form only when the parenthesis holds a top-level comma or a named
/// argument — `clone($a)->m()` still clones the whole `($a)->m()` operand.
/// `None` leaves the cursor where it was.
fn clone_call(&mut self) -> Result<Option<Expr>, String> {
if !self.at_punct("(") {
return Ok(None);
}
let mut depth = 0usize;
let mut function_form = false;
let mut i = self.pos;
while let Some(sp) = self.toks.get(i) {
match &sp.tok {
Tok::Punct("(" | "[" | "{") => depth += 1,
Tok::Punct(")" | "]" | "}") => {
depth -= 1;
if depth == 0 {
break;
}
}
Tok::Punct(",") if depth == 1 => function_form = true,
Tok::Punct("...") if depth == 1 && i == self.pos + 1 => function_form = true,
Tok::Ident(_)
if depth == 1
&& i == self.pos + 1
&& matches!(
self.toks.get(i + 1).map(|s| &s.tok),
Some(Tok::Punct(":"))
) =>
{
function_form = true
}
_ => {}
}
i += 1;
}
if self.nth_is_punct(1, ")") {
function_form = true;
}
if !function_form {
return Ok(None);
}
self.pos += 1; // (
let args = self.arg_list()?;
let fail = |class: &str, msg: String| {
Expr::Throw(Box::new(Expr::New(class.to_string(), vec![Expr::Str(msg)])))
};
let mut slots: [Option<Expr>; 2] = [None, None];
let mut extra: Vec<Expr> = Vec::new();
let mut positional = 0usize;
for arg in args {
let slot = match arg {
Expr::NamedArg(name, value) => match name.as_str() {
"object" => (0, *value),
"withProperties" => (1, *value),
other => {
return Ok(Some(fail(
"Error",
format!("Unknown named parameter ${other}"),
)))
}
},
Expr::Spread(_) => {
return Err(self.bare_fatal_at(
self.line(),
"Argument unpacking in clone() is not supported".to_string(),
))
}
value => {
positional += 1;
if positional > 2 {
extra.push(value);
continue;
}
(positional - 1, value)
}
};
slots[slot.0] = Some(slot.1);
}
let [object, with] = slots;
if object.is_none() && with.is_some() {
return Ok(Some(fail(
"ArgumentCountError",
"clone(): Argument #1 ($object) not passed".to_string(),
)));
}
// A single argument is a plain clone; every other count is checked at
// run time, where the failure carries a `clone(...)` frame.
let mut passed: Vec<Expr> = object.into_iter().chain(with).chain(extra).collect();
if passed.len() == 1 {
return Ok(Some(Expr::Clone(Box::new(passed.remove(0)))));
}
Ok(Some(Expr::Call("__clone_with".to_string(), passed)))
}
/// A prefix `++`/`--`, whose operand PHP's grammar requires to be a
/// *variable* — so a non-variable operand is a syntax error at parse time,
/// not a failure further down the pipeline.
///
/// Where it is caught depends on the operand, and this follows the reference:
/// a bare number can never begin a variable, so the number itself is the
/// unexpected token; anything dereferencable (a string, an array literal, a
/// parenthesised expression) parses first and only then fails, at the token
/// standing where a `->` or `[` would have had to be.
fn incdec_prefix(&mut self, inc: bool) -> Result<Expr, String> {
if matches!(self.peek(), Some(Tok::Int(_) | Tok::Float(_))) {
return Err(self.syntax_error());
}
let target = self.unary()?;
if !is_incdec_target(&target) {
return Err(self.syntax_error());
}
Ok(Expr::IncDec {
target: Box::new(target),
inc,
prefix: true,
})
}
/// The exponent level, sitting *below* unary so `-2 ** 2` parses as
/// `-(2 ** 2)` (PHP binds `**` tighter than unary minus). Right-associative,
/// and its right operand is a full unary expression so `2 ** -1` works.
fn power(&mut self) -> Result<Expr, String> {
let base = self.postfix()?;
if self.eat_punct("**") {
let exp = self.unary()?;
return Ok(Expr::Binary(BinOp::Pow, Box::new(base), Box::new(exp)));
}
Ok(base)
}
fn postfix(&mut self) -> Result<Expr, String> {
let mut e = self.primary()?;
// A number literal is not dereferenceable (`1[0]`, `1.5->p`), so nothing
// may continue it; the token that follows is the caller's to refuse.
if matches!(
self.toks.get(self.pos.wrapping_sub(1)).map(|s| &s.tok),
Some(Tok::Int(_) | Tok::Float(_))
) && matches!(e, Expr::Int(_) | Expr::Float(_))
{
return Ok(e);
}
loop {
if self.eat_punct("[") {
// `$a[]` (append) is only meaningful as an assignment target.
if self.eat_punct("]") {
e = Expr::Append(Box::new(e));
} else {
let idx = self.expression()?;
self.expect_closer("]")?;
e = Expr::Index(Box::new(e), Box::new(idx));
}
} else if self.eat_punct("->") {
// Instance member: `$o->prop` or `$o->method(args)`.
let member = self.object_member()?;
if self.eat_punct("(") {
let name = match &member {
Member::Name(n) => Expr::Str(n.clone()),
Member::Dyn(d) => d.as_ref().clone(),
};
if let Some(fcc) = self.try_fcc(
Expr::Array(
vec![ArrayElem::new(None, e.clone()), ArrayElem::new(None, name)],
ArraySyntax::Short,
),
true,
)? {
e = fcc;
} else {
e = Expr::MethodCall(Box::new(e), member, self.arg_list()?);
}
} else {
e = Expr::PropGet(Box::new(e), member);
}
} else if self.eat_punct("?->") {
// Nullsafe member: `$o?->prop` or `$o?->method(args)`.
let member = self.object_member()?;
if self.eat_punct("(") {
e = Expr::NullsafeMethodCall(Box::new(e), member, self.arg_list()?);
} else {
e = Expr::NullsafePropGet(Box::new(e), member);
}
} else if self.eat_punct("::") {
// Static / scope-resolution access. The left is either a class
// name known now — a bareword, which surfaces here as
// `Expr::ConstFetch` (or a string literal, which PHP resolves
// the same way) — or a dereferenceable expression whose value
// names the class at run time (`$cls::K`, `$obj::m()`).
let class = match e {
Expr::ConstFetch(name) | Expr::Str(name) => ClassRef::Name(name),
other if is_dyn_class_operand(&other) => ClassRef::Expr(Box::new(other)),
_ => {
return Err(format!(
"expected a class name before '::' (line {})",
self.line()
))
}
};
// `Class::$prop` — a static property (the `::` is followed by a
// `$variable`, not a bareword constant/method name).
if let Some(Tok::Var(_) | Tok::Punct("$")) = self.peek() {
let prop = self.static_prop_name()?;
if let (Member::Name(prop), true) = (&prop, self.at_punct("(")) {
self.pos += 1;
// `Class::$method(…)` — a static method call whose name
// a variable holds, not a call of the property's value.
// It runs as the `[class, $method]` callable.
let class_value = match class {
ClassRef::Name(n) if is_class_relative_name(&n) => {
Expr::StaticGet(ClassRef::Name(n), "class".to_string())
}
ClassRef::Name(n) => Expr::Str(n),
ClassRef::Expr(ce) => *ce,
};
let callee = Expr::Array(
vec![
ArrayElem::new(None, class_value),
ArrayElem::new(None, Expr::Var(prop.clone())),
],
ArraySyntax::Short,
);
e = Expr::CallValue(Box::new(callee), self.arg_list()?);
continue;
}
e = Expr::StaticProp(class, prop);
} else if self.eat_punct("{") {
// PHP 8.3 dynamic class constant fetch, `Class::{$expr}`:
// the constant's name is computed, which is exactly what
// `constant("Class::NAME")` resolves.
let name = self.expression()?;
self.expect_punct("}")?;
let class_name = match class {
ClassRef::Name(c) => Expr::Str(c),
ClassRef::Expr(ce) => Expr::Ternary(
Box::new(Expr::Call("is_object".to_string(), vec![(*ce).clone()])),
Box::new(Expr::Call("get_class".to_string(), vec![(*ce).clone()])),
ce,
),
};
let qualified = Expr::Binary(
BinOp::Concat,
Box::new(Expr::Binary(
BinOp::Concat,
Box::new(class_name),
Box::new(Expr::Str("::".to_string())),
)),
Box::new(name),
);
e = Expr::Call("constant".to_string(), vec![qualified]);
} else {
let member = self.member_name()?;
if self.eat_punct("(") {
// The first-class-callable form needs the callable as a
// *value*: `"C::m"` when the class is known, and the
// `[class, method]` array form when it is not — which is
// what `call_user_func_array` accepts for both a
// class-name string and an object.
let callable = match &class {
ClassRef::Name(c) => Expr::Str(format!("{c}::{member}")),
ClassRef::Expr(ce) => Expr::Array(
vec![
ArrayElem::new(None, (**ce).clone()),
ArrayElem::new(None, Expr::Str(member.clone())),
],
ArraySyntax::Short,
),
};
if let Some(fcc) = self.try_fcc(callable, false)? {
e = fcc;
} else {
e = Expr::StaticCall(class, member, self.arg_list()?);
}
} else {
e = Expr::StaticGet(class, member);
}
}
} else if self.at_punct("(") {
// A `( args )` applied to any primary value is a dynamic call: a
// closure held in `$f`, or an immediately-invoked `foo()(…)` /
// `(expr)(…)`. A bareword `name(` is already consumed as
// `Expr::Call` in `primary`, so this only fires on a value callee.
self.pos += 1;
if let Some(fcc) = self.try_fcc(e.clone(), false)? {
e = fcc;
} else {
let args = self.arg_list()?;
e = Expr::CallValue(Box::new(e), args);
}
} else if self.at_punct("++") || self.at_punct("--") {
// Postfix `++`/`--` also takes a *variable*. Unlike the prefix
// form the operand is already parsed, so the operator itself is
// the token PHP reports as unexpected.
if !is_incdec_target(&e) {
return Err(self.syntax_error());
}
let inc = self.at_punct("++");
self.pos += 1;
e = Expr::IncDec {
target: Box::new(e),
inc,
prefix: false,
};
} else {
break;
}
}
Ok(e)
}
/// The class operand of `new` when it is not a bareword name — the
/// grammar's `class_name_reference` minus `class_name`, or `None` when a
/// bareword follows (and nothing was consumed).
///
/// `(expr)` is any expression. Otherwise it is `new_variable`: a simple
/// variable (`$c`, `$$c`, `${expr}`) or `Class::$prop`, extended by `[k]`,
/// `->p`, `?->p` and `::$p` but never by a call — the `(` that follows is
/// the constructor's argument list, so `new $a->b['k']()` instantiates the
/// class named by `$a->b['k']`.
fn new_dynamic_class(&mut self) -> Result<Option<Expr>, String> {
let mut e = match self.peek() {
Some(Tok::Punct("(")) => {
self.pos += 1;
let e = self.expression()?;
self.expect_punct(")")?;
return Ok(Some(e));
}
Some(Tok::Var(_)) | Some(Tok::Punct("$")) => self.primary()?,
Some(Tok::Ident(name))
if matches!(
self.toks.get(self.pos + 1).map(|s| &s.tok),
Some(Tok::Punct("::"))
) && matches!(
self.toks.get(self.pos + 2).map(|s| &s.tok),
Some(Tok::Var(_))
) =>
{
let class = ClassRef::Name(self.resolve_class(&RawName {
text: name.clone(),
kind: NameKind::Unqualified,
}));
self.pos += 2;
Expr::StaticProp(class, Member::Name(self.expect_var()?))
}
_ => return Ok(None),
};
loop {
if self.eat_punct("[") {
let idx = self.expression()?;
self.expect_punct("]")?;
e = Expr::Index(Box::new(e), Box::new(idx));
} else if self.eat_punct("->") {
e = Expr::PropGet(Box::new(e), self.object_member()?);
} else if self.eat_punct("?->") {
e = Expr::NullsafePropGet(Box::new(e), self.object_member()?);
} else if self.at_punct("::")
&& matches!(
self.toks.get(self.pos + 1).map(|s| &s.tok),
Some(Tok::Var(_))
)
{
self.pos += 1;
e = Expr::StaticProp(
ClassRef::Expr(Box::new(e)),
Member::Name(self.expect_var()?),
);
} else {
return Ok(Some(e));
}
}
}
fn primary(&mut self) -> Result<Expr, String> {
// A leading `\` anchors a fully qualified name, and `namespace\` one
// relative to the current namespace. Either is consumed here and
// remembered, since how the name resolves depends on it.
let mut written = NameKind::Unqualified;
if self.at_name_anchor() {
self.pos += 1;
written = NameKind::FullyQualified;
} else if self.at_relative_name() {
self.pos += 2;
written = NameKind::Relative;
}
match self.next() {
Some(Tok::Int(n)) => Ok(Expr::Int(n)),
Some(Tok::Float(f)) => Ok(Expr::Float(f)),
Some(Tok::Str(s)) => Ok(Expr::Str(s)),
Some(Tok::Interp(parts)) => Ok(Expr::Interp(resolve_interp_parts(
parts,
&self.magic.namespace,
&self.imports,
)?)),
Some(Tok::Var(n)) => Ok(Expr::Var(n)),
// `$$x`, `$$$x`, `${expr}` — the sigil takes either a braced
// expression or another variable, and nests, so `$$$x` is two
// lookups.
Some(Tok::Punct("$")) => {
let inner = if self.eat_punct("{") {
let e = self.expression()?;
self.expect_punct("}")?;
e
} else {
self.primary()?
};
Ok(Expr::VarVar(Box::new(inner)))
}
Some(Tok::Punct("(")) => {
let e = self.expression()?;
self.expect_punct(")")?;
Ok(e)
}
Some(Tok::Punct("[")) => self.array_literal("]", ArraySyntax::Short),
Some(Tok::Ident(kw)) if kw.eq_ignore_ascii_case("true") => Ok(Expr::Bool(true)),
Some(Tok::Ident(kw)) if kw.eq_ignore_ascii_case("false") => Ok(Expr::Bool(false)),
Some(Tok::Ident(kw)) if kw.eq_ignore_ascii_case("null") => Ok(Expr::Null),
Some(Tok::Ident(kw)) if kw.eq_ignore_ascii_case("array") => {
self.expect_closer("(")?;
self.array_literal(")", ArraySyntax::Long)
}
// `list($a, $b)` / `list('k' => $v)` — a destructuring language
// construct, not a function call. It is sugar for the `[...]` short
// form, so both lower to the same `Expr::Array` and share the
// compiler's assignment-target destructuring path. Only intercepted
// when followed by `(`, so a bareword `list` still parses as a name.
Some(Tok::Ident(kw)) if kw.eq_ignore_ascii_case("list") => {
self.expect_closer("(")?;
let list = self.array_literal(")", ArraySyntax::List)?;
// `list(...)` is only a destructuring target: unless it is a
// nested element (`,` / `)` / `]` follows) it must meet its `=`.
if !(self.at_punct("=")
|| self.at_punct(",")
|| self.at_punct(")")
|| self.at_punct("]"))
{
return Err(self.syntax_error_expecting("\"=\""));
}
Ok(list)
}
// `exit` / `die` — the one construct whose parentheses AND argument
// are both optional, so `exit;` is a complete expression. Without
// this arm it falls through to the bareword path and reads as an
// undefined constant, and `exit(1)` as an undefined function.
// `die` folds onto `exit`, which is why PHP's own diagnostics for a
// bad `die()` argument all quote `exit()`.
Some(Tok::Ident(kw))
if kw.eq_ignore_ascii_case("exit") || kw.eq_ignore_ascii_case("die") =>
{
let args = if self.eat_punct("(") {
self.arg_list()?
} else {
Vec::new()
};
Ok(Expr::Call("exit".to_string(), args))
}
// `throw e` as a PHP 8 expression, so `$x ?? throw …` and
// `cond ? throw … : …` work; a `throw e;` statement reaches here too.
Some(Tok::Ident(kw)) if kw.eq_ignore_ascii_case("throw") => {
let e = self.expression()?;
Ok(Expr::Throw(Box::new(e)))
}
// `new Class(args)` — the class name is a bareword (or `self`/`parent`/
// `static`); parentheses are optional when there are no arguments.
Some(Tok::Ident(kw)) if kw.eq_ignore_ascii_case("new") => {
// `new class …` declares the class inline. Its arguments come
// BEFORE the `extends`/`implements` clauses, which is the one
// place the grammar differs from a named declaration.
if self.at_kw("class") {
let line = self.line();
self.pos += 1;
let args = if self.eat_punct("(") {
self.arg_list()?
} else {
Vec::new()
};
// The generated `class@anonymous <file>:<line>$<n>` name is
// the compiler's to mint, so `__CLASS__` here waits for the
// running frame to report it.
let dynamic = MagicName::Dynamic(MagicConst::Class {
prefix: String::new(),
suffix: String::new(),
});
let entered = MagicCtx {
class: dynamic.clone(),
owner: dynamic,
trait_name: String::new(),
..self.magic.clone()
};
let saved = std::mem::replace(&mut self.magic, entered);
let decl =
self.class_rest("class@anonymous".to_string(), ClassKind::default(), None);
self.magic = saved;
let mut decl = decl?;
decl.lines.0 = line;
return Ok(Expr::NewAnon {
decl: Box::new(decl),
args,
line,
});
}
let written = self.at_name_anchor() || self.at_relative_name();
if !written {
if let Some(class) = self.new_dynamic_class()? {
let args = if self.eat_punct("(") {
self.arg_list()?
} else {
Vec::new()
};
return Ok(Expr::NewDyn(Box::new(class), args));
}
}
if !written && !matches!(self.peek(), Some(Tok::Ident(_))) {
self.pos += 1;
return Err(self.syntax_error_expecting_at(self.pos - 1, Some("\"class\"")));
}
let raw = self.raw_name()?;
let class = self.resolve_class(&raw);
let args = if self.eat_punct("(") {
self.arg_list()?
} else {
Vec::new()
};
Ok(Expr::New(class, args))
}
// An attributed closure — `#[Attr] fn () => …`, `#[Attr] static function () {}`.
Some(Tok::Punct("#[")) => {
self.pos -= 1;
self.attributes()?;
let attrs = std::mem::take(&mut self.last_attrs);
let mut closure = self.primary()?;
if let Expr::Closure { attrs: a, .. } | Expr::ArrowFn { attrs: a, .. } =
&mut closure
{
*a = attrs;
}
Ok(closure)
}
// `match (subj) { ... }` — only when followed by `(`, so a plain
// bareword `match` still parses as a name.
Some(Tok::Ident(kw)) if kw.eq_ignore_ascii_case("match") => self.match_expr(),
// `static function (…)` / `static fn (…)` — a closure that is NOT
// bound to `$this`. The keyword only affects the binding, so the
// closure itself is parsed by the arms below.
Some(Tok::Ident(kw))
if kw.eq_ignore_ascii_case("static")
&& matches!(self.peek(), Some(Tok::Ident(k))
if k.eq_ignore_ascii_case("fn") || k.eq_ignore_ascii_case("function")) =>
{
let mut closure = self.primary()?;
if let Expr::Closure { is_static, .. } | Expr::ArrowFn { is_static, .. } =
&mut closure
{
*is_static = true;
}
Ok(closure)
}
// Any other `static` must be the `static::` scope: a name cannot follow.
Some(Tok::Ident(kw)) if kw.eq_ignore_ascii_case("static") && !self.at_punct("::") => {
Err(self.syntax_error_expecting("\"::\""))
}
// An anonymous function `function (params) [use (vars)] { body }`.
// (A *named* function is a statement, caught in `statement()`; only
// the expression form — `function (` — reaches here.)
Some(Tok::Ident(kw)) if kw.eq_ignore_ascii_case("function") && self.at_punct("(") => {
let line = self.line_at(self.pos - 1);
let doc = self.take_doc(self.pos - 1);
let saved = self.enter_closure(line);
let params = self.param_list()?;
let mut uses = Vec::new();
if self.eat_kw("use") {
self.expect_closer("(")?;
if !self.at_punct(")") {
loop {
// `use (&$v)` captures the enclosing variable itself
// rather than its value at creation time.
let by_ref = self.eat_punct("&");
if !matches!(self.peek(), Some(Tok::Var(_))) {
// The reference's list is a quirk of its tables: the
// `&` appears once as a word and once as a token.
let listing = if uses.is_empty() {
"variable or \"&\" or token \"&\""
} else {
"\")\""
};
return Err(self.syntax_error_expecting(listing));
}
let name = self.expect_var()?;
uses.push(Capture {
name,
by_ref,
implicit: false,
});
if !self.eat_punct(",") {
break;
}
}
}
self.expect_closer(")")?;
}
let ret = self.return_type()?;
let body = self.block()?;
self.magic = saved;
Ok(Expr::Closure {
params,
uses,
body,
ret,
is_static: false,
line,
end_line: self.line_at(self.pos - 1),
doc,
attrs: Vec::new(),
})
}
// An arrow function `fn (params) => expr` — implicit by-value capture.
Some(Tok::Ident(kw)) if kw.eq_ignore_ascii_case("fn") && self.at_punct("(") => {
let line = self.line_at(self.pos - 1);
let doc = self.take_doc(self.pos - 1);
let saved = self.enter_closure(line);
let params = self.param_list()?;
let ret = self.return_type()?;
self.expect_closer("=>")?;
let body = self.expression()?;
self.magic = saved;
Ok(Expr::ArrowFn {
params,
body: Box::new(body),
ret,
is_static: false,
line,
end_line: self.line_at(self.pos - 1),
doc,
attrs: Vec::new(),
})
}
// `function` / `fn` is reserved: anything but `(` after it is a
// syntax error whose only way forward is the parameter list.
Some(Tok::Ident(kw))
if kw.eq_ignore_ascii_case("function") || kw.eq_ignore_ascii_case("fn") =>
{
Err(self.syntax_error_expecting("\"(\""))
}
// A magic constant. PHP resolves these where they are WRITTEN, so the
// answer comes from the parse context rather than from any table —
// which is also why `__CLASS__` in an inherited method names the class
// that declared it and not the one the call arrived through.
Some(Tok::Ident(kw)) if magic_const_spelling(&kw).is_some() => {
let name = magic_const_spelling(&kw).expect("guarded by the match arm above");
Ok(self.magic_const(name))
}
// Any other `namespace` in an expression is the keyword, which no
// expression can begin with.
Some(Tok::Ident(kw)) if kw.eq_ignore_ascii_case("namespace") => {
Err(self.syntax_error_at(self.pos - 1))
}
Some(Tok::Ident(name)) => {
// A `\`-qualified name — `Foo\BAR`, `A\B\C`. Any LEADING `\` (or
// `namespace\`) was already eaten at the top of `primary`, and
// `written` says which.
let mut qualified = name.clone();
self.raw_name_rest(&mut qualified);
let kind = match written {
NameKind::Unqualified if qualified.contains('\\') => NameKind::Qualified,
k => k,
};
let raw = RawName {
text: qualified,
kind,
};
// A name the language reads as a construct (`isset`, `eval`, …)
// is one only when written bare.
let construct = kind == NameKind::Unqualified;
// `Name::…` — the name is a class, and resolves like one; the
// postfix `::` arm turns this into the class reference.
if self.at_punct("::") {
return Ok(Expr::ConstFetch(self.resolve_class(&raw)));
}
// A bareword followed by `(` is a function call.
if self.eat_punct("(") {
let fname = self.resolve_function(&raw);
let name = if construct { name } else { String::new() };
// `name(...)` — first-class callable syntax → a `Closure`.
if let Some(fcc) = self.try_fcc(Expr::Str(fname.clone()), false)? {
return Ok(fcc);
}
let args = {
// `unset` lists the tokens that could continue its operand,
// `empty` is `empty ( expr )` with nothing reduced before the
// `)`, so the reference lists nothing for either's neighbours.
let listing = if name.eq_ignore_ascii_case("unset") {
Some("\"->\" or \"?->\" or \"[\"")
} else if name.eq_ignore_ascii_case("empty")
|| name.eq_ignore_ascii_case("eval")
{
None
} else {
Some("\")\"")
};
if name.eq_ignore_ascii_case("unset") {
self.unset_arg_list()?
} else {
self.arg_list_listing(listing)?
}
};
// `eval()` is a construct too: it runs in the caller's scope.
if name.eq_ignore_ascii_case("eval") && args.len() == 1 {
return Ok(Expr::Eval(Box::new(args.into_iter().next().unwrap())));
}
// `isset()`/`empty()` are language constructs, not functions:
// they must not error on an undefined variable/key. phplang
// returns `null` for a missing var/index silently, so both
// desugar to plain operators over existing ops.
if name.eq_ignore_ascii_case("empty") && args.len() == 1 {
// empty($x) ≡ !$x over an isset-gated read of $x.
return Ok(Expr::Unary(
UnOp::Not,
Box::new(Expr::EmptyOf(Box::new(args.into_iter().next().unwrap()))),
));
}
if name.eq_ignore_ascii_case("isset") && !args.is_empty() {
// `isset()` reads a VARIABLE and nothing else. A call, a
// `new`, a constant, a literal or any arithmetic is a
// COMPILE-time fatal in the reference, raised before the
// program runs — so `isset(f())` prints nothing at all,
// where evaluating it would have printed whatever `f`
// echoes. Only the outermost node decides: `isset(f()->p)`
// is a property fetch and therefore legal.
if let Some(bad) = args.iter().find(|a| !is_isset_operand(a)) {
let _ = bad;
return Err(self.fatal_at(
self.line(),
"Cannot use isset() on the result of an expression \
(you can use \"null !== expression\" instead)"
.to_string(),
));
}
// isset($a, $b, …) ≡ isset($a) && isset($b) && …
let mut it = args.into_iter();
let mut expr = Expr::IssetOf(Box::new(it.next().unwrap()));
for a in it {
expr = Expr::Binary(
BinOp::And,
Box::new(expr),
Box::new(Expr::IssetOf(Box::new(a))),
);
}
return Ok(expr);
}
// `unset($a, $b[$k], …)` — a construct, not a function call.
if name.eq_ignore_ascii_case("unset") {
return Ok(Expr::Unset(args));
}
Ok(Expr::Call(fname, args))
} else {
// `isset`, `unset`, `empty` and `eval` are constructs that
// cannot stand without their parenthesised operand.
if construct
&& ["isset", "unset", "empty", "eval"]
.iter()
.any(|k| name.eq_ignore_ascii_case(k))
{
return Err(self.syntax_error_expecting("\"(\""));
}
// A constant reference, resolved against the constant table
// at run time. An undefined name throws
// `Error: Undefined constant "<name>"` — PHP 8 behaviour;
// the PHP 7 fallback to the bare name as a string is gone.
//
// The QUALIFIED name is what is looked up, so `Foo\BAR`
// reaches that same throw naming `Foo\BAR`, rather than
// quietly resolving some other constant.
Ok(Expr::ConstFetch(self.resolve_constant(&raw)))
}
}
_ => Err(self.syntax_error_at(self.pos - 1)),
}
}
/// Parse array elements up to `close` (already past the opener).
fn array_literal(&mut self, close: &str, syntax: ArraySyntax) -> Result<Expr, String> {
let mut elems = Vec::new();
while !self.at_punct(close) && !self.at_end() {
// An empty slot — `[, $b]` / `list(, $b)` — is a skipped element in a
// destructuring target. It still consumes a positional index, so it is
// recorded as an `Expr::Hole` element (one the compiler skips when this
// array is used as an assignment LHS, and refuses anywhere else).
if self.at_punct(",") {
self.next();
elems.push(ArrayElem::new(None, Expr::Hole));
continue;
}
// A leading `&` marks a by-reference element: `[&$x, $y] = $a` binds
// `$x` as an alias of `$a[0]`. It may also precede the VALUE of a
// keyed entry (`['k' => &$v]`), which is why it is read in both
// places rather than only at the head of the element.
// `[...$a]` — array unpacking (7.4; string keys 8.1). It carries no
// key of its own, so it rides as a `Spread` VALUE and the compiler
// marks it with `host::SPREAD_KEY` where a key would go.
if self.eat_punct("...") {
let inner = self.expression()?;
elems.push(ArrayElem::new(None, Expr::Spread(Box::new(inner))));
if !self.eat_punct(",") {
break;
}
continue;
}
let by_ref = self.eat_punct("&");
let first = self.expression()?;
if !by_ref && self.eat_punct("=>") {
let val_by_ref = self.eat_punct("&");
let val = self.expression()?;
elems.push(ArrayElem {
key: Some(first),
value: val,
by_ref: val_by_ref,
});
} else {
elems.push(ArrayElem {
key: None,
value: first,
by_ref,
});
}
if !self.eat_punct(",") {
break;
}
}
self.expect_closer(close)?;
Ok(Expr::Array(elems, syntax))
}
/// Parse a `match (subj) { A, B => R, default => D }` expression. The `match`
/// keyword has already been consumed by `primary`.
fn match_expr(&mut self) -> Result<Expr, String> {
self.expect_closer("(")?;
let subj = self.expression()?;
self.expect_punct(")")?;
self.expect_closer("{")?;
let mut arms = Vec::new();
while !self.at_punct("}") && !self.at_end() {
let conds = if self.eat_kw("default") {
None
} else {
let mut cs = vec![self.expression()?];
while self.eat_punct(",") {
// Tolerate a trailing comma before `=>`.
if self.at_punct("=>") {
break;
}
cs.push(self.expression()?);
}
Some(cs)
};
self.expect_closer("=>")?;
let body = self.expression()?;
arms.push(MatchArm {
conds,
body: Box::new(body),
});
if !self.eat_punct(",") {
break;
}
}
self.expect_closer("}")?;
Ok(Expr::Match {
subj: Box::new(subj),
arms,
})
}
}
/// The type name the reference prints for a literal initialiser, or `None` when
/// the expression is not a plain literal and so cannot be judged at compile time.
fn literal_given_type(e: &Expr) -> Option<&'static str> {
match e {
Expr::Null => Some("null"),
Expr::Bool(_) => Some("bool"),
Expr::Int(_) => Some("int"),
Expr::Float(_) => Some("float"),
Expr::Str(_) => Some("string"),
Expr::Interp(parts) if parts.iter().all(|p| matches!(p, InterpPart::Lit(_))) => {
Some("string")
}
Expr::Binary(BinOp::Concat, a, b)
if literal_given_type(a).is_some() && literal_given_type(b).is_some() =>
{
Some("string")
}
Expr::Array(..) => Some("array"),
Expr::Unary(UnOp::Neg | UnOp::Pos, x) => match literal_given_type(x)? {
t @ ("int" | "float") => Some(t),
_ => None,
},
_ => None,
}
}
/// Whether the declared type `ty` accepts a literal of kind `given` the way a
/// constant or property initialiser is checked: strictly, apart from the
/// `int` to `float` widening.
fn type_accepts_literal(ty: &TypeHint, given: &str, value: &Expr) -> bool {
ty.parts.iter().any(|p| {
let p = p.to_ascii_lowercase();
match p.as_str() {
"mixed" => true,
"int" => given == "int",
"float" => matches!(given, "int" | "float"),
"string" => given == "string",
"bool" => given == "bool",
"true" => matches!(value, Expr::Bool(true)),
"false" => matches!(value, Expr::Bool(false)),
"null" => given == "null",
"array" => given == "array",
"iterable" => given == "array",
_ => false,
}
})
}
/// The compile-time fatal for a typed class constant whose literal initialiser
/// the type refuses, or for a type no constant may have.
fn const_type_error(
ty: &TypeHint,
class: &str,
parent: Option<&str>,
cname: &str,
value: &Expr,
) -> Option<String> {
let declared = ty.declared(class, parent);
if let Some(bad) = ty.parts.iter().find(|p| {
matches!(
p.to_ascii_lowercase().as_str(),
"void" | "never" | "callable"
)
}) {
return Some(format!(
"Class constant {class}::{cname} cannot have type {}",
bad.to_ascii_lowercase()
));
}
let given = literal_given_type(value)?;
if type_accepts_literal(ty, given, value) {
return None;
}
Some(format!(
"Cannot use {given} as value for class constant {class}::{cname} of type {declared}"
))
}
/// An `int` literal initialiser becomes the `float` it is declared as — a
/// `float` constant or property written `= 1` holds `1.0` — unless the type
/// takes an `int` itself.
fn widen_int_literal(ty: &TypeHint, value: Expr) -> Expr {
let takes = |n: &str| ty.parts.iter().any(|p| p.eq_ignore_ascii_case(n));
if !takes("float") || takes("int") || takes("mixed") {
return value;
}
match value {
Expr::Int(n) => Expr::Float(n as f64),
Expr::Unary(UnOp::Neg, inner) => match *inner {
Expr::Int(n) => Expr::Float(-(n as f64)),
other => Expr::Unary(UnOp::Neg, Box::new(other)),
},
other => other,
}
}
/// The compile-time fatal for a typed property whose literal default the type
/// refuses — a `null` against a non-nullable type has a message of its own.
fn prop_default_error(
ty: &TypeHint,
class: &str,
parent: Option<&str>,
pname: &str,
value: &Expr,
) -> Option<String> {
let given = literal_given_type(value)?;
if type_accepts_literal(ty, given, value) {
return None;
}
let declared = ty.declared(class, parent);
if given == "null" {
let nullable = if declared.contains('|') || declared.starts_with('?') {
format!("{declared}|null")
} else {
format!("?{declared}")
};
return Some(format!(
"Default value for property of type {declared} may not be null. Use the nullable \
type {nullable} to allow null default value"
));
}
Some(format!(
"Cannot use {given} as default value for property {class}::${pname} of type {declared}"
))
}
/// Binding powers of the `|>` pipe: between the relational operators (13, 14)
/// and `.` (17, 18).
const PIPE_BP: (u8, u8) = (15, 16);
/// `#[\Deprecated(message, since)]`'s literal arguments, by position or name.
/// A non-literal argument leaves its part unset.
pub(crate) fn deprecation_of(args: &[Expr]) -> Deprecation {
let literal = |e: &Expr| match e {
Expr::Str(s) => Some(s.clone()),
Expr::Interp(parts) => parts
.iter()
.map(|p| match p {
InterpPart::Lit(l) => Some(l.as_str()),
InterpPart::Expr(_) => None,
})
.collect::<Option<String>>(),
_ => None,
};
let mut d = Deprecation::default();
for (i, a) in args.iter().enumerate() {
match a {
Expr::NamedArg(n, v) if n.eq_ignore_ascii_case("message") => d.message = literal(v),
Expr::NamedArg(n, v) if n.eq_ignore_ascii_case("since") => d.since = literal(v),
Expr::NamedArg(..) => {}
v if i == 0 => d.message = literal(v),
v if i == 1 => d.since = literal(v),
_ => {}
}
}
d
}