thymeleaf 0.1.0-beta.1

A framework-neutral Thymeleaf-compatible dynamic template engine for Rust
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
use std::any::Any;
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::sync::Arc;

use num_bigint::BigInt;

use crate::context::IExpressionContext;
use crate::exceptions::TemplateProcessingException;
use crate::temporal::TemporalCreationUtils;
use crate::util::StandardExpressionUtils;
use crate::util::{BigDecimalValue, ExpressionUtils, NumberValue, Utf16String};

use super::{
    AdditionExpression, AndExpression, ClassNotFoundError, ConditionalExpression, ConversionResult,
    ConversionValue, DivisionExpression, EqualsExpression, GreaterOrEqualToExpression,
    GreaterThanExpression, IStandardExpression, IStandardVariableExpression,
    IStandardVariableExpressionEvaluator, LessOrEqualToExpression, LessThanExpression,
    LiteralValue, MinusExpression, MultiplicationExpression, NativeExpressionObjectsWrapper,
    NativeShortcutExpression, NegationExpression, NoOpOgnlRuntime, NoSuchMethodError,
    NotEqualsExpression, OgnlError, OgnlRuntime, OrExpression, RemainderExpression,
    StandardExpressionExecutionContext, StandardExpressionResult, StandardExpressions,
    SubtractionExpression, TargetClass, TemplateObject, TemplateValue,
    binary_operation_expression::{evaluate_as_boolean, evaluate_as_number},
    iterator_value::IteratorValue,
    map_entry_value::MapEntryValue,
    stream_value::StreamValue,
};

/// Thymeleaf Standard Dialect 的 OGNL 变量表达式求值器。
///
/// 对应 Java: `org.thymeleaf.standard.expression.OGNLVariableExpressionEvaluator`。
///
/// Rust 不具备 JVM 反射,因此 JavaBean 属性读取通过 `TemplateObject::get_property`
/// SPI 完成;Context、Map、List、数组以及表达式对象保留 OGNL 的动态访问语义。
pub struct NativeVariableExpressionEvaluator {
    apply_ognl_shortcuts: bool,
    runtime: Arc<dyn OgnlRuntime>,
}

impl NativeVariableExpressionEvaluator {
    /// 创建求值器并决定是否优先启用点分属性快速路径。
    #[must_use]
    /// 对应 Java 语义:`OGNLVariableExpressionEvaluator` 的 `new` 行为(Rust 侧辅助/私有路径)。
    pub fn new(apply_ognl_shortcuts: bool) -> Self {
        Self {
            apply_ognl_shortcuts,
            runtime: Arc::new(NoOpOgnlRuntime),
        }
    }

    /// 使用宿主提供的静态成员与构造器运行时创建求值器。
    #[must_use]
    /// 对应 Java 语义:`OGNLVariableExpressionEvaluator` 的 `with_runtime` 行为(Rust 侧辅助/私有路径)。
    pub fn with_runtime(apply_ognl_shortcuts: bool, runtime: Arc<dyn OgnlRuntime>) -> Self {
        Self {
            apply_ognl_shortcuts,
            runtime,
        }
    }

    fn evaluate_computed(
        &self,
        context: &dyn IExpressionContext,
        expression: &dyn IStandardVariableExpression,
        expression_context: &'static StandardExpressionExecutionContext,
    ) -> StandardExpressionResult<Option<Arc<TemplateValue>>> {
        let source = expression.get_expression().ok_or_else(|| {
            processing_error("Expression content is null, which is not allowed".to_owned())
        })?;
        if expression_context.get_restrict_external_access()
            && StandardExpressionUtils::contains_external_access(&source.to_string_lossy())
        {
            return Err(processing_error(
                "Instantiation of new objects and access to static classes or parameters is forbidden in this context"
                    .to_owned(),
            ));
        }

        let restrictions_apply = expression_context.get_restrict_variable_access()
            || expression_context.get_restrict_external_access();
        let cached = expression
            .get_cached_expression()
            .and_then(|value| value.downcast::<ComputedOGNLExpression>().ok());
        let computed = if cached
            .as_deref()
            .is_some_and(|value| !restrictions_apply || !value.is_shortcut())
        {
            cached.expect("cached expression was checked above")
        } else {
            // 对应 Java obtainComputedOGNLExpression:变量访问或外部访问受限时,
            // 必须交给完整 OGNL 路径执行 AST/成员 ACL,不能使用属性 shortcut。
            parse_and_cache_expression(
                expression,
                source,
                self.apply_ognl_shortcuts && !restrictions_apply,
            )
        };

        let result = with_ognl_runtime(Arc::clone(&self.runtime), || {
            with_ognl_locals(|| {
                let result = match &computed.expression {
                    ComputedExpression::Shortcut(shortcut) => match shortcut.evaluate(
                        context,
                        expression.get_use_selection_as_root(),
                        expression_context.get_restrict_variable_access(),
                    ) {
                        Ok(value) => value,
                        Err(
                            super::NativeShortcutError::NotApplicable(_)
                            | super::NativeShortcutError::PropertyGetter { .. },
                        ) => {
                            // 对应 Java evaluate 对
                            // OGNLShortcutExpressionNotApplicableException 的处理:shortcut
                            // 只是优化,不能改变表达式可执行性。失配后立即替换缓存并按
                            // 完整路径求值,后续调用不会再次进入 shortcut。
                            let fallback = parse_and_cache_expression(expression, source, false);
                            evaluate_computed_expression(
                                context,
                                &fallback.expression,
                                expression.get_use_selection_as_root(),
                                expression_context,
                            )?
                        }
                        Err(error) => {
                            let message = error.to_string();
                            return Err(ognl_processing_error(
                                format!(
                                    "Exception evaluating OGNL expression: \"{}\": {message}",
                                    source.to_string_lossy()
                                ),
                                message,
                            ));
                        }
                    },
                    ComputedExpression::Path(path) => evaluate_path(
                        context,
                        path,
                        expression.get_use_selection_as_root(),
                        expression_context,
                    )?,
                    ComputedExpression::Literal(value) => value.to_template_value(),
                    ComputedExpression::Operation(expression) => {
                        expression.execute_with_context(context, expression_context)?
                    }
                    ComputedExpression::StaticReference(reference) => evaluate_static_reference(
                        context,
                        reference,
                        expression.get_use_selection_as_root(),
                        expression_context,
                    )?,
                    ComputedExpression::Constructor(constructor) => evaluate_constructor(
                        context,
                        constructor,
                        expression.get_use_selection_as_root(),
                        expression_context,
                    )?,
                    ComputedExpression::ListLiteral(values) => evaluate_list_literal(
                        context,
                        values,
                        expression.get_use_selection_as_root(),
                        expression_context,
                    )?,
                    ComputedExpression::MapLiteral(entries) => evaluate_map_literal(
                        context,
                        entries,
                        expression.get_use_selection_as_root(),
                        expression_context,
                    )?,
                    ComputedExpression::Inclusion {
                        left,
                        right,
                        negated,
                    } => evaluate_inclusion(
                        context,
                        left,
                        right,
                        *negated,
                        expression.get_use_selection_as_root(),
                        expression_context,
                    )?,
                    ComputedExpression::Sequence(values) => evaluate_sequence(
                        context,
                        values,
                        expression.get_use_selection_as_root(),
                        expression_context,
                    )?,
                    ComputedExpression::Assignment { name, value } => evaluate_assignment(
                        context,
                        name,
                        value,
                        expression.get_use_selection_as_root(),
                        expression_context,
                    )?,
                    ComputedExpression::NativeBinary {
                        operator,
                        left,
                        right,
                    } => evaluate_native_binary(
                        context,
                        *operator,
                        left,
                        right,
                        expression.get_use_selection_as_root(),
                        expression_context,
                    )?,
                    ComputedExpression::BitNegate(value) => evaluate_bit_negate(
                        context,
                        value,
                        expression.get_use_selection_as_root(),
                        expression_context,
                    )?,
                    ComputedExpression::InstanceOf { value, type_name } => evaluate_instance_of(
                        context,
                        value,
                        type_name,
                        expression.get_use_selection_as_root(),
                        expression_context,
                    )?,
                    ComputedExpression::Navigation { root, steps } => evaluate_navigation(
                        context,
                        root,
                        steps,
                        expression.get_use_selection_as_root(),
                        expression_context,
                    )?,
                    ComputedExpression::Unsupported => {
                        return Err(processing_error(format!(
                            "Exception evaluating OGNL expression: \"{}\": unsupported OGNL syntax",
                            source.to_string_lossy()
                        )));
                    }
                };
                Ok(result)
            })
        })?;

        // Context 内部用 TemplateValue::Null 保存 Java null 哨兵,但表达式 API
        // 必须继续以 None 暴露 Java null,DefaultExpression 才会执行右操作数。
        let result = normalize_java_null(result);
        if !expression_context.get_perform_type_conversion() {
            return Ok(result);
        }
        convert_to_string(context, result)
    }
}

impl IStandardVariableExpressionEvaluator for NativeVariableExpressionEvaluator {
    fn evaluate(
        &self,
        context: &dyn IExpressionContext,
        expression: &dyn IStandardVariableExpression,
        expression_context: &'static StandardExpressionExecutionContext,
    ) -> StandardExpressionResult<Option<Arc<TemplateValue>>> {
        self.evaluate_computed(context, expression, expression_context)
    }
}

impl std::fmt::Display for NativeVariableExpressionEvaluator {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str("OGNL")
    }
}

/// 已解析 OGNL 表达式及其可执行表示。
///
/// 对应 Java: `OGNLVariableExpressionEvaluator.ComputedOGNLExpression`。
struct ComputedOGNLExpression {
    expression: ComputedExpression,
}

impl ComputedOGNLExpression {
    fn is_shortcut(&self) -> bool {
        matches!(self.expression, ComputedExpression::Shortcut(_))
    }
}

fn parse_and_cache_expression(
    expression: &dyn IStandardVariableExpression,
    source: &Utf16String,
    apply_shortcuts: bool,
) -> Arc<ComputedOGNLExpression> {
    let value = Arc::new(parse_expression(
        source,
        apply_shortcuts,
        expression.get_use_selection_as_root(),
    ));
    let cached: Arc<dyn std::any::Any + Send + Sync> = value.clone();
    expression.set_cached_expression(Some(cached));
    value
}

/// 在解析类型前执行 Thymeleaf 禁止类型 ACL。
///
/// 对应 Java: `OGNLVariableExpressionEvaluator.ThymeleafACLClassResolver`。
struct ThymeleafACLClassResolver;

impl ThymeleafACLClassResolver {
    fn class_for_name(class_name: &str) -> StandardExpressionResult<&str> {
        if ExpressionUtils::is_type_forbidden(class_name) {
            return Err(processing_error(format!(
                "Access is forbidden for type '{class_name}' in this expression context."
            )));
        }
        ThymeleafDefaultClassResolver::class_for_name(class_name)
    }
}

/// 不会隐式补全 `java.lang.` 的严格类型名解析器。
///
/// 对应 Java: `OGNLVariableExpressionEvaluator.ThymeleafDefaultClassResolver`。
struct ThymeleafDefaultClassResolver;

impl ThymeleafDefaultClassResolver {
    fn class_for_name(class_name: &str) -> StandardExpressionResult<&str> {
        if class_name.trim().is_empty() {
            return Err(processing_error("Class name cannot be empty".to_owned()));
        }
        // Java Thymeleaf 的默认 OGNL ClassResolver 直接调用 Class.forName,不会把
        // `String` 隐式补全为 `java.lang.String`。
        if !class_name.contains('.') {
            return Err(processing_error_with_cause(
                format!("Class not found: {class_name}"),
                ClassNotFoundError::new(class_name.to_owned()),
            ));
        }
        Ok(class_name)
    }
}

/// OGNL 公共成员访问 ACL。
///
/// 对应 Java: `OGNLVariableExpressionEvaluator.ThymeleafACLMemberAccess`。
struct ThymeleafACLMemberAccess;

impl ThymeleafACLMemberAccess {
    fn is_accessible(
        target: Option<&dyn TemplateObject>,
        member_name: &str,
    ) -> StandardExpressionResult<()> {
        if ExpressionUtils::is_member_forbidden(target, member_name) {
            return Err(processing_error(format!(
                "Accessing member '{member_name}' is forbidden in this expression context."
            )));
        }
        Ok(())
    }
}

enum ComputedExpression {
    Shortcut(NativeShortcutExpression),
    Path(OgnlPath),
    Literal(OgnlLiteral),
    Operation(Arc<dyn IStandardExpression>),
    StaticReference(OgnlStaticReference),
    Constructor(OgnlConstructor),
    ListLiteral(Vec<ComputedExpression>),
    MapLiteral(Vec<(Box<ComputedExpression>, Box<ComputedExpression>)>),
    Inclusion {
        left: Box<ComputedExpression>,
        right: Box<ComputedExpression>,
        negated: bool,
    },
    Sequence(Vec<ComputedExpression>),
    Assignment {
        name: Utf16String,
        value: Box<ComputedExpression>,
    },
    NativeBinary {
        operator: OgnlBinaryOperator,
        left: Box<ComputedExpression>,
        right: Box<ComputedExpression>,
    },
    BitNegate(Box<ComputedExpression>),
    InstanceOf {
        value: Box<ComputedExpression>,
        type_name: Utf16String,
    },
    Navigation {
        root: Box<ComputedExpression>,
        steps: Vec<PathStep>,
    },
    Unsupported,
}

#[derive(Clone, Copy)]
enum OgnlBinaryOperator {
    Divide,
    BitOr,
    BitXor,
    BitAnd,
    ShiftLeft,
    ShiftRight,
    UnsignedShiftRight,
}

struct OgnlStaticReference {
    type_name: Utf16String,
    member_name: Utf16String,
    arguments: Option<Vec<ComputedExpression>>,
    trailing_steps: Vec<PathStep>,
}

struct OgnlConstructor {
    type_name: Utf16String,
    arguments: Vec<ComputedExpression>,
    trailing_steps: Vec<PathStep>,
}

struct OgnlLeafExpression {
    source: Utf16String,
    expression: Box<ComputedExpression>,
    use_selection_as_root: bool,
}

impl IStandardExpression for OgnlLeafExpression {
    fn get_string_representation(&self) -> StandardExpressionResult<Utf16String> {
        Ok(self.source.clone())
    }

    fn execute_with_context(
        &self,
        context: &dyn IExpressionContext,
        expression_context: &'static StandardExpressionExecutionContext,
    ) -> StandardExpressionResult<Option<Arc<TemplateValue>>> {
        evaluate_computed_expression(
            context,
            self.expression.as_ref(),
            self.use_selection_as_root,
            expression_context,
        )
    }

    fn execute_raw(
        &self,
        context: &dyn IExpressionContext,
        expression_context: &'static StandardExpressionExecutionContext,
    ) -> StandardExpressionResult<Option<Arc<TemplateValue>>> {
        // 对应 Java `Expression.execute` 的 LiteralValue 不解包语义:
        // 字面量叶子按原始字面量返回(Java OGNL/Thymeleaf 的加法对
        // String 字面量拼接而非数值相加),其他计算表达式与公开执行一致。
        match self.expression.as_ref() {
            ComputedExpression::Literal(OgnlLiteral::String(value)) => Ok(Some(Arc::new(
                TemplateValue::Literal(Arc::new(LiteralValue::new(Some(value.clone())))),
            ))),
            ComputedExpression::Literal(OgnlLiteral::Character(value)) => {
                Ok(Some(Arc::new(TemplateValue::Literal(Arc::new(
                    LiteralValue::new(Some(Utf16String::from_utf16(vec![*value]))),
                )))))
            }
            _ => self.execute_with_context(context, expression_context),
        }
    }
}

enum OgnlLiteral {
    Null,
    Boolean(bool),
    Character(u16),
    Integer(i32),
    Long(i64),
    Float(f32),
    Double(f64),
    BigInteger(num_bigint::BigInt),
    BigDecimal(BigDecimalValue),
    String(Utf16String),
}

impl OgnlLiteral {
    fn to_template_value(&self) -> Option<Arc<TemplateValue>> {
        match self {
            Self::Null => None,
            Self::Boolean(value) => Some(Arc::new(TemplateValue::Boolean(*value))),
            Self::Character(value) => Some(Arc::new(TemplateValue::Character(*value))),
            Self::Integer(value) => Some(Arc::new(TemplateValue::Number(NumberValue::Integer(
                *value,
            )))),
            Self::Long(value) => Some(Arc::new(TemplateValue::Number(NumberValue::Long(*value)))),
            Self::Float(value) => Some(Arc::new(TemplateValue::Number(NumberValue::Float(*value)))),
            Self::Double(value) => {
                Some(Arc::new(TemplateValue::Number(NumberValue::Double(*value))))
            }
            Self::BigInteger(value) => Some(Arc::new(TemplateValue::Number(
                NumberValue::BigInteger(value.clone()),
            ))),
            Self::BigDecimal(value) => Some(Arc::new(TemplateValue::Number(
                NumberValue::BigDecimal(value.clone()),
            ))),
            Self::String(value) => Some(Arc::new(TemplateValue::string(value.clone()))),
        }
    }
}

struct OgnlPath {
    root: PathRoot,
    steps: Vec<PathStep>,
}

enum PathRoot {
    Context(Utf16String),
    ExpressionObject(Utf16String),
}

enum PathStep {
    Property(Utf16String),
    Method(Utf16String, Vec<ComputedExpression>),
    Projection(Box<ComputedExpression>),
    Selection(SelectionKind, Box<ComputedExpression>),
    StringIndex(Utf16String),
    NumericIndex(usize),
    DynamicSubscript(OgnlDynamicSubscript),
    DynamicIndex(Box<ComputedExpression>),
}

#[derive(Clone, Copy)]
enum OgnlDynamicSubscript {
    First,
    Mid,
    Last,
    All,
}

#[derive(Clone, Copy)]
enum SelectionKind {
    All,
    First,
    Last,
}

/// 单个 OGNL 表达式允许的最大 UTF-16 代码单元数。
const MAX_EXPRESSION_LENGTH: usize = 4096;

/// OGNL 递归下降允许的最大嵌套深度。
const MAX_PARSE_DEPTH: usize = 256;

thread_local! {
    static PARSE_DEPTH: Cell<usize> = const { Cell::new(0) };
}

/// 递归深度计数守卫:进入 `parse_ognl_range` 时占用一格,超限返回 `None`,
/// 离开时自动归还。Java 的 OGNL 解析是迭代实现,Rust 递归下降需要结构防御。
struct ParseDepthGuard;

impl ParseDepthGuard {
    fn try_enter() -> Option<Self> {
        let entered = PARSE_DEPTH.with(|depth| {
            if depth.get() >= MAX_PARSE_DEPTH {
                false
            } else {
                depth.set(depth.get() + 1);
                true
            }
        });
        // 惰性构造:`then_some(Self)` 会无条件求值 `Self`,entered=false 时
        // 仍会构造并丢弃带 Drop 的守卫值(深度计数下溢)。
        entered.then(|| Self)
    }
}

impl Drop for ParseDepthGuard {
    fn drop(&mut self) {
        PARSE_DEPTH.with(|depth| depth.set(depth.get() - 1));
    }
}

fn parse_expression(
    source: &Utf16String,
    apply_shortcuts: bool,
    use_selection_as_root: bool,
) -> ComputedOGNLExpression {
    if source.len() > MAX_EXPRESSION_LENGTH {
        return ComputedOGNLExpression {
            expression: ComputedExpression::Unsupported,
        };
    }
    let trimmed = trim(source);
    let expression = parse_ognl_range(trimmed.as_utf16(), apply_shortcuts, use_selection_as_root)
        .unwrap_or(ComputedExpression::Unsupported);
    ComputedOGNLExpression { expression }
}

fn parse_ognl_range(
    input: &[u16],
    apply_shortcuts: bool,
    use_selection_as_root: bool,
) -> Option<ComputedExpression> {
    let _guard = ParseDepthGuard::try_enter()?;
    let input = trim_units(input);
    if input.is_empty() {
        return None;
    }
    if is_outer_parenthesized(input) {
        return parse_ognl_range(
            &input[1..input.len() - 1],
            apply_shortcuts,
            use_selection_as_root,
        );
    }
    let sequence = split_ognl_entries(input)?;
    if sequence.len() > 1 {
        return sequence
            .into_iter()
            .map(|entry| parse_ognl_range(entry, apply_shortcuts, use_selection_as_root))
            .collect::<Option<Vec<_>>>()
            .map(ComputedExpression::Sequence);
    }
    if let Some(position) = find_assignment_operator(input) {
        let target = trim_units(&input[..position]);
        if target.first() != Some(&(b'#' as u16))
            || target.len() < 2
            || !target[1..].iter().copied().all(is_ascii_identifier_part)
        {
            return None;
        }
        let value = parse_ognl_range(
            &input[position + 1..],
            apply_shortcuts,
            use_selection_as_root,
        )?;
        return Some(ComputedExpression::Assignment {
            name: Utf16String::from_utf16(target[1..].to_vec()),
            value: Box::new(value),
        });
    }
    if let Some(navigation) =
        parse_primary_navigation(input, apply_shortcuts, use_selection_as_root)
    {
        return Some(navigation);
    }
    if let Some(collection) =
        parse_collection_literal(input, apply_shortcuts, use_selection_as_root)
    {
        return Some(collection);
    }
    if let Some(reference) = parse_static_reference(input, apply_shortcuts, use_selection_as_root) {
        return Some(ComputedExpression::StaticReference(reference));
    }
    if let Some(constructor) = parse_constructor(input, apply_shortcuts, use_selection_as_root) {
        return Some(ComputedExpression::Constructor(constructor));
    }
    if let Some((question, colon)) = find_conditional(input) {
        let colon = colon?;
        let condition =
            parse_ognl_operand(&input[..question], apply_shortcuts, use_selection_as_root)?;
        let then_expression = parse_ognl_operand(
            &input[question + 1..colon],
            apply_shortcuts,
            use_selection_as_root,
        )?;
        let else_expression =
            parse_ognl_operand(&input[colon + 1..], apply_shortcuts, use_selection_as_root)?;
        return ConditionalExpression::new(
            Some(condition),
            Some(then_expression),
            Some(else_expression),
        )
        .ok()
        .map(|value| ComputedExpression::Operation(Arc::new(value)));
    }

    // 注意:此处不解析 Elvis 简写 `a ?: b`——与 Java 上游一致。Thymeleaf 的
    // default expression 只存在于 `${...}` 之外(Thymeleaf 层 DefaultExpression,
    // 由 expression_parsing_util 解析);`${...}` 内部内容由 OGNL 3.3.4 求值,
    // 而 OGNL 不支持 Elvis 简写(实测抛 ExpressionSyntaxException → 渲染期
    // TemplateInputException)。完整三元 `a ? b : c` OGNL 支持,上方分支保留。
    // Java 3.1.5 实测锚点:`${v ?: 'f'}` 异常、`${v} ?: 'f'` 取默认、
    // `${1 > 2 ? 'y' : 'n'}` 输出 n(golden: ognl_evaluation_golden.txt)。

    macro_rules! binary_group {
        ($operators:expr) => {
            if let Some((position, operator)) = find_binary_operator(input, $operators) {
                let left =
                    parse_ognl_operand(&input[..position], apply_shortcuts, use_selection_as_root)?;
                let right = parse_ognl_operand(
                    &input[position + operator.len()..],
                    apply_shortcuts,
                    use_selection_as_root,
                )?;
                return build_ognl_binary(operator, left, right);
            }
        };
    }
    macro_rules! native_binary_group {
        ($operators:expr, $operator:expr) => {
            if let Some((position, token)) = find_binary_operator(input, $operators) {
                let left =
                    parse_ognl_range(&input[..position], apply_shortcuts, use_selection_as_root)?;
                let right = parse_ognl_range(
                    &input[position + token.len()..],
                    apply_shortcuts,
                    use_selection_as_root,
                )?;
                return Some(ComputedExpression::NativeBinary {
                    operator: $operator,
                    left: Box::new(left),
                    right: Box::new(right),
                });
            }
        };
    }
    binary_group!(&[OP_OR, OP_DOUBLE_PIPE]);
    binary_group!(&[OP_AND, OP_DOUBLE_AMPERSAND]);
    native_binary_group!(&[OP_BOR, OP_PIPE], OgnlBinaryOperator::BitOr);
    native_binary_group!(&[OP_XOR, OP_CARET], OgnlBinaryOperator::BitXor);
    native_binary_group!(&[OP_BAND, OP_AMPERSAND], OgnlBinaryOperator::BitAnd);
    binary_group!(&[OP_NEQ, OP_NE, OP_NOT_EQUALS, OP_EQ, OP_EQUALS]);
    binary_group!(&[
        OP_GTE,
        OP_GE,
        OP_GREATER_EQUAL,
        OP_GT,
        OP_GREATER,
        OP_LTE,
        OP_LE,
        OP_LESS_EQUAL,
        OP_LT,
        OP_LESS,
    ]);
    if let Some((position, operator_length, negated)) = find_inclusion_operator(input) {
        let left = parse_ognl_range(&input[..position], apply_shortcuts, use_selection_as_root)?;
        let right = parse_ognl_range(
            &input[position + operator_length..],
            apply_shortcuts,
            use_selection_as_root,
        )?;
        return Some(ComputedExpression::Inclusion {
            left: Box::new(left),
            right: Box::new(right),
            negated,
        });
    }
    if let Some(position) = find_word_operator(input, OP_INSTANCEOF) {
        let value = parse_ognl_range(&input[..position], apply_shortcuts, use_selection_as_root)?;
        let type_name = trim_units(&input[position + OP_INSTANCEOF.len()..]);
        if type_name.is_empty()
            || !type_name
                .iter()
                .copied()
                .all(|unit| is_ascii_identifier_part(unit) || unit == b'.' as u16)
        {
            return None;
        }
        return Some(ComputedExpression::InstanceOf {
            value: Box::new(value),
            type_name: Utf16String::from_utf16(type_name.to_vec()),
        });
    }
    native_binary_group!(
        &[OP_USHR, OP_UNSIGNED_SHIFT_RIGHT],
        OgnlBinaryOperator::UnsignedShiftRight
    );
    native_binary_group!(&[OP_SHR, OP_SHIFT_RIGHT], OgnlBinaryOperator::ShiftRight);
    native_binary_group!(&[OP_SHL, OP_SHIFT_LEFT], OgnlBinaryOperator::ShiftLeft);
    binary_group!(&[OP_PLUS, OP_MINUS]);
    binary_group!(&[OP_MULTIPLY, OP_MOD, OP_REMAINDER]);
    native_binary_group!(&[OP_DIV, OP_DIVIDE], OgnlBinaryOperator::Divide);

    if input[0] == b'-' as u16 {
        let operand = parse_ognl_operand(&input[1..], apply_shortcuts, use_selection_as_root)?;
        return MinusExpression::new(Some(operand))
            .ok()
            .map(|value| ComputedExpression::Operation(Arc::new(value)));
    }
    if input[0] == b'+' as u16 {
        return parse_ognl_range(&input[1..], apply_shortcuts, use_selection_as_root);
    }
    if input[0] == b'~' as u16 {
        let operand = parse_ognl_range(&input[1..], apply_shortcuts, use_selection_as_root)?;
        return Some(ComputedExpression::BitNegate(Box::new(operand)));
    }
    if input[0] == b'!' as u16 {
        let operand = parse_ognl_operand(&input[1..], apply_shortcuts, use_selection_as_root)?;
        return NegationExpression::new(Some(operand))
            .ok()
            .map(|value| ComputedExpression::Operation(Arc::new(value)));
    }
    if starts_with_word(input, "not") {
        let operand = parse_ognl_operand(&input[3..], apply_shortcuts, use_selection_as_root)?;
        return NegationExpression::new(Some(operand))
            .ok()
            .map(|value| ComputedExpression::Operation(Arc::new(value)));
    }

    let source = Utf16String::from_utf16(input.to_vec());
    if let Some(value) = parse_literal(&source) {
        return Some(ComputedExpression::Literal(value));
    }
    if apply_shortcuts && let Some(levels) = NativeShortcutExpression::parse(Some(&source)) {
        return Some(ComputedExpression::Shortcut(NativeShortcutExpression::new(
            levels,
        )));
    }
    parse_path(&source, apply_shortcuts, use_selection_as_root).map(ComputedExpression::Path)
}

fn parse_primary_navigation(
    input: &[u16],
    apply_shortcuts: bool,
    use_selection_as_root: bool,
) -> Option<ComputedExpression> {
    let root_end = if matches!(input.first(), Some(0x27 | 0x22)) {
        let quote = input[0];
        (1..input.len())
            .find(|position| input[*position] == quote && !is_escaped(input, *position))
            .map(|position| position + 1)?
    } else if input.first() == Some(&(b'(' as u16)) {
        find_closing_parenthesis(input, 0)? + 1
    } else if input.starts_with(&[b'#' as u16, b'{' as u16]) {
        find_closing_delimiter(input, 1, b'{' as u16, b'}' as u16)? + 1
    } else if input.first() == Some(&(b'{' as u16)) {
        find_closing_delimiter(input, 0, b'{' as u16, b'}' as u16)? + 1
    } else {
        return None;
    };
    if root_end == input.len()
        || !matches!(input[root_end], value if value == b'.' as u16 || value == b'[' as u16)
    {
        return None;
    }
    let root = parse_ognl_range(&input[..root_end], apply_shortcuts, use_selection_as_root)?;
    let mut position = root_end;
    let steps = parse_suffix_steps(input, &mut position, apply_shortcuts, use_selection_as_root)?;
    Some(ComputedExpression::Navigation {
        root: Box::new(root),
        steps,
    })
}

fn parse_ognl_operand(
    input: &[u16],
    apply_shortcuts: bool,
    use_selection_as_root: bool,
) -> Option<Arc<dyn IStandardExpression>> {
    let expression = parse_ognl_range(input, apply_shortcuts, use_selection_as_root)?;
    match expression {
        ComputedExpression::Operation(expression) => Some(expression),
        expression => Some(Arc::new(OgnlLeafExpression {
            source: Utf16String::from_utf16(trim_units(input).to_vec()),
            expression: Box::new(expression),
            use_selection_as_root,
        })),
    }
}

fn build_ognl_binary(
    operator: &[u16],
    left: Arc<dyn IStandardExpression>,
    right: Arc<dyn IStandardExpression>,
) -> Option<ComputedExpression> {
    let operator = String::from_utf16_lossy(operator).to_ascii_lowercase();
    macro_rules! create {
        ($type:ty) => {
            <$type>::new(Some(left), Some(right))
                .ok()
                .map(|value| ComputedExpression::Operation(Arc::new(value)))
        };
    }
    match operator.as_str() {
        "or" | "||" => create!(OrExpression),
        "and" | "&&" => create!(AndExpression),
        "eq" | "==" => create!(EqualsExpression),
        "neq" | "ne" | "!=" => create!(NotEqualsExpression),
        "gt" | ">" => create!(GreaterThanExpression),
        "gte" | "ge" | ">=" => create!(GreaterOrEqualToExpression),
        "lt" | "<" => create!(LessThanExpression),
        "lte" | "le" | "<=" => create!(LessOrEqualToExpression),
        "+" => create!(AdditionExpression),
        "-" => create!(SubtractionExpression),
        "*" => create!(MultiplicationExpression),
        "div" | "/" => create!(DivisionExpression),
        "mod" | "%" => create!(RemainderExpression),
        _ => None,
    }
}

fn parse_literal(source: &Utf16String) -> Option<OgnlLiteral> {
    let text = source.to_string_lossy();
    if text == "null" {
        return Some(OgnlLiteral::Null);
    }
    if text == "true" {
        return Some(OgnlLiteral::Boolean(true));
    }
    if text == "false" {
        return Some(OgnlLiteral::Boolean(false));
    }
    if source.as_utf16().len() >= 2
        && matches!(source.as_utf16().first(), Some(0x27 | 0x22))
        && source.as_utf16().last() == source.as_utf16().first()
    {
        let contents = unescape_ognl_string(&source.as_utf16()[1..source.as_utf16().len() - 1])?;
        if source.as_utf16().first() == Some(&(b'\'' as u16)) && contents.len() == 1 {
            return Some(OgnlLiteral::Character(contents[0]));
        }
        return Some(OgnlLiteral::String(Utf16String::from_utf16(contents)));
    }
    let unsigned_source = text.trim_start_matches(['-', '+']);
    let hexadecimal = unsigned_source.starts_with("0x") || unsigned_source.starts_with("0X");
    let (number, suffix) = text
        .char_indices()
        .last()
        .filter(|(_, value)| {
            value.is_ascii_alphabetic()
                && (!hexadecimal || matches!(value.to_ascii_lowercase(), 'h' | 'l'))
        })
        .map_or((text.as_str(), None), |(position, value)| {
            (&text[..position], Some(value.to_ascii_lowercase()))
        });
    let signed = number.starts_with('-') || number.starts_with('+');
    let unsigned = number.trim_start_matches(['-', '+']);
    let radix_value = if unsigned.starts_with("0x") || unsigned.starts_with("0X") {
        i64::from_str_radix(&unsigned[2..], 16).ok().map(|value| {
            if number.starts_with('-') {
                -value
            } else {
                value
            }
        })
    } else if unsigned.len() > 1
        && unsigned.starts_with('0')
        && unsigned.chars().all(|value| matches!(value, '0'..='7'))
    {
        i64::from_str_radix(&unsigned[1..], 8).ok().map(|value| {
            if number.starts_with('-') {
                -value
            } else {
                value
            }
        })
    } else {
        None
    };
    if matches!(suffix, Some('h')) {
        let value = if unsigned.starts_with("0x") || unsigned.starts_with("0X") {
            num_bigint::BigInt::parse_bytes(&unsigned.as_bytes()[2..], 16).map(|value| {
                if number.starts_with('-') {
                    -value
                } else {
                    value
                }
            })
        } else {
            number.parse().ok()
        }?;
        return Some(OgnlLiteral::BigInteger(value));
    }
    if matches!(suffix, Some('b')) {
        return BigDecimalValue::parse(number)
            .ok()
            .map(OgnlLiteral::BigDecimal);
    }
    if matches!(suffix, Some('l')) {
        return radix_value
            .or_else(|| number.parse().ok())
            .map(OgnlLiteral::Long);
    }
    if matches!(suffix, Some('f')) {
        return number.parse().ok().map(OgnlLiteral::Float);
    }
    if matches!(suffix, Some('d')) {
        return number.parse().ok().map(OgnlLiteral::Double);
    }
    if suffix.is_some() || signed && number.len() == 1 {
        return None;
    }
    if let Some(value) = radix_value {
        return i32::try_from(value)
            .map(OgnlLiteral::Integer)
            .ok()
            .or(Some(OgnlLiteral::Long(value)));
    }
    if let Ok(value) = number.parse::<i32>() {
        return Some(OgnlLiteral::Integer(value));
    }
    if let Ok(value) = number.parse::<i64>() {
        return Some(OgnlLiteral::Long(value));
    }
    if let Ok(value) = number.parse::<f64>() {
        return Some(OgnlLiteral::Double(value));
    }
    None
}

fn parse_collection_literal(
    input: &[u16],
    apply_shortcuts: bool,
    use_selection_as_root: bool,
) -> Option<ComputedExpression> {
    let (map, body) =
        if input.starts_with(&[b'#' as u16, b'{' as u16]) && input.last() == Some(&(b'}' as u16)) {
            (true, &input[2..input.len() - 1])
        } else if input.first() == Some(&(b'{' as u16)) && input.last() == Some(&(b'}' as u16)) {
            (false, &input[1..input.len() - 1])
        } else {
            return None;
        };
    let entries = split_ognl_entries(body)?;
    if map {
        let mut values = Vec::with_capacity(entries.len());
        for entry in entries {
            let colon = find_top_level_sequence(entry, &[b':' as u16])?;
            let key = parse_ognl_range(&entry[..colon], apply_shortcuts, use_selection_as_root)?;
            let value =
                parse_ognl_range(&entry[colon + 1..], apply_shortcuts, use_selection_as_root)?;
            values.push((Box::new(key), Box::new(value)));
        }
        Some(ComputedExpression::MapLiteral(values))
    } else {
        entries
            .into_iter()
            .map(|entry| parse_ognl_range(entry, apply_shortcuts, use_selection_as_root))
            .collect::<Option<Vec<_>>>()
            .map(ComputedExpression::ListLiteral)
    }
}

fn split_ognl_entries(input: &[u16]) -> Option<Vec<&[u16]>> {
    if trim_units(input).is_empty() {
        return Some(Vec::new());
    }
    let mut entries = Vec::new();
    let mut start = 0;
    scan_top_level(input, |position, unit| {
        if unit == b',' as u16 {
            entries.push(trim_units(&input[start..position]));
            start = position + 1;
        }
    });
    entries.push(trim_units(&input[start..]));
    entries
        .iter()
        .all(|entry| !entry.is_empty())
        .then_some(entries)
}

fn parse_static_reference(
    input: &[u16],
    apply_shortcuts: bool,
    use_selection_as_root: bool,
) -> Option<OgnlStaticReference> {
    if input.first() != Some(&(b'@' as u16)) {
        return None;
    }
    let second_at = input[1..].iter().position(|unit| *unit == b'@' as u16)? + 1;
    let type_name = Utf16String::from_utf16(trim_units(&input[1..second_at]).to_vec());
    if type_name.is_empty() {
        return None;
    }
    let mut position = second_at + 1;
    let member_start = position;
    while position < input.len() && is_ascii_identifier_part(input[position]) {
        position += 1;
    }
    if position == member_start {
        return None;
    }
    let member_name = Utf16String::from_utf16(input[member_start..position].to_vec());
    let arguments = if input.get(position) == Some(&(b'(' as u16)) {
        let end = find_closing_parenthesis(input, position)?;
        let arguments = split_method_arguments(&input[position + 1..end])?
            .into_iter()
            .map(|argument| {
                parse_expression(
                    &Utf16String::from_utf16(argument.to_vec()),
                    apply_shortcuts,
                    use_selection_as_root,
                )
                .expression
            })
            .collect();
        position = end + 1;
        Some(arguments)
    } else {
        None
    };
    let trailing_steps =
        parse_suffix_steps(input, &mut position, apply_shortcuts, use_selection_as_root)?;
    Some(OgnlStaticReference {
        type_name,
        member_name,
        arguments,
        trailing_steps,
    })
}

fn parse_constructor(
    input: &[u16],
    apply_shortcuts: bool,
    use_selection_as_root: bool,
) -> Option<OgnlConstructor> {
    if !starts_with_word(input, "new") {
        return None;
    }
    let mut position = 3;
    while input.get(position).is_some_and(|unit| *unit <= 0x20) {
        position += 1;
    }
    let type_start = position;
    while input
        .get(position)
        .is_some_and(|unit| is_ascii_identifier_part(*unit) || *unit == b'.' as u16)
    {
        position += 1;
    }
    if position == type_start {
        return None;
    }
    let mut type_name_units = input[type_start..position].to_vec();
    let (arguments, end) = if input.get(position) == Some(&(b'(' as u16)) {
        let end = find_closing_parenthesis(input, position)?;
        let arguments = split_method_arguments(&input[position + 1..end])?;
        (arguments, end)
    } else if input.get(position..position + 2) == Some(&[b'[' as u16, b']' as u16][..]) {
        type_name_units.extend_from_slice(&[b'[' as u16, b']' as u16]);
        position += 2;
        while input.get(position).is_some_and(|unit| *unit <= 0x20) {
            position += 1;
        }
        if input.get(position) != Some(&(b'{' as u16)) {
            return None;
        }
        let end = find_closing_delimiter(input, position, b'{' as u16, b'}' as u16)?;
        let arguments = split_method_arguments(&input[position + 1..end])?;
        (arguments, end)
    } else {
        return None;
    };
    let type_name = Utf16String::from_utf16(type_name_units);
    let arguments = arguments
        .into_iter()
        .map(|argument| {
            parse_expression(
                &Utf16String::from_utf16(argument.to_vec()),
                apply_shortcuts,
                use_selection_as_root,
            )
            .expression
        })
        .collect();
    position = end + 1;
    let trailing_steps =
        parse_suffix_steps(input, &mut position, apply_shortcuts, use_selection_as_root)?;
    Some(OgnlConstructor {
        type_name,
        arguments,
        trailing_steps,
    })
}

fn parse_suffix_steps(
    input: &[u16],
    position: &mut usize,
    apply_shortcuts: bool,
    use_selection_as_root: bool,
) -> Option<Vec<PathStep>> {
    let mut steps = Vec::new();
    while *position < input.len() {
        if input[*position] == b'.' as u16 {
            *position += 1;
            if input.get(*position) == Some(&(b'{' as u16)) {
                let end = find_closing_delimiter(input, *position, b'{' as u16, b'}' as u16)?;
                let body = trim_units(&input[*position + 1..end]);
                let (selection, body) = match body.first().copied() {
                    Some(value) if value == b'?' as u16 => {
                        (Some(SelectionKind::All), trim_units(&body[1..]))
                    }
                    Some(value) if value == b'^' as u16 => {
                        (Some(SelectionKind::First), trim_units(&body[1..]))
                    }
                    Some(value) if value == b'$' as u16 => {
                        (Some(SelectionKind::Last), trim_units(&body[1..]))
                    }
                    _ => (None, body),
                };
                let expression = parse_ognl_range(body, false, true)?;
                steps.push(match selection {
                    Some(kind) => PathStep::Selection(kind, Box::new(expression)),
                    None => PathStep::Projection(Box::new(expression)),
                });
                *position = end + 1;
                continue;
            }
            let start = *position;
            while *position < input.len() && is_ascii_identifier_part(input[*position]) {
                *position += 1;
            }
            if *position == start {
                return None;
            }
            let name = Utf16String::from_utf16(input[start..*position].to_vec());
            if input.get(*position) == Some(&(b'(' as u16)) {
                let end = find_closing_parenthesis(input, *position)?;
                let arguments = split_method_arguments(&input[*position + 1..end])?
                    .into_iter()
                    .map(|argument| {
                        parse_expression(
                            &Utf16String::from_utf16(argument.to_vec()),
                            apply_shortcuts,
                            use_selection_as_root,
                        )
                        .expression
                    })
                    .collect();
                steps.push(PathStep::Method(name, arguments));
                *position = end + 1;
            } else {
                steps.push(PathStep::Property(name));
            }
            continue;
        }
        if input[*position] != b'[' as u16 {
            return None;
        }
        let start = *position + 1;
        let end = find_closing_delimiter(input, *position, b'[' as u16, b']' as u16)?;
        let index = trim_units(&input[start..end]);
        *position = end + 1;
        if index.len() == 1
            && let Some(subscript) = match index[0] {
                value if value == b'^' as u16 => Some(OgnlDynamicSubscript::First),
                value if value == b'|' as u16 => Some(OgnlDynamicSubscript::Mid),
                value if value == b'$' as u16 => Some(OgnlDynamicSubscript::Last),
                value if value == b'*' as u16 => Some(OgnlDynamicSubscript::All),
                _ => None,
            }
        {
            steps.push(PathStep::DynamicSubscript(subscript));
        } else if let Some(OgnlLiteral::String(value)) =
            parse_literal(&Utf16String::from_utf16(index.to_vec()))
        {
            steps.push(PathStep::StringIndex(value));
        } else if let Ok(value) = String::from_utf16_lossy(index).parse::<usize>() {
            steps.push(PathStep::NumericIndex(value));
        } else {
            steps.push(PathStep::DynamicIndex(Box::new(parse_ognl_range(
                index,
                apply_shortcuts,
                use_selection_as_root,
            )?)));
        }
    }
    Some(steps)
}

fn unescape_ognl_string(input: &[u16]) -> Option<Vec<u16>> {
    let mut output = Vec::with_capacity(input.len());
    let mut position = 0;
    while position < input.len() {
        if input[position] != b'\\' as u16 {
            output.push(input[position]);
            position += 1;
            continue;
        }
        position += 1;
        let escaped = *input.get(position)?;
        match escaped {
            value if value == b'n' as u16 => output.push(b'\n' as u16),
            value if value == b'r' as u16 => output.push(b'\r' as u16),
            value if value == b't' as u16 => output.push(b'\t' as u16),
            value if value == b'b' as u16 => output.push(0x08),
            value if value == b'f' as u16 => output.push(0x0c),
            value if matches!(value, 0x27 | 0x22 | 0x5c) => output.push(value),
            _ => {
                // OGNL 不把未知转义当作“删除反斜杠”。这对 `\uXXXX`
                // 这样的模板数据尤其重要:它是待输出的文本,不是 Rust/Java
                // 源代码层面的 Unicode 转义。
                output.push(b'\\' as u16);
                output.push(escaped);
            }
        }
        position += 1;
    }
    Some(output)
}

fn parse_path(
    source: &Utf16String,
    apply_shortcuts: bool,
    use_selection_as_root: bool,
) -> Option<OgnlPath> {
    let input = source.as_utf16();
    let mut position = 0;
    let expression_object = input.first() == Some(&(b'#' as u16));
    if expression_object {
        position += 1;
    }
    let root_start = position;
    while position < input.len() && is_ascii_identifier_part(input[position]) {
        position += 1;
    }
    if position == root_start {
        return None;
    }
    let name = Utf16String::from_utf16(input[root_start..position].to_vec());
    let root = if expression_object {
        PathRoot::ExpressionObject(name)
    } else {
        PathRoot::Context(name)
    };
    let mut steps = Vec::new();
    if input.get(position) == Some(&(b'(' as u16)) {
        let end = find_closing_parenthesis(input, position)?;
        let arguments = split_method_arguments(&input[position + 1..end])?
            .into_iter()
            .map(|argument| {
                parse_expression(
                    &Utf16String::from_utf16(argument.to_vec()),
                    apply_shortcuts,
                    use_selection_as_root,
                )
                .expression
            })
            .collect();
        steps.push(PathStep::Method(
            Utf16String::from_rust_str("__invoke_root__"),
            arguments,
        ));
        position = end + 1;
    }
    steps.extend(parse_suffix_steps(
        input,
        &mut position,
        apply_shortcuts,
        use_selection_as_root,
    )?);
    Some(OgnlPath { root, steps })
}

fn find_closing_parenthesis(input: &[u16], start: usize) -> Option<usize> {
    find_closing_delimiter(input, start, b'(' as u16, b')' as u16)
}

fn find_closing_delimiter(
    input: &[u16],
    start: usize,
    opening: u16,
    closing: u16,
) -> Option<usize> {
    let mut depth = 0usize;
    let mut quote = None;
    let mut position = start + 1;
    while position < input.len() {
        let unit = input[position];
        if let Some(active_quote) = quote {
            if unit == active_quote {
                if input.get(position + 1) == Some(&active_quote) {
                    position += 2;
                    continue;
                }
                quote = None;
            }
        } else if matches!(unit, 0x27 | 0x22) {
            quote = Some(unit);
        } else if unit == opening {
            depth += 1;
        } else if unit == closing {
            if depth == 0 {
                return Some(position);
            }
            depth -= 1;
        }
        position += 1;
    }
    None
}

fn split_method_arguments(input: &[u16]) -> Option<Vec<&[u16]>> {
    if trim_units(input).is_empty() {
        return Some(Vec::new());
    }
    let mut arguments = Vec::new();
    let mut start = 0usize;
    let mut parentheses = 0usize;
    let mut brackets = 0usize;
    let mut braces = 0usize;
    let mut quote = None;
    let mut position = 0usize;
    while position < input.len() {
        let unit = input[position];
        if let Some(active_quote) = quote {
            if unit == active_quote {
                if input.get(position + 1) == Some(&active_quote) {
                    position += 2;
                    continue;
                }
                quote = None;
            }
        } else if matches!(unit, 0x27 | 0x22) {
            quote = Some(unit);
        } else if unit == b'(' as u16 {
            parentheses += 1;
        } else if unit == b')' as u16 {
            parentheses = parentheses.checked_sub(1)?;
        } else if unit == b'[' as u16 {
            brackets += 1;
        } else if unit == b']' as u16 {
            brackets = brackets.checked_sub(1)?;
        } else if unit == b'{' as u16 {
            braces += 1;
        } else if unit == b'}' as u16 {
            braces = braces.checked_sub(1)?;
        } else if unit == b',' as u16 && parentheses == 0 && brackets == 0 && braces == 0 {
            arguments.push(trim_units(&input[start..position]));
            start = position + 1;
        }
        position += 1;
    }
    if quote.is_some() || parentheses != 0 || brackets != 0 || braces != 0 {
        return None;
    }
    arguments.push(trim_units(&input[start..]));
    Some(arguments)
}

fn evaluate_path(
    context: &dyn IExpressionContext,
    path: &OgnlPath,
    use_selection_as_root: bool,
    expression_context: &'static StandardExpressionExecutionContext,
) -> StandardExpressionResult<Option<Arc<TemplateValue>>> {
    let restrict_variable_access = expression_context.get_restrict_variable_access();
    let value = match &path.root {
        PathRoot::Context(name) => {
            if restrict_variable_access && name == &Utf16String::from_rust_str("param") {
                return Err(processing_error(
                    "Access to variable \"param\" is forbidden in this context.".to_owned(),
                ));
            }
            if use_selection_as_root {
                let selection = current_projection_root().or_else(|| {
                    context
                        .as_template_context()
                        .filter(|template_context| template_context.has_selection_target())
                        .and_then(crate::context::ITemplateContext::get_selection_target)
                });
                match selection {
                    Some(selection) => read_dynamic_property(selection.as_ref(), name)?,
                    None => context.get_variable(Some(name)),
                }
            } else {
                context.get_variable(Some(name))
            }
        }
        PathRoot::ExpressionObject(name) => {
            if let Some(value) = current_ognl_local(name) {
                return evaluate_path_steps(
                    context,
                    path,
                    value,
                    use_selection_as_root,
                    expression_context,
                );
            }
            if name == &Utf16String::from_rust_str("this") {
                let root = if let Some(root) = current_projection_root() {
                    Some(root)
                } else if use_selection_as_root {
                    let selection = context
                        .as_template_context()
                        .filter(|template_context| template_context.has_selection_target())
                        .and_then(crate::context::ITemplateContext::get_selection_target);
                    match selection {
                        Some(selection) => Some(selection),
                        None => context
                            .get_expression_objects()
                            .get_object(Some(&Utf16String::from_rust_str("root")))?,
                    }
                } else {
                    context
                        .get_expression_objects()
                        .get_object(Some(&Utf16String::from_rust_str("root")))?
                };
                return evaluate_path_steps(
                    context,
                    path,
                    root,
                    use_selection_as_root,
                    expression_context,
                );
            }
            if restrict_variable_access && NativeExpressionObjectsWrapper::is_restricted(Some(name))
            {
                return Err(processing_error(format!(
                    "Access to variable '#{}' is forbidden in this context.",
                    name.to_string_lossy()
                )));
            }
            context.get_expression_objects().get_object(Some(name))?
        }
    };
    evaluate_path_steps(
        context,
        path,
        value,
        use_selection_as_root,
        expression_context,
    )
}

fn evaluate_path_steps(
    context: &dyn IExpressionContext,
    path: &OgnlPath,
    value: Option<Arc<TemplateValue>>,
    use_selection_as_root: bool,
    expression_context: &'static StandardExpressionExecutionContext,
) -> StandardExpressionResult<Option<Arc<TemplateValue>>> {
    let root_method_name = path_root_method_name(&path.root);
    evaluate_navigation_steps(
        context,
        &path.steps,
        value,
        use_selection_as_root,
        expression_context,
        Some(&root_method_name),
    )
}

fn evaluate_navigation_steps(
    context: &dyn IExpressionContext,
    steps: &[PathStep],
    value: Option<Arc<TemplateValue>>,
    use_selection_as_root: bool,
    expression_context: &'static StandardExpressionExecutionContext,
    root_method_name: Option<&Utf16String>,
) -> StandardExpressionResult<Option<Arc<TemplateValue>>> {
    let mut value = normalize_java_null(value);
    for step in steps {
        let target = value.as_deref().ok_or_else(|| {
            ognl_processing_error(
                "source is null while evaluating OGNL property path".to_owned(),
                "source is null while evaluating OGNL property path".to_owned(),
            )
        })?;
        value = normalize_java_null(match step {
            PathStep::Property(name) | PathStep::StringIndex(name) => {
                read_dynamic_property(target, name)?
            }
            PathStep::Method(name, arguments) => {
                let arguments = arguments
                    .iter()
                    .map(|argument| {
                        evaluate_computed_expression(
                            context,
                            argument,
                            use_selection_as_root,
                            expression_context,
                        )
                    })
                    .collect::<Result<Vec<_>, _>>()?;
                if name == &Utf16String::from_rust_str("__invoke_root__") {
                    let root_method_name = root_method_name.ok_or_else(|| {
                        processing_error("OGNL root invocation has no root method name".to_owned())
                    })?;
                    invoke_dynamic_method(target, root_method_name, &arguments)?
                } else {
                    invoke_dynamic_method(target, name, &arguments)?
                }
            }
            PathStep::Projection(expression) => {
                let values = iterable_values(target).ok_or_else(|| {
                    processing_error(format!(
                        "projection cannot be applied to {}",
                        target.class_name()
                    ))
                })?;
                let projected = values
                    .iter()
                    .map(|item| {
                        with_projection_root(Arc::clone(item), || {
                            evaluate_computed_expression(
                                context,
                                expression,
                                true,
                                expression_context,
                            )
                            .map(|value| value.unwrap_or_else(|| Arc::new(TemplateValue::Null)))
                        })
                    })
                    .collect::<Result<Vec<_>, _>>()?;
                Some(Arc::new(TemplateValue::List(Arc::new(projected))))
            }
            PathStep::Selection(kind, expression) => {
                let values = iterable_values(target).ok_or_else(|| {
                    processing_error(format!(
                        "selection cannot be applied to {}",
                        target.class_name()
                    ))
                })?;
                let mut selected = Vec::new();
                for item in values {
                    let result = with_projection_root(Arc::clone(&item), || {
                        evaluate_computed_expression(context, expression, true, expression_context)
                    })?;
                    if evaluate_as_boolean(result.as_ref())? {
                        selected.push(item);
                        if matches!(kind, SelectionKind::First) {
                            break;
                        }
                    }
                }
                if matches!(kind, SelectionKind::Last) {
                    selected = selected.into_iter().last().into_iter().collect();
                }
                Some(Arc::new(TemplateValue::List(Arc::new(selected))))
            }
            PathStep::DynamicIndex(expression) => {
                let index = evaluate_computed_expression(
                    context,
                    expression,
                    use_selection_as_root,
                    expression_context,
                )?
                .unwrap_or_else(|| Arc::new(TemplateValue::Null));
                match target {
                    TemplateValue::Map(entries) => entries
                        .iter()
                        .find(|(key, _)| key.template_equals(index.as_ref()))
                        .map(|(_, value)| Arc::clone(value)),
                    TemplateValue::List(values) => {
                        let index = ognl_list_index(&index).ok_or_else(|| {
                            processing_error("list index is not an integer".to_owned())
                        })?;
                        Some(values.get(index).cloned().ok_or_else(|| {
                            processing_error(format!("index {index} is out of bounds"))
                        })?)
                    }
                    _ => {
                        return Err(processing_error(format!(
                            "dynamic index cannot be applied to {}",
                            target.class_name()
                        )));
                    }
                }
            }
            PathStep::DynamicSubscript(subscript) => {
                evaluate_dynamic_subscript(target, *subscript)?
            }
            PathStep::NumericIndex(index) => match target {
                TemplateValue::List(values) => values
                    .get(*index)
                    .cloned()
                    .ok_or_else(|| processing_error(format!("index {index} is out of bounds")))?,
                TemplateValue::Bytes(values) => values
                    .get(*index)
                    .map(|value| Arc::new(TemplateValue::Number(NumberValue::Byte(*value))))
                    .ok_or_else(|| processing_error(format!("index {index} is out of bounds")))?,
                TemplateValue::String(value) | TemplateValue::SafeHtml(value) => value
                    .as_utf16()
                    .get(*index)
                    .map(|value| Arc::new(TemplateValue::Character(*value)))
                    .ok_or_else(|| processing_error(format!("index {index} is out of bounds")))?,
                TemplateValue::Object(value) if value.iterable_values().is_some() => value
                    .iterable_values()
                    .and_then(|values| values.get(*index).cloned())
                    .ok_or_else(|| processing_error(format!("index {index} is out of bounds")))?,
                _ => {
                    return Err(processing_error(format!(
                        "numeric index cannot be applied to {}",
                        target.class_name()
                    )));
                }
            }
            .into(),
        });
    }
    Ok(value)
}

fn normalize_java_null(value: Option<Arc<TemplateValue>>) -> Option<Arc<TemplateValue>> {
    value.filter(|value| !matches!(value.as_ref(), TemplateValue::Null))
}

fn evaluate_dynamic_subscript(
    target: &TemplateValue,
    subscript: OgnlDynamicSubscript,
) -> StandardExpressionResult<Option<Arc<TemplateValue>>> {
    let values = match target {
        TemplateValue::List(values) => values.as_ref().clone(),
        TemplateValue::Bytes(values) => values
            .iter()
            .map(|value| Arc::new(TemplateValue::Number(NumberValue::Byte(*value))))
            .collect(),
        TemplateValue::String(value) | TemplateValue::SafeHtml(value) => value
            .as_utf16()
            .iter()
            .map(|value| Arc::new(TemplateValue::Character(*value)))
            .collect(),
        _ => {
            return Err(processing_error(format!(
                "dynamic subscript cannot be applied to {}",
                target.class_name()
            )));
        }
    };
    if matches!(subscript, OgnlDynamicSubscript::All) {
        return Ok(Some(Arc::new(TemplateValue::List(Arc::new(values)))));
    }
    if values.is_empty() {
        return Ok(None);
    }
    let index = match subscript {
        OgnlDynamicSubscript::First => 0,
        OgnlDynamicSubscript::Mid => values.len() / 2,
        OgnlDynamicSubscript::Last => values.len() - 1,
        OgnlDynamicSubscript::All => unreachable!("all was handled above"),
    };
    Ok(values.get(index).cloned())
}

fn iterable_values(target: &TemplateValue) -> Option<Vec<Arc<TemplateValue>>> {
    match target {
        TemplateValue::List(values) => Some(values.as_ref().clone()),
        // OGNL 将 Map 作为其 values 集合参与 projection/selection。
        TemplateValue::Map(entries) => {
            Some(entries.iter().map(|(_, value)| Arc::clone(value)).collect())
        }
        TemplateValue::Bytes(values) => Some(
            values
                .iter()
                .map(|value| Arc::new(TemplateValue::Number(NumberValue::Byte(*value))))
                .collect(),
        ),
        TemplateValue::Object(value) => value.iterable_values(),
        _ => None,
    }
}

thread_local! {
    static PROJECTION_ROOTS: RefCell<Vec<Arc<TemplateValue>>> = const { RefCell::new(Vec::new()) };
}

fn current_projection_root() -> Option<Arc<TemplateValue>> {
    PROJECTION_ROOTS.with(|roots| roots.borrow().last().cloned())
}

fn with_projection_root<T>(root: Arc<TemplateValue>, operation: impl FnOnce() -> T) -> T {
    PROJECTION_ROOTS.with(|roots| roots.borrow_mut().push(root));
    struct ProjectionRootGuard;
    impl Drop for ProjectionRootGuard {
        fn drop(&mut self) {
            PROJECTION_ROOTS.with(|roots| {
                roots.borrow_mut().pop();
            });
        }
    }
    let _guard = ProjectionRootGuard;
    operation()
}

fn evaluate_computed_expression(
    context: &dyn IExpressionContext,
    expression: &ComputedExpression,
    use_selection_as_root: bool,
    expression_context: &'static StandardExpressionExecutionContext,
) -> StandardExpressionResult<Option<Arc<TemplateValue>>> {
    let restrict_variable_access = expression_context.get_restrict_variable_access();
    match expression {
        ComputedExpression::Shortcut(shortcut) => shortcut
            .evaluate(context, use_selection_as_root, restrict_variable_access)
            .map_err(|error| processing_error(error.to_string())),
        ComputedExpression::Path(path) => {
            evaluate_path(context, path, use_selection_as_root, expression_context)
        }
        ComputedExpression::Literal(value) => Ok(value.to_template_value()),
        ComputedExpression::Operation(expression) => {
            expression.execute_with_context(context, expression_context)
        }
        ComputedExpression::StaticReference(reference) => evaluate_static_reference(
            context,
            reference,
            use_selection_as_root,
            expression_context,
        ),
        ComputedExpression::Constructor(constructor) => evaluate_constructor(
            context,
            constructor,
            use_selection_as_root,
            expression_context,
        ),
        ComputedExpression::ListLiteral(values) => {
            evaluate_list_literal(context, values, use_selection_as_root, expression_context)
        }
        ComputedExpression::MapLiteral(entries) => {
            evaluate_map_literal(context, entries, use_selection_as_root, expression_context)
        }
        ComputedExpression::Inclusion {
            left,
            right,
            negated,
        } => evaluate_inclusion(
            context,
            left,
            right,
            *negated,
            use_selection_as_root,
            expression_context,
        ),
        ComputedExpression::Sequence(values) => {
            evaluate_sequence(context, values, use_selection_as_root, expression_context)
        }
        ComputedExpression::Assignment { name, value } => evaluate_assignment(
            context,
            name,
            value,
            use_selection_as_root,
            expression_context,
        ),
        ComputedExpression::NativeBinary {
            operator,
            left,
            right,
        } => evaluate_native_binary(
            context,
            *operator,
            left,
            right,
            use_selection_as_root,
            expression_context,
        ),
        ComputedExpression::BitNegate(value) => {
            evaluate_bit_negate(context, value, use_selection_as_root, expression_context)
        }
        ComputedExpression::InstanceOf { value, type_name } => evaluate_instance_of(
            context,
            value,
            type_name,
            use_selection_as_root,
            expression_context,
        ),
        ComputedExpression::Navigation { root, steps } => evaluate_navigation(
            context,
            root,
            steps,
            use_selection_as_root,
            expression_context,
        ),
        ComputedExpression::Unsupported => Err(processing_error(
            "unsupported OGNL method argument syntax".to_owned(),
        )),
    }
}

fn evaluate_navigation(
    context: &dyn IExpressionContext,
    root: &ComputedExpression,
    steps: &[PathStep],
    use_selection_as_root: bool,
    expression_context: &'static StandardExpressionExecutionContext,
) -> StandardExpressionResult<Option<Arc<TemplateValue>>> {
    let value =
        evaluate_computed_expression(context, root, use_selection_as_root, expression_context)?;
    evaluate_navigation_steps(
        context,
        steps,
        value,
        use_selection_as_root,
        expression_context,
        None,
    )
}

fn evaluate_sequence(
    context: &dyn IExpressionContext,
    values: &[ComputedExpression],
    use_selection_as_root: bool,
    expression_context: &'static StandardExpressionExecutionContext,
) -> StandardExpressionResult<Option<Arc<TemplateValue>>> {
    let mut result = None;
    for value in values {
        result = evaluate_computed_expression(
            context,
            value,
            use_selection_as_root,
            expression_context,
        )?;
    }
    Ok(result)
}

fn evaluate_assignment(
    context: &dyn IExpressionContext,
    name: &Utf16String,
    value: &ComputedExpression,
    use_selection_as_root: bool,
    expression_context: &'static StandardExpressionExecutionContext,
) -> StandardExpressionResult<Option<Arc<TemplateValue>>> {
    if context.get_expression_objects().contains_object(Some(name)) {
        return Err(processing_error(format!(
            "Cannot put entry with key \"{}\" into Expression Objects wrapper map: key matches the name of one of the expression objects",
            name.to_string_lossy()
        )));
    }
    let value =
        evaluate_computed_expression(context, value, use_selection_as_root, expression_context)?;
    set_ognl_local(name.clone(), value.clone());
    Ok(value)
}

fn evaluate_native_binary(
    context: &dyn IExpressionContext,
    operator: OgnlBinaryOperator,
    left: &ComputedExpression,
    right: &ComputedExpression,
    use_selection_as_root: bool,
    expression_context: &'static StandardExpressionExecutionContext,
) -> StandardExpressionResult<Option<Arc<TemplateValue>>> {
    let left =
        evaluate_computed_expression(context, left, use_selection_as_root, expression_context)?
            .unwrap_or_else(|| Arc::new(TemplateValue::Null));
    let right =
        evaluate_computed_expression(context, right, use_selection_as_root, expression_context)?
            .unwrap_or_else(|| Arc::new(TemplateValue::Null));
    if matches!(operator, OgnlBinaryOperator::Divide) {
        return evaluate_ognl_division(left, right);
    }
    let left = numeric_i64(left.as_ref())?;
    let right = numeric_i64(right.as_ref())?;
    let value = match operator {
        OgnlBinaryOperator::Divide => unreachable!("division is handled before integral coercion"),
        OgnlBinaryOperator::BitOr => left | right,
        OgnlBinaryOperator::BitXor => left ^ right,
        OgnlBinaryOperator::BitAnd => left & right,
        OgnlBinaryOperator::ShiftLeft => {
            left.wrapping_shl(u32::try_from(right & 0x3f).unwrap_or_default())
        }
        OgnlBinaryOperator::ShiftRight => {
            left.wrapping_shr(u32::try_from(right & 0x3f).unwrap_or_default())
        }
        OgnlBinaryOperator::UnsignedShiftRight => {
            ((left as u64) >> u32::try_from(right & 0x3f).unwrap_or_default()) as i64
        }
    };
    Ok(Some(Arc::new(TemplateValue::Number(NumberValue::Long(
        value,
    )))))
}

fn evaluate_ognl_division(
    left: Arc<TemplateValue>,
    right: Arc<TemplateValue>,
) -> StandardExpressionResult<Option<Arc<TemplateValue>>> {
    let left_number = match left.as_ref() {
        TemplateValue::Number(value) => Some(value),
        _ => None,
    };
    let right_number = match right.as_ref() {
        TemplateValue::Number(value) => Some(value),
        _ => None,
    };
    if let (Some(left_number), Some(right_number)) = (left_number, right_number)
        && is_integral_number(left_number)
        && is_integral_number(right_number)
    {
        if matches!(left_number, NumberValue::BigInteger(_))
            || matches!(right_number, NumberValue::BigInteger(_))
        {
            let dividend = integral_bigint(left_number);
            let divisor = integral_bigint(right_number);
            if divisor == BigInt::from(0) {
                return Err(processing_error("Division by zero".to_owned()));
            }
            return Ok(Some(Arc::new(TemplateValue::Number(
                NumberValue::BigInteger(dividend / divisor),
            ))));
        }
        let divisor = numeric_i64(right.as_ref())?;
        if divisor == 0 {
            return Err(processing_error("Division by zero".to_owned()));
        }
        let quotient = numeric_i64(left.as_ref())? / divisor;
        let result = if matches!(left_number, NumberValue::Long(_))
            || matches!(right_number, NumberValue::Long(_))
        {
            NumberValue::Long(quotient)
        } else {
            NumberValue::Integer(i32::try_from(quotient).map_err(|error| {
                processing_error(format!("Integer division result is out of range: {error}"))
            })?)
        };
        return Ok(Some(Arc::new(TemplateValue::Number(result))));
    }

    let left_number = evaluate_as_number(Some(&left))?
        .ok_or_else(|| processing_error("Left division operand is not numeric".to_owned()))?;
    let right_number = evaluate_as_number(Some(&right))?
        .ok_or_else(|| processing_error("Right division operand is not numeric".to_owned()))?;
    let result = match left_number.divide_java(&right_number) {
        Ok(result) => result,
        Err(_) => {
            let scale = left_number.scale().max(right_number.scale()).max(10);
            left_number.divide_java_half_up(&right_number, scale)?
        }
    };
    Ok(Some(Arc::new(TemplateValue::Number(
        NumberValue::BigDecimal(result),
    ))))
}

fn is_integral_number(number: &NumberValue) -> bool {
    matches!(
        number,
        NumberValue::BigInteger(_)
            | NumberValue::Byte(_)
            | NumberValue::Short(_)
            | NumberValue::Integer(_)
            | NumberValue::Long(_)
    )
}

fn integral_bigint(number: &NumberValue) -> BigInt {
    match number {
        NumberValue::BigInteger(value) => value.clone(),
        NumberValue::Byte(value) => BigInt::from(*value),
        NumberValue::Short(value) => BigInt::from(*value),
        NumberValue::Integer(value) => BigInt::from(*value),
        NumberValue::Long(value) => BigInt::from(*value),
        _ => unreachable!("caller verifies the integral number family"),
    }
}

fn evaluate_bit_negate(
    context: &dyn IExpressionContext,
    value: &ComputedExpression,
    use_selection_as_root: bool,
    expression_context: &'static StandardExpressionExecutionContext,
) -> StandardExpressionResult<Option<Arc<TemplateValue>>> {
    let value =
        evaluate_computed_expression(context, value, use_selection_as_root, expression_context)?
            .unwrap_or_else(|| Arc::new(TemplateValue::Null));
    Ok(Some(Arc::new(TemplateValue::Number(NumberValue::Long(
        !numeric_i64(value.as_ref())?,
    )))))
}

fn evaluate_instance_of(
    context: &dyn IExpressionContext,
    value: &ComputedExpression,
    type_name: &Utf16String,
    use_selection_as_root: bool,
    expression_context: &'static StandardExpressionExecutionContext,
) -> StandardExpressionResult<Option<Arc<TemplateValue>>> {
    ThymeleafACLClassResolver::class_for_name(&type_name.to_string_lossy())?;
    let value =
        evaluate_computed_expression(context, value, use_selection_as_root, expression_context)?;
    let result = match value.as_deref() {
        None | Some(TemplateValue::Null) => false,
        Some(value) => {
            if let Some(result) =
                current_ognl_runtime().and_then(|runtime| runtime.is_instance_of(value, type_name))
            {
                result.map_err(|error| processing_error(error.to_string()))?
            } else {
                builtin_instance_of(value, &type_name.to_string_lossy())
            }
        }
    };
    Ok(Some(Arc::new(TemplateValue::Boolean(result))))
}

fn builtin_instance_of(value: &TemplateValue, type_name: &str) -> bool {
    if value.class_name() == type_name || type_name == "java.lang.Object" {
        return true;
    }
    match value {
        TemplateValue::String(_) | TemplateValue::SafeHtml(_) => {
            matches!(
                type_name,
                "java.lang.String"
                    | "java.lang.CharSequence"
                    | "java.io.Serializable"
                    | "java.lang.Comparable"
            )
        }
        TemplateValue::Number(_) => matches!(
            type_name,
            "java.lang.Number" | "java.io.Serializable" | "java.lang.Comparable"
        ),
        TemplateValue::Boolean(_) | TemplateValue::Character(_) => {
            matches!(type_name, "java.io.Serializable" | "java.lang.Comparable")
        }
        TemplateValue::List(_) => matches!(
            type_name,
            "java.util.List"
                | "java.util.Collection"
                | "java.lang.Iterable"
                | "java.io.Serializable"
        ),
        TemplateValue::Map(_) => {
            matches!(type_name, "java.util.Map" | "java.io.Serializable")
        }
        TemplateValue::Bytes(_) => matches!(
            type_name,
            "byte[]" | "[B" | "java.lang.Cloneable" | "java.io.Serializable"
        ),
        TemplateValue::Object(value) => value.class_name() == type_name,
        TemplateValue::Literal(_) | TemplateValue::NoOp | TemplateValue::Null => false,
    }
}

/// 将动态索引转换为列表下标,对应 Java OGNL `OgnlOps.getIntValue`
/// (Double/BigDecimal 截断为 int;字符串按数字解析)。
fn ognl_list_index(value: &TemplateValue) -> Option<usize> {
    match value {
        TemplateValue::Number(number) => Some(truncated_i64(number)? as usize),
        other => other
            .to_utf16_string()
            .and_then(|value| value.to_string_lossy().parse::<usize>().ok()),
    }
}

fn truncated_i64(number: &NumberValue) -> Option<i64> {
    match number {
        NumberValue::Byte(value) => Some(i64::from(*value)),
        NumberValue::Short(value) => Some(i64::from(*value)),
        NumberValue::Integer(value) => Some(i64::from(*value)),
        NumberValue::Long(value) => Some(*value),
        NumberValue::Float(value) => Some(*value as i64),
        NumberValue::Double(value) => Some(*value as i64),
        NumberValue::BigDecimal(value) => {
            let divisor = BigInt::from(10_u32).pow(u32::try_from(value.scale()).unwrap_or(0));
            (value.unscaled_value() / divisor).to_string().parse().ok()
        }
        NumberValue::BigInteger(value) => value.to_string().parse().ok(),
        NumberValue::Other { double_value, .. } => Some(*double_value as i64),
    }
}

fn numeric_i64(value: &TemplateValue) -> StandardExpressionResult<i64> {
    match value {
        TemplateValue::Number(NumberValue::Byte(value)) => Ok(i64::from(*value)),
        TemplateValue::Number(NumberValue::Short(value)) => Ok(i64::from(*value)),
        TemplateValue::Number(NumberValue::Integer(value)) => Ok(i64::from(*value)),
        TemplateValue::Number(NumberValue::Long(value)) => Ok(*value),
        TemplateValue::Number(NumberValue::Float(value)) => Ok(*value as i64),
        TemplateValue::Number(NumberValue::Double(value))
        | TemplateValue::Number(NumberValue::Other {
            double_value: value,
            ..
        }) => Ok(*value as i64),
        TemplateValue::Number(NumberValue::BigInteger(value)) => {
            value.to_string().parse().map_err(|error| {
                processing_error(format!("Value cannot be represented as long: {error}"))
            })
        }
        TemplateValue::Number(NumberValue::BigDecimal(value)) => value
            .to_string()
            .parse::<f64>()
            .map(|value| value as i64)
            .map_err(|error| {
                processing_error(format!("Value cannot be represented as long: {error}"))
            }),
        TemplateValue::Boolean(value) => Ok(i64::from(*value)),
        TemplateValue::Character(value) => Ok(i64::from(*value)),
        _ => Err(processing_error(format!(
            "{} cannot be converted to an integral number",
            value.class_name()
        ))),
    }
}

fn evaluate_list_literal(
    context: &dyn IExpressionContext,
    values: &[ComputedExpression],
    use_selection_as_root: bool,
    expression_context: &'static StandardExpressionExecutionContext,
) -> StandardExpressionResult<Option<Arc<TemplateValue>>> {
    let values = values
        .iter()
        .map(|value| {
            evaluate_computed_expression(context, value, use_selection_as_root, expression_context)
                .map(|value| value.unwrap_or_else(|| Arc::new(TemplateValue::Null)))
        })
        .collect::<Result<Vec<_>, _>>()?;
    Ok(Some(Arc::new(TemplateValue::List(Arc::new(values)))))
}

fn evaluate_map_literal(
    context: &dyn IExpressionContext,
    entries: &[(Box<ComputedExpression>, Box<ComputedExpression>)],
    use_selection_as_root: bool,
    expression_context: &'static StandardExpressionExecutionContext,
) -> StandardExpressionResult<Option<Arc<TemplateValue>>> {
    let entries = entries
        .iter()
        .map(|(key, value)| {
            let key = evaluate_computed_expression(
                context,
                key,
                use_selection_as_root,
                expression_context,
            )?
            .unwrap_or_else(|| Arc::new(TemplateValue::Null));
            let value = evaluate_computed_expression(
                context,
                value,
                use_selection_as_root,
                expression_context,
            )?
            .unwrap_or_else(|| Arc::new(TemplateValue::Null));
            Ok((key, value))
        })
        .collect::<StandardExpressionResult<Vec<_>>>()?;
    Ok(Some(Arc::new(TemplateValue::Map(Arc::new(entries)))))
}

fn evaluate_inclusion(
    context: &dyn IExpressionContext,
    left: &ComputedExpression,
    right: &ComputedExpression,
    negated: bool,
    use_selection_as_root: bool,
    expression_context: &'static StandardExpressionExecutionContext,
) -> StandardExpressionResult<Option<Arc<TemplateValue>>> {
    let left =
        evaluate_computed_expression(context, left, use_selection_as_root, expression_context)?
            .unwrap_or_else(|| Arc::new(TemplateValue::Null));
    let right =
        evaluate_computed_expression(context, right, use_selection_as_root, expression_context)?
            .unwrap_or_else(|| Arc::new(TemplateValue::Null));
    let contains = match right.as_ref() {
        TemplateValue::List(values) => values.iter().any(|value| value.template_equals(&left)),
        TemplateValue::Map(entries) => entries
            .iter()
            .any(|(_, value)| value.template_equals(&left)),
        TemplateValue::Bytes(values) => values
            .iter()
            .any(|value| TemplateValue::Number(NumberValue::Byte(*value)).template_equals(&left)),
        TemplateValue::Object(value) => value
            .iterable_values()
            .is_some_and(|values| values.iter().any(|value| value.template_equals(&left))),
        value => value.template_equals(&left),
    };
    Ok(Some(Arc::new(TemplateValue::Boolean(if negated {
        !contains
    } else {
        contains
    }))))
}

fn evaluate_static_reference(
    context: &dyn IExpressionContext,
    reference: &OgnlStaticReference,
    use_selection_as_root: bool,
    expression_context: &'static StandardExpressionExecutionContext,
) -> StandardExpressionResult<Option<Arc<TemplateValue>>> {
    let type_name = reference.type_name.to_string_lossy();
    if expression_context.get_restrict_external_access() {
        return Err(processing_error(format!(
            "Access to type \"{type_name}\" is forbidden"
        )));
    }
    let member = reference.member_name.to_string_lossy();
    let value = if let Some(arguments) = &reference.arguments {
        let arguments = arguments
            .iter()
            .map(|argument| {
                evaluate_computed_expression(
                    context,
                    argument,
                    use_selection_as_root,
                    expression_context,
                )
            })
            .collect::<Result<Vec<_>, _>>()?;
        invoke_static_method(&type_name, &member, &arguments)?
    } else {
        read_static_field(&type_name, &member)?
    };
    evaluate_navigation_steps(
        context,
        &reference.trailing_steps,
        value,
        use_selection_as_root,
        expression_context,
        None,
    )
}

fn evaluate_constructor(
    context: &dyn IExpressionContext,
    constructor: &OgnlConstructor,
    use_selection_as_root: bool,
    expression_context: &'static StandardExpressionExecutionContext,
) -> StandardExpressionResult<Option<Arc<TemplateValue>>> {
    let type_name = constructor.type_name.to_string_lossy();
    if expression_context.get_restrict_external_access() {
        return Err(processing_error(format!(
            "Instantiation of type \"{type_name}\" is forbidden"
        )));
    }
    let arguments = constructor
        .arguments
        .iter()
        .map(|argument| {
            evaluate_computed_expression(
                context,
                argument,
                use_selection_as_root,
                expression_context,
            )
        })
        .collect::<Result<Vec<_>, _>>()?;
    let value = if let Some(result) = current_ognl_runtime()
        .and_then(|runtime| runtime.construct(&constructor.type_name, &arguments))
    {
        result.map_err(|error| processing_error(error.to_string()))?
    } else {
        ThymeleafACLClassResolver::class_for_name(&type_name)?;
        match (type_name.as_str(), arguments.as_slice()) {
            ("java.lang.String", []) => Ok(Some(Arc::new(TemplateValue::string(
                Utf16String::from_rust_str(""),
            )))),
            ("java.lang.String", [value]) => Ok(Some(Arc::new(TemplateValue::string(
                value
                    .as_deref()
                    .and_then(TemplateValue::to_utf16_string)
                    .unwrap_or_else(|| Utf16String::from_rust_str("null")),
            )))),
            ("java.math.BigDecimal", [Some(value)]) => {
                let text = value.to_utf16_string().ok_or_else(|| {
                    processing_error("BigDecimal constructor argument cannot be null".to_owned())
                })?;
                let value = BigDecimalValue::parse(&text.to_string_lossy())
                    .map_err(|error| processing_error(format!("Invalid BigDecimal: {error}")))?;
                Ok(Some(Arc::new(TemplateValue::Number(
                    NumberValue::BigDecimal(value),
                ))))
            }
            ("java.math.BigInteger", [Some(value)]) => {
                let text = value.to_utf16_string().ok_or_else(|| {
                    processing_error("BigInteger constructor argument cannot be null".to_owned())
                })?;
                let value = text
                    .to_string_lossy()
                    .parse()
                    .map_err(|error| processing_error(format!("Invalid BigInteger: {error}")))?;
                Ok(Some(Arc::new(TemplateValue::Number(
                    NumberValue::BigInteger(value),
                ))))
            }
            ("java.util.ArrayList" | "java.util.LinkedList", []) => {
                Ok(Some(Arc::new(TemplateValue::List(Arc::new(Vec::new())))))
            }
            ("java.util.HashMap" | "java.util.LinkedHashMap", []) => {
                Ok(Some(Arc::new(TemplateValue::Map(Arc::new(Vec::new())))))
            }
            ("java.util.HashMap" | "java.util.LinkedHashMap", [Some(value)])
                if matches!(value.as_ref(), TemplateValue::Map(_)) =>
            {
                Ok(Some(Arc::clone(value)))
            }
            _ => Err(processing_error(format!(
                "Constructor for type \"{type_name}\" with {} arguments is not available",
                arguments.len()
            ))),
        }?
    };
    evaluate_navigation_steps(
        context,
        &constructor.trailing_steps,
        value,
        use_selection_as_root,
        expression_context,
        None,
    )
}

fn read_static_field(
    type_name: &str,
    member: &str,
) -> StandardExpressionResult<Option<Arc<TemplateValue>>> {
    let runtime_type_name = Utf16String::from_rust_str(type_name);
    let runtime_member_name = Utf16String::from_rust_str(member);
    if let Some(result) = current_ognl_runtime()
        .and_then(|runtime| runtime.read_static_field(&runtime_type_name, &runtime_member_name))
    {
        return result.map_err(|error| processing_error(error.to_string()));
    }
    ThymeleafACLClassResolver::class_for_name(type_name)?;
    if member == "class" {
        return Ok(Some(class_value(type_name)));
    }
    let value = match (type_name, member) {
        ("java.lang.Math", "PI") => {
            TemplateValue::Number(NumberValue::Double(std::f64::consts::PI))
        }
        ("java.lang.Math", "E") => TemplateValue::Number(NumberValue::Double(std::f64::consts::E)),
        ("java.lang.Boolean", "TRUE") => TemplateValue::Boolean(true),
        ("java.lang.Boolean", "FALSE") => TemplateValue::Boolean(false),
        ("java.lang.Integer", "MAX_VALUE") => TemplateValue::Number(NumberValue::Integer(i32::MAX)),
        ("java.lang.Integer", "MIN_VALUE") => TemplateValue::Number(NumberValue::Integer(i32::MIN)),
        ("java.lang.Long", "MAX_VALUE") => TemplateValue::Number(NumberValue::Long(i64::MAX)),
        ("java.lang.Long", "MIN_VALUE") => TemplateValue::Number(NumberValue::Long(i64::MIN)),
        ("java.math.BigInteger", "ZERO") | ("java.math.BigDecimal", "ZERO") => {
            TemplateValue::Number(NumberValue::Integer(0))
        }
        ("java.math.BigInteger", "ONE") | ("java.math.BigDecimal", "ONE") => {
            TemplateValue::Number(NumberValue::Integer(1))
        }
        ("java.math.BigInteger", "TEN") | ("java.math.BigDecimal", "TEN") => {
            TemplateValue::Number(NumberValue::Integer(10))
        }
        ("java.util.Calendar", "HOUR_OF_DAY") => TemplateValue::Number(NumberValue::Integer(11)),
        ("java.util.Calendar", "MINUTE") => TemplateValue::Number(NumberValue::Integer(12)),
        ("java.util.Calendar", "SECOND") => TemplateValue::Number(NumberValue::Integer(13)),
        ("java.util.Calendar", "MILLISECOND") => TemplateValue::Number(NumberValue::Integer(14)),
        ("java.util.Calendar", "DAY_OF_MONTH" | "DATE") => {
            TemplateValue::Number(NumberValue::Integer(5))
        }
        ("java.util.Calendar", "MONTH") => TemplateValue::Number(NumberValue::Integer(2)),
        ("java.util.Calendar", "YEAR") => TemplateValue::Number(NumberValue::Integer(1)),
        ("org.thymeleaf.TemplateEngine", "TIMER_LOGGER_NAME") => TemplateValue::string(
            Utf16String::from_rust_str("org.thymeleaf.TemplateEngine.TIMER"),
        ),
        _ => {
            return Err(processing_error(format!(
                "Static field \"{member}\" is not available on {type_name}"
            )));
        }
    };
    Ok(Some(Arc::new(value)))
}

fn invoke_static_method(
    type_name: &str,
    member: &str,
    arguments: &[Option<Arc<TemplateValue>>],
) -> StandardExpressionResult<Option<Arc<TemplateValue>>> {
    let runtime_type_name = Utf16String::from_rust_str(type_name);
    let runtime_member_name = Utf16String::from_rust_str(member);
    if let Some(result) = current_ognl_runtime().and_then(|runtime| {
        runtime.invoke_static_method(&runtime_type_name, &runtime_member_name, arguments)
    }) {
        return result.map_err(|error| processing_error(error.to_string()));
    }
    ThymeleafACLClassResolver::class_for_name(type_name)?;
    match (type_name, member, arguments) {
        ("java.lang.Math", "abs", [Some(value)]) => {
            let value = numeric_f64(value)?;
            number_result(value.abs())
        }
        ("java.lang.Math", "ceil", [Some(value)]) => number_result(numeric_f64(value)?.ceil()),
        ("java.lang.Math", "floor", [Some(value)]) => number_result(numeric_f64(value)?.floor()),
        ("java.lang.Math", "sqrt", [Some(value)]) => number_result(numeric_f64(value)?.sqrt()),
        ("java.lang.Math", "cbrt", [Some(value)]) => number_result(numeric_f64(value)?.cbrt()),
        ("java.lang.Math", "sin", [Some(value)]) => number_result(numeric_f64(value)?.sin()),
        ("java.lang.Math", "cos", [Some(value)]) => number_result(numeric_f64(value)?.cos()),
        ("java.lang.Math", "tan", [Some(value)]) => number_result(numeric_f64(value)?.tan()),
        ("java.lang.Math", "log", [Some(value)]) => number_result(numeric_f64(value)?.ln()),
        ("java.lang.Math", "log10", [Some(value)]) => number_result(numeric_f64(value)?.log10()),
        ("java.lang.Math", "exp", [Some(value)]) => number_result(numeric_f64(value)?.exp()),
        ("java.lang.Math", "pow", [Some(left), Some(right)]) => {
            number_result(numeric_f64(left)?.powf(numeric_f64(right)?))
        }
        ("java.lang.Math", "min", [Some(left), Some(right)]) => {
            number_result(numeric_f64(left)?.min(numeric_f64(right)?))
        }
        ("java.lang.Math", "max", [Some(left), Some(right)]) => {
            number_result(numeric_f64(left)?.max(numeric_f64(right)?))
        }
        ("java.lang.Math", "round", [Some(value)]) => Ok(Some(Arc::new(TemplateValue::Number(
            NumberValue::Long(numeric_f64(value)?.round() as i64),
        )))),
        ("java.lang.Integer", "parseInt" | "valueOf", [Some(value)]) => {
            let value = required_utf16_string(value, "Integer text cannot be null")?;
            let parsed = value
                .to_string_lossy()
                .parse::<i32>()
                .map_err(|error| processing_error(error.to_string()))?;
            Ok(Some(Arc::new(TemplateValue::Number(NumberValue::Integer(
                parsed,
            )))))
        }
        ("java.lang.Byte", "parseByte" | "valueOf", [Some(value)]) => {
            let value = required_utf16_string(value, "Byte text cannot be null")?;
            let parsed = value
                .to_string_lossy()
                .parse::<i8>()
                .map_err(|error| processing_error(error.to_string()))?;
            Ok(Some(Arc::new(TemplateValue::Number(NumberValue::Byte(
                parsed,
            )))))
        }
        ("java.lang.Short", "parseShort" | "valueOf", [Some(value)]) => {
            let value = required_utf16_string(value, "Short text cannot be null")?;
            let parsed = value
                .to_string_lossy()
                .parse::<i16>()
                .map_err(|error| processing_error(error.to_string()))?;
            Ok(Some(Arc::new(TemplateValue::Number(NumberValue::Short(
                parsed,
            )))))
        }
        ("java.lang.Long", "parseLong" | "valueOf", [Some(value)]) => {
            let value = required_utf16_string(value, "Long text cannot be null")?;
            let parsed = value
                .to_string_lossy()
                .parse::<i64>()
                .map_err(|error| processing_error(error.to_string()))?;
            Ok(Some(Arc::new(TemplateValue::Number(NumberValue::Long(
                parsed,
            )))))
        }
        ("java.lang.Double", "parseDouble" | "valueOf", [Some(value)]) => {
            let value = required_utf16_string(value, "Double text cannot be null")?;
            let parsed = value
                .to_string_lossy()
                .parse::<f64>()
                .map_err(|error| processing_error(error.to_string()))?;
            number_result(parsed)
        }
        ("java.lang.Boolean", "parseBoolean" | "valueOf", [Some(value)]) => {
            let value = required_utf16_string(value, "Boolean text cannot be null")?;
            Ok(Some(Arc::new(TemplateValue::Boolean(
                value.to_string_lossy().eq_ignore_ascii_case("true"),
            ))))
        }
        ("java.time.LocalDateTime", "of", values @ [_, _, _, _, ..]) => {
            let fields = values
                .iter()
                .map(|value| {
                    value
                        .as_deref()
                        .ok_or_else(|| {
                            processing_error("LocalDateTime field cannot be null".to_owned())
                        })
                        .and_then(|value| {
                            integer_argument(value, "LocalDateTime field is not an integer")
                        })
                        .and_then(|value| {
                            i32::try_from(value)
                                .map_err(|error| processing_error(error.to_string()))
                        })
                })
                .collect::<StandardExpressionResult<Vec<_>>>()?;
            let temporal = TemporalCreationUtils::new()
                .create(&fields)
                .map_err(|error| processing_error(error.to_string()))?;
            Ok(Some(Arc::new(TemplateValue::Object(Arc::new(temporal)))))
        }
        ("java.lang.String", "format", [Some(format), values @ ..]) => {
            let mut output = format
                .to_utf16_string()
                .ok_or_else(|| processing_error("Format cannot be null".to_owned()))?
                .to_string_lossy();
            for value in values {
                let replacement = value
                    .as_deref()
                    .and_then(TemplateValue::to_utf16_string)
                    .map_or_else(|| "null".to_owned(), |value| value.to_string_lossy());
                output = output.replacen("%s", &replacement, 1);
            }
            Ok(Some(Arc::new(TemplateValue::string(
                Utf16String::from_rust_str(&output),
            ))))
        }
        _ => Err(processing_error(format!(
            "Static method \"{member}\" with {} arguments is not available on {type_name}",
            arguments.len()
        ))),
    }
}

fn numeric_f64(value: &TemplateValue) -> StandardExpressionResult<f64> {
    match value {
        TemplateValue::Number(NumberValue::Byte(value)) => Ok(f64::from(*value)),
        TemplateValue::Number(NumberValue::Short(value)) => Ok(f64::from(*value)),
        TemplateValue::Number(NumberValue::Integer(value)) => Ok(f64::from(*value)),
        TemplateValue::Number(NumberValue::Long(value)) => Ok(*value as f64),
        TemplateValue::Number(NumberValue::Float(value)) => Ok(f64::from(*value)),
        TemplateValue::Number(NumberValue::Double(value))
        | TemplateValue::Number(NumberValue::Other {
            double_value: value,
            ..
        }) => Ok(*value),
        TemplateValue::Number(NumberValue::BigInteger(value)) => value
            .to_string()
            .parse()
            .map_err(|error: std::num::ParseFloatError| processing_error(error.to_string())),
        TemplateValue::Number(NumberValue::BigDecimal(value)) => value
            .to_string()
            .parse()
            .map_err(|error: std::num::ParseFloatError| processing_error(error.to_string())),
        _ => Err(processing_error(format!(
            "{} cannot be converted to a number",
            value.class_name()
        ))),
    }
}

fn number_result(value: f64) -> StandardExpressionResult<Option<Arc<TemplateValue>>> {
    Ok(Some(Arc::new(TemplateValue::Number(NumberValue::Double(
        value,
    )))))
}

struct ClassObjectValue {
    type_name: Utf16String,
}

impl super::TemplateObject for ClassObjectValue {
    fn class_name(&self) -> &str {
        "java.lang.Class"
    }

    fn to_utf16_string(&self) -> Utf16String {
        Utf16String::from_rust_str(&format!("class {}", self.type_name.to_string_lossy()))
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn get_property(
        &self,
        property_name: &Utf16String,
    ) -> Option<Result<Option<Arc<TemplateValue>>, super::TemplateObjectPropertyError>> {
        let value = match property_name.to_string_lossy().as_str() {
            "name" => self.type_name.clone(),
            "simpleName" => Utf16String::from_rust_str(
                self.type_name
                    .to_string_lossy()
                    .rsplit('.')
                    .next()
                    .unwrap_or(""),
            ),
            _ => return None,
        };
        Some(Ok(Some(Arc::new(TemplateValue::string(value)))))
    }

    fn invoke_method(
        &self,
        method_name: &Utf16String,
        arguments: &[Option<Arc<TemplateValue>>],
    ) -> Option<Result<Option<Arc<TemplateValue>>, super::TemplateObjectMethodError>> {
        let value = match (method_name.to_string_lossy().as_str(), arguments) {
            ("getName", []) => self.type_name.clone(),
            ("getSimpleName", []) => Utf16String::from_rust_str(
                self.type_name
                    .to_string_lossy()
                    .rsplit('.')
                    .next()
                    .unwrap_or(""),
            ),
            _ => return None,
        };
        Some(Ok(Some(Arc::new(TemplateValue::string(value)))))
    }
}

fn class_value(type_name: &str) -> Arc<TemplateValue> {
    Arc::new(TemplateValue::Object(Arc::new(ClassObjectValue {
        type_name: Utf16String::from_rust_str(type_name),
    })))
}

fn path_root_method_name(root: &PathRoot) -> Utf16String {
    match root {
        PathRoot::Context(name) | PathRoot::ExpressionObject(name) => name.clone(),
    }
}

fn invoke_dynamic_method(
    target: &TemplateValue,
    name: &Utf16String,
    arguments: &[Option<Arc<TemplateValue>>],
) -> StandardExpressionResult<Option<Arc<TemplateValue>>> {
    match (name.to_string_lossy().as_str(), arguments) {
        ("toString", []) => {
            return Ok(target
                .to_utf16_string()
                .map(|value| Arc::new(TemplateValue::string(value))));
        }
        ("getClass", []) => return Ok(Some(class_value(target.class_name()))),
        ("equals", [other]) => {
            return Ok(Some(Arc::new(TemplateValue::Boolean(
                other
                    .as_deref()
                    .is_some_and(|other| target.template_equals(other)),
            ))));
        }
        _ => {}
    }
    match target {
        TemplateValue::Object(value) => {
            if value.class_name() == "java.util.stream.Stream"
                && !matches!(name.to_string_lossy().as_str(), "count" | "iterator")
            {
                return Err(processing_error_with_cause(
                    format!(
                        "method \"{}\" is not callable on {}",
                        name.to_string_lossy(),
                        value.class_name()
                    ),
                    NoSuchMethodError::new(format!(
                        "{}.{}",
                        value.class_name(),
                        name.to_string_lossy()
                    )),
                ));
            }
            ThymeleafACLMemberAccess::is_accessible(Some(value.as_ref()), &name.to_string_lossy())?;
            value.invoke_method(name, arguments).map_or_else(
                || {
                    Err(processing_error(format!(
                        "method \"{}\" is not callable on {}",
                        name.to_string_lossy(),
                        value.class_name()
                    )))
                },
                |result| result.map_err(|error| processing_error(error.to_string())),
            )
        }
        TemplateValue::String(value) | TemplateValue::SafeHtml(value) => {
            invoke_utf16_string_method(value, name, arguments)
        }
        TemplateValue::List(values) => invoke_java_list_method(values, name, arguments),
        TemplateValue::Map(entries) => invoke_java_map_method(entries, name, arguments),
        _ => Err(processing_error(format!(
            "method \"{}\" is not callable on {}",
            name.to_string_lossy(),
            target.class_name()
        ))),
    }
}

fn invoke_java_map_method(
    entries: &[(Arc<TemplateValue>, Arc<TemplateValue>)],
    name: &Utf16String,
    arguments: &[Option<Arc<TemplateValue>>],
) -> StandardExpressionResult<Option<Arc<TemplateValue>>> {
    let name = name.to_string_lossy();
    match (name.as_str(), arguments) {
        ("size", []) => Ok(Some(Arc::new(TemplateValue::Number(NumberValue::Integer(
            i32::try_from(entries.len()).unwrap_or(i32::MAX),
        ))))),
        ("isEmpty", []) => Ok(Some(Arc::new(TemplateValue::Boolean(entries.is_empty())))),
        ("get", [key]) => Ok(entries
            .iter()
            .find(|(candidate, _)| dynamic_values_equal(Some(candidate), key.as_ref()))
            .map(|(_, value)| Arc::clone(value))),
        ("containsKey", [key]) => {
            Ok(Some(Arc::new(TemplateValue::Boolean(entries.iter().any(
                |(candidate, _)| dynamic_values_equal(Some(candidate), key.as_ref()),
            )))))
        }
        ("containsValue", [value]) => {
            Ok(Some(Arc::new(TemplateValue::Boolean(entries.iter().any(
                |(_, candidate)| dynamic_values_equal(Some(candidate), value.as_ref()),
            )))))
        }
        ("keySet", []) => Ok(Some(Arc::new(TemplateValue::List(Arc::new(
            entries.iter().map(|(key, _)| Arc::clone(key)).collect(),
        ))))),
        ("values", []) => Ok(Some(Arc::new(TemplateValue::List(Arc::new(
            entries.iter().map(|(_, value)| Arc::clone(value)).collect(),
        ))))),
        ("entrySet", []) => Ok(Some(Arc::new(TemplateValue::List(Arc::new(
            entries
                .iter()
                .map(|(key, value)| {
                    Arc::new(TemplateValue::Object(Arc::new(MapEntryValue::new(
                        Arc::clone(key),
                        Arc::clone(value),
                    ))))
                })
                .collect(),
        ))))),
        _ => Err(processing_error(format!(
            "method \"{name}\" with {} arguments is not callable on java.util.Map",
            arguments.len()
        ))),
    }
}

fn dynamic_values_equal(
    left: Option<&Arc<TemplateValue>>,
    right: Option<&Arc<TemplateValue>>,
) -> bool {
    match (left.map(Arc::as_ref), right.map(Arc::as_ref)) {
        (None | Some(TemplateValue::Null), None | Some(TemplateValue::Null)) => true,
        (Some(left), Some(right)) => left.template_equals(right),
        _ => false,
    }
}

fn invoke_utf16_string_method(
    value: &Utf16String,
    name: &Utf16String,
    arguments: &[Option<Arc<TemplateValue>>],
) -> StandardExpressionResult<Option<Arc<TemplateValue>>> {
    let name = name.to_string_lossy();
    match (name.as_str(), arguments) {
        ("length", []) => Ok(Some(Arc::new(TemplateValue::Number(NumberValue::Integer(
            i32::try_from(value.len()).unwrap_or(i32::MAX),
        ))))),
        ("isEmpty", []) => Ok(Some(Arc::new(TemplateValue::Boolean(value.is_empty())))),
        ("toString", []) => Ok(Some(Arc::new(TemplateValue::string(value.clone())))),
        ("contains", [Some(argument)]) => {
            let argument = argument.to_utf16_string().ok_or_else(|| {
                processing_error("String.contains argument cannot be null".to_owned())
            })?;
            Ok(Some(Arc::new(TemplateValue::Boolean(
                value
                    .to_string_lossy()
                    .contains(&argument.to_string_lossy()),
            ))))
        }
        ("equalsIgnoreCase", [Some(argument)]) => {
            let argument = required_utf16_string(argument, "String argument cannot be null")?;
            Ok(Some(Arc::new(TemplateValue::Boolean(
                value.to_string_lossy().to_lowercase() == argument.to_string_lossy().to_lowercase(),
            ))))
        }
        ("startsWith", [Some(argument)]) | ("endsWith", [Some(argument)]) => {
            let argument = required_utf16_string(argument, "String argument cannot be null")?;
            let result = if name == "startsWith" {
                value.as_utf16().starts_with(argument.as_utf16())
            } else {
                value.as_utf16().ends_with(argument.as_utf16())
            };
            Ok(Some(Arc::new(TemplateValue::Boolean(result))))
        }
        ("startsWith", [Some(argument), Some(offset)]) => {
            let argument = required_utf16_string(argument, "String argument cannot be null")?;
            let offset = integer_argument(offset, "String offset is not an integer")?;
            let result = usize::try_from(offset)
                .ok()
                .and_then(|offset| value.as_utf16().get(offset..))
                .is_some_and(|remaining| remaining.starts_with(argument.as_utf16()));
            Ok(Some(Arc::new(TemplateValue::Boolean(result))))
        }
        ("substring" | "subSequence", [Some(begin)]) => {
            let begin = string_index(begin, value.len())?;
            Ok(Some(Arc::new(TemplateValue::string(
                Utf16String::from_utf16(value.as_utf16()[begin..].to_vec()),
            ))))
        }
        ("substring" | "subSequence", [Some(begin), Some(end)]) => {
            let begin = string_index(begin, value.len())?;
            let end = string_index(end, value.len())?;
            if begin > end {
                return Err(processing_error(format!(
                    "begin {begin} is greater than end {end}"
                )));
            }
            Ok(Some(Arc::new(TemplateValue::string(
                Utf16String::from_utf16(value.as_utf16()[begin..end].to_vec()),
            ))))
        }
        ("charAt", [Some(index)]) => {
            let index = string_index(index, value.len().saturating_sub(1))?;
            let character = value
                .as_utf16()
                .get(index)
                .copied()
                .ok_or_else(|| processing_error(format!("index {index} is out of bounds")))?;
            Ok(Some(Arc::new(TemplateValue::Character(character))))
        }
        ("indexOf" | "lastIndexOf", [Some(argument)]) => {
            let argument = required_utf16_string(argument, "String argument cannot be null")?;
            if argument.is_empty() {
                let index = if name == "indexOf" {
                    0
                } else {
                    i32::try_from(value.len()).unwrap_or(i32::MAX)
                };
                return Ok(Some(Arc::new(TemplateValue::Number(NumberValue::Integer(
                    index,
                )))));
            }
            let positions = value
                .as_utf16()
                .windows(argument.len())
                .enumerate()
                .filter(|(_, candidate)| *candidate == argument.as_utf16())
                .map(|(index, _)| index);
            let index = if name == "indexOf" {
                positions.into_iter().next()
            } else {
                positions.into_iter().next_back()
            }
            .and_then(|index| i32::try_from(index).ok())
            .unwrap_or(-1);
            Ok(Some(Arc::new(TemplateValue::Number(NumberValue::Integer(
                index,
            )))))
        }
        ("concat", [Some(argument)]) => {
            let argument = required_utf16_string(argument, "String argument cannot be null")?;
            let mut output = value.as_utf16().to_vec();
            output.extend_from_slice(argument.as_utf16());
            Ok(Some(Arc::new(TemplateValue::string(
                Utf16String::from_utf16(output),
            ))))
        }
        ("trim" | "strip", []) => Ok(Some(Arc::new(TemplateValue::string(trim(value))))),
        ("toUpperCase", []) => Ok(Some(Arc::new(TemplateValue::string(
            Utf16String::from_rust_str(&value.to_string_lossy().to_uppercase()),
        )))),
        ("toLowerCase", []) => Ok(Some(Arc::new(TemplateValue::string(
            Utf16String::from_rust_str(&value.to_string_lossy().to_lowercase()),
        )))),
        ("repeat", [Some(count)]) => {
            let count = integer_argument(count, "String repeat count is not an integer")?;
            let count = usize::try_from(count)
                .map_err(|_| processing_error("String repeat count is negative".to_owned()))?;
            Ok(Some(Arc::new(TemplateValue::string(
                Utf16String::from_utf16(value.as_utf16().repeat(count)),
            ))))
        }
        ("getBytes", []) => Ok(Some(Arc::new(TemplateValue::Bytes(Arc::new(
            value
                .to_string_lossy()
                .into_bytes()
                .into_iter()
                .map(|byte| byte as i8)
                .collect(),
        ))))),
        _ => Err(processing_error(format!(
            "method \"{name}\" with {} arguments is not callable on java.lang.String",
            arguments.len()
        ))),
    }
}

fn invoke_java_list_method(
    values: &[Arc<TemplateValue>],
    name: &Utf16String,
    arguments: &[Option<Arc<TemplateValue>>],
) -> StandardExpressionResult<Option<Arc<TemplateValue>>> {
    let name = name.to_string_lossy();
    match (name.as_str(), arguments) {
        ("size", []) => Ok(Some(Arc::new(TemplateValue::Number(NumberValue::Integer(
            i32::try_from(values.len()).unwrap_or(i32::MAX),
        ))))),
        ("isEmpty", []) => Ok(Some(Arc::new(TemplateValue::Boolean(values.is_empty())))),
        ("iterator", []) => Ok(Some(Arc::new(TemplateValue::Object(Arc::new(
            IteratorValue::new(Arc::new(values.to_vec())),
        ))))),
        ("stream", []) => Ok(Some(Arc::new(TemplateValue::Object(Arc::new(
            StreamValue::new(Arc::new(values.to_vec())),
        ))))),
        ("get", [Some(index)]) => {
            let index = match index.as_ref() {
                TemplateValue::Number(NumberValue::Integer(index)) => usize::try_from(*index).ok(),
                TemplateValue::Number(NumberValue::Long(index)) => usize::try_from(*index).ok(),
                _ => None,
            }
            .ok_or_else(|| processing_error("List.get index is not an integer".to_owned()))?;
            values
                .get(index)
                .cloned()
                .map(Some)
                .ok_or_else(|| processing_error(format!("index {index} is out of bounds")))
        }
        ("contains", [value]) => {
            Ok(Some(Arc::new(TemplateValue::Boolean(values.iter().any(
                |candidate| dynamic_values_equal(Some(candidate), value.as_ref()),
            )))))
        }
        ("indexOf" | "lastIndexOf", [value]) => {
            let indexes = values
                .iter()
                .enumerate()
                .filter(|(_, candidate)| dynamic_values_equal(Some(candidate), value.as_ref()))
                .map(|(index, _)| index);
            let index = if name == "indexOf" {
                indexes.into_iter().next()
            } else {
                indexes.into_iter().next_back()
            }
            .and_then(|index| i32::try_from(index).ok())
            .unwrap_or(-1);
            Ok(Some(Arc::new(TemplateValue::Number(NumberValue::Integer(
                index,
            )))))
        }
        ("subList", [Some(begin), Some(end)]) => {
            let begin = list_index(begin, values.len())?;
            let end = list_index(end, values.len())?;
            if begin > end {
                return Err(processing_error(format!(
                    "fromIndex({begin}) > toIndex({end})"
                )));
            }
            Ok(Some(Arc::new(TemplateValue::List(Arc::new(
                values[begin..end].to_vec(),
            )))))
        }
        _ => Err(processing_error(format!(
            "method \"{name}\" with {} arguments is not callable on java.util.List",
            arguments.len()
        ))),
    }
}

fn required_utf16_string(
    value: &TemplateValue,
    message: &str,
) -> StandardExpressionResult<Utf16String> {
    value
        .to_utf16_string()
        .ok_or_else(|| processing_error(message.to_owned()))
}

fn integer_argument(value: &TemplateValue, message: &str) -> StandardExpressionResult<i64> {
    match value {
        TemplateValue::Number(NumberValue::Byte(value)) => Ok(i64::from(*value)),
        TemplateValue::Number(NumberValue::Short(value)) => Ok(i64::from(*value)),
        TemplateValue::Number(NumberValue::Integer(value)) => Ok(i64::from(*value)),
        TemplateValue::Number(NumberValue::Long(value)) => Ok(*value),
        _ => Err(processing_error(message.to_owned())),
    }
}

fn string_index(value: &TemplateValue, maximum: usize) -> StandardExpressionResult<usize> {
    let index = integer_argument(value, "String index is not an integer")?;
    let index = usize::try_from(index)
        .map_err(|_| processing_error(format!("index {index} is out of bounds")))?;
    if index > maximum {
        return Err(processing_error(format!("index {index} is out of bounds")));
    }
    Ok(index)
}

fn list_index(value: &TemplateValue, maximum: usize) -> StandardExpressionResult<usize> {
    let index = integer_argument(value, "List index is not an integer")?;
    let index = usize::try_from(index)
        .map_err(|_| processing_error(format!("index {index} is out of bounds")))?;
    if index > maximum {
        return Err(processing_error(format!("index {index} is out of bounds")));
    }
    Ok(index)
}

fn read_dynamic_property(
    target: &TemplateValue,
    name: &Utf16String,
) -> StandardExpressionResult<Option<Arc<TemplateValue>>> {
    if name == &Utf16String::from_rust_str("class") {
        if let TemplateValue::Map(entries) = target
            && let Some(value) = entries.iter().find_map(|(key, value)| {
                matches!(
                    key.as_ref(),
                    TemplateValue::String(key_value) | TemplateValue::SafeHtml(key_value)
                        if key_value.as_ref() == name
                )
                .then(|| Arc::clone(value))
            })
        {
            return Ok(Some(value));
        }
        if let TemplateValue::Object(value) = target
            && let Some(result) = value.get_property(name)
        {
            // OGNL 的专用 PropertyAccessor(例如 ContextMap)先于 Object#getClass;
            // 因而名为 class 的上下文变量必须遮蔽反射类属性。
            return result.map_err(|error| processing_error(error.to_string()));
        }
        return Ok(Some(class_value(target.class_name())));
    }
    match target {
        TemplateValue::Map(entries) => match name.to_string_lossy().as_str() {
            "size" => Ok(Some(Arc::new(TemplateValue::Number(NumberValue::Integer(
                i32::try_from(entries.len()).unwrap_or(i32::MAX),
            ))))),
            "isEmpty" | "empty" => Ok(Some(Arc::new(TemplateValue::Boolean(entries.is_empty())))),
            "keys" | "keySet" => Ok(Some(Arc::new(TemplateValue::List(Arc::new(
                entries.iter().map(|(key, _)| Arc::clone(key)).collect(),
            ))))),
            "values" => Ok(Some(Arc::new(TemplateValue::List(Arc::new(
                entries.iter().map(|(_, value)| Arc::clone(value)).collect(),
            ))))),
            _ => Ok(entries.iter().find_map(|(key, value)| {
                matches!(
                    key.as_ref(),
                    TemplateValue::String(key_value) | TemplateValue::SafeHtml(key_value)
                        if key_value.as_ref() == name
                )
                .then(|| Arc::clone(value))
            })),
        },
        TemplateValue::List(values) => match name.to_string_lossy().as_str() {
            "size" | "length" => Ok(Some(Arc::new(TemplateValue::Number(NumberValue::Integer(
                i32::try_from(values.len()).unwrap_or(i32::MAX),
            ))))),
            "isEmpty" | "empty" => Ok(Some(Arc::new(TemplateValue::Boolean(values.is_empty())))),
            _ => Err(processing_error(format!(
                "property \"{}\" is not readable on {}",
                name.to_string_lossy(),
                target.class_name()
            ))),
        },
        TemplateValue::Bytes(values) if name == &Utf16String::from_rust_str("length") => {
            Ok(Some(Arc::new(TemplateValue::Number(NumberValue::Integer(
                i32::try_from(values.len()).unwrap_or(i32::MAX),
            )))))
        }
        TemplateValue::String(value) | TemplateValue::SafeHtml(value) => {
            match name.to_string_lossy().as_str() {
                "length" => Ok(Some(Arc::new(TemplateValue::Number(NumberValue::Integer(
                    i32::try_from(value.len()).unwrap_or(i32::MAX),
                ))))),
                "isEmpty" | "empty" => Ok(Some(Arc::new(TemplateValue::Boolean(value.is_empty())))),
                _ => Err(processing_error(format!(
                    "property \"{}\" is not readable on {}",
                    name.to_string_lossy(),
                    target.class_name()
                ))),
            }
        }
        TemplateValue::Object(value) => {
            let property_name = name.to_string_lossy();
            let acl_member_name = match (value.class_name(), property_name.as_str()) {
                ("java.lang.Class", "name") => "getName",
                ("java.lang.Class", "simpleName") => "getSimpleName",
                ("java.lang.Class", "package") => "getPackage",
                ("java.util.Map$Entry", "key") => "getKey",
                ("java.util.Map$Entry", "value") => "getValue",
                _ => property_name.as_str(),
            };
            ThymeleafACLMemberAccess::is_accessible(Some(value.as_ref()), acl_member_name)?;
            value.get_property(name).map_or_else(
                || {
                    Err(processing_error(format!(
                        "property \"{}\" is not readable on {}",
                        name.to_string_lossy(),
                        value.class_name()
                    )))
                },
                |result| result.map_err(|error| processing_error(error.to_string())),
            )
        }
        TemplateValue::Null => Err(ognl_processing_error(
            format!(
                "source is null for getProperty(null, \"{}\")",
                name.to_string_lossy()
            ),
            format!(
                "source is null for getProperty(null, \"{}\")",
                name.to_string_lossy()
            ),
        )),
        _ => Err(processing_error(format!(
            "property \"{}\" is not readable on {}",
            name.to_string_lossy(),
            target.class_name()
        ))),
    }
}

fn convert_to_string(
    context: &dyn IExpressionContext,
    value: Option<Arc<TemplateValue>>,
) -> StandardExpressionResult<Option<Arc<TemplateValue>>> {
    let Some(value) = value else {
        return Ok(None);
    };
    let service = StandardExpressions::get_conversion_service(context.get_configuration())?;
    let conversion_value = match value.as_ref() {
        TemplateValue::Null => ConversionValue::Null,
        TemplateValue::String(string) | TemplateValue::SafeHtml(string) => {
            ConversionValue::String(string)
        }
        object => ConversionValue::Object(object),
    };
    let converted = service
        .convert(
            Some(context.as_any()),
            conversion_value,
            Some(&TargetClass::String),
        )
        .map_err(|error| Box::new(error) as super::StandardExpressionError)?;
    Ok(match converted {
        ConversionResult::Null => None,
        ConversionResult::BorrowedString(value) => {
            Some(Arc::new(TemplateValue::string(value.clone())))
        }
        ConversionResult::OwnedString(value) => Some(Arc::new(TemplateValue::string(value))),
        ConversionResult::BorrowedObject(_) | ConversionResult::OwnedObject(_) => {
            return Err(processing_error(
                "Conversion service returned a non-String value for String.class".to_owned(),
            ));
        }
    })
}

fn trim(input: &Utf16String) -> Utf16String {
    Utf16String::from_utf16(trim_units(input.as_utf16()).to_vec())
}

fn trim_units(input: &[u16]) -> &[u16] {
    let start = input
        .iter()
        .position(|unit| *unit > 0x20)
        .unwrap_or(input.len());
    let end = input
        .iter()
        .rposition(|unit| *unit > 0x20)
        .map_or(start, |position| position + 1);
    &input[start..end]
}

fn is_ascii_identifier_part(value: u16) -> bool {
    value == b'_' as u16
        || value == b'$' as u16
        || (b'a' as u16..=b'z' as u16).contains(&value)
        || (b'A' as u16..=b'Z' as u16).contains(&value)
        || (b'0' as u16..=b'9' as u16).contains(&value)
}

fn find_conditional(input: &[u16]) -> Option<(usize, Option<usize>)> {
    let mut question = None;
    let mut colon = None;
    let mut nested_conditionals = 0usize;
    scan_top_level(input, |position, unit| {
        if unit == b'?' as u16
            && next_non_whitespace(input, position + 1)
                .is_none_or(|next| input[next] != b':' as u16)
        {
            if question.is_none() {
                question = Some(position);
            } else {
                nested_conditionals += 1;
            }
        } else if unit == b':' as u16 && question.is_some() && colon.is_none() {
            if nested_conditionals == 0 {
                colon = Some(position);
            } else {
                nested_conditionals -= 1;
            }
        }
    });
    question.map(|position| (position, colon))
}

fn next_non_whitespace(input: &[u16], mut position: usize) -> Option<usize> {
    while input.get(position).is_some_and(|unit| *unit <= 0x20) {
        position += 1;
    }
    (position < input.len()).then_some(position)
}

fn find_assignment_operator(input: &[u16]) -> Option<usize> {
    let mut found = None;
    scan_top_level(input, |position, unit| {
        if found.is_some() || unit != b'=' as u16 {
            return;
        }
        let before = position
            .checked_sub(1)
            .and_then(|index| input.get(index))
            .copied();
        let after = input.get(position + 1).copied();
        if !before.is_some_and(|value| {
            [b'=' as u16, b'!' as u16, b'<' as u16, b'>' as u16].contains(&value)
        }) && after != Some(b'=' as u16)
        {
            found = Some(position);
        }
    });
    found
}

fn find_word_operator(input: &[u16], operator: &[u16]) -> Option<usize> {
    find_binary_operator(input, &[operator]).map(|(position, _)| position)
}

fn find_binary_operator<'a>(
    input: &[u16],
    operators: &'a [&'a [u16]],
) -> Option<(usize, &'a [u16])> {
    let mut found = None;
    scan_top_level(input, |position, _| {
        for operator in operators {
            if position + operator.len() <= input.len()
                && eq_ignore_ascii_case(&input[position..position + operator.len()], operator)
                && operator_boundary(input, position, operator)
                && !((operator == &OP_MINUS || operator == &OP_PLUS)
                    && is_unary_sign_position(input, position))
            {
                let replace =
                    found
                        .as_ref()
                        .is_none_or(|(old_position, old_operator): &(usize, &[u16])| {
                            position > *old_position
                                || (position == *old_position
                                    && operator.len() > old_operator.len())
                        });
                if replace {
                    found = Some((position, *operator));
                }
            }
        }
    });
    found.filter(|(position, operator)| {
        !trim_units(&input[..*position]).is_empty()
            && !trim_units(&input[*position + operator.len()..]).is_empty()
    })
}

fn is_unary_sign_position(input: &[u16], position: usize) -> bool {
    let prefix = trim_units(&input[..position]);
    let Some(last) = prefix.last().copied() else {
        return true;
    };
    if [
        b'+' as u16,
        b'-' as u16,
        b'*' as u16,
        b'/' as u16,
        b'%' as u16,
        b'<' as u16,
        b'>' as u16,
        b'=' as u16,
        b'!' as u16,
        b'&' as u16,
        b'|' as u16,
        b'^' as u16,
        b'~' as u16,
        b'?' as u16,
        b':' as u16,
        b',' as u16,
        b'(' as u16,
        b'[' as u16,
        b'{' as u16,
    ]
    .contains(&last)
    {
        return true;
    }
    [OP_DIV, OP_MOD, OP_AND, OP_OR].iter().any(|operator| {
        prefix.len() >= operator.len()
            && eq_ignore_ascii_case(&prefix[prefix.len() - operator.len()..], operator)
            && prefix
                .get(prefix.len().saturating_sub(operator.len() + 1))
                .is_none_or(|unit| !is_word_unit(*unit))
    })
}

fn find_inclusion_operator(input: &[u16]) -> Option<(usize, usize, bool)> {
    let mut found = None;
    scan_top_level(input, |position, _| {
        if position + OP_IN.len() > input.len()
            || !eq_ignore_ascii_case(&input[position..position + OP_IN.len()], OP_IN)
            || !operator_boundary(input, position, OP_IN)
        {
            return;
        }

        let mut before_in = position;
        while before_in > 0 && input[before_in - 1] <= 0x20 {
            before_in -= 1;
        }
        let not_start = before_in.checked_sub(3);
        let negated = not_start.is_some_and(|start| {
            eq_ignore_ascii_case(&input[start..before_in], OP_NOT)
                && start
                    .checked_sub(1)
                    .and_then(|index| input.get(index))
                    .is_none_or(|unit| !is_word_unit(*unit))
        });
        let operator_start = if negated {
            not_start.expect("negated operator has a start")
        } else {
            position
        };
        let operator_length = position + OP_IN.len() - operator_start;
        if !trim_units(&input[..operator_start]).is_empty()
            && !trim_units(&input[position + OP_IN.len()..]).is_empty()
            && found
                .as_ref()
                .is_none_or(|(old_position, _, _)| operator_start > *old_position)
        {
            found = Some((operator_start, operator_length, negated));
        }
    });
    found
}

fn operator_boundary(input: &[u16], position: usize, operator: &[u16]) -> bool {
    if operator
        .iter()
        .all(|unit| is_ascii_alphabetic(*unit) || *unit == b' ' as u16)
    {
        let before = position.checked_sub(1).and_then(|index| input.get(index));
        let after = input.get(position + operator.len());
        return before.is_none_or(|unit| !is_word_unit(*unit))
            && after.is_none_or(|unit| !is_word_unit(*unit));
    }
    if operator == OP_MINUS {
        let before = position.checked_sub(1).and_then(|index| input.get(index));
        let after = input.get(position + 1);
        return before.is_none_or(|unit| !is_word_unit(*unit))
            || after.is_none_or(|unit| !is_word_unit(*unit))
            || before.is_some_and(|unit| (b'0' as u16..=b'9' as u16).contains(unit))
            || after.is_some_and(|unit| (b'0' as u16..=b'9' as u16).contains(unit));
    }
    true
}

fn find_top_level_sequence(input: &[u16], sequence: &[u16]) -> Option<usize> {
    let mut found = None;
    scan_top_level(input, |position, _| {
        if found.is_none()
            && position + sequence.len() <= input.len()
            && input[position..position + sequence.len()] == *sequence
        {
            found = Some(position);
        }
    });
    found
}

fn scan_top_level(input: &[u16], mut visitor: impl FnMut(usize, u16)) {
    let mut parentheses = 0_i32;
    let mut brackets = 0_i32;
    let mut braces = 0_i32;
    let mut quote = None;
    for (position, unit) in input.iter().copied().enumerate() {
        if let Some(active_quote) = quote {
            if unit == active_quote && !is_escaped(input, position) {
                quote = None;
            }
            continue;
        }
        if matches!(unit, 0x27 | 0x22) {
            quote = Some(unit);
            continue;
        }
        match unit {
            value if value == b'(' as u16 => parentheses += 1,
            value if value == b')' as u16 => parentheses -= 1,
            value if value == b'[' as u16 => brackets += 1,
            value if value == b']' as u16 => brackets -= 1,
            value if value == b'{' as u16 => braces += 1,
            value if value == b'}' as u16 => braces -= 1,
            _ if parentheses == 0 && brackets == 0 && braces == 0 => visitor(position, unit),
            _ => {}
        }
    }
}

fn is_outer_parenthesized(input: &[u16]) -> bool {
    if input.first() != Some(&(b'(' as u16)) || input.last() != Some(&(b')' as u16)) {
        return false;
    }
    let mut level = 0_i32;
    let mut quote = None;
    for (position, unit) in input.iter().copied().enumerate() {
        if let Some(active_quote) = quote {
            if unit == active_quote && !is_escaped(input, position) {
                quote = None;
            }
        } else if matches!(unit, 0x27 | 0x22) {
            quote = Some(unit);
        } else if unit == b'(' as u16 {
            level += 1;
        } else if unit == b')' as u16 {
            level -= 1;
            if level == 0 && position + 1 != input.len() {
                return false;
            }
        }
    }
    level == 0 && quote.is_none()
}

fn starts_with_word(input: &[u16], word: &str) -> bool {
    let word = word.as_bytes();
    input.len() > word.len()
        && input[..word.len()]
            .iter()
            .zip(word)
            .all(|(left, right)| ascii_lower(*left) == u16::from(right.to_ascii_lowercase()))
        && !is_word_unit(input[word.len()])
}

fn eq_ignore_ascii_case(left: &[u16], right: &[u16]) -> bool {
    left.len() == right.len()
        && left
            .iter()
            .zip(right)
            .all(|(left, right)| ascii_lower(*left) == ascii_lower(*right))
}

fn is_word_unit(unit: u16) -> bool {
    is_ascii_alphabetic(unit)
        || (b'0' as u16..=b'9' as u16).contains(&unit)
        || matches!(unit, value if value == b'_' as u16 || value == b'$' as u16)
}

fn is_ascii_alphabetic(unit: u16) -> bool {
    (b'a' as u16..=b'z' as u16).contains(&unit) || (b'A' as u16..=b'Z' as u16).contains(&unit)
}

fn ascii_lower(unit: u16) -> u16 {
    if (b'A' as u16..=b'Z' as u16).contains(&unit) {
        unit + u16::from(b'a' - b'A')
    } else {
        unit
    }
}

fn is_escaped(input: &[u16], position: usize) -> bool {
    let mut slash_count = 0;
    let mut current = position;
    while current > 0 && input[current - 1] == b'\\' as u16 {
        slash_count += 1;
        current -= 1;
    }
    slash_count % 2 == 1
}

const OP_OR: &[u16] = &[b'o' as u16, b'r' as u16];
const OP_DOUBLE_PIPE: &[u16] = &[b'|' as u16, b'|' as u16];
const OP_AND: &[u16] = &[b'a' as u16, b'n' as u16, b'd' as u16];
const OP_DOUBLE_AMPERSAND: &[u16] = &[b'&' as u16, b'&' as u16];
const OP_BOR: &[u16] = &[b'b' as u16, b'o' as u16, b'r' as u16];
const OP_PIPE: &[u16] = &[b'|' as u16];
const OP_XOR: &[u16] = &[b'x' as u16, b'o' as u16, b'r' as u16];
const OP_CARET: &[u16] = &[b'^' as u16];
const OP_BAND: &[u16] = &[b'b' as u16, b'a' as u16, b'n' as u16, b'd' as u16];
const OP_AMPERSAND: &[u16] = &[b'&' as u16];
const OP_NEQ: &[u16] = &[b'n' as u16, b'e' as u16, b'q' as u16];
const OP_NE: &[u16] = &[b'n' as u16, b'e' as u16];
const OP_NOT_EQUALS: &[u16] = &[b'!' as u16, b'=' as u16];
const OP_EQ: &[u16] = &[b'e' as u16, b'q' as u16];
const OP_EQUALS: &[u16] = &[b'=' as u16, b'=' as u16];
const OP_GTE: &[u16] = &[b'g' as u16, b't' as u16, b'e' as u16];
const OP_GE: &[u16] = &[b'g' as u16, b'e' as u16];
const OP_GREATER_EQUAL: &[u16] = &[b'>' as u16, b'=' as u16];
const OP_GT: &[u16] = &[b'g' as u16, b't' as u16];
const OP_GREATER: &[u16] = &[b'>' as u16];
const OP_LTE: &[u16] = &[b'l' as u16, b't' as u16, b'e' as u16];
const OP_LE: &[u16] = &[b'l' as u16, b'e' as u16];
const OP_LESS_EQUAL: &[u16] = &[b'<' as u16, b'=' as u16];
const OP_LT: &[u16] = &[b'l' as u16, b't' as u16];
const OP_LESS: &[u16] = &[b'<' as u16];
const OP_NOT: &[u16] = &[b'n' as u16, b'o' as u16, b't' as u16];
const OP_IN: &[u16] = &[b'i' as u16, b'n' as u16];
const OP_INSTANCEOF: &[u16] = &[
    b'i' as u16,
    b'n' as u16,
    b's' as u16,
    b't' as u16,
    b'a' as u16,
    b'n' as u16,
    b'c' as u16,
    b'e' as u16,
    b'o' as u16,
    b'f' as u16,
];
const OP_SHIFT_LEFT: &[u16] = &[b'<' as u16, b'<' as u16];
const OP_SHL: &[u16] = &[b's' as u16, b'h' as u16, b'l' as u16];
const OP_SHIFT_RIGHT: &[u16] = &[b'>' as u16, b'>' as u16];
const OP_SHR: &[u16] = &[b's' as u16, b'h' as u16, b'r' as u16];
const OP_UNSIGNED_SHIFT_RIGHT: &[u16] = &[b'>' as u16, b'>' as u16, b'>' as u16];
const OP_USHR: &[u16] = &[b'u' as u16, b's' as u16, b'h' as u16, b'r' as u16];
const OP_PLUS: &[u16] = &[b'+' as u16];
const OP_MINUS: &[u16] = &[b'-' as u16];
const OP_MULTIPLY: &[u16] = &[b'*' as u16];
const OP_DIV: &[u16] = &[b'd' as u16, b'i' as u16, b'v' as u16];
const OP_DIVIDE: &[u16] = &[b'/' as u16];
const OP_MOD: &[u16] = &[b'm' as u16, b'o' as u16, b'd' as u16];
const OP_REMAINDER: &[u16] = &[b'%' as u16];

thread_local! {
    static OGNL_RUNTIMES: RefCell<Vec<Arc<dyn OgnlRuntime>>> = const { RefCell::new(Vec::new()) };
    static OGNL_LOCALS: RefCell<Vec<HashMap<Utf16String, Option<Arc<TemplateValue>>>>> =
        const { RefCell::new(Vec::new()) };
}

fn current_ognl_local(name: &Utf16String) -> Option<Option<Arc<TemplateValue>>> {
    OGNL_LOCALS.with(|scopes| {
        scopes
            .borrow()
            .last()
            .and_then(|scope| scope.get(name).cloned())
    })
}

fn set_ognl_local(name: Utf16String, value: Option<Arc<TemplateValue>>) {
    OGNL_LOCALS.with(|scopes| {
        if let Some(scope) = scopes.borrow_mut().last_mut() {
            scope.insert(name, value);
        }
    });
}

fn with_ognl_locals<T>(operation: impl FnOnce() -> T) -> T {
    OGNL_LOCALS.with(|scopes| scopes.borrow_mut().push(HashMap::new()));
    struct OgnlLocalsGuard;
    impl Drop for OgnlLocalsGuard {
        fn drop(&mut self) {
            OGNL_LOCALS.with(|scopes| {
                scopes.borrow_mut().pop();
            });
        }
    }
    let _guard = OgnlLocalsGuard;
    operation()
}

fn current_ognl_runtime() -> Option<Arc<dyn OgnlRuntime>> {
    OGNL_RUNTIMES.with(|runtimes| runtimes.borrow().last().cloned())
}

fn with_ognl_runtime<T>(runtime: Arc<dyn OgnlRuntime>, operation: impl FnOnce() -> T) -> T {
    OGNL_RUNTIMES.with(|runtimes| runtimes.borrow_mut().push(runtime));
    struct OgnlRuntimeGuard;
    impl Drop for OgnlRuntimeGuard {
        fn drop(&mut self) {
            OGNL_RUNTIMES.with(|runtimes| {
                runtimes.borrow_mut().pop();
            });
        }
    }
    let _guard = OgnlRuntimeGuard;
    operation()
}

fn processing_error(message: String) -> super::StandardExpressionError {
    Box::new(TemplateProcessingException::new(Some(message)))
}

fn processing_error_with_cause<E>(message: String, cause: E) -> super::StandardExpressionError
where
    E: std::error::Error + Send + Sync + 'static,
{
    Box::new(TemplateProcessingException::with_cause(
        Some(message),
        cause,
    ))
}

fn ognl_processing_error(message: String, ognl_message: String) -> super::StandardExpressionError {
    Box::new(TemplateProcessingException::with_cause(
        Some(message),
        OgnlError::new(ognl_message),
    ))
}

// ===========================================================================
// 表达式动态分派器直接单测(不经过渲染管线)
// ===========================================================================

#[cfg(test)]
#[cfg(test)]
mod dispatcher_direct_tests {
    use super::{
        ComputedExpression, invoke_static_method, invoke_utf16_string_method, parse_ognl_range,
    };
    use crate::expression::TemplateValue;
    use crate::util::{NumberValue, Utf16String};
    use std::sync::Arc;

    fn js(value: &str) -> Utf16String {
        Utf16String::from_rust_str(value)
    }

    fn text(value: &Arc<TemplateValue>) -> String {
        value
            .to_utf16_string()
            .map_or_else(|| "null".to_owned(), |value| value.to_string_lossy())
    }

    #[test]
    fn invoke_utf16_string_method_dispatch_matches_java() {
        let target = js("Hello World");
        let result = invoke_utf16_string_method(&target, &js("length"), &[])
            .expect("length ok")
            .expect("non-null");
        assert_eq!(text(&result), "11");
        let result = invoke_utf16_string_method(&js(""), &js("isEmpty"), &[])
            .expect("isEmpty ok")
            .expect("non-null");
        assert_eq!(text(&result), "true");
        let result = invoke_utf16_string_method(&target, &js("toString"), &[])
            .expect("toString ok")
            .expect("non-null");
        assert_eq!(text(&result), "Hello World");
        let result = invoke_utf16_string_method(
            &target,
            &js("contains"),
            &[Some(Arc::new(TemplateValue::string(js("World"))))],
        )
        .expect("contains ok")
        .expect("non-null");
        assert_eq!(text(&result), "true");
        let result = invoke_utf16_string_method(
            &target,
            &js("contains"),
            &[Some(Arc::new(TemplateValue::string(js("xyz"))))],
        )
        .expect("contains ok")
        .expect("non-null");
        assert_eq!(text(&result), "false");
        let result = invoke_utf16_string_method(
            &target,
            &js("charAt"),
            &[Some(Arc::new(TemplateValue::Number(NumberValue::Integer(
                1,
            ))))],
        )
        .expect("charAt ok")
        .expect("non-null");
        assert_eq!(text(&result), "e");
        // 未知方法 -> 错误(Java String 方法分派拒绝)
        assert!(invoke_utf16_string_method(&target, &js("noSuchMethod"), &[]).is_err());
        // 参数个数不匹配 -> 错误
        assert!(invoke_utf16_string_method(&target, &js("charAt"), &[]).is_err());
    }

    #[test]
    fn invoke_static_method_dispatch_matches_java() {
        let number = |value: i64| Some(Arc::new(TemplateValue::Number(NumberValue::Long(value))));
        // Java Math 静态方法返回 double:sqrt(16.0)=4.0、ceil(7.0)=7.0
        let result = invoke_static_method("java.lang.Math", "sqrt", &[number(16)])
            .expect("sqrt ok")
            .expect("non-null");
        assert_eq!(text(&result), "4.0");
        let result = invoke_static_method("java.lang.Math", "ceil", &[number(7)])
            .expect("ceil ok")
            .expect("non-null");
        assert_eq!(text(&result), "7.0");
        // abs 用 double 输入(Java Math.abs(double) 返回 double)
        let double = Some(Arc::new(TemplateValue::Number(NumberValue::Double(-5.5))));
        let result = invoke_static_method("java.lang.Math", "abs", &[double])
            .expect("abs ok")
            .expect("non-null");
        assert_eq!(text(&result), "5.5");
        // 未知静态成员 -> 错误
        assert!(invoke_static_method("java.lang.Math", "noSuchMember", &[]).is_err());
        // 空类名 -> 错误
        assert!(invoke_static_method("", "abs", &[number(1)]).is_err());
    }

    #[test]
    fn parse_ognl_range_sequence_and_assignment() {
        // 集合字面量 {1,2,3} -> ListLiteral 3 项
        let input: Vec<u16> = "{1,2,3}".encode_utf16().collect();
        let parsed = parse_ognl_range(&input, true, false).expect("list literal parses");
        match parsed {
            ComputedExpression::ListLiteral(items) => {
                assert_eq!(items.len(), 3, "list literal 为 3 项");
            }
            _ => panic!("expected ListLiteral for {{1,2,3}}"),
        }

        // 顶层逗号序列 1,2,3 -> Sequence 3 项
        let input: Vec<u16> = "1,2,3".encode_utf16().collect();
        let parsed = parse_ognl_range(&input, true, false).expect("sequence parses");
        match parsed {
            ComputedExpression::Sequence(items) => {
                assert_eq!(items.len(), 3, "顶层序列为 3 项");
            }
            _ => panic!("expected Sequence for 1,2,3"),
        }

        // 赋值:`#x = 'y'`
        let input: Vec<u16> = "#x = 'y'".encode_utf16().collect();
        let parsed = parse_ognl_range(&input, true, false).expect("assignment parses");
        match parsed {
            ComputedExpression::Assignment { name, .. } => {
                assert_eq!(name.to_string_lossy(), "x");
            }
            _ => panic!("expected Assignment"),
        }

        // 无效输入 -> None
        assert!(parse_ognl_range(&[], true, false).is_none());
        let bad: Vec<u16> = "..".encode_utf16().collect();
        assert!(parse_ognl_range(&bad, true, false).is_none());
        // 非 # 前缀的赋值目标 -> None
        let bad: Vec<u16> = "x = 1".encode_utf16().collect();
        assert!(parse_ognl_range(&bad, true, false).is_none());
    }
}