A
download jclexpreval.pas
Language: Delphi
LOC: 3180
Project Info
XVCL
Server: SourceForge
Type: cvs
...rge\x\xvcl\xvcl\JCL\Source\
   _source_.dof
   DJCL50.dpk
   JCL.INC
   Jcl8087.pas
   JclAppInst.pas
   JclBase.pas
   JclCOM.pas
   JclComplex.pas
   JclCounter.pas
   JclDateTime.pas
   JclDebug.pas
   JclExcel.pas
   jclexpreval.pas
   JclFileUtils.pas
   JclGraphics.pas
   JclGraphUtils.pas
   JclHookExcept.pas
   JclIniFiles.pas
   JclLANMan.pas
   JclLocales.pas
   JclLogic.pas
   JclMapi.pas
   JclMath.pas
   JclMime.pas
   JclMiscel.pas
   JclMultimedia.pas
   JclNTFS.pas
   JclPeImage.pas
   JclPrint.pas
   JclRegistry.pas
   JclResources.pas
   JclRTF.pas
   JclRTTI.pas
   JclSecurity.pas
   JclShell.pas
   JclSscanf.pas
   JclStatistics.pas
   JclStrHashMap.pas
   JclStrings.pas
   JclSynch.pas
   JclSysInfo.pas
   JclSysUtils.pas
   JclUnicode.pas
   JclUnicode.rc
   JclUnitConv.pas
   JclWin32.pas
   LM.pas

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
{******************************************************************************}
{                                                                              }
{ Project JEDI Code Library (JCL)                                              }
{                                                                              }
{ The contents of this file are subject to the Mozilla Public License Version  }
{ 1.1 (the "License"); you may not use this file except in compliance with the }
{ License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ }
{                                                                              }
{ Software distributed under the License is distributed on an "AS IS" basis,   }
{ WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for }
{ the specific language governing rights and limitations under the License.    }
{                                                                              }
{ The Original Code is JclExprEval.pas.                                        }
{                                                                              }
{ The Initial Developer of the Original Code is documented in the accompanying }
{ help file JCL.chm. Portions created by these individuals are Copyright (C)   }
{ 2001 of these individuals.                                                   }
{                                                                              }
{ Description: Mathematical expression evaluator.                              }
{ Unit Owner: Barry Kelly.                                                     }
{                                                                              }
{******************************************************************************}
{                                                                              }
{ This unit contains three expression evaluators, each tailored for different  }
{ usage patterns. It also contains the component objects, so that a customized }
{ expression evaluator can be assembled relatively easily.                     }
{                                                                              }
{ Unit owner: Barry Kelly                                                      }
{ Last modified: June 14, 2001                                                  }
{                                                                              }
{******************************************************************************}

{ Brief: This unit contains the expression evaluator.
  Description:
    The key classes are TEvaluator, TCompiledEvaluator and
    TExpressionCompiler.
    <p>
    * For single evaluations of multiple expressions, use TEvaluator.
    * For many evaluations of the same expression, use TCompiledEvaluator.
    * For many evaluations of many expressions, use TExpressionCompiler.
    <p>
    Customized evaluators can be put together from constituent parts. }
unit JclExprEval;

{$INCLUDE JCL.INC}

interface

uses SysUtils, Classes, JclBase, JclSysUtils, JclStrHashMap, JclResources;

const
  { Brief: Initial size of internal hash lists created by TEasyEvaluator
      descendants, and also TExpressionCompiler. }
  C_ExprEval_HashSize = 127;

type
  { Brief: Exception class used by the expression evaluator. }
  EJclExprEvalError = class(EJclError);

const
  { Brief: Set of characters that will be skipped before a token read
    commences.
    See Also: TExprLexer }
  ExprWhiteSpace = [#1..#32];

type
  { Brief: Floating-point type used by TLexer and TParser.Evaluate. }
  TFloat = Double;
  { Brief: Pointer to TFloat. }
  PFloat = ^TFloat;

  { Brief: 32-bit IEEE standard floating-point value. }
  TFloat32 = Single;
  { <COMBINE TFloat32> }
  PFloat32 = ^TFloat32;

  { Brief: 64-bit IEEE standard floating-point value. }
  TFloat64 = Double;
  { <COMBINE TFloat64> }
  PFloat64 = ^TFloat64;

  { Brief: 80-bit Intel extended precision floating-point value. }
  TFloat80 = Extended;
  { <COMBINE TFloat80> }
  PFloat80 = ^TFloat80;

  { Brief: A function type taking no parameters. }
  TFloatFunc = function: TFloat;
  { <COMBINE TFloatFunc> }
  TFloat32Func = function: TFloat32;
  { <COMBINE TFloatFunc> }
  TFloat64Func = function: TFloat64;
  { <COMBINE TFloatFunc> }
  TFloat80Func = function: TFloat80;

  { Brief: A function type taking a single parameter. }
  TUnaryFunc = function(x: TFloat): TFloat;
  { <COMBINE TUnaryFunc> }
  TUnary32Func = function(x: TFloat32): TFloat32;
  { <COMBINE TUnaryFunc> }
  TUnary64Func = function(x: TFloat64): TFloat64;
  { <COMBINE TUnaryFunc> }
  TUnary80Func = function(x: TFloat80): TFloat80;

  { Brief: A function type taking two parameters. }
  TBinaryFunc = function(x, y: TFloat): TFloat;
  { <COMBINE TBinaryFunc> }
  TBinary32Func = function(x, y: TFloat32): TFloat32;
  { <COMBINE TBinaryFunc> }
  TBinary64Func = function(x, y: TFloat64): TFloat64;
  { <COMBINE TBinaryFunc> }
  TBinary80Func = function(x, y: TFloat80): TFloat80;

  { Brief: A function type taking three parameters. }
  TTernaryFunc = function(x, y, z: TFloat): TFloat;
  { <COMBINE TTernaryFunc> }
  TTernary32Func = function(x, y, z: TFloat32): TFloat32;
  { <COMBINE TTernaryFunc> }
  TTernary64Func = function(x, y, z: TFloat64): TFloat64;
  { <COMBINE TTernaryFunc> }
  TTernary80Func = function(x, y, z: TFloat80): TFloat80;

type
{ Forward Declarations }
  TExprLexer = class;
  TExprCompileParser = class;
  TExprEvalParser = class;
  TExprSym = class;
  TExprNode = class;
  TExprNodeFactory = class;

  { Brief: Finds a symbol corresponding to an identifier.
    Description:
      Expressions composed solely of numbers and operators may be
      evaluated quite easily, but to make an expression evaluator really
      useful requires that things like named constants, variables and
      functions be added as well.
      <p>
      To allow a defined set of constants, variables and functions
      to be used in multiple evaluators (and mixed and matched according
      to need), the task of handling symbol resolution is devolved to
      an object known as a <i>context</i>.
      <p>
      Contexts are not required to be flat; indeed, they are expected to
      be compound objects, which devolve to other, more specialized contexts
      to do actual resolution.
      <p>
      As an example, consider the way names are resolved in Object Pascal.
      The set of valid symbols is initially defined by the System unit, and
      then added to with each unit named in the uses clause. When a method
      is being compiled, private, protected and public names come into the
      namespace; they aren't in effect with methods of other classes. In
      a similar way, contexts can be built up according to requirements.
    Note: Don't construct instances of TExprContext directly, since it is
      abstract; instead, construct a concrete descendant.
    See Also:
      TExprHashContext, TExprSetContext }
  TExprContext = class
  public
    { Finds a symbol corresponding to an identifier.
      Parameters: s: The identifier of the symbol to find.
      Returns: The symbol object, or nil if not found. }
    function Find(const AName: string): TExprSym; virtual; abstract;
  end;

  { Brief: A context class that uses a hash map for its implementation.
    Description:
      This is a concrete context class that uses a hash map for symbol
      lookup. The fact that it uses a hash for its implementation means that
      symbol lookup takes a constant time, i.e. it is independant of the
      actual number of symbols stored in the context; however, this
      guarantee depends on the internal hash map's internal table being
      large enough to minimize collisions.
      <p>
    Note: Case sensitivity is also a concern; see the Create method. }
  TExprHashContext = class(TExprContext)
  private
    FHashMap: TStringHashMap;
  public
    { Brief: Creates an instance of THashContext.
      Parameters:
        ACaseSensitive: Whether this context should be case sensitive or not.
        AHashSize: The hash size to pass on to the internal
          hash map structure.
      Description:
        This constructs an instance of THashContext. The first
        parameter indicates case sensitivity; the meaning of the second
        parameter is slightly more subtle. It tells the context what
        value to pass on to the internal hash map's constructor. A large
        value will mean that the context will take up quite a bit of memory
        even when it is empty (4 bytes are added for every increase of 1
        in the hash size). For good performance, the hash should roughly
        be the expected average amount of items to be held in the hash.
        The performance degradation for too small hash tables is logarithmic,
        however, so only in pathalogical cases should this be a concern.
      Note: It is fairly important that the hash size not be an even
        number; it's best if it is a prime number, although typically
        a power of 2 minus one does fairly well (e.g. 127, 2047, etc.).
      See Also: TStringHashMap }
    constructor Create(
      ACaseSensitive: Boolean{$IFDEF SUPPORTS_DEFAULTPARAMS} = False{$ENDIF};
      AHashSize: Integer{$IFDEF SUPPORTS_DEFAULTPARAMS} = 127{$ENDIF});

    { Brief: Destroys this instance. Use Free instead. }
    destructor Destroy; override;

    { Brief: Adds a symbol to this context.
      Parameters:
        ASymbol: The symbol object to add.
      Description:
        Once a symbol has been added, the context takes over ownership
        of it, and will free it when it is itself destroyed. }
    procedure Add(ASymbol: TExprSym);

    { Brief: Removes a symbol from this context.
      Parameters:
        AName: symbol to remove and free.
      Description:
        The symbol object refered to by AName will be destroyed. }
    procedure Remove(const AName: string);

    function Find(const AName: string): TExprSym; override;
  end;

  { Brief: A compound context object for combining multiple contexts.
    Description:
      A context class that contains a set of other contexts, which it
      searches in order, starting with the most recently added. }
  TExprSetContext = class(TExprContext)
  private
    FList: TList;
    FOwnsContexts: Boolean;
    function GetContexts(AIndex: Integer): TExprContext;
    function GetCount: Integer;
  public
    { Brief: Constructs an instance.
      Parameters:
        AOwnsContexts: Determines whether this context object
          should free contexts when they are deleted. You can use
          Extract to remove a context while keeping it intact. }
    constructor Create(AOwnsContexts: Boolean);

    { Brief: Destroys the TExprSetContext instance. Use Free instead. }
    destructor Destroy; override;

    { Brief: Adds a context to the set.
      Parameters:
        AContext: Context to add to the set of contexts. }
    procedure Add(AContext: TExprContext);
    { Brief: Removes a context.
      Parameters:
        AContext: Context to remove. }
    procedure Remove(AContext: TExprContext);
    { Brief: Removes a context by index.
      Parameters:
        AIndex: Index of context to remove. }
    procedure Delete(AIndex: Integer);
    { Brief: Removes a context without freeing it (if AOwnsContexts was
        passed as True in the constructor Create).
      Parameters:
        AContext: Context to remove.
      Returns:
        The context passed in (AContext). }
    function Extract(AContext: TExprContext): TExprContext;

    { Brief: Returns the number of contexts held by this set. }
    property Count: Integer read GetCount;
    { Brief: Accesses an internal context by index. }
    property Contexts[AIndex: Integer]: TExprContext read GetContexts;

    { Brief: Access to the internal list of contexts for advanced
        operations. }
    property InternalList: TList read FList;

    function Find(const AName: string): TExprSym; override;
  end;

  { Brief: Represents a symbol that may be found in an input stream.
    Description:
      An instance of this class is responsible for turning input lexemes
      (from the lexer) into either a concrete result (Evaluate) or
      expression nodes (Compile).
      <p>
      Because this class has state (properties like Lexer, EvalParser,
      CompileParser, NodeFactory), <b>a symbol should never be used by
      two threads simultaneously</b>. This design decision was taken to
      maximize ease of creating new symbols.
      <p>
      It is, however, safe to implement recursive symbols (i.e. a symbol
      that calls itself, even though it might be through another evaluator
      with different Lexer etc.) because the state is saved before Evaluate
      or Compile is called, and restored afterwards. }
  TExprSym = class
  private
    FIdent: string;
    FLexer: TExprLexer;
    FEvalParser: TExprEvalParser;
    FCompileParser: TExprCompileParser;
    FNodeFactory: TExprNodeFactory;
  public
    { Brief: Constructs a new instance.
      Parameters:
        AIdent: Identifier token that should trigger this symbol. }
    constructor Create(const AIdent: string);

    { Brief: Evaluates this symbol.
      Description:
        This method is called by an evaluating Parser when it finds this
        symbol in its stream. It should call methods of the lexer and parser
        and ultimately return a value that represents the value of this
        symbol. The Lexer is positioned at the first token following the
        symbol.
      See Also:
        TExprSym.Compile, TExprSym.Lexer, TExprSym.EvalParser }
    function Evaluate: TFloat; virtual; abstract;

    { Brief: Compiles this symbol.
      Description:
        This method is called by a compiling Parser when it finds this symbol
        in its stream. It should call methods of the lexer and parser
        and ultimately return an expression node that contains all the
        necessary state to evaluate this symbol at expression evaluation
        time. The Lexer is positioned at the first token following the
        symbol.
      See Also:
        TExprNode, TExprSym.Evaluate, TExprSym.Lexer, TExprSym.CompileParser }
    function Compile: TExprNode; virtual; abstract;

    { Brief: Identifier token that should trigger this symbol. }
    property Ident: string read FIdent;

    { Brief: The lexical analyser that found this symbol in its stream.
      Description:
        This property is set by the parser when it finds this symbol in the
        input stream. This is done so that the Evaluate and Compile methods
        can perform things like reading parameters etc., when they work
        out their context.
      See Also: TExprSym.EvalParser, TExprSym.CompileParser,
        TExprSym.NodeFactory, TExprLexer }
    property Lexer: TExprLexer read FLexer write FLexer;

    { Brief: The compile parser that found this symbol in its stream.
      Description:
        This property is set by a compiling parser when it finds this
        symbol in its input stream. This is done so that the Compile method
        can perform things like reading parameters etc., when it gathers
        sufficient information for compilation.
      See Also: TExprSym.EvalParser, TExprSym.Lexer, TExprSym.NodeFactory,
        TExprCompileParser }
    property CompileParser: TExprCompileParser read FCompileParser
      write FCompileParser;

    { Brief: The evaluation parser that found this symbol in its stream.
      Description:
        This property is set by an evaluating parser when it finds this
        symbol in its input stream. This is done so that the Evaluate method
        can perform things like reading parameters etc., when it gathers
        sufficient information for evaluation.
      See Also: TExprSym.CompileParser, TExprSym.Lexer, TExprSym.NodeFactory,
        TExprEvalParser }
    property EvalParser: TExprEvalParser read FEvalParser write FEvalParser;

    { Brief: The expression node factory object for creating expression
        node instances.
      Description:
        This property is set by a compiling parser when it finds this symbol
        in its input stream. It is set to nil for an evaluating stream, so
        it is only valid to use this property in the Compile method. It is
        should be used to construct expression nodes with sufficient state
        to calculate the value of this symbol at expression evaluation time.
      See Also: TExprSym.Lexer, TExprSym.CompileParser, TExprSym.Compile,
        TExprNodeFactory }
    property NodeFactory: TExprNodeFactory read FNodeFactory write FNodeFactory;
  end;

  { Brief: The type of token found by TExprLexer. }
  TExprToken = (

    // specials
    etEof,
    etNumber,
    etIdentifier,

    // user extension tokens
    etUser0, etUser1, etUser2, etUser3, etUser4, etUser5, etUser6, etUser7,
    etUser8, etUser9, etUser10, etUser11, etUser12, etUser13, etUser14, etUser15,
    etUser16, etUser17, etUser18, etUser19, etUser20, etUser21, etUser22, etUser23,
    etUser24, etUser25, etUser26, etUser27, etUser28, etUser29, etUser30, etUser31,

    // compound tokens
    etNotEqual, // <>
    etLessEqual, // <=
    etGreaterEqual, // >=

    // ASCII normal & ordinals

    etBang, // '!' #$21 33
    etDoubleQuote, // '"' #$22 34
    etHash, // '#' #$23 35
    etDollar, // '$' #$24 36
    etPercent, // '%' #$25 37
    etAmpersand, // '&' #$26 38
    etSingleQuote, // '''' #$27 39
    etLParen, // '(' #$28 40
    etRParen, // ')' #$29 41
    etAsterisk, // '*' #$2A 42
    etPlus, // '+' #$2B 43
    etComma, // ',' #$2C 44
    etMinus, // '-' #$2D 45
    etDot, // '.' #$2E 46
    etForwardSlash, // '/' #$2F 47

    // 48..57 - numbers...

    etColon, // ':' #$3A 58
    etSemiColon, // ';' #$3B 59
    etLessThan, // '<' #$3C 60
    etEqualTo, // '=' #$3D 61
    etGreaterThan, // '>' #$3E 62
    etQuestion, // '?' #$3F 63
    etAt, // '@' #$40 64

    // 65..90 - capital letters...

    etLBracket, // '[' #$5B 91
    etBackSlash, // '\' #$5C 92
    etRBracket, // ']' #$5D 93
    etArrow, // '^' #$5E 94
    // 95 - underscore
    etBackTick, // '`' #$60 96

    // 97..122 - small letters...

    etLBrace, // '{' #$7B 123
    etPipe, // '|' #$7C 124
    etRBrace, // '}' #$7D 125
    etTilde, // '~' #$7E 126
    et127, // '' #$7F 127
    etEuro, // '' #$80 128
    et129, // '' #$81 129
    et130, // '' #$82 130
    et131, // '' #$83 131
    et132, // '' #$84 132
    et133, // '' #$85 133
    et134, // '' #$86 134
    et135, // '' #$87 135
    et136, // '' #$88 136
    et137, // '' #$89 137
    et138, // '' #$8A 138
    et139, // '' #$8B 139
    et140, // '' #$8C 140
    et141, // '' #$8D 141
    et142, // '' #$8E 142
    et143, // '' #$8F 143
    et144, // '' #$90 144
    et145, // '' #$91 145
    et146, // '' #$92 146
    et147, // '' #$93 147
    et148, // '' #$94 148
    et149, // '' #$95 149
    et150, // '' #$96 150
    et151, // '' #$97 151
    et152, // '' #$98 152
    et153, // '' #$99 153
    et154, // '' #$9A 154
    et155, // '' #$9B 155
    et156, // '' #$9C 156
    et157, // '' #$9D 157
    et158, // '' #$9E 158
    et159, // '' #$9F 159
    et160, // '' #$A0 160
    et161, // '' #$A1 161
    et162, // '' #$A2 162
    et163, // '' #$A3 163
    et164, // '' #$A4 164
    et165, // '' #$A5 165
    et166, // '' #$A6 166
    et167, // '' #$A7 167
    et168, // '' #$A8 168
    et169, // '' #$A9 169
    et170, // '' #$AA 170
    et171, // '' #$AB 171
    et172, // '' #$AC 172
    et173, // '' #$AD 173
    et174, // '' #$AE 174
    et175, // '' #$AF 175
    et176, // '' #$B0 176
    et177, // '' #$B1 177
    et178, // '' #$B2 178
    et179, // '' #$B3 179
    et180, // '' #$B4 180
    et181, // '' #$B5 181
    et182, // '' #$B6 182
    et183, // '' #$B7 183
    et184, // '' #$B8 184
    et185, // '' #$B9 185
    et186, // '' #$BA 186
    et187, // '' #$BB 187
    et188, // '' #$BC 188
    et189, // '' #$BD 189
    et190, // '' #$BE 190
    et191, // '' #$BF 191
    et192, // '' #$C0 192
    et193, // '' #$C1 193
    et194, // '' #$C2 194
    et195, // '' #$C3 195
    et196, // '' #$C4 196
    et197, // '' #$C5 197
    et198, // '' #$C6 198
    et199, // '' #$C7 199
    et200, // '' #$C8 200
    et201, // '' #$C9 201
    et202, // '' #$CA 202
    et203, // '' #$CB 203
    et204, // '' #$CC 204
    et205, // '' #$CD 205
    et206, // '' #$CE 206
    et207, // '' #$CF 207
    et208, // '' #$D0 208
    et209, // '' #$D1 209
    et210, // '' #$D2 210
    et211, // '' #$D3 211
    et212, // '' #$D4 212
    et213, // '' #$D5 213
    et214, // '' #$D6 214
    et215, // '' #$D7 215
    et216, // '' #$D8 216
    et217, // '' #$D9 217
    et218, // '' #$DA 218
    et219, // '' #$DB 219
    et220, // '' #$DC 220
    et221, // '' #$DD 221
    et222, // '' #$DE 222
    et223, // '' #$DF 223
    et224, // '' #$E0 224
    et225, // '' #$E1 225
    et226, // '' #$E2 226
    et227, // '' #$E3 227
    et228, // '' #$E4 228
    et229, // '' #$E5 229
    et230, // '' #$E6 230
    et231, // '' #$E7 231
    et232, // '' #$E8 232
    et233, // '' #$E9 233
    et234, // '' #$EA 234
    et235, // '' #$EB 235
    et236, // '' #$EC 236
    et237, // '' #$ED 237
    et238, // '' #$EE 238
    et239, // '' #$EF 239
    et240, // '' #$F0 240
    et241, // '' #$F1 241
    et242, // '' #$F2 242
    et243, // '' #$F3 243
    et244, // '' #$F4 244
    et245, // '' #$F5 245
    et246, // '' #$F6 246
    et247, // '' #$F7 247
    et248, // '' #$F8 248
    et249, // '' #$F9 249
    et250, // '' #$FA 250
    et251, // '' #$FB 251
    et252, // '' #$FC 252
    et253, // '' #$FD 253
    et254, // '' #$FE 254
    et255, // '' #$FF 255
    etInvalid // invalid token type
  );

  { Brief: A lexical analyser.
    Description:
      An object of this class breaks up an input stream into lexemes -
      that is, it breaks down the input stream into tokens with two
      properties: type and content. The type describes what sort of
      token the current token is. The content gives further information
      about some tokens.

      <p>For example, if the incoming stream is 'a + 03.60', then the lexical
      analyser will break it down into 3 tokens:
        * type (CurrTok): etIdentifier; content: TokenAsString = 'a'
        * type: etPlus; content: n/a
        * type: etNumber; content: TokenAsNumber = 3.6,
          also TokenAsString = '03.60'

      The token type is given by the CurrTok property, and the token
        content is given by the TokenAsString and TokenAsNumber properties.

      <p>The current token is skipped and the next token loaded when the
        NextTok method is called. When the end of the input stream is
        found, CurrTok will be equal to etEof, and repeated calls of
        NextTok won't do anything (i.e. CurrTok will remain equal to etEof). }
  TExprLexer = class
  protected
    { Brief: NextTok should set as appropriate. }
    FCurrTok: TExprToken;
    { Brief: NextTok should set as appropriate. }
    FTokenAsNumber: TFloat;
    { Brief: NextTok should set as appropriate. }
    FTokenAsString: string;
  public
    { Brief: Constructs an instance and calls Reset. }
    constructor Create;

    { Brief: Skips the current token and gets the next token.
      Description:
        This method is called by Reset (and thus implicitly by Create), so
        it doesn't need to be called to get the first token in the stream.

        <p>This method does the following jobs:
          * Skips whitespace
          * Determines token type from the first character after
            whitespace has been skipped
          * Reads in the rest of that token, based on the first character,
            possibly refining the token type based on further characters.
            For example, if '<' is read on the input stream, the token could
            be etLessThan, etNotEqual ('<>') or etLessEqual ('<=').
        After a call to this method, CurrTok will give the current token
        type, and TokenAsString and TokenAsNumber will give extra
        information as appropriate for the token type. }
    procedure NextTok; virtual; abstract;

    { Brief: Resets the position of the lexer to the start of its
        input stream.
      Description:
        Overridden implementations should call this at the <b>end</b> of
        their implementations, because it calls NextTok by default. }
    procedure Reset; virtual;

    { Brief: String information about the current token if that is
        appropriate.
      Description:
        This property is usually valid for tokens that don't have a fixed
        length, like etIdentifier and etNumber. It contains the text as
        found in the source stream, possibly after a little preprocessing
        (for instance, if the lexer supported strings, then this could
        return the string with control characters expanded). It is set by
        NextTok.
      See Also: NextTok, TokenAsNumber, CurrTok }
    property TokenAsString: string read FTokenAsString;

    { Brief: Number information about the current token if that is
        appropriate.
      Description:
        This property is usually only valid for well-formed integer or
        floating-point numbers found in the source text. It is set by
        NextTok.
      See Also: NextTok, TokenAsString, CurrTok }
    property TokenAsNumber: TFloat read FTokenAsNumber;

    { Brief: The current token type.
      Description:
        This contains the type of the token just read by NextTok.
      See Also: NextTok, TokenAsString, TokenAsNumber }
    property CurrTok: TExprToken read FCurrTok;
  end;

  { Brief: A node in an expression DAG (directed acyclic graph).
    Description:
      This is the abstract object from which all expression DAG nodes
      descend. TExprNodeFactory has responsibility for constructing
      the correct class and acts as a container for TExprNode descendant
      instances.
    Note: Don't construct TExprNode objects directly; call the methods
      of a TExprNodeFactory instance. }
  TExprNode = class
  private
    FDepList: TList;
    function GetDepCount: Integer;
    function GetDeps(AIndex: Integer): TExprNode;
  public
    { Brief: Constructs an instance.
      Parameters:
        ADepList: A list of dependancies, nodes this expression node
          depends on.
      Description:
        The dependancy list passed into this constructor should be the
        <b>direct</b> dependancies of this node. }
    constructor Create(const ADepList: array of TExprNode);
    { Brief: Destroys an instance. Use Free instead. }
    destructor Destroy; override;
    { Brief: Adds a dependancy.
      Parameters:
        ADep: Dependancy to add.
      Description:
        This method adds a dependancy to this node. }
    procedure AddDep(ADep: TExprNode);
    { Brief: Number of dependancies this node has. }
    property DepCount: Integer read GetDepCount;
    { Brief: Accesses a dependancy based on index. }
    property Deps[AIndex: Integer]: TExprNode read GetDeps; default;
    { Brief: Access to the internal dependancy list for advanced
      optimization strategies. }
    property DepList: TList read FDepList;
  end;

  { Brief: A factory class for TExprNode objects.
    Description:
      When compiling an expression, the expression must be broken down
      into 'atomic' components, like add, subtract, load constant,
      load variable, call function etc. Because different compilation
      strategies may involve different atomic node classes, the task
      of atomic node construction is given to a separate factory object.
      This object should keep a list of all the nodes it has constructed,
      and act as an interface for the construction of new nodes.
      <p>
      Concrete descendants of this factory should have a GenCode method
      that is specific to the implementation strategy. That GenCode method
      is a prime candidate for expression optimizations like common
      sub-expression elimination, constant sub-expression evaluation, etc. }
  TExprNodeFactory = class
  public
    { Brief: Loads the variable pointed to by ALoc.
      Description:
        Generates a node that will load a variable from a pointer. The
        type is important, because variables of different types are of
        different sizes and have different formats.
      Parameters:
        ALoc: Location of the variable to load. }
    function LoadVar32(ALoc: PFloat32): TExprNode; virtual; abstract;
    { <COMBINE LoadVar32> }
    function LoadVar64(ALoc: PFloat64): TExprNode; virtual; abstract;
    { <COMBINE LoadVar32> }
    function LoadVar80(ALoc: PFloat80): TExprNode; virtual; abstract;

    { Brief: Loads a constant value.
      Description:
        Generates a node that will load a constant value. The type is
        important because less precision will mean faster evaluation.
      Parameters:
        AValue: The value to load. }
    function LoadConst32(AValue: TFloat32): TExprNode; virtual; abstract;
    { <COMBINE LoadConst32> }
    function LoadConst64(AValue: TFloat64): TExprNode; virtual; abstract;
    { <COMBINE LoadConst32> }
    function LoadConst80(AValue: TFloat80): TExprNode; virtual; abstract;

    { Brief: Calls a function.
      Description:
        Generates a node that will call a function, possibly with
        parameters. There are 4 basic types of functions directly supported
        here: no parameters (Float*), 1 parameter (Unary*), 2 parameters
        (Binary*) and 3 parameters (Ternary*). }
    function CallFloatFunc(AFunc: TFloatFunc): TExprNode; virtual; abstract;
    { <COMBINE CallFloatFunc> }
    function CallFloat32Func(AFunc: TFloat32Func): TExprNode; virtual; abstract;
    { <COMBINE CallFloatFunc> }
    function CallFloat64Func(AFunc: TFloat64Func): TExprNode; virtual; abstract;
    { <COMBINE CallFloatFunc> }
    function CallFloat80Func(AFunc: TFloat80Func): TExprNode; virtual; abstract;
    { <COMBINE CallFloatFunc> }
    function CallUnaryFunc(AFunc: TUnaryFunc; x: TExprNode): TExprNode; virtual; abstract;
    { <COMBINE CallFloatFunc> }
    function CallUnary32Func(AFunc: TUnary32Func; x: TExprNode): TExprNode; virtual; abstract;
    { <COMBINE CallFloatFunc> }
    function CallUnary64Func(AFunc: TUnary64Func; x: TExprNode): TExprNode; virtual; abstract;
    { <COMBINE CallFloatFunc> }
    function CallUnary80Func(AFunc: TUnary80Func; x: TExprNode): TExprNode; virtual; abstract;
    { <COMBINE CallFloatFunc> }
    function CallBinaryFunc(AFunc: TBinaryFunc; x, y: TExprNode): TExprNode; virtual; abstract;
    { <COMBINE CallFloatFunc> }
    function CallBinary32Func(AFunc: TBinary32Func; x, y: TExprNode): TExprNode; virtual; abstract;
    { <COMBINE CallFloatFunc> }
    function CallBinary64Func(AFunc: TBinary64Func; x, y: TExprNode): TExprNode; virtual; abstract;
    { <COMBINE CallFloatFunc> }
    function CallBinary80Func(AFunc: TBinary80Func; x, y: TExprNode): TExprNode; virtual; abstract;
    { <COMBINE CallFloatFunc> }
    function CallTernaryFunc(AFunc: TTernaryFunc; x, y, z: TExprNode): TExprNode; virtual; abstract;
    { <COMBINE CallFloatFunc> }
    function CallTernary32Func(AFunc: TTernary32Func; x, y, z: TExprNode): TExprNode; virtual; abstract;
    { <COMBINE CallFloatFunc> }
    function CallTernary64Func(AFunc: TTernary64Func; x, y, z: TExprNode): TExprNode; virtual; abstract;
    { <COMBINE CallFloatFunc> }
    function CallTernary80Func(AFunc: TTernary80Func; x, y, z: TExprNode): TExprNode; virtual; abstract;

    { Brief: Performs an arithmetic operation.
      Description:
        These functions generate nodes that perform an arithmetic operation
        on their operands. }
    function Add(ALeft, ARight: TExprNode): TExprNode; virtual; abstract;
    { <COMBINE Add> }
    function Subtract(ALeft, ARight: TExprNode): TExprNode; virtual; abstract;
    { <COMBINE Add> }
    function Multiply(ALeft, ARight: TExprNode): TExprNode; virtual; abstract;
    { <COMBINE Add> }
    function Divide(ALeft, ARight: TExprNode): TExprNode; virtual; abstract;
    { <COMBINE Add> }
    function Negate(AValue: TExprNode): TExprNode; virtual; abstract;

    { Brief: Performs a comparison.
      Parameters:
        ALeft: Left side of comparison.
        ARight: Right side of comparison.
      Returns:
        A node that represents this comparison.
      Description:
        Compare returns a node that evaluates to -1, 0, or 1 depending on
        whether ALeft is less than, equal to, or greater than ARight,
        respectively. }
    function Compare(ALeft, ARight: TExprNode): TExprNode; virtual; abstract;

    { Brief: Overloaded declarations for auto-selection of correct
        function in code.
      Description:
        These functions should auto-select the correct function for
        the input variable in code, making it more maintainable. }
    function LoadVar(ALoc: PFloat32): TExprNode; overload;
    { <COMBINE TExprNodeFactory.LoadVar@PFloat32> }
    function LoadVar(ALoc: PFloat64): TExprNode; overload;
    { <COMBINE TExprNodeFactory.LoadVar@PFloat32> }
    function LoadVar(ALoc: PFloat80): TExprNode; overload;
    { <COMBINE TExprNodeFactory.LoadVar@PFloat32> }
    function LoadConst(AValue: TFloat32): TExprNode; overload;
    { <COMBINE TExprNodeFactory.LoadVar@PFloat32> }
    function LoadConst(AValue: TFloat64): TExprNode; overload;
    { <COMBINE TExprNodeFactory.LoadVar@PFloat32> }
    function LoadConst(AValue: TFloat80): TExprNode; overload;
  end;

  { Brief: A compiling parser.
    Description:
      This is a compiling parser. It analyses the input stream of tokens
      from its lexer using a grammar and builds a graph of nodes that
      contains enough information to be converted into a high-speed
      evaluation structure, or possibly even machine code.

      <p>The key methods are Create and Compile.
    See Also: TExprEvalParser, TExprLexer, TExprSym }
  TExprCompileParser = class
  private
    FContext: TExprContext;
    FLexer: TExprLexer;
    FNodeFactory: TExprNodeFactory;
  public
    { Brief: Constructs an instance.
      Parameters:
        ALexer: The source of tokens to use. It doesn't take ownership
          of the lexer.
        ANodeFactory: The factory object to use for creating expression
          nodes. It doesn't take ownership of the factory. }
    constructor Create(ALexer: TExprLexer; ANodeFactory: TExprNodeFactory);

    { Brief: Compiles an expression from the lexical source.
      Description:
        This method compiles the expression by descending through its
        grammatical methods, starting with compile_expr.
      Returns: The top-level expression node. }
    function Compile: TExprNode; virtual;

    { Brief: The source of tokens for this parser. }
    property Lexer: TExprLexer read FLexer;

    { Brief: The node factory object that constructs concrete node types. }
    property NodeFactory: TExprNodeFactory read FNodeFactory;

    { Brief: The context object used for symbol lookup.
      Description:
        This property gives the context object that will be used for
        symbol lookup. Whenever an identifier is found in the input
        stream, the context will be searched (with TContext.Find), and the
        symbol found will have its <LINK TExprSym.Compile, Compile>
        method called. If no symbol is found or the Context property is nil,
        then an exception will be raised.  }
    property Context: TExprContext read FContext write FContext;

    // grammar starts here

    { Brief: Compiles relational operators and uses compile_simple_expr. }
    function compile_expr(ASkip: Boolean): TExprNode; virtual;
    { Brief: Compiles +, -, etc and uses compile_term. }
    function compile_simple_expr(ASkip: Boolean): TExprNode;
    { Brief: Compiles *, /, etc and uses compile_signed_factor. }
    function compile_term(ASkip: Boolean): TExprNode;
    { Brief: Compiles unary negate etc, and uses compile_factor. }
    function compile_signed_factor(ASkip: Boolean): TExprNode;
    { Brief: Compiles subexpressions (i.e. '(' & ')'), numbers, but defers
        identifiers to compile_ident_factor. }
    function compile_factor: TExprNode;
    { Brief: Looks up the symbol corresponding to an identifier and
        returns its compilation. }
    function compile_ident_factor: TExprNode;
  end;

  { Brief: An evaluating parser.
    Description:
      This is an evaluating parser. It evaluates the result of an expression
      as it grammatically analyses the input stream of tokens from its lexer.
      It returns a floating-point value.
    See Also: TExprCompileParser, TExprLexer, TExprSym }
  TExprEvalParser = class
  private
    FContext: TExprContext;
    FLexer: TExprLexer;
  public
    { Brief: Constructs an instance.
      Parameters:
        ALexer: The source of tokens to use. It doesn't take ownership
          of the lexer. }
    constructor Create(ALexer: TExprLexer);

    { Brief: Evaluates an expression from the lexical source.
      Description:
        This method evaluates the expression by descending through its
        grammatical methods, starting with eval_expr.
      Returns: The result of the evaluation. }
    function Evaluate: TFloat; virtual;

    { Brief: The source of tokens for this parser. }
    property Lexer: TExprLexer read FLexer;

    { Brief: The context object used for symbol lookup.
      Description:
        This property gives the context object that will be used for
        symbol lookup. Whenever an identifier is found in the input
        stream, the context will be searched (with TContext.Find), and
        the symbol found will have its <LINK TExprSym.Evaluate, Evaluate>
        method called. If no symbol is found or the Context property is nil,
        then an exception will be raised.  }
    property Context: TExprContext read FContext write FContext;

    // grammar starts here

    { Brief: Evaluates relational operators and uses eval_simple_expr. }
    function eval_expr(ASkip: Boolean): TFloat; virtual;
    { Brief: Evaluates +, -, etc and uses eval_term. }
    function eval_simple_expr(ASkip: Boolean): TFloat;
    { Brief: Evaluates *, /, etc and uses eval_signed_factor. }
    function eval_term(ASkip: Boolean): TFloat;
    { Brief: Evaluates unary negate etc, and uses eval_factor. }
    function eval_signed_factor(ASkip: Boolean): TFloat;
    { Brief: Evaluates subexpressions (i.e. '(' & ')'), numbers, but defers
        identifiers to eval_ident_factor. }
    function eval_factor: TFloat;
    { Brief: Looks up the symbol corresponding to an identifier and
        returns its evaluation. }
    function eval_ident_factor: TFloat;
  end;

{ some concrete class descendants follow... }

type
  { Brief: A simple expression lexical analyser. }
  TExprSimpleLexer = class(TExprLexer)
  protected
    { Brief: Current position in buffer. }
    FCurrPos: PChar;
    { Brief: Buffer containing expression. }
    FBuf: string;
    { Brief: Sets a new buffer and calls Reset. }
    procedure SetBuf(const ABuf: string);
  public
    { Brief: Constructs an instance with a buffer ABuf.
      Parameters:
        ABuf: A string containing an expression. }
    constructor Create(const ABuf: string);

    procedure NextTok; override;
    procedure Reset; override;

    { Brief: Buffer to read expression from.
      Description:
        Set this to change the source text the lexer extracts its tokens
        from. When it is set, the property setter calls the Reset method,
        so the lexer will be in a valid state to serve tokens. }
    property Buf: string read FBuf write SetBuf;
  end;

type
  { Brief: An operation that can be executed by a TExprVirtMach instance.
    Description:
      TExprVirtMachOp is the kernel of TExprVirtMach's operation. The
      containing class (TExprVirtMach) is just that - a container, and
      it just executes the instructions in order to do work.
      <p>
      Each instruction has a virtual Execute method, which should read
      input from somewhere and write output to somewhere else. Typically,
      the input is a series of pointers to floating-point variables, and
      the output is to one or more member variables. The output acts as
      input for instructions further on in the execution stream; for this
      mechanism to work, the inputs of downstream instructions must be
      'wired' to the outputs of upstream instructions.
    See Also: TExprVirtMach }
  TExprVirtMachOp = class
  private
    function GetOutputLoc: PFloat;
  protected
    { Brief: The actual variable this operation will write its output to.
      Description:
        This is the internal storage variable this operation will write
        its output to. Operations that use this operation for input should
        take the address of this variable (through the OutputLoc property)
        to get the result of evaluating this operation.
        <p>
        It is protected to allow easy (and fast) access for descendants.
      See Also: OutputLoc }
    FOutput: TFloat;
  public
    { Brief: Executes this instruction.
      Description:
        This method executes this instruction, reading from its inputs
        and writing to its output location. It returns False to terminate
        the execution sequence early; usually it returns True. }
    procedure Execute; virtual; abstract;

    { Brief: The address to which this operation will write its output to.
      See Also: FOutput }
    property OutputLoc: PFloat read GetOutputLoc;
  end;

  { Brief: A virtual machine for evaluating expressions relatively quickly.
    See Also: TExprVirtMachNodeFactory, TExprVirtMachOp }
  TExprVirtMach = class
  private
    FCodeList: TList;
    FConstList: TList;
  public
    { Brief: Constructs an instance. }
    constructor Create;
    { Brief: Destroys an instance. Use Free instead. }
    destructor Destroy; override;

    { Brief: Adds an operation to the end of the list of operations.
      Parameters:
        AOp: The operation to add. }
    procedure Add(AOp: TExprVirtMachOp);

    { Brief: Adds a constant to the constant list.
      Parameters:
        AOp: The constant to add. }
    procedure AddConst(AOp: TExprVirtMachOp);

    { Brief: Clears any stored code. }
    procedure Clear;

    { Brief: Executes the stored code and returns the result.
      Returns:
        The value output by the last instruction executed (the result).
      Description:
        This method executes the stored instructions in order starting
        at the beginning until it either runs out of instructions or it
        encounters a halt instruction. }
    function Execute: TFloat;
  end;

  { Brief: A node factory for virtual machine instructions.
    Description:
      This is a factory class for the default virtual machine.
    See Also: TExprVirtMach }
  TExprVirtMachNodeFactory = class(TExprNodeFactory)
  private
    FNodeList: TList;

    function AddNode(ANode: TExprNode): TExprNode;
    procedure DoClean(AVirtMach: TExprVirtMach);
    procedure DoConsts(AVirtMach: TExprVirtMach);
    procedure DoCode(AVirtMach: TExprVirtMach);
  public
    { Brief: Constructs an instance. }
    constructor Create;

    { Brief: Destroys an instance. Use Free instead. }
    destructor Destroy; override;

    { Brief: Generates code for a virtual machine.
      Parameters:
        AVirtMach: The virtual machine to generate code for.
      Description:
        This method converts the internal node DAG into instructions for
        the virtual machine passed in. }
    procedure GenCode(AVirtMach: TExprVirtMach);

    function LoadVar32(ALoc: PFloat32): TExprNode; override;
    function LoadVar64(ALoc: PFloat64): TExprNode; override;
    function LoadVar80(ALoc: PFloat80): TExprNode; override;
    function LoadConst32(AValue: TFloat32): TExprNode; override;
    function LoadConst64(AValue: TFloat64): TExprNode; override;
    function LoadConst80(AValue: TFloat80): TExprNode; override;

    function CallFloatFunc(AFunc: TFloatFunc): TExprNode; override;
    function CallFloat32Func(AFunc: TFloat32Func): TExprNode; override;
    function CallFloat64Func(AFunc: TFloat64Func): TExprNode; override;
    function CallFloat80Func(AFunc: TFloat80Func): TExprNode; override;
    function CallUnaryFunc(AFunc: TUnaryFunc; x: TExprNode): TExprNode; override;
    function CallUnary32Func(AFunc: TUnary32Func; x: TExprNode): TExprNode; override;
    function CallUnary64Func(AFunc: TUnary64Func; x: TExprNode): TExprNode; override;
    function CallUnary80Func(AFunc: TUnary80Func; x: TExprNode): TExprNode; override;
    function CallBinaryFunc(AFunc: TBinaryFunc; x, y: TExprNode): TExprNode; override;
    function CallBinary32Func(AFunc: TBinary32Func; x, y: TExprNode): TExprNode; override;
    function CallBinary64Func(AFunc: TBinary64Func; x, y: TExprNode): TExprNode; override;
    function CallBinary80Func(AFunc: TBinary80Func; x, y: TExprNode): TExprNode; override;
    function CallTernaryFunc(AFunc: TTernaryFunc; x, y, z: TExprNode): TExprNode; override;
    function CallTernary32Func(AFunc: TTernary32Func; x, y, z: TExprNode): TExprNode; override;
    function CallTernary64Func(AFunc: TTernary64Func; x, y, z: TExprNode): TExprNode; override;
    function CallTernary80Func(AFunc: TTernary80Func; x, y, z: TExprNode): TExprNode; override;

    function Add(ALeft, ARight: TExprNode): TExprNode; override;
    function Subtract(ALeft, ARight: TExprNode): TExprNode; override;
    function Multiply(ALeft, ARight: TExprNode): TExprNode; override;
    function Divide(ALeft, ARight: TExprNode): TExprNode; override;
    function Negate(AValue: TExprNode): TExprNode; override;
    function Compare(ALeft, ARight: TExprNode): TExprNode; override;
  end;

{ some concrete symbols }

type
  { Brief: Symbol for a constant of type TFloat. }
  TExprConstSym = class(TExprSym)
  private
    FValue: TFloat;
  public
    { Brief: Constructs an instance.
      Parameters:
        AIdent: Identifier for this constant.
        AValue: Value this identifier should evaluate to. }
    constructor Create(const AIdent: string; AValue: TFloat);
    function Evaluate: TFloat; override;
    function Compile: TExprNode; override;
  end;

  { Brief: Symbol for a constant of type TFloat32. }
  TExprConst32Sym = class(TExprSym)
  private
    FValue: TFloat32;
  public
    { Brief: Constructs an instance.
      Parameters:
        AIdent: Identifier for this constant.
        AValue: Value this identifier should evaluate to. }
    constructor Create(const AIdent: string; AValue: TFloat32);
    function Evaluate: TFloat; override;
    function Compile: TExprNode; override;
  end;

  { Brief: Symbol for a constant of type TFloat64. }
  TExprConst64Sym = class(TExprSym)
  private
    FValue: TFloat64;
  public
    { Brief: Constructs an instance.
      Parameters:
        AIdent: Identifier for this constant.
        AValue: Value this identifier should evaluate to. }
    constructor Create(const AIdent: string; AValue: TFloat64);
    function Evaluate: TFloat; override;
    function Compile: TExprNode; override;
  end;

  { Brief: Symbol for a constant of type TFloat80. }
  TExprConst80Sym = class(TExprSym)
  private
    FValue: TFloat80;
  public
    { Brief: Constructs an instance.
      Parameters:
        AIdent: Identifier for this constant.
        AValue: Value this identifier should evaluate to. }
    constructor Create(const AIdent: string; AValue: TFloat80);
    function Evaluate: TFloat; override;
    function Compile: TExprNode; override;
  end;

  { Brief: This class evaluates and / or compiles code for a 32-bit
    FP variable. }
  TExprVar32Sym = class(TExprSym)
  private
    FLoc: PFloat32;
  public
    { Brief: Constructs a symbol representing a 32-bit FP variable.
      Parameters:
        AIdent: Name of the variable.
        ALoc: Address of the variable. }
    constructor Create(const AIdent: string; ALoc: PFloat32);

    function Evaluate: TFloat; override;
    function Compile: TExprNode; override;
  end;

  { Brief: This class evaluates and / or compiles code for a 64-bit
    FP variable. }
  TExprVar64Sym = class(TExprSym)
  private
    FLoc: PFloat64;
  public
    { Brief: Constructs a symbol representing a 64-bit FP variable.
      Parameters:
        AIdent: Name of the variable.
        ALoc: Address of the variable. }
    constructor Create(const AIdent: string; ALoc: PFloat64);

    function Evaluate: TFloat; override;
    function Compile: TExprNode; override;
  end;

  { Brief: This class evaluates and / or compiles code for an 80-bit
    FP variable. }
  TExprVar80Sym = class(TExprSym)
  private
    FLoc: PFloat80;
  public
    { Brief: Constructs a symbol representing an 80-bit FP variable.
      Parameters:
        AIdent: Name of the variable.
        ALoc: Address of the variable. }
    constructor Create(const AIdent: string; ALoc: PFloat80);

    function Evaluate: TFloat; override;
    function Compile: TExprNode; override;
  end;

  { Brief: A helper ancestor for function symbols.
    Description:
      This is a useful class to use as an ancestor for function symbols
      because it has protected methods to read parameters. }
  TExprAbstractFuncSym = class(TExprSym)
  protected
    { Brief: Evaluates the first argument using the EvalParser.
      Returns:
        The evaluation of the first argument.
      Description:
        This method will raise an exception if there is a missing '(' or
        missing first argument. }
    function EvalFirstArg: TFloat;
    { Brief: Evaluates a second or subsequent argument using EvalParser.
      Returns:
        The evaluation of the next argument.
      Description:
        This method will raise an exception if there is a missing ',' or
        missing argument after the comma. }
    function EvalNextArg: TFloat;
    { Brief: Compiles the first argument using the CompileParser.
      Returns:
        The compiled node for the first argument.
      Description:
        This method will raise an exception if there is a missing '(' or
        missing first argument. }
    function CompileFirstArg: TExprNode;
    { Brief: Compiles a second or subsequent argument using CompileParser.
      Returns:
        The compiled node for the next argument.
      Description:
        This method will raise an exception if there is a missing ',' or
        missing argument after the comma. }
    function CompileNextArg: TExprNode;
    { Brief: Reads in the end of an argument list.
      Description:
        This method will raise an exception if the current token isn't ')'.
        After checking, it skips the right parenthesis. }
    procedure EndArgs;
  end;

  { Brief: Function symbol for TFloatFunc. }
  TExprFuncSym = class(TExprAbstractFuncSym)
  private
    FFunc: TFloatFunc;
  public
    { Brief: Constructs an instance.
      Parameters:
        AIdent: Identifier for this function.
        AFunc: Function that evaluates this symbol. }
    constructor Create(const AIdent: string; AFunc: TFloatFunc);
    function Evaluate: TFloat; override;
    function Compile: TExprNode; override;
  end;

  { Brief: Function symbol for TFloat32Func. }
  TExprFloat32FuncSym = class(TExprAbstractFuncSym)
  private
    FFunc: TFloat32Func;
  public
    { Brief: Constructs an instance.
      Parameters:
        AIdent: Identifier for this function.
        AFunc: Function that evaluates this symbol. }
    constructor Create(const AIdent: string; AFunc: TFloat32Func);
    function Evaluate: TFloat; override;
    function Compile: TExprNode; override;
  end;

  { Brief: Function symbol for TFloat64Func. }
  TExprFloat64FuncSym = class(TExprAbstractFuncSym)
  private
    FFunc: TFloat64Func;
  public
    { Brief: Constructs an instance.
      Parameters:
        AIdent: Identifier for this function.
        AFunc: Function that evaluates this symbol. }
    constructor Create(const AIdent: string; AFunc: TFloat64Func);
    function Evaluate: TFloat; override;
    function Compile: TExprNode; override;
  end;

  { Brief: Function symbol for TFloat80Func. }
  TExprFloat80FuncSym = class(TExprAbstractFuncSym)
  private
    FFunc: TFloat80Func;
  public
    { Brief: Constructs an instance.
      Parameters:
        AIdent: Identifier for this function.
        AFunc: Function that evaluates this symbol. }
    constructor Create(const AIdent: string; AFunc: TFloat80Func);
    function Evaluate: TFloat; override;
    function Compile: TExprNode; override;
  end;

  { Brief: Function symbol for TUnaryFunc. }
  TExprUnaryFuncSym = class(TExprAbstractFuncSym)
  private
    FFunc: TUnaryFunc;
  public
    { Brief: Constructs an instance.
      Parameters:
        AIdent: Identifier for this function.
        AFunc: Function that evaluates this symbol. }
    constructor Create(const AIdent: string; AFunc: TUnaryFunc);
    function Evaluate: TFloat; override;
    function Compile: TExprNode; override;
  end;

  { Brief: Function symbol for TUnary32Func. }
  TExprUnary32FuncSym = class(TExprAbstractFuncSym)
  private
    FFunc: TUnary32Func;
  public
    { Brief: Constructs an instance.
      Parameters:
        AIdent: Identifier for this function.
        AFunc: Function that evaluates this symbol. }
    constructor Create(const AIdent: string; AFunc: TUnary32Func);
    function Evaluate: TFloat; override;
    function Compile: TExprNode; override;
  end;

  { Brief: Function symbol for TUnary64Func. }
  TExprUnary64FuncSym = class(TExprAbstractFuncSym)
  private
    FFunc: TUnary64Func;
  public
    { Brief: Constructs an instance.
      Parameters:
        AIdent: Identifier for this function.
        AFunc: Function that evaluates this symbol. }
    constructor Create(const AIdent: string; AFunc: TUnary64Func);
    function Evaluate: TFloat; override;
    function Compile: TExprNode; override;
  end;

  { Brief: Function symbol for TUnary80Func. }
  TExprUnary80FuncSym = class(TExprAbstractFuncSym)
  private
    FFunc: TUnary80Func;
  public
    { Brief: Constructs an instance.
      Parameters:
        AIdent: Identifier for this function.
        AFunc: Function that evaluates this symbol. }
    constructor Create(const AIdent: string; AFunc: TUnary80Func);
    function Evaluate: TFloat; override;
    function Compile: TExprNode; override;
  end;

  { Brief: Function symbol for TBinaryFunc. }
  TExprBinaryFuncSym = class(TExprAbstractFuncSym)
  private
    FFunc: TBinaryFunc;
  public
    { Brief: Constructs an instance.
      Parameters:
        AIdent: Identifier for this function.
        AFunc: Function that evaluates this symbol. }
    constructor Create(const AIdent: string; AFunc: TBinaryFunc);
    function Evaluate: TFloat; override;
    function Compile: TExprNode; override;
  end;

  { Brief: Function symbol for TBinary32Func. }
  TExprBinary32FuncSym = class(TExprAbstractFuncSym)
  private
    FFunc: TBinary32Func;
  public
    { Brief: Constructs an instance.
      Parameters:
        AIdent: Identifier for this function.
        AFunc: Function that evaluates this symbol. }
    constructor Create(const AIdent: string; AFunc: TBinary32Func);
    function Evaluate: TFloat; override;
    function Compile: TExprNode; override;
  end;

  { Brief: Function symbol for TBinary64Func. }
  TExprBinary64FuncSym = class(TExprAbstractFuncSym)
  private
    FFunc: TBinary64Func;
  public
    { Brief: Constructs an instance.
      Parameters:
        AIdent: Identifier for this function.
        AFunc: Function that evaluates this symbol. }
    constructor Create(const AIdent: string; AFunc: TBinary64Func);
    function Evaluate: TFloat; override;
    function Compile: TExprNode; override;
  end;

  { Brief: Function symbol for TBinary80Func. }
  TExprBinary80FuncSym = class(TExprAbstractFuncSym)
  private
    FFunc: TBinary80Func;
  public
    { Brief: Constructs an instance.
      Parameters:
        AIdent: Identifier for this function.
        AFunc: Function that evaluates this symbol. }
    constructor Create(const AIdent: string; AFunc: TBinary80Func);
    function Evaluate: TFloat; override;
    function Compile: TExprNode; override;
  end;

  { Brief: Function symbol for TTernaryFunc. }
  TExprTernaryFuncSym = class(TExprAbstractFuncSym)
  private
    FFunc: TTernaryFunc;
  public
    { Brief: Constructs an instance.
      Parameters:
        AIdent: Identifier for this function.
        AFunc: Function that evaluates this symbol. }
    constructor Create(const AIdent: string; AFunc: TTernaryFunc);
    function Evaluate: TFloat; override;
    function Compile: TExprNode; override;
  end;

  { Brief: Function symbol for TTernary32Func. }
  TExprTernary32FuncSym = class(TExprAbstractFuncSym)
  private
    FFunc: TTernary32Func;
  public
    { Brief: Constructs an instance.
      Parameters:
        AIdent: Identifier for this function.
        AFunc: Function that evaluates this symbol. }
    constructor Create(const AIdent: string; AFunc: TTernary32Func);
    function Evaluate: TFloat; override;
    function Compile: TExprNode; override;
  end;

  { Brief: Function symbol for TTernary64Func. }
  TExprTernary64FuncSym = class(TExprAbstractFuncSym)
  private
    FFunc: TTernary64Func;
  public
    { Brief: Constructs an instance.
      Parameters:
        AIdent: Identifier for this function.
        AFunc: Function that evaluates this symbol. }
    constructor Create(const AIdent: string; AFunc: TTernary64Func);
    function Evaluate: TFloat; override;
    function Compile: TExprNode; override;
  end;

  { Brief: Function symbol for TTernary80Func. }
  TExprTernary80FuncSym = class(TExprAbstractFuncSym)
  private
    FFunc: TTernary80Func;
  public
    { Brief: Constructs an instance.
      Parameters:
        AIdent: Identifier for this function.
        AFunc: Function that evaluates this symbol. }
    constructor Create(const AIdent: string; AFunc: TTernary80Func);
    function Evaluate: TFloat; override;
    function Compile: TExprNode; override;
  end;

type
  { Brief: This is an abstract class that provides friendly methods for
      adding constanst, variables, functions and external contexts.
    Description:
      This is an abstract class provided so that symbols can be added
      to descendants' internal contexts with minimum hassle. Use a concrete
      descendant, like TEvaluator or TCompiledEvaluator instead. }
  TEasyEvaluator = class
  private
    FOwnContext: TExprHashContext;
    FExtContextSet: TExprSetContext;
    FInternalContextSet: TExprSetContext;
  protected
    { Brief: Provides protected access to the internal context set.
      Description:
        This is provided so that descendants can set their parser's Context
        property. }
    property InternalContextSet: TExprSetContext read FInternalContextSet;
  public
    { Brief: Creates an instance. }
    constructor Create;
    { Brief: Destroys an instance. Use Free instead. }
    destructor Destroy; override;

    { Brief: Adds a variable.
      Parameters:
        AName: Identifier of variable to add.
        AVar: Location of variable to add.
      Description:
        Adds a variable to the internal context. Whenever the variable
        is found in an expression, its current value will be inserted.
      Note: An assumption that may be made by optimizing compilers is that
        functions don't modify variables, and that functions may be called
        in any order.
      Note: Any variables added using these methods will override
        identifiers of the same name in external contexts added through
        ExtContextSet. }
    procedure AddVar(const AName: string; var AVar: TFloat32); overload;
    { <COMBINE TEasyEvaluator.AddVar@string@TFloat32> }
    procedure AddVar(const AName: string; var AVar: TFloat64); overload;
    { <COMBINE TEasyEvaluator.AddVar@string@TFloat32> }
    procedure AddVar(const AName: string; var AVar: TFloat80); overload;

    { Brief: Adds a constant.
      Parameters:
        AName: Identifier for the constant.
        AConst: Value of constant.
      Description:
        Adds a constant to the internal context. Constants are different
        from variables because sub-expressions made entirely from
        constants may be evaluated only once (at compile time), and that
        value used for all subsequent evaluations.
      Note: Any constants added using these methods will override
        identifiers of the same name in external contexts added through
        ExtContextSet. }
    procedure AddConst(const AName: string; AConst: TFloat32); overload;
    { <COMBINE TEasyEvaluator.AddConst@string@TFloat32> }
    procedure AddConst(const AName: string; AConst: TFloat64); overload;
    { <COMBINE TEasyEvaluator.AddConst@string@TFloat32> }
    procedure AddConst(const AName: string; AConst: TFloat80); overload;

    { Brief: Adds a function.
      Parameters:
        AName: Identifier for the function.
        AFunc: Function pointer that evaluates the function.
      Description:
        Adds a function to the internal context. Multiple calls to the
        same function with the same parameters <b>might</b> be resolved to
        a single call during common sub-expression elimination (CSE)
        optimization. A possible workaround would be to add a fake extra
        parameter and pass in different constant for each distinct call.
      Note: Any functions added using these methods will override
        identifiers of the same name in external contexts added through
        ExtContextSet. }
    procedure AddFunc(const AName: string; AFunc: TFloat32Func); overload;
    { <COMBINE TEasyEvaluator.AddFunc@string@TFloat32Func> }
    procedure AddFunc(const AName: string; AFunc: TFloat64Func); overload;
    { <COMBINE TEasyEvaluator.AddFunc@string@TFloat32Func> }
    procedure AddFunc(const AName: string; AFunc: TFloat80Func); overload;
    { <COMBINE TEasyEvaluator.AddFunc@string@TFloat32Func> }
    procedure AddFunc(const AName: string; AFunc: TUnary32Func); overload;
    { <COMBINE TEasyEvaluator.AddFunc@string@TFloat32Func> }
    procedure AddFunc(const AName: string; AFunc: TUnary64Func); overload;
    { <COMBINE TEasyEvaluator.AddFunc@string@TFloat32Func> }
    procedure AddFunc(const AName: string; AFunc: TUnary80Func); overload;
    { <COMBINE TEasyEvaluator.AddFunc@string@TFloat32Func> }
    procedure AddFunc(const AName: string; AFunc: TBinary32Func); overload;
    { <COMBINE TEasyEvaluator.AddFunc@string@TFloat32Func> }
    procedure AddFunc(const AName: string; AFunc: TBinary64Func); overload;
    { <COMBINE TEasyEvaluator.AddFunc@string@TFloat32Func> }
    procedure AddFunc(const AName: string; AFunc: TBinary80Func); overload;
    { <COMBINE TEasyEvaluator.AddFunc@string@TFloat32Func> }
    procedure AddFunc(const AName: string; AFunc: TTernary32Func); overload;
    { <COMBINE TEasyEvaluator.AddFunc@string@TFloat32Func> }
    procedure AddFunc(const AName: string; AFunc: TTernary64Func); overload;
    { <COMBINE TEasyEvaluator.AddFunc@string@TFloat32Func> }
    procedure AddFunc(const AName: string; AFunc: TTernary80Func); overload;

    { Brief: Removes an identifier from the internal context.
      Parameters:
        AName: Identifier to remove.
      Description:
        This method removes an identifier from the internal context and
        frees its associated symbol.
      Note: This is the only way to remove a single identifier from the
        internal context (call Clear to remove all identifiers). }
    procedure Remove(const AName: string);
    { Brief: Clears all identifiers from the internal context.
      Description:
        This method clears the internal context of symbols. It doesn't
        affect any contexts added through ExtContextSet. }
    procedure Clear;

    { Brief: A set of external contexts that are looked up after
        the internal context.
      Description:
        This property allows the addition of multiple utility contexts
        to this expression evaluator. Things like function libraries,
        variable sets, constant libraries etc. may be added using methods
        of this property. }
    property ExtContextSet: TExprSetContext read FExtContextSet;
  end;

  { Brief: Quick evaluator shell object.
    Description:
      This is an encapsulation of a simple lexer and an evaluating
      parser. It evaluates while parsing, and it doesn't store any
      compiled expression. This means it evaluates quite quickly, but
      isn't very fast for repeated evaluations of the same expression.

    Example:
      Create a new project, remove the default form and replace the contents
      of the project file with this:
      <code>
        uses SysUtils, JclExprEval, Dialogs;

        function MyAdder(x, y: Double): Double;
        begin
          Result := x + y + 0.12;
        end;

        var
          evaluator: TEvaluator;
          x: Double;
          y: Extended;
        begin
          evaluator := TEvaluator.Create;
          try
            evaluator.AddVar('x', x);
            evaluator.AddVar('y', y);
            evaluator.AddFunc('MyAdder', MyAdder);

            x := 3.5;
            y := 0.7;
            ShowMessage(Format('Delphi says: %.4g',
              [MyAdder(x, y)]));
            ShowMessage(Format('TEvaluator says: %.4g',
              [evaluator.Evaluate('MyAdder(x, y)')]));
          finally
            evaluator.Free;
          end;
        end.
      </code> }
  TEvaluator = class(TEasyEvaluator)
  private
    FLexer: TExprSimpleLexer;
    FParser: TExprEvalParser;
  public
    { Brief: Constructs an instance. }
    constructor Create;
    { Brief: Destroys an instance. Use Free instead. }
    destructor Destroy; override;

    { Brief: Evaluates an expression.
      Parameters:
        AExpr: The expression to evaluate.
      Returns:
        The result of the evaluation.
      Description:
        This sets the lexer source to AExpr, and calls the parser's
        <link TExprEvalParser.Evaluate, Evaluate> method. }
    function Evaluate(const AExpr: string): TFloat;
  end;

  { Brief: An evaluator that first compiles an expression into an
      intermediate form, then evaluates it on demand.
    Description:
      This evaluator is suitable for applications like graphing, where
      there is just one expression which is constantly evaluated with
      variables and/or functions changing value. It takes longer to
      compile than TEvaluator does to evaluate, but once compiled is
      much faster. }
  TCompiledEvaluator = class(TEasyEvaluator)
  private
    FExpr: string;
    FVirtMach: TExprVirtMach;
  public
    { Brief: Constructs an instance. }
    constructor Create;
    destructor Destroy; override;

    { Brief: Compiles an expression.
      Parameters:
        AExpr: The expression to compile.
      Description:
        Compiles the expression given by AExpr, and stores its compiled
        state internally, so that it can be evaluated quickly. }
    procedure Compile(const AExpr: string);
    { Brief: Evaluates the internal compiled expression.
      Returns: The result of the evaluation.
      Description:
        Executes the internal compiled state, and returns the evaluation.
        If there was an error while compiling, or the object is just after
        being created, it returns zero. }
    function Evaluate: TFloat;
  end;

  {TODO: change this definition to be just a normal function pointer, not
    a closure; will require a small executable memory allocater, and a
    couple of injected instructions. Similar concept to
    Forms.MakeObjectInstance.

    This will allow compiled expressions to be used as functions in
    contexts. Parameters won't be supported, though; I'll think about
    this. }

  { Brief: A compiled expression, which may be called directly to evaluate. }
  TCompiledExpression = function: TFloat of object;

  { Brief: An expression compiler, for multiple expressions.
    Description:
      This is a multiple expression compiler. It compiles expressions into
      function pointers, so that the function pointer can be called as if
      it were an ordinary Delphi function. It takes longer to compile an
      expression than TEvaluator does to evaluate, but once compiled it is
      much faster at evaluating.
      <p>
      It is suitable for spreadsheet-like applications, where there may
      be thousands of functions, all of which have to be evaluated
      quickly and repeatedly. }
  TExpressionCompiler = class(TEasyEvaluator)
  private
    FExprHash: TStringHashMap;
  public
    { Brief: Constructs an instance. }
    constructor Create;
    destructor Destroy; override;

    { Brief: Compiles an expression into a function pointer.
      Parameters:
        AExpr: Expression to compile.
      Returns:
        A function pointer which, when called, will evaluate the result of
        the expression and return it.
      Description:
        This method compiles the given expression into an internal
        representation (a reference to which is kept internally), and
        returns a function pointer that evaluates the expression
        whenever called.
        <p>
        Because a reference is kept internally, to free the expression
        (and thus release its resources), either the Remove or Delete
        methods must be called. Calling Clear will free all expressions,
        as will freeing this compiler. }
    function Compile(const AExpr: string): TCompiledExpression;
    { Brief: Frees a compiled expression.
      Parameters:
        AExpr: Expression to remove.
      Description:
        Remove frees the expression into which AExpr was compiled. AExpr is
        used as a string to look up a hash map, so it should be identical
        to the string passed in to Compile. }
    procedure Remove(const AExpr: string);
    { Brief: Frees a compiled expression.
      Parameters:
        ACompiledExpression: Expression to remove.
      Description:
        Delete frees the expression referenced by ACompiledExpression. }
    procedure Delete(ACompiledExpression: TCompiledExpression);
    { Brief: Clears all compiled expressions.
      Description:
        This method frees all internal compiled expressions; this will
        invalidate any remaining compiled expression function pointers,
        and subsequntly calling one of these remaining function pointers
        will result in undefined behaviour (probably an access violation). }
    procedure Clear;
  end;

implementation

{ TExprHashContext }

constructor TExprHashContext.Create(ACaseSensitive: Boolean;
  AHashSize: Integer);
begin
  if ACaseSensitive then
    FHashMap := TStringHashMap.Create(CaseSensitiveTraits, AHashSize)
  else
    FHashMap := TStringHashMap.Create(CaseInsensitiveTraits, AHashSize);
end;

destructor TExprHashContext.Destroy;
begin
  FHashMap.Iterate(nil, Iterate_FreeObjects);
  FHashMap.Free;
  inherited Destroy;
end;

procedure TExprHashContext.Add(ASymbol: TExprSym);
begin
  FHashMap.Add(ASymbol.Ident, ASymbol);
end;

procedure TExprHashContext.Remove(const AName: string);
begin
  TObject(FHashMap.Remove(AName)).Free;
end;

function TExprHashContext.Find(const AName: string): TExprSym;
begin
  if not FHashMap.Find(AName, Result) then
    Result := nil;
end;

{ TExprSetContext }

procedure TExprSetContext.Add(AContext: TExprContext);
begin
  FList.Add(AContext);
end;

constructor TExprSetContext.Create(AOwnsContexts: Boolean);
begin
  FOwnsContexts := AOwnsContexts;
  FList := TList.Create;
end;

procedure TExprSetContext.Delete(AIndex: Integer);
begin
  if FOwnsContexts then
    TObject(FList[AIndex]).Free;
  FList.Delete(AIndex);
end;

destructor TExprSetContext.Destroy;
begin
  if FOwnsContexts then
    ClearObjectList(FList);
  FList.Free;
  inherited Destroy;
end;

function TExprSetContext.Extract(AContext: TExprContext): TExprContext;
begin
  Result := AContext;
  FList.Remove(AContext);
end;

function TExprSetContext.Find(const AName: string): TExprSym;
var
  i: Integer;
begin
  Result := nil;
  for i := Count - 1 downto 0 do
  begin
    Result := Contexts[i].Find(AName);
    if Result <> nil then
      Exit;
  end;
end;

function TExprSetContext.GetContexts(AIndex: Integer): TExprContext;
begin
  Result := TExprContext(FList[AIndex]);
end;

function TExprSetContext.GetCount: Integer;
begin
  Result := FList.Count;
end;

procedure TExprSetContext.Remove(AContext: TExprContext);
begin
  FList.Remove(AContext);
  if FOwnsContexts then
    AContext.Free;
end;

{ TExprSym }

constructor TExprSym.Create(const AIdent: string);
begin
  FIdent := AIdent;
end;

{ TExprLexer }

constructor TExprLexer.Create;
begin
  Reset;
end;

procedure TExprLexer.Reset;
begin
  NextTok;
end;

{ TExprCompileParser }

constructor TExprCompileParser.Create(ALexer: TExprLexer;
  ANodeFactory: TExprNodeFactory);
begin
  FLexer := ALexer;
  FNodeFactory := ANodeFactory;
end;

function TExprCompileParser.Compile: TExprNode;
begin
  Result := compile_expr(False);
end;

function TExprCompileParser.compile_expr(ASkip: Boolean): TExprNode;
begin
  Result := compile_simple_expr(ASkip);

  { Utilize some of these compound instructions to test DAG optimization
    techniques later on.

    Playing a few games after much hard work, too.
    Functional programming is fun! :-> BJK }
  while True do
    case Lexer.CurrTok of
      etEqualTo: // =
      begin
        // need to return 1 if true, 0 if false
        // compare will return 0 if true, -1 / +1 if false
        // squaring will force a positive or zero value
        // subtract value from 1 to get answer
        // IOW: 1 - Sqr(Compare(x, y))

        // first, get comparison
        Result := NodeFactory.Compare(Result, compile_simple_expr(True));

        // next, square comparison - note that this
        // forces a common sub-expression; parse tree will no longer
        // be a tree, but a DAG
        Result := NodeFactory.Multiply(Result, Result);

        // finally, subtract from one
        Result := NodeFactory.Subtract(
          NodeFactory.LoadConst32(1),
          Result
        );
      end;

      etNotEqual: // <>
      begin
        // same as above, but without the subtract
        Result := NodeFactory.Compare(Result, compile_simple_expr(True));
        Result := NodeFactory.Multiply(Result, Result);
      end;

      etLessThan: // <
      begin
        // have 1 for less than, 0 for equal, 0 for greater than too
        // c = compare(x, y)
        // d = c * c
        // if less than, d = 1, c = -1; d - c = 2
        // if greater than, d = c = 1;  d - c = 0
        // if equal, d = c = 0;         d - c = 0
        // IOW: (Sqr(compare(x, y)) - compare(x, y)) / 2

        // get comparison
        Result := NodeFactory.Compare(Result, compile_simple_expr(True));
        // subtract from square
        Result := NodeFactory.Subtract(
          NodeFactory.Multiply(
            Result,
            Result
          ),
          Result
        );
        // divide by two
        Result := NodeFactory.Divide(Result, NodeFactory.LoadConst32(2));
      end;

      etLessEqual: // <=
      begin
        // less than or equal to return 1, greater than returns 0
        // c = compare(x, y)
        // d = c * c
        // <  c = -1, d = 1, c + d = 0
        // =  c = 0,  d = 0, c + d = 0
        // >  c = +1, d = 1, c + d = 2
        // then divide by two, take away from 1
        // IOW: 1 - (compare(x, y) + Sqr(compare(x, y))) / 2
        Result := NodeFactory.Compare(Result, compile_simple_expr(True));
        // now, for some fun!
        Result := NodeFactory.Subtract(
          NodeFactory.LoadConst32(1),
          NodeFactory.Divide(
            NodeFactory.Add(
              Result,
              NodeFactory.Multiply(
                Result,
                Result
              )
            ),
            NodeFactory.LoadConst32(2)
          )
        );
      end;

      etGreaterThan: // >
      begin
        // same as <=, without the taking away from 1 bit
        Result := NodeFactory.Compare(Result, compile_simple_expr(True));
        Result := NodeFactory.Divide(
          NodeFactory.Add(
            Result,
            NodeFactory.Multiply(
              Result,
              Result
            )
          ),
          NodeFactory.LoadConst32(2)
        );
      end;

      etGreaterEqual: // >=
      begin
        // same as less than, but subtract from one
        Result := NodeFactory.Compare(Result, compile_simple_expr(True));
        Result := NodeFactory.Subtract(
          NodeFactory.Multiply(
            Result,
            Result
          ),
          Result
        );
        Result := NodeFactory.Divide(Result, NodeFactory.LoadConst32(2));
        Result := NodeFactory.Subtract(NodeFactory.LoadConst32(1), Result);
      end;
    else
      Break;
    end;
end;

function TExprCompileParser.compile_simple_expr(ASkip: Boolean): TExprNode;
begin
  Result := compile_term(ASkip);

  while True do
    case Lexer.CurrTok of
      etPlus:
        Result := NodeFactory.Add(Result, compile_term(True));
      etMinus:
        Result := NodeFactory.Subtract(Result, compile_term(True));
    else
      Break;
    end;
end;

function TExprCompileParser.compile_term(ASkip: Boolean): TExprNode;
begin
  Result := compile_signed_factor(ASkip);

  while True do
    case Lexer.CurrTok of
      etAsterisk:
        Result := NodeFactory.Multiply(Result, compile_signed_factor(True));
      etForwardSlash:
        Result := NodeFactory.Divide(Result, compile_signed_factor(True));
    else
      Break;
    end;
end;

function TExprCompileParser.compile_signed_factor(ASkip: Boolean): TExprNode;
var
  neg: Boolean;
begin
  if ASkip then
    Lexer.NextTok;

  neg := False;
  while True do
  begin
    case Lexer.CurrTok of
      etPlus:
        { do nothing };
      etMinus:
        neg := not neg;
    else
      Break;
    end;
    Lexer.NextTok;
  end;

  Result := compile_factor;
  if neg then
    Result := NodeFactory.Negate(Result);
end;

function TExprCompileParser.compile_factor: TExprNode;
begin
  case Lexer.CurrTok of
    etNumber:
    begin
      Result := NodeFactory.LoadConst64(Lexer.TokenAsNumber);
      Lexer.NextTok;
    end;

    etIdentifier:
      Result := compile_ident_factor;

    etLParen:
    begin
      Result := compile_expr(True);
      if Lexer.CurrTok <> etRParen then
        raise EJclExprEvalError.CreateResRec(@RsExprEvalRParenExpected);
      Lexer.NextTok;
    end;
  else
    raise EJclExprEvalError.CreateResRec(@RsExprEvalFactorExpected);
  end;
end;

function TExprCompileParser.compile_ident_factor: TExprNode;
var
  sym: TExprSym;
  oldCompileParser: TExprCompileParser;
  oldLexer: TExprLexer;
  oldNodeFactory: TExprNodeFactory;
begin
  { find symbol }
  if FContext = nil then
    raise EJclExprEvalError.CreateResRecFmt(@RsExprEvalUnknownSymbol,
      [Lexer.TokenAsString]);
  sym := FContext.Find(Lexer.TokenAsString);
  if sym = nil then
    raise EJclExprEvalError.CreateResRecFmt(@RsExprEvalUnknownSymbol,
      [Lexer.TokenAsString]);

  Lexer.NextTok;

  { set symbol properties }
  oldCompileParser := sym.CompileParser;
  oldLexer := sym.Lexer;
  oldNodeFactory := sym.NodeFactory;
  sym.FLexer := Lexer;
  sym.FCompileParser := Self;
  sym.FNodeFactory := NodeFactory;
  try
    { compile symbol }
    Result := sym.Compile;
  finally
    sym.FLexer := oldLexer;
    sym.FCompileParser := oldCompileParser;
    sym.FNodeFactory := oldNodeFactory;
  end;
end;

{ TExprEvalParser }

constructor TExprEvalParser.Create(ALexer: TExprLexer);
begin
  FLexer := ALexer;
end;

function TExprEvalParser.Evaluate: TFloat;
begin
  Result := eval_expr(False);
end;

function TExprEvalParser.eval_expr(ASkip: Boolean): TFloat;
begin
  Result := eval_simple_expr(ASkip);

  while True do
    case Lexer.CurrTok of
      etEqualTo: // =
        if Result = eval_simple_expr(True) then
          Result := 1
        else
          Result := 0;
      etNotEqual: // <>
        if Result <> eval_simple_expr(True) then
          Result := 1
        else
          Result := 0;
      etLessThan: // <
        if Result < eval_simple_expr(True) then
          Result := 1
        else
          Result := 0;
      etLessEqual: // <=
        if Result <= eval_simple_expr(True) then
          Result := 1
        else
          Result := 0;
      etGreaterThan: // >
        if Result > eval_simple_expr(True) then
          Result := 1
        else
          Result := 0;
      etGreaterEqual: // >=
        if Result >= eval_simple_expr(True) then
          Result := 1
        else
          Result := 0;
    else
      Break;
    end;
end;

function TExprEvalParser.eval_simple_expr(ASkip: Boolean): TFloat;
begin
  Result := eval_term(ASkip);

  while True do
    case Lexer.CurrTok of
      etPlus:
        Result := Result + eval_term(True);
      etMinus:
        Result := Result - eval_term(True);
    else
      Exit;
    end;
end;

function TExprEvalParser.eval_term(ASkip: Boolean): TFloat;
begin
  Result := eval_signed_factor(ASkip);

  while True do
    case Lexer.CurrTok of
      etAsterisk:
        Result := Result * eval_signed_factor(True);
      etForwardSlash:
        Result := Result / eval_signed_factor(True);
    else
      Exit;
    end;
end;

function TExprEvalParser.eval_signed_factor(ASkip: Boolean): TFloat;
var
  neg: Boolean;
begin
  if ASkip then
    Lexer.NextTok;

  neg := False;
  while True do
  begin
    case Lexer.CurrTok of
      etPlus:
        { do nothing };
      etMinus:
        neg := not neg;
    else
      Break;
    end;
    Lexer.NextTok;
  end;

  Result := eval_factor;
  if neg then
    Result := - Result;
end;

function TExprEvalParser.eval_factor: TFloat;
begin
  case Lexer.CurrTok of
    etIdentifier:
      Result := eval_ident_factor;

    etLParen:
    begin
      Result := eval_expr(True);
      if Lexer.CurrTok <> etRParen then
        raise EJclExprEvalError.CreateResRec(@RsExprEvalRParenExpected);
      Lexer.NextTok;
    end;

    etNumber:
    begin
      Result := Lexer.TokenAsNumber;
      Lexer.NextTok;
    end;
  else
    raise EJclExprEvalError.CreateResRec(@RsExprEvalFactorExpected);
  end;
end;

function TExprEvalParser.eval_ident_factor: TFloat;
var
  sym: TExprSym;
  oldEvalParser: TExprEvalParser;
  oldLexer: TExprLexer;
begin
  { find symbol }
  if FContext = nil then
    raise EJclExprEvalError.CreateResRecFmt(@RsExprEvalUnknownSymbol,
      [Lexer.TokenAsString]);
  sym := FContext.Find(Lexer.TokenAsString);
  if sym = nil then
    raise EJclExprEvalError.CreateResRecFmt(@RsExprEvalUnknownSymbol,
      [Lexer.TokenAsString]);

  Lexer.NextTok;

  { set symbol properties }
  oldEvalParser := sym.FEvalParser;
  oldLexer := sym.Lexer;
  sym.FLexer := Lexer;
  sym.FEvalParser := Self;
  try
    { evaluate symbol }
    Result := sym.Evaluate;
  finally
    sym.FLexer := oldLexer;
    sym.FEvalParser := oldEvalParser;
  end;
end;

{ TExprSimpleLexer }

constructor TExprSimpleLexer.Create(const ABuf: string);
begin
  FBuf := ABuf;
  inherited Create;
end;

procedure TExprSimpleLexer.NextTok;
var
  { register variable optimization }
  cp: PChar;
  start: PChar;
const
  CharToTokenMap: array[Char] of TExprToken =
  (
    {#0..#31}
    etInvalid, etInvalid, etInvalid, etInvalid, etInvalid, etInvalid, etInvalid, etInvalid,
    etInvalid, etInvalid, etInvalid, etInvalid, etInvalid, etInvalid, etInvalid, etInvalid,
    etInvalid, etInvalid, etInvalid, etInvalid, etInvalid, etInvalid, etInvalid, etInvalid,
    etInvalid, etInvalid, etInvalid, etInvalid, etInvalid, etInvalid, etInvalid, etInvalid,
    {#32} etInvalid,
    {#33} etBang, {#34} etDoubleQuote, {#35} etHash, {#36} etDollar,
    {#37} etPercent, {#38} etAmpersand, {#39} etSingleQuote, {#40} etLParen,
    {#41} etRParen, {#42} etAsterisk, {#43} etPlus, {#44} etComma,
    {#45} etMinus, {#46} etDot, {#47} etForwardSlash,
    // 48..57 - numbers...
    etInvalid, etInvalid, etInvalid, etInvalid,
    etInvalid, etInvalid, etInvalid, etInvalid,
    etInvalid, etInvalid,
    {#58} etColon, {#59} etSemiColon, {#60} etLessThan, {#61} etEqualTo,
    {#62} etGreaterThan, {#63} etQuestion, {#64} etAt,
    // 65..90 - capital letters...
    etInvalid, etInvalid, etInvalid, etInvalid,
    etInvalid, etInvalid, etInvalid, etInvalid,
    etInvalid, etInvalid, etInvalid, etInvalid,
    etInvalid, etInvalid, etInvalid, etInvalid,
    etInvalid, etInvalid, etInvalid, etInvalid,
    etInvalid, etInvalid, etInvalid, etInvalid,
    etInvalid, etInvalid,
    {#91} etLBracket, {#92} etBackSlash, {#93} etRBracket, {#94} etArrow,
    etInvalid, // 95 - underscore
    {#96} etBackTick,
    // 97..122 - small letters...
    etInvalid, etInvalid, etInvalid, etInvalid,
    etInvalid, etInvalid, etInvalid, etInvalid,
    etInvalid, etInvalid, etInvalid, etInvalid,
    etInvalid, etInvalid, etInvalid, etInvalid,
    etInvalid, etInvalid, etInvalid, etInvalid,
    etInvalid, etInvalid, etInvalid, etInvalid,
    etInvalid, etInvalid,
    {#123} etLBrace,
    {#124} etPipe, {#125} etRBrace, {#126} etTilde, {#127} et127,
    {#128} etEuro, {#129} et129, {#130} et130, {#131} et131,
    {#132} et132, {#133} et133, {#134} et134, {#135} et135,
    {#136} et136, {#137} et137, {#138} et138, {#139} et139,
    {#140} et140, {#141} et141, {#142} et142, {#143} et143,
    {#144} et144, {#145} et145, {#146} et146, {#147} et147,
    {#148} et148, {#149} et149, {#150} et150, {#151} et151,
    {#152} et152, {#153} et153, {#154} et154, {#155} et155,
    {#156} et156, {#157} et157, {#158} et158, {#159} et159,
    {#160} et160, {#161} et161, {#162} et162, {#163} et163,
    {#164} et164, {#165} et165, {#166} et166, {#167} et167,
    {#168} et168, {#169} et169, {#170} et170, {#171} et171,
    {#172} et172, {#173} et173, {#174} et174, {#175} et175,
    {#176} et176, {#177} et177, {#178} et178, {#179} et179,
    {#180} et180, {#181} et181, {#182} et182, {#183} et183,
    {#184} et184, {#185} et185, {#186} et186, {#187} et187,
    {#188} et188, {#189} et189, {#190} et190, {#191} et191,
    {#192} et192, {#193} et193, {#194} et194, {#195} et195,
    {#196} et196, {#197} et197, {#198} et198, {#199} et199,
    {#200} et200, {#201} et201, {#202} et202, {#203} et203,
    {#204} et204, {#205} et205, {#206} et206, {#207} et207,
    {#208} et208, {#209} et209, {#210} et210, {#211} et211,
    {#212} et212, {#213} et213, {#214} et214, {#215} et215,
    {#216} et216, {#217} et217, {#218} et218, {#219} et219,
    {#220} et220, {#221} et221, {#222} et222, {#223} et223,
    {#224} et224, {#225} et225, {#226} et226, {#227} et227,
    {#228} et228, {#229} et229, {#230} et230, {#231} et231,
    {#232} et232, {#233} et233, {#234} et234, {#235} et235,
    {#236} et236, {#237} et237, {#238} et238, {#239} et239,
    {#240} et240, {#241} et241, {#242} et242, {#243} et243,
    {#244} et244, {#245} et245, {#246} et246, {#247} et247,
    {#248} et248, {#249} et249, {#250} et250, {#251} et251,
    {#252} et252, {#253} et253, {#254} et254, {#255} et255
  );
begin
  cp := FCurrPos;

  { skip whitespace }
  while cp^ in ExprWhiteSpace do
    Inc(cp);

  { determine token type }
  case cp^ of
    #0:
      FCurrTok := etEof;

    'a'..'z', 'A'..'Z', '_':
    begin
      start := cp;
      Inc(cp);
      while cp^ in ['0'..'9', 'a'..'z', 'A'..'Z', '_'] do
        Inc(cp);
      SetString(FTokenAsString, start, cp - start);
      FCurrTok := etIdentifier;
    end;

    '0'..'9':
    begin
      start := cp;

      { read in integer part of mantissa }
      while cp^ in ['0'..'9'] do
        Inc(cp);

      { check for and read in fraction part of mantissa }
      if cp^ = '.' then
      begin
        Inc(cp);
        while cp^ in ['0'..'9'] do
          Inc(cp);
      end;

      { check for and read in exponent }
      if cp^ in ['e', 'E'] then
      begin
        Inc(cp);
        if cp^ in ['+', '-'] then
          Inc(cp);
        while cp^ in ['0'..'9'] do
          Inc(cp);
      end;

      { evaluate number }
      SetString(FTokenAsString, start, cp - start);
      FTokenAsNumber := StrToFloat(FTokenAsString);

      FCurrTok := etNumber;
    end;

    '<':
    begin
      Inc(cp);
      case cp^ of
        '=':
        begin
          FCurrTok := etLessEqual;
          Inc(cp);
        end;

        '>':
        begin
          FCurrTok := etNotEqual;
          Inc(cp);
        end;
      else
        FCurrTok := etLessThan;
      end;
    end;

    '>':
    begin
      Inc(cp);
      if cp^ = '=' then
      begin
        FCurrTok := etGreaterEqual;
        Inc(cp);
      end else
        FCurrTok := etGreaterThan;
    end;

  else
    { map character to token }
    FCurrTok := CharToTokenMap[cp^];
    Inc(cp);
  end;

  FCurrPos := cp;
end;

procedure TExprSimpleLexer.Reset;
begin
  FCurrPos := PChar(FBuf);
  inherited Reset;
end;

procedure TExprSimpleLexer.SetBuf(const ABuf: string);
begin
  FBuf := ABuf;
  Reset;
end;

{ TExprNode }

constructor TExprNode.Create(const ADepList: array of TExprNode);
var
  i: Integer;
begin
  FDepList := TList.Create;

  for i := 0 to High(ADepList) do
    AddDep(ADepList[i]);
end;

destructor TExprNode.Destroy;
begin
  FDepList.Free;
  inherited Destroy;
end;

procedure TExprNode.AddDep(ADep: TExprNode);
begin
  FDepList.Add(ADep);
end;

function TExprNode.GetDepCount: Integer;
begin
  Result := FDepList.Count;
end;

function TExprNode.GetDeps(AIndex: Integer): TExprNode;
begin
  Result := TExprNode(FDepList[AIndex]);
end;

{ TExprNodeFactory }

function TExprNodeFactory.LoadVar(ALoc: PFloat32): TExprNode;
begin
  Result := LoadVar32(ALoc);
end;

function TExprNodeFactory.LoadVar(ALoc: PFloat64): TExprNode;
begin
  Result := LoadVar64(ALoc);
end;

function TExprNodeFactory.LoadVar(ALoc: PFloat80): TExprNode;
begin
  Result := LoadVar80(ALoc);
end;

function TExprNodeFactory.LoadConst(AValue: TFloat32): TExprNode;
begin
  Result := LoadConst32(AValue);
end;

function TExprNodeFactory.LoadConst(AValue: TFloat64): TExprNode;
begin
  Result := LoadConst64(AValue);
end;

function TExprNodeFactory.LoadConst(AValue: TFloat80): TExprNode;
begin
  Result := LoadConst80(AValue);
end;

{ TEvaluator }

constructor TEvaluator.Create;
begin
  inherited Create;

  FLexer := TExprSimpleLexer.Create('');
  FParser := TExprEvalParser.Create(FLexer);

  FParser.Context := InternalContextSet;
end;

destructor TEvaluator.Destroy;
begin
  FParser.Free;
  FLexer.Free;
  inherited Destroy;
end;

function TEvaluator.Evaluate(const AExpr: string): TFloat;
begin
  FLexer.Buf := AExpr;
  Result := FParser.Evaluate;
end;

{ TExprVirtMachOp }

function TExprVirtMachOp.GetOutputLoc: PFloat;
begin
  Result := @FOutput;
end;

{ ================================ }
{ Virtual machine operators follow }
{ ================================ }

type
  { abstract base for var readers }
  TExprVarVmOp = class(TExprVirtMachOp)
  private
    FVarLoc: Pointer;
  public
    constructor Create(AVarLoc: Pointer);
  end;

  TExprVarVmOpClass = class of TExprVarVmOp;

  { the var readers }

  TExprVar32VmOp = class(TExprVarVmOp)
  public
    procedure Execute; override;
  end;

  TExprVar64VmOp = class(TExprVarVmOp)
  public
    procedure Execute; override;
  end;

  TExprVar80VmOp = class(TExprVarVmOp)
  public
    procedure Execute; override;
  end;

  { the const holder }
  TExprConstVmOp = class(TExprVirtMachOp)
  public
    constructor Create(AValue: TFloat);
    { null function }
    procedure Execute; override;
  end;

  { abstract unary operator }
  TExprUnaryVmOp = class(TExprVirtMachOp)
  protected
    FInput: PFloat;
  public
    constructor Create(AInput: PFloat);
    property Input: PFloat read FInput write FInput;
  end;

  TExprUnaryVmOpClass = class of TExprUnaryVmOp;

  { abstract binary operator }
  TExprBinaryVmOp = class(TExprVirtMachOp)
  protected
    FLeft: PFloat;
    FRight: PFloat;
  public
    constructor Create(ALeft, ARight: PFloat);
    property Left: PFloat read FLeft write FLeft;
    property Right: PFloat read FRight write FRight;
  end;

  TExprBinaryVmOpClass = class of TExprBinaryVmOp;

  { the 4 basic binary operators }

  TExprAddVmOp = class(TExprBinaryVmOp)
  public
    procedure Execute; override;
  end;

  TExprSubtractVmOp = class(TExprBinaryVmOp)
  public
    procedure Execute; override;
  end;

  TExprMultiplyVmOp = class(TExprBinaryVmOp)
  public
    procedure Execute; override;
  end;

  TExprDivideVmOp = class(TExprBinaryVmOp)
  public
    procedure Execute; override;
  end;

  TExprCompareVmOp = class(TExprBinaryVmOp)
  public
    procedure Execute; override;
  end;

  { the unary operators }

  TExprNegateVmOp = class(TExprUnaryVmOp)
  public
    procedure Execute; override;
  end;

  { function calls }

  TExprCallFloatVmOp = class(TExprVirtMachOp)
  private
    FFunc: TFloatFunc;
  public
    constructor Create(AFunc: TFloatFunc);
    procedure Execute; override;
  end;

  TExprCallFloat32VmOp = class(TExprVirtMachOp)
  private
    FFunc: TFloat32Func;
  public
    constructor Create(AFunc: TFloat32Func);
    procedure Execute; override;
  end;

  TExprCallFloat64VmOp = class(TExprVirtMachOp)
  private
    FFunc: TFloat64Func;
  public
    constructor Create(AFunc: TFloat64Func);
    procedure Execute; override;
  end;

  TExprCallFloat80VmOp = class(TExprVirtMachOp)
  private
    FFunc: TFloat80Func;
  public
    constructor Create(AFunc: TFloat80Func);
    procedure Execute; override;
  end;

  TExprCallUnaryVmOp = class(TExprVirtMachOp)
  private
    FFunc: TUnaryFunc;
    FX: PFloat;
  public
    constructor Create(AFunc: TUnaryFunc; x: PFloat);
    procedure Execute; override;
  end;

  TExprCallUnary32VmOp = class(TExprVirtMachOp)
  private
    FFunc: TUnary32Func;
    FX: PFloat;
  public
    constructor Create(AFunc: TUnary32Func; x: PFloat);
    procedure Execute; override;
  end;

  TExprCallUnary64VmOp = class(TExprVirtMachOp)
  private
    FFunc: TUnary64Func;
    FX: PFloat;
  public
    constructor Create(AFunc: TUnary64Func; x: PFloat);
    procedure Execute; override;
  end;

  TExprCallUnary80VmOp = class(TExprVirtMachOp)
  private
    FFunc: TUnary80Func;
    FX: PFloat;
  public
    constructor Create(AFunc: TUnary80Func; x: PFloat);
    procedure Execute; override;
  end;

  TExprCallBinaryVmOp = class(TExprVirtMachOp)
  private
    FFunc: TBinaryFunc;
    FX, FY: PFloat;
  public
    constructor Create(AFunc: TBinaryFunc; x, y: PFloat);
    procedure Execute; override;
  end;

  TExprCallBinary32VmOp = class(TExprVirtMachOp)
  private
    FFunc: TBinary32Func;
    FX, FY: PFloat;
  public
    constructor Create(AFunc: TBinary32Func; x, y: PFloat);
    procedure Execute; override;
  end;

  TExprCallBinary64VmOp = class(TExprVirtMachOp)
  private
    FFunc: TBinary64Func;
    FX, FY: PFloat;
  public
    constructor Create(AFunc: TBinary64Func; x, y: PFloat);
    procedure Execute; override;
  end;

  TExprCallBinary80VmOp = class(TExprVirtMachOp)
  private
    FFunc: TBinary80Func;
    FX, FY: PFloat;
  public
    constructor Create(AFunc: TBinary80Func; x, y: PFloat);
    procedure Execute; override;
  end;

  TExprCallTernaryVmOp = class(TExprVirtMachOp)
  private
    FFunc: TTernaryFunc;
    FX, FY, FZ: PFloat;
  public
    constructor Create(AFunc: TTernaryFunc; x, y, z: PFloat);
    procedure Execute; override;
  end;

  TExprCallTernary32VmOp = class(TExprVirtMachOp)
  private
    FFunc: TTernary32Func;
    FX, FY, FZ: PFloat;
  public
    constructor Create(AFunc: TTernary32Func; x, y, z: PFloat);
    procedure Execute; override;
  end;

  TExprCallTernary64VmOp = class(TExprVirtMachOp)
  private
    FFunc: TTernary64Func;
    FX, FY, FZ: PFloat;
  public
    constructor Create(AFunc: TTernary64Func; x, y, z: PFloat);
    procedure Execute; override;
  end;

  TExprCallTernary80VmOp = class(TExprVirtMachOp)
  private
    FFunc: TTernary80Func;
    FX, FY, FZ: PFloat;
  public
    constructor Create(AFunc: TTernary80Func; x, y, z: PFloat);
    procedure Execute; override;
  end;

{ TExprVar32VmOp }

procedure TExprVar32VmOp.Execute;
begin
  FOutput := PFloat32(FVarLoc)^;
end;

{ TExprVar64VmOp }

procedure TExprVar64VmOp.Execute;
begin
  FOutput := PFloat64(FVarLoc)^;
end;

{ TExprVar80VmOp }

procedure TExprVar80VmOp.Execute;
begin
  FOutput := PFloat80(FVarLoc)^;
end;

{ TExprConstVmOp }

constructor TExprConstVmOp.Create(AValue: TFloat);
begin
  FOutput := AValue;
end;

procedure TExprConstVmOp.Execute;
begin
end;

{ TExprUnaryVmOp }

constructor TExprUnaryVmOp.Create(AInput: PFloat);
begin
  FInput := AInput;
end;

{ TExprBinaryVmOp }

constructor TExprBinaryVmOp.Create(ALeft, ARight: PFloat);
begin
  FLeft := ALeft;
  FRight := ARight;
end;

{ TExprAddVmOp }

procedure TExprAddVmOp.Execute;
begin
  FOutput := FLeft^ + FRight^;
end;

{ TExprSubtractVmOp }

procedure TExprSubtractVmOp.Execute;
begin
  FOutput := FLeft^ - FRight^;
end;

{ TExprMultiplyVmOp }

procedure TExprMultiplyVmOp.Execute;
begin
  FOutput := FLeft^ * FRight^;
end;

{ TExprDivideVmOp }

procedure TExprDivideVmOp.Execute;
begin
  FOutput := FLeft^ / FRight^;
end;

{ TExprCompareVmOp }

procedure TExprCompareVmOp.Execute;
begin
  if FLeft^ < FRight^ then
    FOutput := -1
  else if FLeft^ > FRight^ then
    FOutput := 1
  else
    FOutput := 0;
end;

{ TExprNegateVmOp }

procedure TExprNegateVmOp.Execute;
begin
  FOutput := - FInput^;
end;

{ TExprVarVmOp }

constructor TExprVarVmOp.Create(AVarLoc: Pointer);
begin
  FVarLoc := AVarLoc;
end;

{ TExprCallFloatVmOp }

constructor TExprCallFloatVmOp.Create(AFunc: TFloatFunc);
begin
  FFunc := AFunc;
end;

procedure TExprCallFloatVmOp.Execute;
begin
  FOutput := FFunc;
end;

{ TExprCallFloat32VmOp }

constructor TExprCallFloat32VmOp.Create(AFunc: TFloat32Func);
begin
  FFunc := AFunc;
end;

procedure TExprCallFloat32VmOp.Execute;
begin
  FOutput := FFunc;
end;

{ TExprCallFloat64VmOp }

constructor TExprCallFloat64VmOp.Create(AFunc: TFloat64Func);
begin
  FFunc := AFunc;
end;

procedure TExprCallFloat64VmOp.Execute;
begin
  FOutput := FFunc;
end;

{ TExprCallFloat80VmOp }

constructor TExprCallFloat80VmOp.Create(AFunc: TFloat80Func);
begin
  FFunc := AFunc;
end;

procedure TExprCallFloat80VmOp.Execute;
begin
  FOutput := FFunc;
end;

{ TExprCallUnaryVmOp }

constructor TExprCallUnaryVmOp.Create(AFunc: TUnaryFunc; x: PFloat);
begin
  FFunc := AFunc;
  FX := x;
end;

procedure TExprCallUnaryVmOp.Execute;
begin
  FOutput := FFunc(FX^);
end;

{ TExprCallUnary32VmOp }

constructor TExprCallUnary32VmOp.Create(AFunc: TUnary32Func; x: PFloat);
begin
  FFunc := AFunc;
  FX := x;
end;

procedure TExprCallUnary32VmOp.Execute;
begin
  FOutput := FFunc(FX^);
end;

{ TExprCallUnary64VmOp }

constructor TExprCallUnary64VmOp.Create(AFunc: TUnary64Func; x: PFloat);
begin
  FFunc := AFunc;
  FX := x;
end;

procedure TExprCallUnary64VmOp.Execute;
begin
  FOutput := FFunc(FX^);
end;

{ TExprCallUnary80VmOp }

constructor TExprCallUnary80VmOp.Create(AFunc: TUnary80Func; x: PFloat);
begin
  FFunc := AFunc;
  FX := x;
end;

procedure TExprCallUnary80VmOp.Execute;
begin
  FOutput := FFunc(FX^);
end;

{ TExprCallBinaryVmOp }

constructor TExprCallBinaryVmOp.Create(AFunc: TBinaryFunc; x, y: PFloat);
begin
  FFunc := AFunc;
  FX := x;
  FY := y;
end;

procedure TExprCallBinaryVmOp.Execute;
begin
  FOutput := FFunc(FX^, FY^);
end;

{ TExprCallBinary32VmOp }

constructor TExprCallBinary32VmOp.Create(AFunc: TBinary32Func; x,
  y: PFloat);
begin
  FFunc := AFunc;
  FX := x;
  FY := y;
end;

procedure TExprCallBinary32VmOp.Execute;
begin
  FOutput := FFunc(FX^, FY^);
end;

{ TExprCallBinary64VmOp }

constructor TExprCallBinary64VmOp.Create(AFunc: TBinary64Func; x,
  y: PFloat);
begin
  FFunc := AFunc;
  FX := x;
  FY := y;
end;

procedure TExprCallBinary64VmOp.Execute;
begin
  FOutput := FFunc(FX^, FY^);
end;

{ TExprCallBinary80VmOp }

constructor TExprCallBinary80VmOp.Create(AFunc: TBinary80Func; x,
  y: PFloat);
begin
  FFunc := AFunc;
  FX := x;
  FY := y;
end;

procedure TExprCallBinary80VmOp.Execute;
begin
  FOutput := FFunc(FX^, FY^);
end;

{ TExprCallTernaryVmOp }

constructor TExprCallTernaryVmOp.Create(AFunc: TTernaryFunc; x, y,
  z: PFloat);
begin
  FFunc := AFunc;
  FX := x;
  FY := y;
  FZ := z;
end;

procedure TExprCallTernaryVmOp.Execute;
begin
  FOutput := FFunc(FX^, FY^, FZ^);
end;

{ TExprCallTernary32VmOp }

constructor TExprCallTernary32VmOp.Create(AFunc: TTernary32Func; x, y,
  z: PFloat);
begin
  FFunc := AFunc;
  FX := x;
  FY := y;
  FZ := z;
end;

procedure TExprCallTernary32VmOp.Execute;
begin
  FOutput := FFunc(FX^, FY^, FZ^);
end;

{ TExprCallTernary64VmOp }

constructor TExprCallTernary64VmOp.Create(AFunc: TTernary64Func; x, y,
  z: PFloat);
begin
  FFunc := AFunc;
  FX := x;
  FY := y;
  FZ := z;
end;

procedure TExprCallTernary64VmOp.Execute;
begin
  FOutput := FFunc(FX^, FY^, FZ^);
end;

{ TExprCallTernary80VmOp }

constructor TExprCallTernary80VmOp.Create(AFunc: TTernary80Func; x, y,
  z: PFloat);
begin
  FFunc := AFunc;
  FX := x;
  FY := y;
  FZ := z;
end;

procedure TExprCallTernary80VmOp.Execute;
begin
  FOutput := FFunc(FX^, FY^, FZ^);
end;

{ ================================ }
{ End of virtual machine operators }
{ ================================ }

{ TExprVirtMach }

constructor TExprVirtMach.Create;
begin
  FCodeList := TList.Create;
  FConstList := TList.Create;
end;

destructor TExprVirtMach.Destroy;
begin
  FreeObjectList(FCodeList);
  FreeObjectList(FConstList);
  inherited Destroy;
end;

function TExprVirtMach.Execute: TFloat;
type
  PExprVirtMachOp = ^TExprVirtMachOp;
var
  i: Integer;
  pop: PExprVirtMachOp;
begin
  if FCodeList.Count <> 0 then
  begin
    { The code that follows is the same as this, but a lot faster
    for i := 0 to FCodeList.Count - 1 do
      TExprVirtMachOp(FCodeList[i]).Execute; }
    i := FCodeList.Count;
    pop := @FCodeList.List^[0];
    while i > 0 do
    begin
      pop^.Execute;
      Inc(pop);
      Dec(i);
    end;
    Result := TExprVirtMachOp(FCodeList[FCodeList.Count - 1]).FOutput;
  end
  else
    Result := 0;
end;

procedure TExprVirtMach.Add(AOp: TExprVirtMachOp);
begin
  FCodeList.Add(AOp);
end;

procedure TExprVirtMach.AddConst(AOp: TExprVirtMachOp);
begin
  FConstList.Add(AOp);
end;

procedure TExprVirtMach.Clear;
begin
  ClearObjectList(FCodeList);
  ClearObjectList(FConstList);
end;

{ TExprVirtMachNode }

type
  TExprVirtMachNode = class(TExprNode)
  private
    FExprVmCode: TExprVirtMachOp;
    function GetVmDeps(AIndex: Integer): TExprVirtMachNode;
  public
    procedure GenCode(AVirtMach: TExprVirtMach); virtual; abstract;

    property ExprVmCode: TExprVirtMachOp read FExprVmCode;

    { this property saves typecasting to access ExprVmCode }
    property VmDeps[AIndex: Integer]: TExprVirtMachNode read GetVmDeps; default;
  end;

function TExprVirtMachNode.GetVmDeps(AIndex: Integer): TExprVirtMachNode;
begin
  Result := TExprVirtMachNode(FDepList[AIndex]);
end;

{ ============================================= }
{ Concrete expression nodes for virtual machine }
{ ============================================= }

type
  TExprUnaryVmNode = class(TExprVirtMachNode)
  private
    FUnaryClass: TExprUnaryVmOpClass;
  public
    constructor Create(AUnaryClass: TExprUnaryVmOpClass;
      const ADeps: array of TExprNode);
    procedure GenCode(AVirtMach: TExprVirtMach); override;
  end;

  TExprBinaryVmNode = class(TExprVirtMachNode)
  private
    FBinaryClass: TExprBinaryVmOpClass;
  public
    constructor Create(ABinaryClass: TExprBinaryVmOpClass;
      const ADeps: array of TExprNode);
    procedure GenCode(AVirtMach: TExprVirtMach); override;
  end;

  TExprConstVmNode = class(TExprVirtMachNode)
  private
    FValue: TFloat;
  public
    constructor Create(AValue: TFloat);
    procedure GenCode(AVirtMach: TExprVirtMach); override;
  end;

  TExprVar32VmNode = class(TExprVirtMachNode)
  private
    FValue: PFloat32;
  public
    constructor Create(AValue: PFloat32);
    procedure GenCode(AVirtMach: TExprVirtMach); override;
  end;

  TExprVar64VmNode = class(TExprVirtMachNode)
  private
    FValue: PFloat64;
  public
    constructor Create(AValue: PFloat64);
    procedure GenCode(AVirtMach: TExprVirtMach); override;
  end;

  TExprVar80VmNode = class(TExprVirtMachNode)
  private
    FValue: PFloat80;
  public
    constructor Create(AValue: PFloat80);
    procedure GenCode(AVirtMach: TExprVirtMach); override;
  end;

  TExprCallFloatVmNode = class(TExprVirtMachNode)
  private
    FFunc: TFloatFunc;
  public
    constructor Create(AFunc: TFloatFunc);
    procedure GenCode(AVirtMach: TExprVirtMach); override;
  end;

  TExprCallFloat32VmNode = class(TExprVirtMachNode)
  private
    FFunc: TFloat32Func;
  public
    constructor Create(AFunc: TFloat32Func);
    procedure GenCode(AVirtMach: TExprVirtMach); override;
  end;

  TExprCallFloat64VmNode = class(TExprVirtMachNode)
  private
    FFunc: TFloat64Func;
  public
    constructor Create(AFunc: TFloat64Func);
    procedure GenCode(AVirtMach: TExprVirtMach); override;
  end;

  TExprCallFloat80VmNode = class(TExprVirtMachNode)
  private
    FFunc: TFloat80Func;
  public
    constructor Create(AFunc: TFloat80Func);
    procedure GenCode(AVirtMach: TExprVirtMach); override;
  end;

  TExprCallUnaryVmNode = class(TExprVirtMachNode)
  private
    FFunc: TUnaryFunc;
  public
    constructor Create(AFunc: TUnaryFunc; x: TExprNode);
    procedure GenCode(AVirtMach: TExprVirtMach); override;
  end;

  TExprCallUnary32VmNode = class(TExprVirtMachNode)
  private
    FFunc: TUnary32Func;
  public
    constructor Create(AFunc: TUnary32Func; x: TExprNode);
    procedure GenCode(AVirtMach: TExprVirtMach); override;
  end;

  TExprCallUnary64VmNode = class(TExprVirtMachNode)
  private
    FFunc: TUnary64Func;
  public
    constructor Create(AFunc: TUnary64Func; x: TExprNode);
    procedure GenCode(AVirtMach: TExprVirtMach); override;
  end;

  TExprCallUnary80VmNode = class(TExprVirtMachNode)
  private
    FFunc: TUnary80Func;
  public
    constructor Create(AFunc: TUnary80Func; x: TExprNode);
    procedure GenCode(AVirtMach: TExprVirtMach); override;
  end;

  TExprCallBinaryVmNode = class(TExprVirtMachNode)
  private
    FFunc: TBinaryFunc;
  public
    constructor Create(AFunc: TBinaryFunc; x, y: TExprNode);
    procedure GenCode(AVirtMach: TExprVirtMach); override;
  end;

  TExprCallBinary32VmNode = class(TExprVirtMachNode)
  private
    FFunc: TBinary32Func;
  public
    constructor Create(AFunc: TBinary32Func; x, y: TExprNode);
    procedure GenCode(AVirtMach: TExprVirtMach); override;
  end;

  TExprCallBinary64VmNode = class(TExprVirtMachNode)
  private
    FFunc: TBinary64Func;
  public
    constructor Create(AFunc: TBinary64Func; x, y: TExprNode);
    procedure GenCode(AVirtMach: TExprVirtMach); override;
  end;

  TExprCallBinary80VmNode = class(TExprVirtMachNode)
  private
    FFunc: TBinary80Func;
  public
    constructor Create(AFunc: TBinary80Func; x, y: TExprNode);
    procedure GenCode(AVirtMach: TExprVirtMach); override;
  end;

  TExprCallTernaryVmNode = class(TExprVirtMachNode)
  private
    FFunc: TTernaryFunc;
  public
    constructor Create(AFunc: TTernaryFunc; x, y, z: TExprNode);
    procedure GenCode(AVirtMach: TExprVirtMach); override;
  end;

  TExprCallTernary32VmNode = class(TExprVirtMachNode)
  private
    FFunc: TTernary32Func;
  public
    constructor Create(AFunc: TTernary32Func; x, y, z: TExprNode);
    procedure GenCode(AVirtMach: TExprVirtMach); override;
  end;

  TExprCallTernary64VmNode = class(TExprVirtMachNode)
  private
    FFunc: TTernary64Func;
  public
    constructor Create(AFunc: TTernary64Func; x, y, z: TExprNode);
    procedure GenCode(AVirtMach: TExprVirtMach); override;
  end;

  TExprCallTernary80VmNode = class(TExprVirtMachNode)
  private
    FFunc: TTernary80Func;
  public
    constructor Create(AFunc: TTernary80Func; x, y, z: TExprNode);
    procedure GenCode(AVirtMach: TExprVirtMach); override;
  end;

  TExprCompareVmNode = class(TExprVirtMachNode)
  public
    constructor Create(ALeft, ARight: TExprNode);
    procedure GenCode(AVirtMach: TExprVirtMach); override;
  end;

{ TExprUnaryVmNode }

constructor TExprUnaryVmNode.Create(AUnaryClass: TExprUnaryVmOpClass;
  const ADeps: array of TExprNode);
begin
  FUnaryClass := AUnaryClass;
  inherited Create(ADeps);
  Assert(FDepList.Count = 1);
end;

procedure TExprUnaryVmNode.GenCode(AVirtMach: TExprVirtMach);
begin
  FExprVmCode := FUnaryClass.Create(VmDeps[0].ExprVmCode.OutputLoc);
  AVirtMach.Add(FExprVmCode);
end;

{ TExprBinaryVmNode }

constructor TExprBinaryVmNode.Create(ABinaryClass: TExprBinaryVmOpClass;
  const ADeps: array of TExprNode);
begin
  FBinaryClass := ABinaryClass;
  inherited Create(ADeps);
  Assert(FDepList.Count = 2);
end;

procedure TExprBinaryVmNode.GenCode(AVirtMach: TExprVirtMach);
begin
  FExprVmCode := FBinaryClass.Create(
    VmDeps[0].ExprVmCode.OutputLoc,
    VmDeps[1].ExprVmCode.OutputLoc
  );
  AVirtMach.Add(FExprVmCode);
end;

{ TExprConstVmNode }

constructor TExprConstVmNode.Create(AValue: TFloat);
begin
  FValue := AValue;
  inherited Create([]);
end;

procedure TExprConstVmNode.GenCode(AVirtMach: TExprVirtMach);
begin
  FExprVmCode := TExprConstVmOp.Create(FValue);
  AVirtMach.AddConst(FExprVmCode);
end;

{ TExprVar32VmNode }

constructor TExprVar32VmNode.Create(AValue: PFloat32);
begin
  FValue := AValue;
  inherited Create([]);
end;

procedure TExprVar32VmNode.GenCode(AVirtMach: TExprVirtMach);
begin
  FExprVmCode := TExprVar32VmOp.Create(FValue);
  AVirtMach.Add(FExprVmCode);
end;

{ TExprVar64VmNode }

constructor TExprVar64VmNode.Create(AValue: PFloat64);
begin
  FValue := AValue;
  inherited Create([]);
end;

procedure TExprVar64VmNode.GenCode(AVirtMach: TExprVirtMach);
begin
  FExprVmCode := TExprVar64VmOp.Create(FValue);
  AVirtMach.Add(FExprVmCode);
end;

{ TExprVar80VmNode }

constructor TExprVar80VmNode.Create(AValue: PFloat80);
begin
  FValue := AValue;
  inherited Create([]);
end;

procedure TExprVar80VmNode.GenCode(AVirtMach: TExprVirtMach);
begin
  FExprVmCode := TExprVar80VmOp.Create(FValue);
  AVirtMach.Add(FExprVmCode);
end;

{ =========================================== }
{ End of expression nodes for virtual machine }
{ =========================================== }

{ TExprVirtMachNodeFactory }

constructor TExprVirtMachNodeFactory.Create;
begin
  FNodeList := TList.Create;
end;

destructor TExprVirtMachNodeFactory.Destroy;
begin
  FreeObjectList(FNodeList);
  inherited Destroy;
end;

function TExprVirtMachNodeFactory.AddNode(ANode: TExprNode): TExprNode;
begin
  Result := ANode;
  FNodeList.Add(ANode);
end;

procedure TExprVirtMachNodeFactory.GenCode(AVirtMach: TExprVirtMach);
begin
  {TODO: optimize the expression tree into a DAG (i.e. find CSEs) and
    evaluate constant subexpressions, implement strength reduction, etc. }

  {TODO: move optimization logic (as far as possible) into ancestor classes
    once tested and interfaces are solid, so that other evaluation strategies
    can take advantage of these optimizations. }

  DoClean(AVirtMach);
  DoConsts(AVirtMach);
  DoCode(AVirtMach);
end;

function TExprVirtMachNodeFactory.LoadVar32(ALoc: PFloat32): TExprNode;
begin
  Result := AddNode(TExprVar32VmNode.Create(ALoc));
end;

function TExprVirtMachNodeFactory.LoadVar64(ALoc: PFloat64): TExprNode;
begin
  Result := AddNode(TExprVar64VmNode.Create(ALoc));
end;

function TExprVirtMachNodeFactory.LoadVar80(ALoc: PFloat80): TExprNode;
begin
  Result := AddNode(TExprVar80VmNode.Create(ALoc));
end;

function TExprVirtMachNodeFactory.LoadConst32(AValue: TFloat32): TExprNode;
begin
  Result := AddNode(TExprConstVmNode.Create(AValue));
end;

function TExprVirtMachNodeFactory.LoadConst64(AValue: TFloat64): TExprNode;
begin
  Result := AddNode(TExprConstVmNode.Create(AValue));
end;

function TExprVirtMachNodeFactory.LoadConst80(AValue: TFloat80): TExprNode;
begin
  Result := AddNode(TExprConstVmNode.Create(AValue));
end;

function TExprVirtMachNodeFactory.Add(ALeft, ARight: TExprNode): TExprNode;
begin
  Result := AddNode(TExprBinaryVmNode.Create(TExprAddVmOp, [ALeft, ARight]));
end;

function TExprVirtMachNodeFactory.Subtract(ALeft, ARight: TExprNode): TExprNode;
begin
  Result := AddNode(TExprBinaryVmNode.Create(TExprSubtractVmOp, [ALeft, ARight]));
end;

function TExprVirtMachNodeFactory.Multiply(ALeft, ARight: TExprNode): TExprNode;
begin
  Result := AddNode(TExprBinaryVmNode.Create(TExprMultiplyVmOp, [ALeft, ARight]));
end;

function TExprVirtMachNodeFactory.Divide(ALeft, ARight: TExprNode): TExprNode;
begin
  Result := AddNode(TExprBinaryVmNode.Create(TExprDivideVmOp, [ALeft, ARight]));
end;

function TExprVirtMachNodeFactory.Negate(AValue: TExprNode): TExprNode;
begin
  Result := AddNode(TExprUnaryVmNode.Create(TExprNegateVmOp, [AValue]));
end;

procedure TExprVirtMachNodeFactory.DoClean(AVirtMach: TExprVirtMach);
var
  i: Integer;
begin
  { clean up in preparation for code generation }
  AVirtMach.Clear;
  for i := 0 to FNodeList.Count - 1 do
    TExprVirtMachNode(FNodeList[i]).FExprVmCode := nil;
end;

procedure TExprVirtMachNodeFactory.DoConsts(AVirtMach: TExprVirtMach);
var
  i: Integer;
  node: TExprVirtMachNode;
begin
  { process consts }
  for i := 0 to FNodeList.Count - 1 do
  begin
    node := TExprVirtMachNode(FNodeList[i]);
    if (node is TExprConstVmNode) and (node.ExprVmCode = nil) then
      node.GenCode(AVirtMach);
  end;
end;

procedure TExprVirtMachNodeFactory.DoCode(AVirtMach: TExprVirtMach);
var
  i: Integer;
  node: TExprVirtMachNode;
begin
  { process code }
  for i := 0 to FNodeList.Count - 1 do
  begin
    node := TExprVirtMachNode(FNodeList[i]);
    if node.ExprVmCode = nil then
      node.GenCode(AVirtMach);
  end;
end;

function TExprVirtMachNodeFactory.CallFloatFunc(AFunc: TFloatFunc): TExprNode;
begin
  Result := AddNode(TExprCallFloatVmNode.Create(AFunc));
end;

function TExprVirtMachNodeFactory.CallFloat32Func(AFunc: TFloat32Func): TExprNode;
begin
  Result := AddNode(TExprCallFloat32VmNode.Create(AFunc));
end;

function TExprVirtMachNodeFactory.CallFloat64Func(AFunc: TFloat64Func): TExprNode;
begin
  Result := AddNode(TExprCallFloat64VmNode.Create(AFunc));
end;

function TExprVirtMachNodeFactory.CallFloat80Func(AFunc: TFloat80Func): TExprNode;
begin
  Result := AddNode(TExprCallFloat80VmNode.Create(AFunc));
end;

function TExprVirtMachNodeFactory.CallUnaryFunc(AFunc: TUnaryFunc;
  x: TExprNode): TExprNode;
begin
  Result := AddNode(TExprCallUnaryVmNode.Create(AFunc, x));
end;

function TExprVirtMachNodeFactory.CallUnary32Func(AFunc: TUnary32Func;
  x: TExprNode): TExprNode;
begin
  Result := AddNode(TExprCallUnary32VmNode.Create(AFunc, x));
end;

function TExprVirtMachNodeFactory.CallUnary64Func(AFunc: TUnary64Func;
  x: TExprNode): TExprNode;
begin
  Result := AddNode(TExprCallUnary64VmNode.Create(AFunc, x));
end;

function TExprVirtMachNodeFactory.CallUnary80Func(AFunc: TUnary80Func;
  x: TExprNode): TExprNode;
begin
  Result := AddNode(TExprCallUnary80VmNode.Create(AFunc, x));
end;

function TExprVirtMachNodeFactory.CallBinaryFunc(AFunc: TBinaryFunc;
  x, y: TExprNode): TExprNode;
begin
  Result := AddNode(TExprCallBinaryVmNode.Create(AFunc, x, y));
end;

function TExprVirtMachNodeFactory.CallBinary32Func(AFunc: TBinary32Func;
  x, y: TExprNode): TExprNode;
begin
  Result := AddNode(TExprCallBinary32VmNode.Create(AFunc, x, y));
end;

function TExprVirtMachNodeFactory.CallBinary64Func(AFunc: TBinary64Func;
  x, y: TExprNode): TExprNode;
begin
  Result := AddNode(TExprCallBinary64VmNode.Create(AFunc, x, y));
end;

function TExprVirtMachNodeFactory.CallBinary80Func(AFunc: TBinary80Func;
  x, y: TExprNode): TExprNode;
begin
  Result := AddNode(TExprCallBinary80VmNode.Create(AFunc, x, y));
end;

function TExprVirtMachNodeFactory.CallTernaryFunc(AFunc: TTernaryFunc;
  x, y, z: TExprNode): TExprNode;
begin
  Result := AddNode(TExprCallTernaryVmNode.Create(AFunc, x, y, z));
end;

function TExprVirtMachNodeFactory.CallTernary32Func(AFunc: TTernary32Func;
  x, y, z: TExprNode): TExprNode;
begin
  Result := AddNode(TExprCallTernary32VmNode.Create(AFunc, x, y, z));
end;

function TExprVirtMachNodeFactory.CallTernary64Func(AFunc: TTernary64Func;
  x, y, z: TExprNode): TExprNode;
begin
  Result := AddNode(TExprCallTernary64VmNode.Create(AFunc, x, y, z));
end;

function TExprVirtMachNodeFactory.CallTernary80Func(AFunc: TTernary80Func;
  x, y, z: TExprNode): TExprNode;
begin
  Result := AddNode(TExprCallTernary80VmNode.Create(AFunc, x, y, z));
end;

function TExprVirtMachNodeFactory.Compare(ALeft, ARight: TExprNode): TExprNode;
begin
  Result := AddNode(TExprCompareVmNode.Create(ALeft, ARight));
end;

{ TCompiledEvaluator }

constructor TCompiledEvaluator.Create;
begin
  inherited Create;
  FVirtMach := TExprVirtMach.Create;
end;

destructor TCompiledEvaluator.Destroy;
begin
  FVirtMach.Free;
  inherited Destroy;
end;

procedure TCompiledEvaluator.Compile(const AExpr: string);
var
  lex: TExprSimpleLexer;
  parse: TExprCompileParser;
  nodeFactory: TExprVirtMachNodeFactory;
begin
  if AExpr <> FExpr then
  begin
    FExpr := AExpr;
    FVirtMach.Clear;

    parse := nil;
    nodeFactory := nil;
    lex := TExprSimpleLexer.Create(FExpr);
    try
      nodeFactory := TExprVirtMachNodeFactory.Create;
      parse := TExprCompileParser.Create(lex, nodeFactory);
      parse.Context := InternalContextSet;
      parse.Compile;
      nodeFactory.GenCode(FVirtMach);
    finally
      parse.Free;
      nodeFactory.Free;
      lex.Free;
    end;
  end;
end;

function TCompiledEvaluator.Evaluate: TFloat;
begin
  Result := FVirtMach.Execute;
end;

{ TExprVar32Sym }

constructor TExprVar32Sym.Create(const AIdent: string; ALoc: PFloat32);
begin
  Assert(ALoc <> nil);
  FLoc := ALoc;
  inherited Create(AIdent);
end;

function TExprVar32Sym.Compile: TExprNode;
begin
  Result := NodeFactory.LoadVar32(FLoc);
end;

function TExprVar32Sym.Evaluate: TFloat;
begin
  Result := FLoc^;
end;

{ TExprVar64Sym }

constructor TExprVar64Sym.Create(const AIdent: string; ALoc: PFloat64);
begin
  Assert(ALoc <> nil);
  FLoc := ALoc;
  inherited Create(AIdent);
end;

function TExprVar64Sym.Compile: TExprNode;
begin
  Result := NodeFactory.LoadVar64(FLoc);
end;

function TExprVar64Sym.Evaluate: TFloat;
begin
  Result := FLoc^;
end;

{ TExprVar80Sym }

constructor TExprVar80Sym.Create(const AIdent: string; ALoc: PFloat80);
begin
  Assert(ALoc <> nil);
  FLoc := ALoc;
  inherited Create(AIdent);
end;

function TExprVar80Sym.Compile: TExprNode;
begin
  Result := NodeFactory.LoadVar80(FLoc);
end;

function TExprVar80Sym.Evaluate: TFloat;
begin
  Result := FLoc^;
end;

{ TExprCallFloatVmNode }

constructor TExprCallFloatVmNode.Create(AFunc: TFloatFunc);
begin
  FFunc := AFunc;
  inherited Create([]);
end;

procedure TExprCallFloatVmNode.GenCode(AVirtMach: TExprVirtMach);
begin
  FExprVmCode := TExprCallFloatVmOp.Create(FFunc);
  AVirtMach.Add(FExprVmCode);
end;

{ TExprCallFloat32VmNode }

constructor TExprCallFloat32VmNode.Create(AFunc: TFloat32Func);
begin
  FFunc := AFunc;
  inherited Create([]);
end;

procedure TExprCallFloat32VmNode.GenCode(AVirtMach: TExprVirtMach);
begin
  FExprVmCode := TExprCallFloat32VmOp.Create(FFunc);
  AVirtMach.Add(FExprVmCode);
end;

{ TExprCallFloat64VmNode }

constructor TExprCallFloat64VmNode.Create(AFunc: TFloat64Func);
begin
  FFunc := AFunc;
  inherited Create([]);
end;

procedure TExprCallFloat64VmNode.GenCode(AVirtMach: TExprVirtMach);
begin
  FExprVmCode := TExprCallFloat64VmOp.Create(FFunc);
  AVirtMach.Add(FExprVmCode);
end;

{ TExprCallFloat80VmNode }

constructor TExprCallFloat80VmNode.Create(AFunc: TFloat80Func);
begin
  FFunc := AFunc;
  inherited Create([]);
end;

procedure TExprCallFloat80VmNode.GenCode(AVirtMach: TExprVirtMach);
begin
  FExprVmCode := TExprCallFloat80VmOp.Create(FFunc);
  AVirtMach.Add(FExprVmCode);
end;

{ TExprCallUnaryVmNode }

constructor TExprCallUnaryVmNode.Create(AFunc: TUnaryFunc; x: TExprNode);
begin
  FFunc := AFunc;
  inherited Create([x]);
end;

procedure TExprCallUnaryVmNode.GenCode(AVirtMach: TExprVirtMach);
begin
  FExprVmCode := TExprCallUnaryVmOp.Create(
    FFunc,
    VmDeps[0].ExprVmCode.OutputLoc
  );
  AVirtMach.Add(FExprVmCode);
end;

{ TExprCallUnary32VmNode }

constructor TExprCallUnary32VmNode.Create(AFunc: TUnary32Func; x: TExprNode);
begin
  FFunc := AFunc;
  inherited Create([x]);
end;

procedure TExprCallUnary32VmNode.GenCode(AVirtMach: TExprVirtMach);
begin
  FExprVmCode := TExprCallUnary32VmOp.Create(
    FFunc,
    VmDeps[0].ExprVmCode.OutputLoc
  );
  AVirtMach.Add(FExprVmCode);
end;

{ TExprCallUnary64VmNode }

constructor TExprCallUnary64VmNode.Create(AFunc: TUnary64Func;
  x: TExprNode);
begin
  FFunc := AFunc;
  inherited Create([x]);
end;

procedure TExprCallUnary64VmNode.GenCode(AVirtMach: TExprVirtMach);
begin
  FExprVmCode := TExprCallUnary64VmOp.Create(
    FFunc,
    VmDeps[0].ExprVmCode.OutputLoc
  );
  AVirtMach.Add(FExprVmCode);
end;

{ TExprCallUnary80VmNode }

constructor TExprCallUnary80VmNode.Create(AFunc: TUnary80Func;
  x: TExprNode);
begin
  FFunc := AFunc;
  inherited Create([x]);
end;

procedure TExprCallUnary80VmNode.GenCode(AVirtMach: TExprVirtMach);
begin
  FExprVmCode := TExprCallUnary80VmOp.Create(
    FFunc,
    VmDeps[0].ExprVmCode.OutputLoc
  );
  AVirtMach.Add(FExprVmCode);
end;

{ TExprCallBinaryVmNode }

constructor TExprCallBinaryVmNode.Create(AFunc: TBinaryFunc; x,
  y: TExprNode);
begin
  FFunc := AFunc;
  inherited Create([x, y]);
end;

procedure TExprCallBinaryVmNode.GenCode(AVirtMach: TExprVirtMach);
begin
  FExprVmCode := TExprCallBinaryVmOp.Create(
    FFunc,
    VmDeps[0].ExprVmCode.OutputLoc,
    VmDeps[1].ExprVmCode.OutputLoc
  );
  AVirtMach.Add(FExprVmCode);
end;

{ TExprCallBinary32VmNode }

constructor TExprCallBinary32VmNode.Create(AFunc: TBinary32Func; x,
  y: TExprNode);
begin
  FFunc := AFunc;
  inherited Create([x, y]);
end;

procedure TExprCallBinary32VmNode.GenCode(AVirtMach: TExprVirtMach);
begin
  FExprVmCode := TExprCallBinary32VmOp.Create(
    FFunc,
    VmDeps[0].ExprVmCode.OutputLoc,
    VmDeps[1].ExprVmCode.OutputLoc
  );
  AVirtMach.Add(FExprVmCode);
end;

{ TExprCallBinary64VmNode }

constructor TExprCallBinary64VmNode.Create(AFunc: TBinary64Func; x,
  y: TExprNode);
begin
  FFunc := AFunc;
  inherited Create([x, y]);
end;

procedure TExprCallBinary64VmNode.GenCode(AVirtMach: TExprVirtMach);
begin
  FExprVmCode := TExprCallBinary64VmOp.Create(
    FFunc,
    VmDeps[0].ExprVmCode.OutputLoc,
    VmDeps[1].ExprVmCode.OutputLoc
  );
  AVirtMach.Add(FExprVmCode);
end;

{ TExprCallBinary80VmNode }

constructor TExprCallBinary80VmNode.Create(AFunc: TBinary80Func; x,
  y: TExprNode);
begin
  FFunc := AFunc;
  inherited Create([x, y]);
end;

procedure TExprCallBinary80VmNode.GenCode(AVirtMach: TExprVirtMach);
begin
  FExprVmCode := TExprCallBinary80VmOp.Create(
    FFunc,
    VmDeps[0].ExprVmCode.OutputLoc,
    VmDeps[1].ExprVmCode.OutputLoc
  );
  AVirtMach.Add(FExprVmCode);
end;

{ TExprCallTernaryVmNode }

constructor TExprCallTernaryVmNode.Create(AFunc: TTernaryFunc; x, y,
  z: TExprNode);
begin
  FFunc := AFunc;
  inherited Create([x, y, z]);
end;

procedure TExprCallTernaryVmNode.GenCode(AVirtMach: TExprVirtMach);
begin
  FExprVmCode := TExprCallTernaryVmOp.Create(
    FFunc,
    VmDeps[0].ExprVmCode.OutputLoc,
    VmDeps[1].ExprVmCode.OutputLoc,
    VmDeps[2].ExprVmCode.OutputLoc
  );
  AVirtMach.Add(FExprVmCode);
end;

{ TExprCallTernary32VmNode }

constructor TExprCallTernary32VmNode.Create(AFunc: TTernary32Func; x, y,
  z: TExprNode);
begin
  FFunc := AFunc;
  inherited Create([x, y, z]);
end;

procedure TExprCallTernary32VmNode.GenCode(AVirtMach: TExprVirtMach);
begin
  FExprVmCode := TExprCallTernary32VmOp.Create(
    FFunc,
    VmDeps[0].ExprVmCode.OutputLoc,
    VmDeps[1].ExprVmCode.OutputLoc,
    VmDeps[2].ExprVmCode.OutputLoc
  );
  AVirtMach.Add(FExprVmCode);
end;

{ TExprCallTernary64VmNode }

constructor TExprCallTernary64VmNode.Create(AFunc: TTernary64Func; x, y,
  z: TExprNode);
begin
  FFunc := AFunc;
  inherited Create([x, y, z]);
end;

procedure TExprCallTernary64VmNode.GenCode(AVirtMach: TExprVirtMach);
begin
  FExprVmCode := TExprCallTernary64VmOp.Create(
    FFunc,
    VmDeps[0].ExprVmCode.OutputLoc,
    VmDeps[1].ExprVmCode.OutputLoc,
    VmDeps[2].ExprVmCode.OutputLoc
  );
  AVirtMach.Add(FExprVmCode);
end;

{ TExprCallTernary80VmNode }

constructor TExprCallTernary80VmNode.Create(AFunc: TTernary80Func; x, y,
  z: TExprNode);
begin
  FFunc := AFunc;
  inherited Create([x, y, z]);
end;

procedure TExprCallTernary80VmNode.GenCode(AVirtMach: TExprVirtMach);
begin
  FExprVmCode := TExprCallTernary80VmOp.Create(
    FFunc,
    VmDeps[0].ExprVmCode.OutputLoc,
    VmDeps[1].ExprVmCode.OutputLoc,
    VmDeps[2].ExprVmCode.OutputLoc
  );
  AVirtMach.Add(FExprVmCode);
end;

{ TExprCompareVmNode }

constructor TExprCompareVmNode.Create(ALeft, ARight: TExprNode);
begin
  inherited Create([ALeft, ARight]);
end;

procedure TExprCompareVmNode.GenCode(AVirtMach: TExprVirtMach);
begin
  FExprVmCode := TExprCompareVmOp.Create(
    VmDeps[0].ExprVmCode.OutputLoc,
    VmDeps[1].ExprVmCode.OutputLoc
  );
  AVirtMach.Add(FExprVmCode);
end;

{ TExprAbstractFuncSym }

function TExprAbstractFuncSym.CompileFirstArg: TExprNode;
begin
  if Lexer.CurrTok <> etLParen then
    raise EJclExprEvalError.CreateResRec(@RsExprEvalFirstArg);
  Result := CompileParser.compile_expr(True);
end;

function TExprAbstractFuncSym.CompileNextArg: TExprNode;
begin
  if Lexer.CurrTok <> etComma then
    raise EJclExprEvalError.CreateResRec(@RsExprEvalNextArg);
  Result := CompileParser.compile_expr(True);
end;

function TExprAbstractFuncSym.EvalFirstArg: TFloat;
begin
  if Lexer.CurrTok <> etLParen then
    raise EJclExprEvalError.CreateResRec(@RsExprEvalFirstArg);
  Result := EvalParser.eval_expr(True);
end;

function TExprAbstractFuncSym.EvalNextArg: TFloat;
begin
  if Lexer.CurrTok <> etComma then
    raise EJclExprEvalError.CreateResRec(@RsExprEvalNextArg);
  Result := EvalParser.eval_expr(True);
end;

procedure TExprAbstractFuncSym.EndArgs;
begin
  if Lexer.CurrTok <> etRParen then
    raise EJclExprEvalError.CreateResRec(@RsExprEvalEndArgs);
  Lexer.NextTok;
end;

{ TExprFuncSym }

constructor TExprFuncSym.Create(const AIdent: string; AFunc: TFloatFunc);
begin
  Assert(Assigned(AFunc));
  inherited Create(AIdent);
  FFunc := AFunc;
end;

function TExprFuncSym.Compile: TExprNode;
begin
  Result := NodeFactory.CallFloatFunc(FFunc);
end;

function TExprFuncSym.Evaluate: TFloat;
begin
  Result := FFunc;
end;

{ TExprFloat32FuncSym }

constructor TExprFloat32FuncSym.Create(const AIdent: string;
  AFunc: TFloat32Func);
begin
  Assert(Assigned(AFunc));
  inherited Create(AIdent);
  FFunc := AFunc;
end;

function TExprFloat32FuncSym.Compile: TExprNode;
begin
  Result := NodeFactory.CallFloat32Func(FFunc);
end;

function TExprFloat32FuncSym.Evaluate: TFloat;
begin
  Result := FFunc;
end;

{ TExprFloat64FuncSym }

constructor TExprFloat64FuncSym.Create(const AIdent: string;
  AFunc: TFloat64Func);
begin
  Assert(Assigned(AFunc));
  inherited Create(AIdent);
  FFunc := AFunc;
end;

function TExprFloat64FuncSym.Compile: TExprNode;
begin
  Result := NodeFactory.CallFloat64Func(FFunc);
end;

function TExprFloat64FuncSym.Evaluate: TFloat;
begin
  Result := FFunc;
end;

{ TExprFloat80FuncSym }

constructor TExprFloat80FuncSym.Create(const AIdent: string;
  AFunc: TFloat80Func);
begin
  Assert(Assigned(AFunc));
  inherited Create(AIdent);
  FFunc := AFunc;
end;

function TExprFloat80FuncSym.Compile: TExprNode;
begin
  Result := NodeFactory.CallFloat80Func(FFunc);
end;

function TExprFloat80FuncSym.Evaluate: TFloat;
begin
  Result := FFunc;
end;

{ TExprUnaryFuncSym }

constructor TExprUnaryFuncSym.Create(const AIdent: string;
  AFunc: TUnaryFunc);
begin
  Assert(Assigned(AFunc));
  inherited Create(AIdent);
  FFunc := AFunc;
end;

function TExprUnaryFuncSym.Compile: TExprNode;
begin
  Result := NodeFactory.CallUnaryFunc(FFunc, CompileFirstArg);
  EndArgs;
end;

function TExprUnaryFuncSym.Evaluate: TFloat;
begin
  Result := FFunc(EvalFirstArg);
  EndArgs;
end;

{ TExprUnary32FuncSym }

constructor TExprUnary32FuncSym.Create(const AIdent: string;
  AFunc: TUnary32Func);
begin
  Assert(Assigned(AFunc));
  inherited Create(AIdent);
  FFunc := AFunc;
end;

function TExprUnary32FuncSym.Compile: TExprNode;
begin
  Result := NodeFactory.CallUnary32Func(FFunc, CompileFirstArg);
  EndArgs;
end;

function TExprUnary32FuncSym.Evaluate: TFloat;
begin
  Result := FFunc(EvalFirstArg);
  EndArgs;
end;

{ TExprUnary64FuncSym }

constructor TExprUnary64FuncSym.Create(const AIdent: string;
  AFunc: TUnary64Func);
begin
  Assert(Assigned(AFunc));
  inherited Create(AIdent);
  FFunc := AFunc;
end;

function TExprUnary64FuncSym.Compile: TExprNode;
begin
  Result := NodeFactory.CallUnary64Func(FFunc, CompileFirstArg);
  EndArgs;
end;

function TExprUnary64FuncSym.Evaluate: TFloat;
begin
  Result := FFunc(EvalFirstArg);
  EndArgs;
end;

{ TExprUnary80FuncSym }

constructor TExprUnary80FuncSym.Create(const AIdent: string;
  AFunc: TUnary80Func);
begin
  Assert(Assigned(AFunc));
  inherited Create(AIdent);
  FFunc := AFunc;
end;

function TExprUnary80FuncSym.Compile: TExprNode;
begin
  Result := NodeFactory.CallUnary80Func(FFunc, CompileFirstArg);
  EndArgs;
end;

function TExprUnary80FuncSym.Evaluate: TFloat;
begin
  Result := FFunc(EvalFirstArg);
  EndArgs;
end;

{ TExprBinaryFuncSym }

constructor TExprBinaryFuncSym.Create(const AIdent: string;
  AFunc: TBinaryFunc);
begin
  Assert(Assigned(AFunc));
  inherited Create(AIdent);
  FFunc := AFunc;
end;

function TExprBinaryFuncSym.Compile: TExprNode;
var
  x, y: TExprNode;
begin
  // must be called this way, because evaluation order of function
  // parameters is not defined; we need CompileFirstArg to be called
  // first.
  x := CompileFirstArg;
  y := CompileNextArg;
  EndArgs;
  Result := NodeFactory.CallBinaryFunc(FFunc, x, y);
end;

function TExprBinaryFuncSym.Evaluate: TFloat;
var
  x, y: TFloat;
begin
  x := EvalFirstArg;
  y := EvalNextArg;
  Result := FFunc(x, y);
  EndArgs;
end;

{ TExprBinary32FuncSym }

constructor TExprBinary32FuncSym.Create(const AIdent: string;
  AFunc: TBinary32Func);
begin
  Assert(Assigned(AFunc));
  inherited Create(AIdent);
  FFunc := AFunc;
end;

function TExprBinary32FuncSym.Compile: TExprNode;
var
  x, y: TExprNode;
begin
  x := CompileFirstArg;
  y := CompileNextArg;
  EndArgs;
  Result := NodeFactory.CallBinary32Func(FFunc, x, y);
end;

function TExprBinary32FuncSym.Evaluate: TFloat;
var
  x, y: TFloat;
begin
  x := EvalFirstArg;
  y := EvalNextArg;
  EndArgs;
  Result := FFunc(x, y);
end;

{ TExprBinary64FuncSym }

constructor TExprBinary64FuncSym.Create(const AIdent: string;
  AFunc: TBinary64Func);
begin
  Assert(Assigned(AFunc));
  inherited Create(AIdent);
  FFunc := AFunc;
end;

function TExprBinary64FuncSym.Compile: TExprNode;
var
  x, y: TExprNode;
begin
  x := CompileFirstArg;
  y := CompileNextArg;
  EndArgs;
  Result := NodeFactory.CallBinary64Func(FFunc, x, y);
end;

function TExprBinary64FuncSym.Evaluate: TFloat;
var
  x, y: TFloat;
begin
  x := EvalFirstArg;
  y := EvalNextArg;
  EndArgs;
  Result := FFunc(x, y);
end;

{ TExprBinary80FuncSym }

constructor TExprBinary80FuncSym.Create(const AIdent: string;
  AFunc: TBinary80Func);
begin
  Assert(Assigned(AFunc));
  inherited Create(AIdent);
  FFunc := AFunc;
end;

function TExprBinary80FuncSym.Compile: TExprNode;
var
  x, y: TExprNode;
begin
  x := CompileFirstArg;
  y := CompileNextArg;
  EndArgs;
  Result := NodeFactory.CallBinary80Func(FFunc, x, y);
end;

function TExprBinary80FuncSym.Evaluate: TFloat;
var
  x, y: TFloat;
begin
  x := EvalFirstArg;
  y := EvalNextArg;
  EndArgs;
  Result := FFunc(x, y);
end;

{ TExprTernaryFuncSym }

constructor TExprTernaryFuncSym.Create(const AIdent: string;
  AFunc: TTernaryFunc);
begin
  Assert(Assigned(AFunc));
  inherited Create(AIdent);
  FFunc := AFunc;
end;

function TExprTernaryFuncSym.Compile: TExprNode;
var
  x, y, z: TExprNode;
begin
  x := CompileFirstArg;
  y := CompileNextArg;
  z := CompileNextArg;
  EndArgs;
  Result := NodeFactory.CallTernaryFunc(FFunc, x, y, z);
end;

function TExprTernaryFuncSym.Evaluate: TFloat;
var
  x, y, z: TFloat;
begin
  x := EvalFirstArg;
  y := EvalNextArg;
  z := EvalNextArg;
  EndArgs;
  Result := FFunc(x, y, z);
end;

{ TExprTernary32FuncSym }

constructor TExprTernary32FuncSym.Create(const AIdent: string;
  AFunc: TTernary32Func);
begin
  Assert(Assigned(AFunc));
  inherited Create(AIdent);
  FFunc := AFunc;
end;

function TExprTernary32FuncSym.Compile: TExprNode;
var
  x, y, z: TExprNode;
begin
  x := CompileFirstArg;
  y := CompileNextArg;
  z := CompileNextArg;
  EndArgs;
  Result := NodeFactory.CallTernary32Func(FFunc, x, y, z);
end;

function TExprTernary32FuncSym.Evaluate: TFloat;
var
  x, y, z: TFloat;
begin
  x := EvalFirstArg;
  y := EvalNextArg;
  z := EvalNextArg;
  EndArgs;
  Result := FFunc(x, y, z);
end;

{ TExprTernary64FuncSym }

constructor TExprTernary64FuncSym.Create(const AIdent: string;
  AFunc: TTernary64Func);
begin
  Assert(Assigned(AFunc));
  inherited Create(AIdent);
  FFunc := AFunc;
end;

function TExprTernary64FuncSym.Compile: TExprNode;
var
  x, y, z: TExprNode;
begin
  x := CompileFirstArg;
  y := CompileNextArg;
  z := CompileNextArg;
  EndArgs;
  Result := NodeFactory.CallTernary64Func(FFunc, x, y, z);
end;

function TExprTernary64FuncSym.Evaluate: TFloat;
var
  x, y, z: TFloat;
begin
  x := EvalFirstArg;
  y := EvalNextArg;
  z := EvalNextArg;
  EndArgs;
  Result := FFunc(x, y, z);
end;

{ TExprTernary80FuncSym }

constructor TExprTernary80FuncSym.Create(const AIdent: string;
  AFunc: TTernary80Func);
begin
  Assert(Assigned(AFunc));
  inherited Create(AIdent);
  FFunc := AFunc;
end;

function TExprTernary80FuncSym.Compile: TExprNode;
begin
  Result := NodeFactory.CallTernary80Func(FFunc, CompileFirstArg,
    CompileNextArg, CompileNextArg);
  EndArgs;
end;

function TExprTernary80FuncSym.Evaluate: TFloat;
var
  x, y, z: TFloat;
begin
  x := EvalFirstArg;
  y := EvalNextArg;
  z := EvalNextArg;
  EndArgs;
  Result := FFunc(x, y, z);
end;

{ TExprConstSym }

function TExprConstSym.Compile: TExprNode;
begin
  Result := NodeFactory.LoadConst(FValue);
end;

constructor TExprConstSym.Create(const AIdent: string; AValue: TFloat);
begin
  inherited Create(AIdent);
  FValue := AValue;
end;

function TExprConstSym.Evaluate: TFloat;
begin
  Result := FValue;
end;

{ TExprConst32Sym }

constructor TExprConst32Sym.Create(const AIdent: string; AValue: TFloat32);
begin
  inherited Create(AIdent);
  FValue := AValue;
end;

function TExprConst32Sym.Compile: TExprNode;
begin
  Result := NodeFactory.LoadConst(FValue);
end;

function TExprConst32Sym.Evaluate: TFloat;
begin
  Result := FValue;
end;

{ TExprConst64Sym }

constructor TExprConst64Sym.Create(const AIdent: string; AValue: TFloat64);
begin
  inherited Create(AIdent);
  FValue := AValue;
end;

function TExprConst64Sym.Compile: TExprNode;
begin
  Result := NodeFactory.LoadConst(FValue);
end;

function TExprConst64Sym.Evaluate: TFloat;
begin
  Result := FValue;
end;

{ TExprConst80Sym }

constructor TExprConst80Sym.Create(const AIdent: string; AValue: TFloat80);
begin
  inherited Create(AIdent);
  FValue := AValue;
end;

function TExprConst80Sym.Compile: TExprNode;
begin
  Result := NodeFactory.LoadConst(FValue);
end;

function TExprConst80Sym.Evaluate: TFloat;
begin
  Result := FValue;
end;

{ TEasyEvaluator }

constructor TEasyEvaluator.Create;
begin
  FOwnContext := TExprHashContext.Create(False, C_ExprEval_HashSize);
  FExtContextSet := TExprSetContext.Create(False);
  FInternalContextSet := TExprSetContext.Create(False);

  // user added names get precedence over external context's names
  FInternalContextSet.Add(FExtContextSet);
  FInternalContextSet.Add(FOwnContext);
end;

destructor TEasyEvaluator.Destroy;
begin
  FInternalContextSet.Free;
  FOwnContext.Free;
  FExtContextSet.Free;
  inherited Destroy;
end;

procedure TEasyEvaluator.AddConst(const AName: string; AConst: TFloat80);
begin
  FOwnContext.Add(TExprConst80Sym.Create(AName, AConst));
end;

procedure TEasyEvaluator.AddConst(const AName: string; AConst: TFloat64);
begin
  FOwnContext.Add(TExprConst64Sym.Create(AName, AConst));
end;

procedure TEasyEvaluator.AddConst(const AName: string; AConst: TFloat32);
begin
  FOwnContext.Add(TExprConst32Sym.Create(AName, AConst));
end;

procedure TEasyEvaluator.AddVar(const AName: string; var AVar: TFloat32);
begin
  FOwnContext.Add(TExprVar32Sym.Create(AName, @AVar));
end;

procedure TEasyEvaluator.AddVar(const AName: string; var AVar: TFloat64);
begin
  FOwnContext.Add(TExprVar64Sym.Create(AName, @AVar));
end;

procedure TEasyEvaluator.AddVar(const AName: string; var AVar: TFloat80);
begin
  FOwnContext.Add(TExprVar80Sym.Create(AName, @AVar));
end;

procedure TEasyEvaluator.AddFunc(const AName: string; AFunc: TFloat32Func);
begin
  FOwnContext.Add(TExprFloat32FuncSym.Create(AName, AFunc));
end;

procedure TEasyEvaluator.AddFunc(const AName: string; AFunc: TFloat64Func);
begin
  FOwnContext.Add(TExprFloat64FuncSym.Create(AName, AFunc));
end;

procedure TEasyEvaluator.AddFunc(const AName: string; AFunc: TFloat80Func);
begin
  FOwnContext.Add(TExprFloat80FuncSym.Create(AName, AFunc));
end;

procedure TEasyEvaluator.AddFunc(const AName: string; AFunc: TUnary32Func);
begin
  FOwnContext.Add(TExprUnary32FuncSym.Create(AName, AFunc));
end;

procedure TEasyEvaluator.AddFunc(const AName: string; AFunc: TUnary64Func);
begin
  FOwnContext.Add(TExprUnary64FuncSym.Create(AName, AFunc));
end;

procedure TEasyEvaluator.AddFunc(const AName: string; AFunc: TUnary80Func);
begin
  FOwnContext.Add(TExprUnary80FuncSym.Create(AName, AFunc));
end;

procedure TEasyEvaluator.AddFunc(const AName: string; AFunc: TBinary32Func);
begin
  FOwnContext.Add(TExprBinary32FuncSym.Create(AName, AFunc));
end;

procedure TEasyEvaluator.AddFunc(const AName: string; AFunc: TBinary64Func);
begin
  FOwnContext.Add(TExprBinary64FuncSym.Create(AName, AFunc));
end;

procedure TEasyEvaluator.AddFunc(const AName: string; AFunc: TBinary80Func);
begin
  FOwnContext.Add(TExprBinary80FuncSym.Create(AName, AFunc));
end;

procedure TEasyEvaluator.AddFunc(const AName: string; AFunc: TTernary32Func);
begin
  FOwnContext.Add(TExprTernary32FuncSym.Create(AName, AFunc));
end;

procedure TEasyEvaluator.AddFunc(const AName: string; AFunc: TTernary64Func);
begin
  FOwnContext.Add(TExprTernary64FuncSym.Create(AName, AFunc));
end;

procedure TEasyEvaluator.AddFunc(const AName: string; AFunc: TTernary80Func);
begin
  FOwnContext.Add(TExprTernary80FuncSym.Create(AName, AFunc));
end;

procedure TEasyEvaluator.Clear;
begin
  FOwnContext.FHashMap.Iterate(nil, Iterate_FreeObjects);
  FOwnContext.FHashMap.Clear;
end;

procedure TEasyEvaluator.Remove(const AName: string);
begin
  FOwnContext.Remove(AName);
end;

{ TExpressionCompiler }

type
  TInternalCompiledExpression = class
  private
    FVirtMach: TExprVirtMach;
    FRefCount: Integer;
  public
    constructor Create(AVirtMach: TExprVirtMach);
    destructor Destroy; override;
    property VirtMach: TExprVirtMach read FVirtMach;
    property RefCount: Integer read FRefCount write FRefCount;
  end;

constructor TExpressionCompiler.Create;
begin
  FExprHash := TStringHashMap.Create(CaseInsensitiveTraits,
    C_ExprEval_HashSize);
  inherited Create;
end;

destructor TExpressionCompiler.Destroy;
begin
  FExprHash.Iterate(nil, Iterate_FreeObjects);
  inherited Destroy;
end;

function TExpressionCompiler.Compile(const AExpr: string): TCompiledExpression;
var
  ice: TInternalCompiledExpression;
  vm: TExprVirtMach;
  parser: TExprCompileParser;
  lexer: TExprSimpleLexer;
  nodeFactory: TExprVirtMachNodeFactory;
begin
  if FExprHash.Find(AExpr, ice) then
  begin
    // expression already exists, add reference
    Result := ice.VirtMach.Execute;
    ice.RefCount := ice.RefCount + 1;
  end
  else
  begin
    // compile fresh expression
    parser := nil;
    nodeFactory := nil;
    lexer := TExprSimpleLexer.Create(AExpr);
    try
      nodeFactory := TExprVirtMachNodeFactory.Create;
      parser := TExprCompileParser.Create(lexer, nodeFactory);
      parser.Context := InternalContextSet;
      parser.Compile;

      ice := nil;
      vm := TExprVirtMach.Create;
      try
        nodeFactory.GenCode(vm);
        ice := TInternalCompiledExpression.Create(vm);
        ice.RefCount := 1;
        FExprHash.Add(AExpr, ice);
      except
        ice.Free;
        vm.Free;
        raise;
      end;
    finally
      nodeFactory.Free;
      parser.Free;
      lexer.Free;
    end;

    Result := ice.VirtMach.Execute;
  end;
end;

type
  TIceFindResult = record
    Found: Boolean;
    Ce: TCompiledExpression;
    Ice: TInternalCompiledExpression;
    Expr: string;
  end;
  PIceFindResult = ^TIceFindResult;

function Iterate_FindIce(AUserData: Pointer; const AStr: string;
  var APtr: Pointer): Boolean;
var
  pifr: PIceFindResult;
  ice: TInternalCompiledExpression;
  ce: TCompiledExpression;
begin
  pifr := AUserData;
  ice := APtr;
  ce := ice.VirtMach.Execute;

  if (TMethod(pifr^.Ce).Code = TMethod(ce).Code) and
    (TMethod(pifr^.Ce).Data = TMethod(ce).Data) then
  begin
    pifr^.Found := True;
    pifr^.Ice := ice;
    pifr^.Expr := AStr;
    Result := False;
  end else
    Result := True;
end;

procedure TExpressionCompiler.Delete(ACompiledExpression: TCompiledExpression);
var
  ifr: TIceFindResult;
begin
  ifr.Found := False;
  ifr.Ce := ACompiledExpression;
  ifr.Ice := nil;
  ifr.Expr := '';
  FExprHash.Iterate(@ifr, Iterate_FindIce);
  if not ifr.Found then
    raise EJclExprEvalError.CreateResRec(@RsExprEvalExprPtrNotFound);
  Remove(ifr.Expr);
end;

procedure TExpressionCompiler.Remove(const AExpr: string);
var
  ice: TInternalCompiledExpression;
begin
  if not FExprHash.Find(AExpr, ice) then
    raise EJclExprEvalError.CreateResRecFmt(@RsExprEvalExprNotFound,
      [AExpr]);

  ice.RefCount := ice.RefCount - 1;
  if ice.RefCount = 0 then
  begin
    ice.Free;
    FExprHash.Remove(AExpr);
  end;
end;

procedure TExpressionCompiler.Clear;
begin
  FExprHash.Iterate(nil, Iterate_FreeObjects);
end;

{ TInternalCompiledExpression }

constructor TInternalCompiledExpression.Create(AVirtMach: TExprVirtMach);
begin
  FVirtMach := AVirtMach;
end;

destructor TInternalCompiledExpression.Destroy;
begin
  FVirtMach.Free;
  inherited Destroy;
end;

end.

About Koders | Resources | Downloads | Support | Black Duck | Terms of Service | DMCA | Privacy Policy | Contact Us