[r5987]: incubator / regex / regex.cls  Maximize  Restore  History

Download this file

5449 lines (4817 with data), 184.2 kB

   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
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
/*----------------------------------------------------------------------------*/
/* */
/* Copyright (c) 2007 Rexx Language Association. All rights reserved. */
/* */
/* This program and the accompanying materials are made available under */
/* the terms of the Common Public License v1.0 which accompanies this */
/* distribution. A copy is also available at the following address: */
/* http://www.oorexx.org/license.html */
/* */
/* Redistribution and use in source and binary forms, with or */
/* without modification, are permitted provided that the following */
/* conditions are met: */
/* */
/* Redistributions of source code must retain the above copyright */
/* notice, this list of conditions and the following disclaimer. */
/* Redistributions in binary form must reproduce the above copyright */
/* notice, this list of conditions and the following disclaimer in */
/* the documentation and/or other materials provided with the distribution. */
/* */
/* Neither the name of Rexx Language Association nor the names */
/* of its contributors may be used to endorse or promote products */
/* derived from this software without specific prior written permission. */
/* */
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS */
/* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT */
/* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS */
/* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT */
/* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, */
/* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED */
/* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, */
/* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY */
/* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING */
/* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS */
/* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/* */
/*----------------------------------------------------------------------------*/
-- ::options trace i
::class Pattern public
-- compile a string regex expression into a pattern
::method compile class
-- the compiler is configurable, but there is a default
use strict arg pattern, compiler = (.RegexCompiler~new)
return compiler~compile(pattern)
-- compile a string regex expression used as replacement text
-- into a pattern
::method compileReplacement class
-- the compiler is configurable, but there is a default
use strict arg pattern, compiler = (.RegexCompiler~new)
return compiler~compileReplacement(pattern)
::method init
expose pattern root groups
use strict arg pattern, root, groups
::attribute pattern GET
::attribute groups GET
::attribute root GET
-- retrieve the number of capturing groups
-- contained within this pattern.
::attribute groupCount GET
expose groups
return groups~items
::method string
expose pattern
return pattern
-- simple one time match operation on a regular expression and
-- a region within a string. Returns .true if this is an exact
-- match for the entire region
::method matches
use strict arg text, start = 1, end = (text~length)
-- create a matching context for this
context = .MatchContext~new(text, start, end)
-- and just perform a match on this
return context~matches(self)
-- simple one time match operation on a regular expression and
-- a region within a string. Returns a MatchResult item if this
-- matches at the starting position (but not necessarily the entire
-- string)
::method match
use strict arg text, start = 1
-- create a matching context for this
context = .MatchContext~new(text)
-- and just perform a match on this
return context~match(self, start)
-- simple one time match operation on a regular expression and
-- a region within a string. Returns .true if the region starts
-- with the given pattern
::method startsWith
use strict arg text, start = 1
-- create a matching context for this
context = .MatchContext~new(text)
-- and just perform a match on this
return context~startsWith(self, start)
-- search a region of a string for a regex value. Only the
-- section between the start position and the given length
-- are searched. The return value is a MatchResult object with the
-- full details of the match.
::method find
use strict arg text, start = 1
-- create a matching context for this
context = .MatchContext~new(text)
-- and just perform a search and return the match position
-- value
return context~find(self, start)
-- split a string into an array of segments using a regular expression
-- as the match position
::method split
use strict arg text, limit = (-1)
list = .array~new -- our set of match results
indexPosition = 1 -- split always starts at the beginning
-- now loop until we no longer match
result = self~find(text, indexPosition)
-- non-limited is more typical and simpler
if limit < 0 then do
-- now loop until we no longer match
result = self~find(text, indexPosition)
do while result~matched
list~append(result~prefix)
-- advance to the next position. Note that
-- this works correctly even if the match length
-- is a null string
indexPosition = result~nextMatch
end
end
else do
count = 0
do while count < limit
-- now loop until we no longer match
result = self~find(text, indexPosition)
if \result~matched then do
leave
end
list~append(result~prefix)
-- advance to the next position. Note that
-- this works correctly even if the match length
-- is a null string
indexPosition = result~nextMatch
count += 1
end
end
-- append and tail piece, if there is one
if indexPosition <= text~length then do
list~append(text~substr(indexPosition))
end
return list
-- return a set of match metrics for this pattern instance
::method matchMetrics
expose root
use strict arg
metrics = .MatchMetrics~new
-- forward this to the matching tree
root~calculateMatchMetrics(metrics)
return metrics
-- perform an inplace replacement in a mutableBuffer
::method replaceBuffer
use arg text, replacement
-- do the search first. If not there, then there's
-- no need to compile the replacement piece
matchResult = self~find(text)
if \matchResult~matched then do
-- this is a wrappered match result with a 0 replacement length
return .ReplacementMatchResult~new(matchResult, 0)
end
-- if the replacement is in string form, then convert into
-- a replacer
if replacement~isA(.String) then do
replacement = self~class~compileReplacement(replacement)
end
-- perform the replacement using the matchResult context
replacementLength = replacement~replace(text, matchResult)
-- and merge the match result with the replacement metric
return .ReplacementMatchResult~new(matchResult, replacementLength)
::class RegexCompiler public
::constant METACHARACTERS "([{\^$|]})?*+."
::constant CLASSMETACHARACTERS "[]"
::constant CLOSURECHARACTERS "*+?{"
::constant WORDCHARACTERS 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_'
::constant DIGITCHARACTERS '0123456789'
::constant LOWERCASECHARACTERS "abcdefghijklmnopqrstuvwxyz"
::constant UPPERCASECHARACTERS "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
::constant WHITESPACECHARACTERS '20090a0b0c0d'x
-- options constants for the different compiler modes
::constant multiline "MULTILINE"
::constant singleline "SINGLELINE"
::constant internetlines "INTERNETLINES"
::constant unixlines "UNIXLINES"
::constant caseless "CASELESS"
::constant respectcase "RESPECTCASE"
::constant dotall "DOTALL"
::constant dotrestricted "DOTRESTRICTED"
-- Initialize the class families the first time they are used
::method initClassFamilies private
expose classFamilies
if classFamilies \= .nil then do
return
end
classFamilies = .directory~new
classFamilies["LOWER"] = self~lowerCaseCharacters
classFamilies["UPPER"] = self~upperCaseCharacters
classFamilies["ASCII"] = xrange('00'x, '7F'x)
classFamilies["ALPHA"] = classFamilies["LOWER"] || classFamilies["UPPER"]
classFamilies["DIGIT"] = self~digitCharacters
classFamilies["ALNUM"] = classFamilies["ALPHA"] || classFamilies["DIGIT"]
classFamilies["PUNCT"] = "!""#$%&'()*+,-./:;<=>?@[\]^_`{|}~"
classFamilies["GRAPH"] = classFamilies["ALNUM"] || classFamilies["PUNCT"]
classFamilies["PRINT"] = classFamilies["GRAPH"]
classFamilies["BLANK"] = " " || '09'x
classFamilies["CNTRL"] = xrange("00"x, "1F"x) || "7F"x
classFamilies["XDIGIT"] = "0123456789abcdefABCDEF"
classFamilies["ODIGIT"] = "01234567"
classFamilies["SPACE"] = self~whiteSpaceCharacters
classFamilies["WORD"] = self~wordCharacters
classFamilies["REXXSYMBOL"] = classFamilies["ALNUM"] || ".!?_"
classFamilies["REXXVARIABLESTART"] = classFamilies["ALPHA"] || "!?_"
classFamilies["REXXOPERATOR"] = "+-\/%*|&=<>" || 'aaac'x
classFamilies["REXXSPECIAL"] = ",;:~()[]"
classFamilies["EMAILUSERNAME"] = classFamilies["ALNUM"] || ".!#$%&'*+/=?^_`{|}~-"
classFamilies["URLUSERNAME"] = classFamilies["ALNUM"] || "-._~%!$&'()*+,;="
classFamilies["URLVALID]"] = classFamilies["ALNUM"] || "-._~%!$&'()*+,;=:@/?"
-- Initialize the named patterns the first time they are used
::method initNamedPatterns private
expose namedPatterns
if namedPatterns \= .nil then do
return
end
namedPatterns = .directory~new
namedPatterns['TOPLEVELDOMAIN'] = "(?:\p{Alpha}{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum|travel)\b"
namedPatterns['EMAILUSERNAME'] = "(?:\p{EmailUserName}+(?:\.\p{EmailUserName}+)*)"
namedPatterns['INTERNETDOMAIN'] = "(?:\p{Alnum}(?:[\p{Alnum}-]*\p{Alnum})?\.)+\m{TopLevelDomain}"
namedPatterns['EMAIL'] = "(?<username>\m{EmailUserName})@(?<domain>\m{InternetDomain})"
namedPatterns['IPV4DIGITS'] = "(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])"
namedPatterns['IPV4ADDRESS'] = "\b\m{IPV4Digits}\.\m{IPV4Digits}\.\m{IPV4Digits}\.\m{IPV4Digits}\b"
namedPatterns['STANDARDIPV6ADDRESS'] = "(?<![:.\w])(?:\p{Alnum}{1,4}:){7}\p{Alnum}{1,4}(?![:.\w])"
namedPatterns['URLPROTOCOL'] = "\p{Alpha}[\p{Alnum}+\-.]*:"
namedPatterns['URLUSER'] = "\p{URLUSERNAME}+@"
namedPatterns['IPV6HOST'] = "\[[\p{XDigit}:.]+\]"
namedPatterns['IPV6FUTUREHOST'] = "\[v[\p{XDigit}][\p{XDigit}\-._~%!$&'()*+,;=:]+\]"
namedPatterns['URLPORT'] = ":[0-9]+"
namedPatterns['URLPATH'] = "(/[\p{Alnum}\-._~%!$&'()*+,;=:@]+)*/"
namedPatterns['URLQUERY'] = "\?[\p{URLValid}]*"
namedPatterns['URLFRAGMENT'] = "\#[p{URLValid}]*"
namedPatterns['URL'] = "(?<protocol>\m{URLProtocol})(?<user>\m{URLUser})?(?<host>\m{InternetDomain}|\m{IPv6Host}|\m{IPv6FutureHost})(?<port>\m{URLPort})(?<path>\m{URLPath})(?<query>\m{URLQuery})?(?<fragment>\m{URLFragment})?"
-- retrieve a name class family from the list of registered class families
-- subclasses are free to override this method to provide additional
-- class families
::method classFamily
expose classFamilies
use strict arg name
name = name~upper -- make sure we always use an uppercase name
-- initialize the class families
self~initClassFamilies
return classFamilies[name]
-- register additional class families with a compiler instance
::method registerClassFamily
expose classFamilies
use strict arg name, chars
name = name~upper -- make sure we always use an uppercase name
-- initialize the class families
self~initClassFamilies
-- allow any class family to be redefined
classFamilies[name] = chars
-- retrieve a named pattern instance from the list of registered
-- patterns. Subclasses are free to override this lookup to provide
-- additional named patterns
::method namedPattern
expose namedPatterns
use strict arg name
name = name~upper -- make sure we always use an uppercase name
-- initialize the class-provided set
self~initNamedPatterns
pattern = namedPatterns[name]
-- still in string symbolic form?
if pattern~isa(.String) then do
-- compile this on demand and update
-- the table so it can be reused
-- make a copy of the current compiler instance to
-- pick up the options, but not mess up the state
-- of the pattern currently being compiled
patternCompiler = self~copy
pattern = patternCompiler~compile(pattern)
namedPatterns[name] = pattern
end
return pattern -- now in pattern form
-- register additional named patterns with a compiler instance
::method registerNamedPattern
expose namedPatterns
use strict arg name, pattern
name = name~upper -- make sure we always use an uppercase name
-- initialize the standard pattern set
self~initNamedPatterns
-- allow any class family to be redefined
namedPatterns[name] = pattern
-- initialize a regex compiler instance
::method init
expose classFamilies namedPatterns
classFamilies = .nil -- we might not need either of these,
namedPatterns = .nil -- so they are lazily initialized
use strict arg options = .nil
-- set default options
self~multiLineMode = .false
self~unixLinesMode = .false
self~caselessMode = .false
self~dotAllMode = .false
self~validateOptions(arg(1))
-- the following CONSTANTs define the valid options; split into two parts for
-- readability and source line length
-- NB DO NOT change the order without modifying the code in validateOptions()
::constant validOptions1 "MULTILINE SINGLELINE INTERNETLINES UNIXLINES"
::constant validOptions2 "CASELESS RESPECTCASE DOTALL DOTRESTRICTED"
-- validate any options passed to the compiler when created
::method validateOptions private
use arg options
if options == .nil then do
return
end
options = options~upper
-- combine the two lists of options
validOptions = self~validOptions1 self~validOptions2
do while options \== ""
parse var options option options
select
-- option = MULTILINE
when validOptions~word(1)~abbrev(option, 1) then do
self~multiLineMode = .true
end
-- option = SINGLELINE
when validOptions~word(2)~abbrev(option, 1) then do
self~multiLineMode = .false
end
-- option = INTERNETLINES
when validOptions~word(3)~abbrev(option, 1) then do
self~unixLinesMode = .false
end
-- option = UNIXLINES
when validOptions~word(4)~abbrev(option, 1) then do
self~unixLinesMode = .true
end
-- option = CASELESS
when validOptions~word(5)~abbrev(option, 1) then do
self~caselessMode = .true
end
-- option = RESPECTCASE
when validOptions~word(6)~abbrev(option, 1) then do
self~caselessMode = .false
end
-- option = DOTALL
when validOptions~word(7)~abbrev(option, 4) then do
self~dotAllMode = .true
end
-- option = DOTRESTRICTED
when validOptions~word(8)~abbrev(option, 4) then do
self~dotAllMode = .false
end
otherwise do
raise syntax 93.915 array(validOptions, option)
end
end
end
-- compile a regex expression using the posix-like
-- regular expression syntax
::method compile
expose pattern current length groups groupCount
use strict arg pattern
current = 1 -- always start at the beginning
length = pattern~length
groups = .nil -- no group information until we hit the first capturing group
groupCount = 0 -- This is for the group numbering
-- create the group reference item for the main matching context
self~createGroupReference(0)
-- this is the last node that will get control only if all other
-- elements match cleanly. The expression parser hooks this up to the
-- end of the expression graph.
lastNode = .TerminatorNode~new
rootNode = self~parseExpression(lastNode)
-- and return a usable pattern for this
return .Pattern~new(pattern, rootNode, groups)
-- we occasionally need to retrieve the current position
::attribute current GET
-- extract a substring from the parsing context
::method extract
expose pattern
use arg start, end
return pattern~substr(start, end - start)
-- extract the next character and step the parsing position
-- Returns .nil if past the end of the pattern
::method next
expose pattern current length
-- .nil triggers the end of the parsing
if current > length then do
return .nil
end
-- grab the character at the current position and
-- step to the next slot
ch = pattern~subchar(current)
current = current + 1
return ch
-- peek at the current parsing position without stepping
-- the cursor. Returns .nil if past the end of the pattern.
::method peek
expose pattern current length
if current > length then do
return .nil
end
ch = pattern~subchar(current)
return ch
-- peek at the next at a given offset from the current parsing position without
-- moving the cursor. The offset can be positive or negative. Returns .nil
-- if the resulting position is beyond the pattern bounds
::method peekOffset
expose pattern current length
use arg offset
position = current + offset
if position > length | position < 1 then do
return .nil
end
ch = pattern~subchar(position)
return ch
-- process reading of a single character, taking escaping
-- into account
::method singleChar
ch = self~next
-- have an escape character?
if ch == '\' then do
return self~parseEscapedCharacters
end
return ch -- return whatever this is, including .nil
-- move the cursor to a previous position, ensuring that we
-- don't move past the beginning
::method previous
expose current length
current = max(current - 1, 1)
-- test if a character is a metacharacter that needs to be skipped
::method isMetaCharacter
use arg ch
return self~METACHARACTERS~pos(ch) > 0
-- test if a character is a metacharacter in the context of parsing
-- a class range
::method isClassMetaCharacter
use arg ch
return self~CLASSMETACHARACTERS~pos(ch) > 0
-- test if a character is a closure character
-- a class range
::method isClosureCharacter
use arg ch
return self~CLOSURECHARACTERS~pos(ch) > 0
-- extract a string from a pattern that is delimited
-- by a pair of markers
::method extractDelimited
expose pattern current length
use arg start, end
-- In theory, we should be at the start delimiter now. If
-- not there, this is an error
if \pattern~match(current, start) then do
raise syntax 13.900 array("Delimiter character" start "expected for delimited string")
end
-- step over the delimiter
startPos = current + start~length
-- and look for the closing delimiter
endPos = pattern~pos(end, startPos)
if endPos == 0 then do
raise syntax 6.900 array("Missing closing delimeter" end)
end
current = endPos + end~length -- position past the read position
-- and return the string between the markers
return pattern~substr(startPos, endPos - startPos)
-- extract a numeric value from the stream. Terminates
-- on the first non-numeric character or the EOS.
::method parseNumber
number = ""
do forever
ch = self~next
if ch == .nil then do
leave
end
if \ch~datatype("W") then do
-- non-numeric character, so backup and quit the loop
self~previous
leave
end
-- add to the accumulator
number = number || ch
end
-- nothing valid found, return .nil as the failure value
if number == '' then do
return .nil
end
return number
-- Parse out an expression tree and compile into a directed graph of
-- match nodes. This version handles alternative forms. If not
-- part of an alternative sequence, it just returns the base sub expression.
::method parseExpression
expose pattern matchNodes current length
use arg terminator -- this is the end node that gets plugged into the end of the expression.
alternative = .nil -- if we have alternatives in this expression, we group them all
do forever
-- parse a sequence and chain up with the terminator
node = self~parseSequence(terminator)
-- if there is no node here, this could be a "dangling"
-- "|" on the end of an alternative. If this is the case,
-- (i.e., we've been accumulating alternatives), then add
-- a special everything matcher to the end and finish up
if node == .nil then do
if alternative \= .nil then do
-- add a node that will match everything
alternative~addAlternative(.EverythingNode~new)
return alternative
end
-- We expected something here and got nothing
raise syntax 93.900 array("Invalid regular expression sequence")
end
-- if we've had at least one choice, then this just gets added to the
-- list
if alternative \== .nil then do
alternative~addAlternative(node)
end
-- look ahead to see if this is again part of an alternation
ch = self~peek
if ch \== '|' then do
-- not an alternative....see what we need to return
if alternative == .nil then do
return node
end
else do
return alternative
end
end
else do
self~next -- step over over the | operator
-- if we've only processed the first node, create an alternative and
-- add the node.
if alternative == .nil then do
alternative = .AlternativeNode~new
-- this now assumes the terminator
alternative~next = terminator
-- add the node to the alternative
alternative~addAlternative(node)
end
end
end
-- parse out a subexpression. This also handles any of the modifiers
-- that might be associated with a single subexpression
::method parseSequence
use arg terminator
firstNode = .nil
lastNode = .nil
do forever
ch = self~peek
select
-- this is an end of string, done parsing
when .nil == ch then do
leave
end
-- either of these is a terminator for the sequence.
-- if this is "|", the caller will accumulate the alternatives.
-- if this is ")", then this is the close of a group
when ch == '|' | ch == ')' then do
-- allow the caller to handle
leave;
end
-- a class of characters
when ch == '[' then do
self~next
node = self~parseClass
end
-- start of a group. We'll process and then recurse
when ch == '(' then do
self~next
-- parse out the group expression, then chain the
-- entire section into our graph. All subsequent
-- bits follow the group sequence.
groupInfo = self~parseGroup
-- This could be a standalone flag group or a comment. In that case,
-- the compiler mode flags have been processed, but there
-- is no node to handle. Just skip over this and keep parsing
if groupInfo == .nil then do
iterate
end
if firstNode == .nil then do
firstNode = groupInfo~firstNode
end
else do
lastNode~next = groupInfo~firstNode
end
lastNode = groupInfo~lastNode
iterate -- closure has already been handled
end
-- a start anchor
when ch == '^' then do
self~next
node = self~parseStartAnchor
end
-- end anchor variants
when ch == '$' then do
self~next
node = self~parseEndAnchor
end
-- match any character
when ch == '.' then do
self~next
node = self~parseDot
end
-- various escape characters
when ch == '\' then do
self~next
node = self~parseEscapes
end
-- these are not expected here
when ch == '?' | ch == '*' | ch == '+' then do
raise syntax 13.900 array ("Unexpected modifier character '"||ch||"'" )
end
otherwise do
-- an atom string that is taken as-is
node = self~parseAtom
end
end
node = self~parseClosure(node)
-- now process the chaining
if firstNode == .nil then do
firstNode = node
lastNode = node
end
else do
lastNode~next = node
lastNode = node
end
end
-- it's possible there is nothing to return. In that case, just
-- return .nil to indicate we have nothing here
if firstNode == .nil then do
return .nil
end
else do
-- put the terminator as the next element of the last node of
-- the chain.
lastNode~next = terminator
end
return firstNode
-- create an appropriate start anchor (^) based on the
-- current mode flags
::method parseStartAnchor
-- if operating in single line mode, this is just
-- a text beginning
if \self~multiLineMode then do
return .BeginTextNode~new
end
else if self~unixLinesMode then do
return .UnixMultilineCaretNode~new
end
else do
return .InternetMultilineCaretNode~new
end
-- Handle adding a handler for a $ anchor to the tree. The operation
-- depends on the multiLine and unixLines flags. If not in multiLine,
-- this will only match on the end of text OR if positioned on the appropriate
-- linend marker that is at the end of the text. If in multiline mode,
-- then this will also recognize interior linend sequences.
::method parseEndAnchor
-- an end anchor, which has 4 possibilities
-- in multiline mode? interior linends are recognized
if self~multiLineMode then do
-- return the version appropriate to the linend style
if self~unixLinesMode then do
return .UnixMultiLineEndNode~new
end
else do
return .InternetMultiLineEndNode~new
end
end
else do
-- return the version appropriate to the linend style
if self~unixLinesMode then do
return .UnixLineEndNode~new
end
else do
return .InternetLineEndNode~new
end
end
-- a match anything character. The meaning of
-- "match anything" differs depending on options
::method parseDot
if self~dotAllMode then do
return .AllDotNode~new
end
else if self~unixLinesMode then do
return .UnixDotNode~new
end
else do
return .InternetDotNode~new
end
-- parse the full range of escapes, including the operations. This
-- returns a node to handle the escaped character
::method parseEscapes
-- There are overlaps between the excaped operations and the escaped
-- characters (\b is both backspace and word boundary, depending on context)
-- Allow this override to occur by processing the operations first. In
-- contexts where word boundaries don't apply, this step is skipped.
-- there are more complex operations that are escaped
node = self~parseEscapedOperations
-- if a recognized operation, return that
if node \= .nil then do
return node
end
-- now check for escaped characters that are really class nodes
char = self~parseEscapedCharacters
if char == .nil then do
raise syntax 13.900 array("Invalid character after \ escape character")
end
-- this just parsed a single character, turn it into a
-- node
return .StringNode~new(char)
-- create a new group item for the pattern's list of numbered capture groups
::method newGroup
expose groupCount
groupCount += 1 -- each group gets allocated when first encountered
-- we treat all of these as named groups, so just
-- allocate one with the counter name
self~createGroupReference(groupCount)
return groupCount
-- Create the group reference item for a numbered or named group.
-- A named group can be used in multiple places
::method getGroupReference
expose groups
use arg id
-- prevent numeric names from overlapping with the numbered groups
if id~datatype('Whole') then do
raise syntax 93.900 array("Numeric names cannot be use for named groups; found" id);
end
return self~createGroupReference(id)
-- create a group reference item in our set of groups
::method createGroupReference private
expose groups
use arg id
if groups == .nil then do
groups = .directory~new
end
groupInfo = .GroupReference~new(id)
groups[id] = groupInfo
return groupInfo
-- test if a given named group has been encountered yet
-- (used for resolving back references)
::method haveGroup
expose groups
use arg id
return groups~hasIndex(id)
-- parse group information
::method parseGroup
-- group specifications can change the mode settings, but the
-- scope of the change is limited to the containing group.
-- We need to restore these once we're finished parsing the group
savedFlags = self~saveFlags
-- most groups require closure, but not all
closure = .true
-- we return a directory of information about this group
groupInfo = .directory~new
ch = self~peek
-- do we have a group qualifier. These are all non-capturing groups
if ch == '?' then do
self~next -- step over the peeked character
ch = self~peek
select
-- (?: is a non-capturing group. Just like a normal group,
-- but without the capture part
when ch == ':' then do
self~next -- step over the peeked character
-- non capture group
group = .GroupEnvelope~new
-- parse the encapsulated group expression. This gets
-- slotted between the group element and the terminator
group~next = self~parseExpression(group~terminator)
-- to wire in to the caller, we need to provide a node that
-- is plugged into the previous node, and a node that will be
-- the new tail end of the chain.
groupInfo~firstNode = group
groupInfo~lastNode = group~terminator
end
-- (?> is an atomic capturing group. Once it matches,
-- it does not give up whatever it matched.
when ch == '>' then do
self~next -- step over the peeked character
-- an atomic group. Matching is managed differently
group = .GroupEnvelope~new
-- parse the encapsulated group expression. This gets
-- slotted between the group element and the terminator
group~next = self~parseExpression(group~terminator)
-- wrap this with an encapsulating atomic node.
wrapper = .AtomicGroupNode~new(group)
-- wrappered nodes fill both roles
groupInfo~firstNode = wrapper
groupInfo~lastNode = wrapper
end
-- positive zero-length lookahead. This checks that the given
-- pattern is at the current position, but it's match is always
-- zero-length, so it does not step the position nor does it's
-- match position count toward the bounds of the final match
when ch == '=' then do
self~next -- step over the peeked character
-- parse the encapsulated group expression, but terminate
-- with a branch terminator node.
node = self~parseExpression(.nil)
-- this is a special wrapper
wrapper = .PositiveLookAheadNode~new(node)
-- wrappered nodes fill both roles
groupInfo~firstNode = wrapper
groupInfo~lastNode = wrapper
-- zero length matches do not have closures
closure = .false
end
-- this is a lookbehind. It checks the data before the current
-- position
when ch == '!' then do
self~next -- step over the peeked character
-- parse the encapsulated group expression, but terminate
-- with a branch terminator node.
node = self~parseExpression(.nil)
-- this is a special wrapper
wrapper = .NegativeLookAheadNode~new(node)
-- wrappered nodes fill both roles
groupInfo~firstNode = wrapper
groupInfo~lastNode = wrapper
-- zero length matches do not have closures
closure = .false
end
-- Three possibilities here:
-- 1) (?<=... a "zero-width positive lookbehind"
-- 2) (?<!... a "zero-width negative lookbehind"
-- 3) (?<xxxxx>... a named capture group
when ch == '<' then do
self~next -- step over the peeked character
-- a look behind. These are a pain. We can only
-- support this if the pattern has a deterministic
-- max and min. Before we can decide, we need to
-- extract the group expression and then calculate
-- the metrics for the entire expression tree.
-- this is the '=' or '!' qualifier
ch = self~peek
if ch == '=' | ch == '!' then do
self~next -- step over the modifier
-- parse the encapsulated group expression, but terminate
-- with a normal terminator node. This will perform a
-- and of range check on the matches to ensure the
-- tests will butt up against the current position.
node = self~parseExpression(.TerminatorNode~new)
-- gather some metrics. If there is a deterministic maximum,
-- we can optimize the back search by using it. Otherwise,
-- we just go back to the beginning
metrics = self~getPatternMetrics(node)
-- create the matcher type based on the modifier
if ch == '=' then do
wrapper = .PositiveLookBehindNode~new(node, metrics)
end
else if ch == '!' then do
wrapper = .NegativeLookBehindNode~new(node, metrics)
end
-- wrappered nodes fill both roles
groupInfo~firstNode = wrapper
groupInfo~lastNode = wrapper
-- zero length matches do not have closures
closure = .false
end
else do
-- back up for the delimiter parsing
self~previous
-- and parse out the delimited name
referenceName = self~extractDelimited('<', '>')
-- apply Rexx symbol rules to the name and make uppercase
referenceName = referenceName~upper
-- add this to our reference table
self~getGroupReference(referenceName)
-- a named capturing group
group = .CapturingGroupEnvelope~new(referenceName)
-- parse the encapsulated group expression. This gets
-- slotted between the group element and the terminator
group~next = self~parseExpression(group~terminator)
-- to wire in to the caller, we need to provide a node that
-- is plugged into the previous node, and a node that will be
-- the new tail end of the chain.
groupInfo~firstNode = group
groupInfo~lastNode = group~terminator
-- we need the group id to process the closure
groupInfo~id = referenceName
end
end
-- a conditional node. These are a bit more complex
when ch == '(' then do
node = self~parseConditional
-- add this to the returned group information. This still
-- needs to have closures processed
groupInfo~firstNode = node
groupInfo~lastNode = node
end
-- documentation in a regex...can you imagine that!
when ch == '#' then do
self~previous -- step back to the '(' that started the group
self~previous
-- just swallow the comment group and continue
self~extractDelimited('(', ')')
return .nil
end
-- a boundary defined by a character class
when ch == 'b' then do
self~next
ch = self~peek
-- the default type is simple class boundary
boundaryType = .ClassBoundaryNode
select
-- Not on a class boundary
when ch == '^' then do
boundaryType = .NotClassBoundaryNode
self~next
end
-- beginning of the sequence boundary
when ch == '<' then do
boundaryType = .BeginClassBoundaryNode
self~next
end
when ch == '>' then do
boundaryType = .EndClassBoundaryNode
self~next
end
otherwise do
-- the default type is simple class boundary
boundaryType = .ClassBoundaryNode
end
end
ch = self~next
if ch \= '[' then do
raise syntax 93.900 array("Missing class definition for (?b) boundary match")
end
-- parse out the class definition
node = self~parseClass
-- create the boundary checker
wrapper = boundaryType~new(node)
-- wrappered nodes fill both roles
groupInfo~firstNode = wrapper
groupInfo~lastNode = wrapper
-- zero length matches do not have closures
closure = .false
end
otherwise do
-- if .true, this is a closed modifier. A
-- closed modifier will last for the lifetime
-- of its enclosing group. This set of parens
-- is ignored for the purposes of restoring the
-- flag settings
if self~parseFlag then do
return .nil
end
-- non capture group after the flag value
group = .GroupEnvelope~new
-- parse the encapsulated group expression. This gets
-- slotted between the group element and the terminator
group~next = self~parseExpression(group~terminator)
-- to wire in to the caller, we need to provide a node that
-- is plugged into the previous node, and a node that will be
-- the new tail end of the chain.
groupInfo~firstNode = group
groupInfo~lastNode = group~terminator
end
end
end
else do
-- we're looking at the start of the sequence inside because we peeked
-- at the character
-- this is a capturing group
id = self~newGroup
group = .CapturingGroupEnvelope~new(id)
-- parse the encapsulated group expression. This gets
-- slotted between the group element and the terminator
group~next = self~parseExpression(group~terminator)
-- to wire in to the caller, we need to provide a node that
-- is plugged into the previous node, and a node that will be
-- the new tail end of the chain.
groupInfo~firstNode = group
groupInfo~lastNode = group~terminator
groupInfo~id = id
end
-- we should be positioned at the closing paren now. Make sure
-- it is there
ch = self~next
if ch \== ')' then do
raise syntax 93.900 array("Missing closing ')' for a group")
end
-- restore the flags now to the original state
self~restoreFlags(savedFlags)
-- we need to process this differently, since there are different
-- repetitors needed to handle updating group information
if closure then do
self~parseGroupClosure(groupInfo)
end
-- return the new chain information.
return groupInfo
-- parse a conditional node in the form "(?(cond)then|else)
::method parseConditional
-- we're positioned at the the ( that starts the conditional now.
-- step over that and examine the different options
self~next
ch = self~peek -- get the next character and process the different options
select
-- this is a lookahead or lookbehind construct
when ch == '?' then do
-- step ahead one character and see which
-- flavor this is
self~next
ch = self~peek
select
-- forward lookahead test
when ch == '=' then do
self~next -- step over the peeked character
-- parse the encapsulated group expression, but terminate
-- with a branch terminator node.
node = self~parseExpression(.nil)
-- this is a special wrapper
condition = .PositiveLookAheadNode~new(node)
end
-- this is a negative lookahead.
when ch == '!' then do
self~next -- step over the peeked character
-- parse the encapsulated group expression, but terminate
-- with a branch terminator node.
node = self~parseExpression(.nil)
-- this is a special wrapper
condition = .NegativeLookAheadNode~new(node)
end
-- Three possibilities here:
-- 1) (?<=... a "zero-width positive lookbehind"
-- 2) (?<!... a "zero-width negative lookbehind"
when ch == '<' then do
self~next -- step over the peeked character
-- a look behind. These are a pain. We can only
-- support this if the pattern has a deterministic
-- max and min. Before we can decide, we need to
-- extract the group expression and then calculate
-- the metrics for the entire expression tree.
-- this is the "=" or "!" qualifier
ch = self~peek
if ch == '=' | ch == '!' then do
self~next -- step over the modifier
-- parse the encapsulated group expression, but terminate
-- with a normal terminator node. This will perform a
-- and of range check on the matches to ensure the
-- tests will butt up against the current position.
node = self~parseExpression(.nil)
-- gather some metrics. If there is a deterministic maximum,
-- we can optimize the back search by using it. Otherwise,
-- we just go back to the beginning
metrics = self~getPatternMetrics(node)
-- create the matcher type based on the modifier
if ch == '=' then do
condition = .PositiveLookBehindNode~new(node, metrics)
end
else if ch == '!' then do
condition = .NegativeLookBehindNode~new(node, metrics)
end
end
else do
raise syntax 93.900 array("Unknown conditional type '"ch"'")
end
end
otherwise do
raise syntax 93.900 array("Unknown conditional type '"ch"'")
end
end
-- we should be positioned at the closing paren now. Make sure
-- it is there
ch = self~next
if ch \== ')' then do
raise syntax 93.900 array("Missing closing ')' for a group")
end
end
-- a back reference test. This is of the form (?(name)...
-- we're looking at the first character, so back up and
-- extract the name using the '(' and ')' delimiters
otherwise do
-- potentially a compound back reference name? This requires
-- more complicated parsing
if ch == '<' then do
-- parse out the group name
path = .array~new
self~parseGroupName(path)
-- we can validate the first, the rest are very dynamic
if \self~haveGroup(path[1]) then do
raise syntax 93.900 array("Unrecognized group back reference:" path[1])
end
-- the more typical case of a single level conditional. This just
-- checks on group participation
if path~items == 1 then do
-- a named back reference to previous node
condition = .BackReferenceTestNode~new(path[1])
end
else do
-- a more complex look up
condition = .ResultBackReferenceTestNode~new(path)
end
end
else do
self~previous
referenceName = self~extractDelimited('(', ')')
referenceName = referenceName~upper -- all names are stored in uppercase
-- a named back reference to previous node
condition = .BackReferenceTestNode~new(referenceName)
end
end
end
-- ok, we have the conditional part, now parse out the then and optional
-- else sections
-- NOTE: we need to parse this as a sequence, not as an expression
-- because the | is an expression end delimiter
thenNode = self~parseSequence(.nil)
ch = self~peek
-- have the | part?
if ch == '|' then do
self~next -- step over the |
-- now parse out the else section. NOTE: parse sequence
-- needs to be used because we don't accept alternatives
-- unless in a group
elseNode = self~parseSequence(.nil)
node = .IfThenElseNode~new(condition, thenNode, elseNode)
end
else do
-- simple then node
node = .IfThenNode~new(condition, thenNode)
end
return node
-- calculate the match metrics for a given pattern.
::method getPatternMetrics
use arg head
metrics = .MatchMetrics~new
-- forward this to the matching tree
head~calculateMatchMetrics(metrics)
return metrics
-- parse options flags in the expressions
::method parseFlag
ch = self~next
setting = .true
-- multiple flags can appear in a group
do forever
select
-- we're using unix linends
when ch == 'd' then do
self~unixLinesMode = setting
setting = .true -- reset for an additional mode flag
end
-- case insensitive matching
when ch == 'i' then do
self~caselessMode = setting
setting = .true -- reset for an additional mode flag
end
-- linends are recognized at other than the end of the data
when ch == 'm' then do
self~multiLineMode = setting
setting = .true -- reset for an additional mode flag
end
-- "single line" mode.
when ch == 's' then do
self~dotAllMode = setting
setting = .true -- reset for an additional mode flag
end
-- turning a flag off
when ch == '-' then do
-- if we're already negated, this is an error.
if \setting then do
raise syntax 93.915 array("dims", ch)
-- this is a mode negation
end
setting = .false
end
-- this is the (?f:X) form. The caller needs to
-- process the rest of the group. Return .false to
-- indicate there's more to do.
when ch == ':' then do
return .false
end
-- if the flag terminator is the closing paren, then
-- this group is a closed flag group. The return value
-- tells the caller there's nothing left in the group to
-- process
when ch == ')' then do
return .true
end
otherwise do
raise syntax 93.915 array("dims-", ch)
end
end
ch = self~next -- step to the next character
end
-- various option flags
::attribute unixLinesMode
::attribute caselessMode
::attribute multiLineMode
::attribute dotAllMode
-- take a snapshot of our option flags for saving
-- and restoring around groups that alter the flags
-- just in the local context. Returns a directory
-- with the flag settings
::method saveFlags
flags = .directory~new
flags~unixLinesMode = self~unixLinesMode
flags~caselessMode = self~caselessMode
flags~multiLineMode = self~multiLineMode
flags~dotAllMode = self~dotAllMode
return flags
-- restore the flag settings from a previous
-- saveFlags collection
::method restoreFlags
use arg flags
self~unixLinesMode = flags~unixLinesMode
self~caselessMode = flags~caselessMode
self~multiLineMode = flags~multiLineMode
self~dotAllMode = flags~dotAllMode
-- process the closures for a group node. This handles all of the
-- repetition count details
::method parseGroupClosure
use arg groupInfo
-- we're parsing any closure items that may follow the group itself.
-- If there are closure items to process, this will end up adjusting the
-- firstNode/lastNode information in groupInfo
-- this will be the piece that's consumed by a potential closure item.
target = groupInfo~firstNode
ch = self~peek
select
when ch == '?' then do
self~next
-- a question repetitor
ch = self~peek
if ch == '?' then do
self~next
node = .ReluctantGroupQuestionNode~new(groupInfo~id, target)
end
else if ch == '+' then do
self~next
node = .PossessiveGroupQuestionNode~new(groupInfo~id, target)
end
else do
node = .GreedyGroupQuestionNode~new(groupInfo~id, target)
end
end
when ch == '*' then do
self~next
-- zero or more occurrences
ch = self~peek
if ch == '?' then do
self~next
node = .ReluctantGroupRepetitionNode~new(groupInfo~id, target, 0, 999999999)
end
else if ch == '+' then do
self~next
node = .PossessiveGroupRepetitionNode~new(groupInfo~id, target, 0, 999999999)
end
else do
node = .GreedyGroupRepetitionNode~new(groupInfo~id, target, 0, 999999999)
end
end
when ch == '+' then do
self~next
-- one or more occurrences
ch = self~peek
if ch == '?' then do
self~next
node = .ReluctantGroupRepetitionNode~new(groupInfo~id, target, 1, 999999999)
end
else if ch == '+' then do
self~next
node = .PossessiveGroupRepetitionNode~new(groupInfo~id, target, 1, 999999999)
end
else do
node = .GreedyGroupRepetitionNode~new(groupInfo~id, target, 1, 999999999)
end
end
when ch == '{' then do
self~next
min = self~parseNumber
max = min
ch = self~next
if ch == ',' then do
max = self~parseNumber
ch = self~next
end
if ch \= '}' then do
raise syntax 36.900 array("Missing closing '}' for repetition count")
end
--
if .nil == min then do
raise syntax 93.900 array("Invalid repetition count minimum")
end
-- we use the default digits maximum for max if not specified
if max == .nil then do
max = 999999999
end
if max < min then do
raise syntax 93.900 array("Repetition maximum:" max", is less than minimum:" min)
end
ch = self~peek
if ch == '?' then do
self~next
node = .ReluctantGroupRepetitionNode~new(groupInfo~id, target, min, max)
end
else if ch == '+' then do
self~next
node = .PossessiveGroupRepetitionNode~new(groupInfo~id, target, min, max)
end
else do
node = .GreedyGroupRepetitionNode~new(groupInfo~id, target, min, max)
end
end
otherwise do
-- no additional closure
return
end
end
-- stick branch terminator after the end of this. The
-- question node will handle the repetitions.
groupInfo~lastNode~next = .nil
-- this is atomic, and handles both roles
groupInfo~firstNode = node
groupInfo~lastNode = node
return
-- process the closure for a node. Because a sequence might have
-- modifiers, we might need to wrap the node sequence in
-- an enclosing node that handles the modifiers
::method parseClosure
use arg target
ch = self~next
select
-- A question modifier, which itself might have a
-- modifier to control the operating mode
when ch == '?' then do
-- a question repetitor
ch = self~peek
-- ?? operates in reluctant mode
if ch == '?' then do
self~next
return .ReluctantQuestionNode~new(target)
end
-- possesive question mode
else if ch == '+' then do
self~next
return .PossessiveQuestionNode~new(target)
end
else do
-- no modifier is greedy
return .GreedyQuestionNode~new(target)
end
end
-- zero or more occurrences. This also operates with mode
-- modifiers
when ch == '*' then do
ch = self~peek
if ch == '?' then do
self~next
return .ReluctantRepetitionNode~new(target, 0, 999999999)
end
else if ch == '+' then do
self~next
return .PossessiveRepetitionNode~new(target, 0, 999999999)
end
else do
return .GreedyRepetitionNode~new(target, 0, 999999999)
end
end
-- one or more occurrences. Also with different modes of
-- operation
when ch == '+' then do
ch = self~peek
if ch == '?' then do
self~next
return .ReluctantRepetitionNode~new(target, 1, 999999999)
end
else if ch == '+' then do
self~next
return .PossessiveRepetitionNode~new(target, 1, 999999999)
end
else do
return .GreedyRepetitionNode~new(target, 1, 999999999)
end
end
-- {min[,max]} range
when ch == '{' then do
min = self~parseNumber
max = min
ch = self~next
if ch == ',' then do
max = self~parseNumber
ch = self~next
end
-- must be a closing '}' on this
if ch \= '}' then do
raise syntax 36.900 array("Missing closing '}' for repetition count")
end
--
if .nil == min then do
raise syntax 93.900 array("Invalid repetition count minimum")
end
-- we use the default digits maximum for max if not specified
if max == .nil then do
max = 999999999
end
if max < min then do
raise syntax 93.900 array("Repetition maximum:" max", is less than minimum:" min)
end
ch = self~peek
if ch == '?' then do
self~next
return .ReluctantRepetitionNode~new(target, min, max)
end
else if ch == '+' then do
self~next
return .PossessiveRepetitionNode~new(target, min, max)
end
else do
return .GreedyRepetitionNode~new(target, min, max)
end
end
otherwise do
-- no additional closure. make sure we put the character
-- we just borrowed back...but only if it was a real character!
if ch \= .nil then do
self~previous
end
return target
end
end
-- parse a [abc] class modifier
::method parseClass
-- parse the section of the class, which may
-- included nested pieces
node = self~parseClassSection
ch = self~next
if ch \= ']' then do
raise syntax 36.900 array("Missing closing ']' for character class")
end
return node
-- parse out the characters between a class section.
::method parseClassSection
expose current length pattern
previousNode = .nil
negated = .false
firstchar = .true
-- we look until the end of input or until we hit our
-- closing delimiter
do forever
ch = self~peek -- just taking a peek
select
-- our caller checks for the closing piece, so
-- just return what we have and allow them to issue
-- the error message
when ch == .nil then do
return previousNode
end
-- negation of the class
when ch == '^' then do
if firstChar then do
self~next
negated = .true
iterate -- go around and check the next character
end
end
-- this is likely the close of our section, so
-- finish up and let the caller determine if this is good
when ch == ']' then do
-- we've hit the end of this class spec, time to return.
return previousNode
end
-- nested section within a class. These are OR'd together
when ch == '[' then do
self~next -- step over the delimiter
subNode = self~parseClass
-- if we already have a node within the class, we combine this
-- using a logical op
if .nil == previousNode then do
previousNode = subNode
end
else do
previousNode = .ClassOrNode~new(previousNode, subNode)
end
end
when ch == '&' then do
self~next -- step over the first &
ch = self~peek
if ch == '&' then do -- this is a logical "&&"
if prev == .nil then do
raise syntax 35.900 array("Missing left term for '&&' operator")
end
self~next -- step over the peeked character
rightHand = .nil
do forever
ch = self~peek -- peek so we don't ruin undoing a .nil read
select
when ch == '[' then do
self~next -- step over the peeked character
-- embedded class...recursively parse, and chain up, if necessary
node = self~parseClass
if rightHand == .nil then do
rightHand = node
end
else do
-- chain up the logical operation
rightHand = .ClassAndNode~new(rightHand, node);
end
end
when ch == ']' | ch == '&' then do
-- either the complete end, or a section end.
leave
end
otherwise do
-- parse out the next section
node = self~parseClassSection
if rightHand == .nil then do
rightHand = node
end
else do
-- chain up the logical operation
rightHand = .ClassAndNode~new(rightHand, node);
end
end
end
end
-- must have both a left term and a right term here
if rightHand == .nil then do
raise syntax 35.900 array("Missing right term for '&&' operator")
end
-- This might be the entire term, or needs to be AND'd with
-- the working chain
if previousNode == .nil then do
previousNode = rightHand
end
else do
previousNode = .ClassAndNode~new(previousNode, rightHand)
end
end
else do
-- unread the character...the "&" is just a literal char
self~previous
end
end
-- possibly a predefined class or named class family. This is
-- handled here
when ch == '\' then do
self~next -- step over the peeked character
-- see if this is one of the special classes
subNode = self~parseEscapedClasses
-- if we have something special here, add this to the
-- group chain
if subNode \= .nil then do
-- sort of a pain, but if this is a quoted string in the
-- class, we need to convert that into a class node
if subNode~isa(.StringNode) then do
-- create the appropriate class node
subNode = self~classNode(subNode~matchString, negated)
end
-- if we already have a node within the class, we combine this
-- using a logical op
if .nil == previousNode then do
previousNode = subNode
end
else do
previousNode = .ClassOrNode~new(previousNode, subNode)
end
end
else do
self~previous -- handled in the block parsing
end
end
otherwise do
nop -- nothing extra to do here
end
end
-- processed all of the special chars, we should be looking at class characters.
-- process this into a node.
node = self~parseClassRange(negated)
-- if this is a negation, then this is an AND operation
if negated then do
if previousNode \= .nil then do
previousNode = .ClassAndNode~new(previousNode, node)
end
else do
previousNode = node
end
end
else do
-- not negated, so this just adds to the list
if previousNode \= .nil then do
previousNode = .ClassOrNode~new(previousNode, node)
end
else do
previousNode = node
end
end
negated = .false
end
-- parse a range of characters for a class. This should either
-- be a set of specifically specified characters (including escaped
-- characters, or a range in the form "x-z". The range will be terminated
-- by any of the meta characters. We may also encounter a named family
-- class, in which case we'll return just that piece. Range negations have
-- already been processed by our caller
::method parseClassRange
use arg negated -- determines the type of node we return
firstchar = .true
characters = ""
do forever
ch = self~peek -- just peek at the next character
-- we can terminate on the end of data or the closing bracket
if ch == .nil then do
leave
end
-- is this any of e or a nested range?
-- stop here
else if self~isClassMetaCharacter(ch) then do
-- quit now...we only peeked at this character,
-- so it's still there
leave
end
-- an escape character...this might be a real escaped character or
-- a more complex operation. If it's a character, accept it now, otherwise
-- stop parsing here and allow the higher level to handle the escaped
-- operation
else if ch == '\' then do
self~next -- step over the escape
ch = self~parseEscapedCharacters
-- if this doesn't parse into a character, then step back and
-- finish up here
if ch == .nil then do
self~previous
leave
end
-- we have the character for adding to this range
end
-- if the current position is the sequence '&&', this is
-- an interesection. If it is a single '&', we use the character
-- as is
else if ch == '&' then do
if self~peekOffset(1) == '&' then do
-- still positioned at the first '&'. The
-- intersection will be processed at a higher level
leave
end
self~next -- step over the character
end
else do
-- Simple character added to the range
ch = self~next
end
-- this could be followed by a '-' character
if self~peek == '-' then do
-- skip over that and get the next character
self~next
endRange = self~next
-- missing closing class piece? Return now and allow caller
-- to handle
if endRange == .nil then do
leave
end
-- a '-' at the very end of a range is interpretered as a
-- '-' character rather than the range operator. Also,
-- in a '--' sequence, the second '-' is just the character.
if \self~isClassMetaCharacter(endRange) then do
-- if the endRange character is an escape, then we
-- need to process both characters
if endRange == '\' then do
self~previous
endRange = self~singleChar
-- if not valid, we have a problem of some sort
if endRange == .nil then do
leave
end
end
-- replace the character with the end range
ch = xrange(ch, endRange)
end
else do
self~previous -- back up and process the closing on the next loop
end
end
-- add this to the accumulator
characters = characters || ch
end
-- return the node based on the class modifier
return self~classNode(characters, negated)
-- parse a named class family and turn it into an equivalent family class
::method parseNamedClassFamily
use arg negated
familyName = self~extractDelimited('{', '}')
if familyName~match(1, "Is") then do
familyName = familyName~substr(3)
end
return self~createNamedClassFamily(familyName, negated)
-- create a named class family
::method createNamedClassFamily
use arg familyName, negated
familyChars = self~classFamily(familyName)
if familyChars == .nil then do
raise syntax 93.900 array("Unknown named class family '"familyName"'")
end
-- now return the appropriate node type for the match
-- NOTE: Not sure I know how the caseless flag is supposed to be
-- applied here. For example, with the Java implementation,
-- (?i)/p{Lower} does not match A. The other sources of information
-- don't really touch on it. I'm inclined to have it work with case
-- insensitive matches, but this is not a strong stance.
return self~classNode(familyChars, negated)
-- parse out a section of as-is characters that conforms to an atom
-- specification
::method parseAtom
characters = ""
do forever
ch = self~next
select
when ch = .nil then do
leave
end
when ch == '\' then do
ch = self~parseEscapedCharacters
-- this is either an invalid escape char, or an operation
-- we push the char back on, and stop processing.
if ch == .nil then do
self~previous
leave
end
end
-- if this is a non-escaped special char,
-- backup and finish up this section
when self~isMetaCharacter(ch) then do
self~previous
leave
end
otherwise do
-- We have a good character, but it might be followed
-- by a modifier. If it is, push it back and terminate
-- the parsing here.
test = self~peek
if test \= .nil, self~isClosureCharacter(test) > 0 then do
-- if there are more than one character here,
-- back up and return what we have.
if characters \== '' then do
self~previous
end
else do
-- otherwise, this single character is the entire atom
-- the closure characters will apply to it
characters = ch
end
leave
end
characters = characters || ch
end
end
end
return self~stringNode(characters)
-- create a node for matching a character string
::method stringNode
use arg string
if self~caselessMode then do
return .CaselessStringNode~new(string)
end
else do
return .StringNode~new(string)
end
-- create a node for matching a a range of characters. Which
-- node gets created depends on whether this is a negation operation
-- and whether caseless matches are called for.
::method classNode
use arg characters, negated
-- if this is a ^ form, then we need the appropriate reverse node
if negated then do
if self~caselessMode then do
return .CaselessNotClassNode~new(characters)
end
else do
return .NotClassNode~new(characters)
end
end
-- normal matching mode, which also has two forms
else do
if self~caselessMode then do
return .CaselessClassNode~new(characters)
end
else do
return .ClassNode~new(characters)
end
end
-- parse out an escaped character
::method parseEscapedCharacters private
ch = self~next
select
when ch == '0' then do
-- octal character value
firstDigit = self~readOctal
if .nil \= firstDigit then do
secondDigit = self~readOctal
if .nil \= secondDigit then do
thirdDigit = self~readOctal
if .nil \= thirdDigit then do
if firstDigit <= 3 then do
return d2c((firstDigit * 64) + (secondDigit * 8) + thirdDigit)
end
-- not a value 3 digit octal, so only use 2
self~previous
end
return d2c((firstDigit * 8) + secondDigit)
end
return d2c(firstDigit)
end
raise syntax 93.900 array("Missing octal character")
end
-- alert (bell)
when ch == 'a' then do
return '07'x
end
-- backspace (only valid in a class...this is a word boundary elsewhere)
when ch == 'b' then do
return '08'x
end
-- control character corresponding to "x". The
-- allowed control charaters are the values a-z or A-Z. The
-- resulting character will be the value '01'x through '1a'x (decimal 26)
-- Either upper or lowercase letters are permitted
when ch == 'c' then do
control = self~next
if .nil == control then do
raise syntax 93.900 array("Character expected after \c escape")
end
-- check and convert the lower case characters
ctrl = self~LOWERCASECHARACTERS~pos(control)
if ctrl \= 0 then do
return d2c(ctrl)
end
-- now uppercase versions
ctrl = self~UPPERCASECHARACTERS~pos(control)
if ctrl \= 0 then do
return d2c(ctrl)
end
raise syntax 93.900 array("Invalid \c control character name")
end
when ch == 'e' then do
return '1b'x -- escape char
end
when ch == 'f' then do
return '0c'x -- form feed
end
when ch == 'n' then do
return '0a'x -- new line
end
when ch == 'r' then do
return '0d'x -- carriage return
end
when ch == 't' then do
return '09'x -- horizontal tab
end
when ch == 'v' then do
return '0b'x -- vertical tab
end
when ch == 'x' then do -- hex encoded character
-- hex value
return x2c(self~readHex || self~readHex)
end
otherwise do
-- if not one of the reserved characters at this point, we return the escaped char
if '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ<>'~pos(ch) == 0 then do
return ch
end
-- this is either an operation or invalid. We leave that for another phase
self~previous
return .nil
end
end
-- special escaped operations, including the special character classes
::method parseEscapedOperations private
-- try for one of the classes first
class = self~parseEscapedClasses
-- done
if class \== .nil then do
return class
end
-- The next category of escape are the different anchor/group indicators.
-- These are only allowed at a top-level context
ch = self~next
select
when .nil == ch then do
raise syntax 93.900 array("Missing character after escape")
end
-- numbered back reference
when '123456789'~pos(ch) > 0 then do
-- a back reference
if \self~haveGroup(ch) then do
raise syntax 93.900 array("Unrecognized group back reference" ch)
end
if self~caselessMode then do
return .CaselessGroupBackReferenceNode~new(ch)
end
else do
return .GroupBackReferenceNode~new(ch)
end
end
-- named back reference
when ch == 'k' then do
-- a \k back reference can be complicated
return self~parseNamedGroup
end
-- reference to a registered pattern
when ch == 'm' then do
-- get the pattern name
patternName = self~extractDelimited('{', '}')
patternName = patternName~upper
pattern = self~namedPattern(patternName)
if pattern == .nil then do
raise syntax 93.900 array("Unrecognized pattern reference:" patternName)
end
-- this handles the indirection
return .PatternNode~new(patternName, pattern)
end
-- start of text anchor
when ch == 'A' then do
return .BeginTextNode~new
end
-- NOT on a word boundary anchor
when ch == 'B' then do
return .NotClassBoundaryNode~new(self~createNamedClassFamily("WORD", .false))
end
-- ON a word boundary anchor
when ch == 'b' then do
return .ClassBoundaryNode~new(self~createNamedClassFamily("WORD", .false))
end
-- Beginning word boundary anchor
when ch == '<' then do
return .BeginClassBoundaryNode~new(self~createNamedClassFamily("WORD", .false))
end
-- End of word boundary anchor
when ch == '>' then do
return .EndClassBoundaryNode~new(self~createNamedClassFamily("WORD", .false))
end
-- Last match. We do iteration a little differently, so this
-- really matches the start of the text region we're looking at.
when ch == 'G' then do
return .LastMatchNode~new
end
-- this is like $, but it always is an end of input or linend
-- match, rather than multiline
when ch == 'Z' then do
if self~unixLinesMode then do
return .UnixLineEndNode~new
end
else do
return .InternetLineEndNode~new
end
end
-- always match the end of the text
when ch == 'z' then do
return .TextEndNode~new
end
otherwise do
self~previous -- revert the read character
return .nil -- return the failure indicator
end
end
-- parse a group back reference. The back reference is in the
-- form <group{result<group...>}> for as many levels as are needed.
-- Thus <group> will return the match value for named group "group".
-- <group{result}> will return the named result "result" within group
-- "group", while <group{result<subgroup>}> will return the value of
-- group "subgroup" within named result "result" of group "group"
::method parseNamedGroup
-- create an accumulator, and start parsing the potentially lengthy group name
path = .array~new
self~parseGroupName(path)
-- the first level is all we can verify exists at this point
if \self~haveGroup(path[1]) then do
raise syntax 93.900 array("Unrecognized group back reference:" path[1])
end
-- just a simple group reference?
if path~items == 1 then do
if self~caselessMode then do
return .CaselessGroupBackReferenceNode~new(path[1])
end
else do
return .GroupBackReferenceNode~new(path[1])
end
end
-- more complex path resolution required
else do
if self~caselessMode then do
return .CaselessResultBackReferenceNode~new(path)
end
else do
return .ResultBackReferenceNode~new(path)
end
end
referenceName = "" -- the accumulated name
loop forever
ch = self~next -- get the next character
-- end of the group name portion?
if ch == '>' then do
-- apply Rexx symbol rules to the name and make uppercase
referenceName = referenceName~upper
if \nested then do
if \self~haveGroup(referenceName) then do
raise syntax 93.900 array("Unrecognized group back reference:" referenceName)
end
if self~caselessMode then do
return .CaselessGroupBackReferenceNode~new(referenceName)
end
else do
return .GroupBackReferenceNode~new(referenceName)
end
end
end
-- result reference inside of a group
else if ch == '{' then do
-- we allow a default here...going right to the
-- result means use the 0 group.
if referenceName == "" then do
referenceName = "0"
end
-- get the result portion
resultNode = self~parseResultName
-- now get an appropriate node to handle the group cascade of names
if self~caselessMode then do
return .CaselessGroupResultBackReferenceNode~new(referenceName, resultNode)
end
else do
return .GroupResultBackReferenceNode~new(referenceName, resultNode)
end
end
end
-- parse a the group portion of a resulution path
::method parseGroupName
-- this is the path accumulator array
use arg path
self~next -- step over the '<' delimiter that started this
referenceName = "" -- the accumulated name
loop forever
ch = self~next -- get the next character
if ch == .nil then do
raise syntax 93.900 array("Missing closing '>' on group name")
end
-- end of the group name portion?
else if ch == '>' then do
-- an empty reference
if referenceName == "" then do
referenceName = "0"
end
-- apply Rexx symbol rules to the name and make uppercase
referenceName = referenceName~upper
path~append(referenceName)
return
end
-- result reference inside of a group
else if ch == '{' then do
-- we allow a default here...going right to the
-- result means use the 0 group.
if referenceName == "" then do
referenceName = "0"
end
-- apply Rexx symbol rules to the name and make uppercase
referenceName = referenceName~upper
path~append(referenceName)
self~previous
-- get the result portion
self~parseResultName(path)
-- perform the delimiter check
ch = self~next
if ch \== '>' then do
raise syntax 93.900 array("Missing closing '>' on group name")
end
return
end
else do
referenceName = referenceName || ch
end
end
-- parse a the result portion of a resulution path
::method parseResultName
-- this is the path accumulator array
use arg path
self~next -- step over the '<' delimiter that started this
referenceName = "" -- the accumulated name
loop forever
ch = self~next -- get the next character
if ch == .nil then do
raise syntax 93.900 array("Missing closing '}' on result name")
end
-- end of the result name portion?
else if ch == '}' then do
-- apply Rexx symbol rules to the name and make uppercase
referenceName = referenceName~upper
path~append(referenceName)
return
end
-- group reference inside of a result
else if ch == '<' then do
-- apply Rexx symbol rules to the name and make uppercase
referenceName = referenceName~upper
path~append(referenceName)
self~previous
-- get the result portion
self~parseGroupName(path)
-- perform the delimiter check. We should have
-- a } after the close of the group name.
ch = self~next
if ch \== '}' then do
raise syntax 93.900 array("Missing closing '}' on result name")
end
return
end
else do
referenceName = referenceName || ch
end
end
-- special escaped character classes, including the named class families
::method parseEscapedClasses private
ch = self~next
select
when .nil == ch then do
raise syntax 93.900 array("Missing character after escape")
end
-- NOT a digit
when ch == 'D' then do
-- no need to handle caseless matches here
return self~createNamedClassFamily("Digit", .true)
end
-- Is a digit
when ch == 'd' then do
-- no need to handle caseless matches here
return self~createNamedClassFamily("Digit", .false)
end
-- quoted literal..return the entire group
when ch == 'Q' then do
return self~parseLiteral
end
-- NOT whitespace
when ch == 'S' then do
-- no need to handle caseless matches here
return self~createNamedClassFamily("Space", .true)
end
-- is whitespace
when ch == 's' then do
-- no need to handle caseless matches here
return self~createNamedClassFamily("Space", .false)
end
-- NOT a word character
when ch == 'W' then do
-- This includes all of the upper and lower case letters, so no
-- caseless considerations to worry about
return self~createNamedClassFamily("Word", .true)
end
-- is a word character
when ch == 'w' then do
-- This includes all of the upper and lower case letters, so no
-- caseless considerations to worry about
return self~createNamedClassFamily("Word", .false)
end
-- named class family
when ch == 'p' then do
-- parse out the named property
return self~parseNamedClassFamily(.false)
end
-- negation of the a named class family
when ch == 'P' then do
-- parse out the named property
return self~parseNamedClassFamily(.true)
end
otherwise do
-- back off the character..might be some other type of operation
self~previous
return .nil -- return a failure indicator
end
end
-- parse out a literal defined by using the \Q and \E delimiters
::method parseLiteral private
current = self~current
endPosition = -1
do forever
ch = self~next
if .nil == ch then do
endPosition = self~current
leave
end
if ch == '\' then do
modifier = self~peek
if .nil == modifier then do
raise syntax 93.900 array("Missing closing \E following \Q")
end
if modifier == 'E' then do
endPosition = self~current - 1
self~next -- step over the closing bit
leave
end
end
end
return self~stringNode(self~extract(current, endPosition))
-- read and validate a octal value in an escaped value, returning the
-- eqivalent character value. Since octal escapes are variable length,
-- we just return .nil rather than raise a syntax error.
::method readOctal private
ch = self~next
if ch == .nil then do
return .nil
end
if ch < '0' | ch > '7' then do
self~previous
return .nil
end
return ch
-- read and validate a hex encoded character in an escaped value, returning
-- the character equivalent
::method readHex private
ch = self~next
if .nil \= ch then do
if '1234567890abcdefABCDEF'~pos(ch) == 0 then do
raise syntax 93.900 array("Invalid hex digit '"ch"'")
end
return ch
end
-- we can directly raise a syntax error for reading hex
raise syntax 93.900 array("Hex digit expected")
-- Start of nodes that implement the various matching algorithms
-- base class for all matching nodes
::class MatchNode
::constant wordChars 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_'
::method init
expose next
next = .nil
::attribute next
-- invoke the next handler in the chain
::method matchNext
expose next
use arg context, position, target
-- if there is not node attached, assume it matches
if next == .nil then do
-- set the end match position
context~matchEnd = position
-- this is always a successful match. This really just
-- records the last position of this branch segment.
return .true
end
-- just send this along
return next~match(context, position, target)
-- calculate the length of this match, if possible. The
-- default implementation assumes the length of this node is zero and
-- just passes the request down the chain
::method calculateMatchMetrics
expose next
use arg metrics
if next \== .nil then do
next~calculateMatchMetrics(metrics)
end
::method calculateChildMatchMetrics
use arg child
-- get our repetition node values as if it was the only thing of interest
submetrics = .MatchMetrics~new
child~calculateMatchMetrics(submetrics)
return submetrics
-- add a .TerminatorNode terminator to a node that will
-- be used as part of a composite
::method terminate
expose next
-- if we don't have a successor yet or our successor
-- is a normal terminator, then set our successor to be
-- the branch version. The latter case generally happens
-- when a parsed sequence is wrapped in an alteration
if next == .nil | next~isa(.TerminatorNode) then do
-- matchNext handles the .nil like it was a terminator
-- terminate is only called for side branches, so we can
-- eliminate that extra node
self~next = .nil
end
else do
-- we have a child node, make sure that child has a
-- terminator
self~next~terminate
end
-- A node that will match anything. This is typically
-- used when an alternative is expressed as "this|that|".
-- The trailing "|" indicates that we always have a match,
-- even if it is zero-length
::class EveryThingNode subclass MatchNode
::method match
use arg context, position, target
-- we always match, so just send along to the successor
return self~matchNext(context, position, target)
-- A node that enforces anchoring at the beginning of the text
::class BeginTextNode subclass MatchNode
::method match
use arg context, position, target
-- if not at the beginning, this fails
if \context~atStart(position) then do
return .false
end
-- forward and complete
return self~matchNext(context, position, target)
-- A node that enforces anchoring at the end of the text
::class EndTextNode subclass MatchNode
::method match
use arg context, position, target
-- must be at the end to match
if \context~checkEnd(position) then do
return .false
end
-- forward and complete
return self~matchNext(context, position, target)
-- A node that enforces a match at the beginning of a boundary defined
-- by a class of characters
::class ClassBoundaryNode subclass MatchNode
::method init
expose boundaryClass
use arg boundaryClass
self~init:super
boundaryClass~terminate
::method match
use arg context, position, target
-- At the very end (e.g., past the end really), the last character
-- must be of the boundary character. Note that we need to check for a
-- null string condition too
if context~checkEnd(position) then do
-- also at the beginning means this is a
-- null string. No characters to check means not a
-- word boundary
if context~atStart(position) then do
return .false
end
-- not a word character in the previous position? This fails
if \self~checkBoundary(context, position - 1, target) then do
return .false
end
-- good so far, pass this along
return self~matchNext(context, position, target)
end
-- if at the start of the range, the character must be of the class character
-- NB, the at the end check above handled the null string case, so we
-- can check the first character unconditionally
if context~atStart(position) then do
-- not a class character in the current position? This fails
if \self~checkBoundary(context, position, target) then do
return .false
end
-- good so far, pass this along
return self~matchNext(context, position, target)
end
-- exclusive OR situation. Only one of these should be a class character to
-- qualify as a boundary
if self~checkBoundary(context, position, target) && self~checkBoundary(context, position - 1, target) then do
return self~matchNext(context, position, target)
end
return .false
-- simple method to perform the boundary test. A negative test
-- will override this
::method checkBoundary
expose boundaryClass
use arg context, position, target
return boundaryClass~match(context, position, target)
-- the inverse of a class boundary match. Matches only if the current
-- position is NOT on a class boundary
::class NotClassBoundaryNode subclass ClassBoundaryNode
::method match
use arg context, position, target
-- At the very end (e.g., past the end really), the last character
-- must be a word character. Note that we need to check for a
-- null string condition too
if context~checkEnd(position) then do
-- also at the beginning means this is a
-- null string. No characters to check means not a
-- word boundary
if context~atStart(position) then do
-- a null string is not a word boundary, so this passes
return self~matchNext(context, position, target)
end
-- a word character in the previous position? This fails
if self~checkBoundary(context, position - 1, target) then do
return .false
end
-- good so far, pass this along
return self~matchNext(context, position, target)
end
-- if at the start of the range, the character must be a word character
-- NB, the at the end check above handled the null string case, so we
-- can check the first character unconditionally
if context~atStart(position) then do
-- a word character in the current position? This fails
if target~matchChar(position, self~wordChars) then do
return .false
end
-- good so far, pass this along
return self~matchNext(context, position, target)
end
-- exclusive OR situation. If one is a boundary and the other not, this fails
-- qualify as a boundary
if self~checkBoundary(context, position, target) && self~checkBoundary(context, position - 1, target) then do
return .false
end
-- forward along
return self~matchNext(context, position, target)
-- Test if on the beginning boundary of a character class. To qualify,
-- the current position must be a class character and the previous
-- character must NOT be a class character or be the beginning of
-- the range
::class BeginClassBoundaryNode subclass ClassBoundaryNode
::method match
use arg context, position, target
-- At the very end (e.g., past the end really), by definition this
-- cannot be a beginning word boundary.
if context~checkEnd(position) then do
return .false
end
-- if the current character is not a class character, this fails too
if \self~checkBoundary(context, position, target) then do
return .false
end
-- if the position is the start of the range,
-- this passes
if context~atStart(position) then do
return self~matchNext(context, position, target)
end
-- the previous character must NOT be a class character to pass
if \self~checkBoundary(context, position - 1, target) then do
return self~matchNext(context, position, target)
end
return .false
-- Test if on the ending boundary of a character class. To qualify,
-- the current position must be the end of the range or,
-- NOT be a class character and the previous character must
-- be a class character.
::class EndClassBoundaryNode subclass ClassBoundaryNode
::method match
use arg context, position, target
-- At the very beginning? by definition this
-- cannot be a ending word boundary.
if context~atStart(position) then do
return .false
end
-- if the previous character is not a class character, this fails too
if \self~checkBoundary(context, position - 1, target) then do
return .false
end
-- if the position is the end, this passes
if context~checkEnd(position) then do
return self~matchNext(context, position, target)
end
-- the current character MUST NOT be a word character to pass
if \self~checkBoundary(context, position, target) then do
return self~matchNext(context, position, target)
end
return .false
-- retrieves the last match information. Since a match context
-- only implements a single match, this is the same as the starting
-- position of the context.
::class LastMatchNode subclass MatchNode
::method match
use arg context, position, target
if position \= context~regionStart then do
return .false
end
return self~matchNext(context, position, target)
-- Generic "dot". This matches everything but the end of
-- of data
::class AllDotNode subclass MatchNode
::method match
use arg context, position, target
if context~checkEnd(position) then do
return .false
end
-- always true at this node, so just return the successor result.
return self~matchNext(context, position + 1, target)
::method calculateMatchMetrics
use arg metrics
-- a dot is always a single character, so easy to manage
metrics~addLength(1)
self~calculateMatchMetrics:super(metrics)
-- like all dot node, but doesn't match lineends (CRLF sequences,
-- in this case)
::class InternetDotNode subclass AllDotNode
::method match
use arg context, position, target
if context~checkEnd(position) then do
return .false
end
-- if positioned on ANY linend char, this is a failure
if target~matchChar(position, '0d0a'x) then do
return .false
end
-- always true at this point, so just return the successor result.
return self~matchNext(context, position + 1, target)
-- like all dot node, but doesn't match lineends (Unix mode, so
-- this is just linefeeds)
::class UnixDotNode subclass AllDotNode
::method match
use arg context, position, target
if context~checkEnd(position) then do
return .false
end
-- if positioned on a linefeed char, this is a failure
if target~match(position, '0a'x) then do
return .false
end
-- always true at this point, so just return the successor result.
return self~matchNext(context, position + 1, target)
-- match a string of characters
::class StringNode subclass matchNode
::method init
expose matchString
use arg matchString
self~init:super
::attribute matchString -- useful for debugging
::method match
expose matchString
use arg context, position, target
-- must have at least the same length as the string available
if context~checkEnd(position + matchString~length - 1) then do
return .false
end
-- if no match, fail
if \target~match(position, matchString) then do
return .false
end
-- continue checking after this position
return self~matchNext(context, position + matchString~length, target)
::method calculateMatchMetrics
expose matchString
use arg metrics
-- always the length of this string
metrics~addLength(matchString~length)
self~calculateMatchMetrics:super(metrics)
-- a caseless match for a string
::class CaselessStringNode subclass StringNode
::method match
use arg context, position, target
matchString = self~matchString
-- must have at least the same length as the string available
if context~checkEnd(position + matchString~length - 1) then do
return .false
end
if \target~caselessMatch(position, matchString) then do
return .false
end
-- continue checking after this position
return self~matchNext(context, position + matchString~length, target)
-- match for a defined set of characters
::class ClassNode subclass MatchNode
::method init
expose characters
use arg characters
self~init:super
-- the characters we check against
::attribute characters GET
::method match
expose characters
use arg context, position, target
if context~checkEnd(position) then do
return .false
end
-- must match at least one of these
if \self~characterMatch(position, target, characters) then do
return .false
end
return self~matchNext(context, position + 1, target)
-- apply the appropriate character match operation for a given subclass
::method characterMatch
use arg position, target, characters
return target~matchChar(position, characters)
::method calculateMatchMetrics
use arg metrics
-- also just a single character match
metrics~addLength(1)
self~calculateMatchMetrics:super(metrics)
-- an inversion of the class node
::class NotClassNode subclass ClassNode
-- apply the appropriate character match operation for a given subclass
::method characterMatch
use arg position, target, characters
-- this must NOT match any of the charactets
return \target~matchChar(position, characters)
-- caseless match for a defined set of characters
::class CaselessClassNode subclass ClassNode
-- apply the appropriate character match operation for a given subclass
::method characterMatch
use arg position, target, characters
-- this must match any of the charactets
return target~caselessMatchChar(position, characters)
-- caseless match for a defined set of characters
::class CaselessNotClassNode subclass ClassNode
-- apply the appropriate character match operation for a given subclass
::method characterMatch
use arg position, target, characters
-- this must NOT match any of the charactets
return \target~caselessMatchChar(position, characters)
-- the intersection of multiple class node definitions
::class ClassIntersectionNode subclass MatchNode
::method init
expose subExpressions
use arg subExpressions
self~init:super
::method match
expose subExpressions
use arg context, position, target
do test over subExpressions
if \test~match(context, position, target) then do
return .false
end
end
return self~matchNext(context, position + 1, target)
::method calculateMatchMetrics
use arg metrics
-- also just a single character match
metrics~addLength(1)
self~calculateMatchMetrics:super(metrics)
-- match on a series of OR expressions
::class AlternativeNode subclass MatchNode
::method init
expose alternatives
-- these are accumulated during parsing
alternatives = .array~new
self~init:super
::method match
expose alternatives
use arg context, position, target
-- return on the first match
do alternative over alternatives
-- we try each alternative, then the subsequent
-- nodes. We only return true IFF we get a match
-- in both places. This really is a branch point, not
-- a "select the one that matches" situation
if alternative~match(context, position, target) then do
-- once we get a match, send this along to the next
if self~matchNext(context, context~matchEnd, target) then do
return .true
end
end
end
return .false
-- calculate match metrics for an alternative node
::method calculateMatchMetrics
expose alternatives
use arg metrics
-- create a metrics item for the merge
accumulator = .MatchMetrics~new
-- set a large minimum for the start
accumulator~minLength = 999999999
-- we need to analyze all of the alternative paths.
do alternative over alternatives
-- get our repetition node values as if it was the only thing of interest
submetrics = self~calculateChildMatchMetrics(alternative)
-- merge these into our accumulator
accumulator~mergeMetrics(submetrics)
end
-- add these into full set
metrics~addMetrics(accumulator)
-- send this along
self~calculateMatchMetrics:super(metrics)
-- add an expression to our list of alternatives
::method addAlternative
expose alternatives
use arg newChoice
newChoice~terminate -- make sure this has a terminator
alternatives~append(newChoice)
-- check for a lineend in non-unix mode. This matches on a '\r\n' sequence
-- or the END of input, but only if the lineend sequence is at the very end
::class InternetLineEndNode subclass MatchNode
::method match
use arg context, position, target
if context~checkEnd(position) then do
-- we still need to forward this along, even if we've hit the
-- end position to ensure the terminators get poked.
return self~matchNext(context, position, target)
end
endPosition = context~endPosition - 2
-- Current position too early to be a terminal linend?
-- this is definitely not a match
if position < endPosition then do
return .false
end
-- must be a \r\n sequence here, or this is not a match
if \target~match(position, '0d0a'x) then do
return .false
end
-- we still need to forward this along, even if we've hit the
-- end position to ensure the terminators get poked. NOTE: We do
-- NOT step over the linend here. The following characters still
-- exist, but are not skipped over
return self~matchNext(context, position, target)
-- check for a lineend in non-unix mode. This matches on a '\n' character
-- or the END of input, but only if the lineend character is at the very end
::class UnixLineEndNode subclass MatchNode
::method match
use arg context, position, target
if context~checkEnd(position) then do
-- we still need to forward this along, even if we've hit the
-- end position to ensure the terminators get poked.
return self~matchNext(context, position, target)
end
endPosition = context~endPosition - 1
-- Current position too early to be a terminal linend?
-- this is definitely not a match
if position < endPosition then do
return .false
end
-- must be a \n character here, or this is not a match
if \target~match(position, '0a'x) then do
return .false
end
-- we still need to forward this along, even if we've hit the
-- end position to ensure the terminators get poked. NOTE: We do
-- NOT step over the linend here. The following characters still
-- exist, but are not skipped over
return self~matchNext(context, position, target)
-- check for a lineend in non-unix, multiline mode. This matches on a '\r\n' sequence
-- OR the end of the input
::class InternetMultiLineEndNode subclass MatchNode
::method match
use arg context, position, target
-- end match, this is true
if context~checkEnd(position) then do
-- we still need to forward this along, even if we've hit the
-- end position to ensure the terminators get poked.
return self~matchNext(context, position, target)
end
endPosition = context~endPosition - 2
-- not enough room for a linend?
if position > endPosition then do
return .false
end
-- if the current position does not match a linend sequence, this fails
if \target~match(position, '0d0a'x) then do
return .false
end
-- we still need to forward this along, even if we've hit the
-- end position to ensure the terminators get poked. NOTE: We do
-- NOT step over the linend here. The following characters still
-- exist, but are not skipped over
return self~matchNext(context, position, target)
-- check for a lineend in unix mode. This matches on a '\n' sequence
-- but NOT the end of the input
::class UnixMultiLineEndNode subclass MatchNode
::method match
use arg context, position, target
-- end match, this is true
if context~checkEnd(position) then do
-- we still need to forward this along, even if we've hit the
-- end position to ensure the terminators get poked.
return self~matchNext(context, position, target)
end
endPosition = context~endPosition - 1
-- if the current position does not match a linend sequence, this fails
if \target~match(position, '0a'x) then do
return .false
end
-- we still need to forward this along, even if we've hit the
-- end position to ensure the terminators get poked. NOTE: We do
-- NOT step over the linend here. The following characters still
-- exist, but are not skipped over
return self~matchNext(context, position, target)
-- check for being at the end of the text string. Does not recognize linend sequences.
::class TextEndNode subclass MatchNode
::method match
use arg context, position, target
if context~checkEnd(position) then do
return self~matchNext(context, position, target)
end
return .false
-- Base class for the different Question nodes. The init and
-- calculateMatchMetrics are the same, but the matching logic is different
::class QuestionNode subclass MatchNode
::method init
expose optional
use arg optional
self~init:super
optional~terminate -- these needs termination
::attribute optional GET
::method calculateMatchMetrics
expose optional
use arg metrics
-- our following match pattern is optional, so we ignore any
-- additions it makes to the metrics before sending it down the chain.
minLength = metrics~minLength
optional~calculateMatchMetrics(metrics)
metrics~minLength = minLength
-- this is no longer deterministic because it depends on context
metrics~deterministic = .false
self~calculateMatchMetrics:super(metrics)
-- a question node that implements greedy matching semantics. It will
-- match itself first, and back off if it does not find a match.
::class GreedyQuestionNode subclass QuestionNode
::method match
use arg context, position, target
-- if we match the optional part, and if we match the following part,
-- this is gold.
if self~optional~match(context, position, target) then do
if self~matchNext(context, context~matchEnd, target) then do
return .true
end
end
-- try again, but without the optional section.
return self~matchNext(context, position, target)
-- reluctant question node. If the following part matches,
-- it will not perform it's own match.
::class ReluctantQuestionNode subclass QuestionNode
::method match
use arg context, position, target
-- first try for a match on the trailing part. If that matches, we ignore
-- the optional section
if self~matchNext(context, position, target) then do
return .true
end
-- try again, but without the optional section.
if \self~optional~match(context, position, target) then do
return .false
end
return self~matchNext(context, context~matchPosition, target)
-- possessive question node. If it has a match itself, it will
-- not back up...EVER!
::class PossessiveQuestionNode subclass QuestionNode
::method match
use arg context, position, target
-- try for the optional match...no backtracking if it is a match.
if self~optional~match(context, position, target) then do
position = context~matchEnd
end
return self~matchNext(context, position, target)
-- a mixin used for the different varieties of group nodes to implement
-- common methods
::class GroupNodeMixin mixinclass MatchNode
::method init
expose id
use arg id
-- get the group reference for a question node. This will also
-- set this as the current group in the group context
::method getGroupReference
expose id
use arg context
-- if this is a capturing group, return the
-- saved item. Otherwise, return a dummy to handle
-- the save/restore logic
if id \= .nil then do
group = context~getGroupReference(id)
end
else do
group = .GroupReference~new
end
-- make this the current group
context~enterGroup(group)
return group
-- invoke the next handler in the chain. This is an
-- override that will pop the group context before
-- making a call out to a successor node.
::method matchNext
use arg context, position, target
context~exitGroup -- we're done
return self~matchNext:super(context, position, target)
-- invoke the next handler in the chain. This will pop and
-- push the group context around the call out
::method wrappedMatchNext
use arg context, position, target
info = context~exitGroup -- we're leaving this context
ret = self~matchNext:super(context, position, target)
context~enterGroup(info) -- reset this as the current group
return ret
-- Base class for the different Group Question nodes. The init and
-- calculateMatchMetrics are the same, but the matching logic is different
::class GroupQuestionNode subclass QuestionNode inherit GroupNodeMixin
::method init
expose id
use arg id, optional
self~init:super(optional)
self~init:.GroupNodeMixin(id) -- the mixing manages the id portion
::method calculateMatchMetrics
use arg metrics
-- our following match pattern is optional, so we ignore any
-- additions it makes to the metrics before sending it down the chain.
minLength = metrics~minLength
self~optional~calculateMatchMetrics(metrics)
metrics~minLength = minLength
-- also no longer deterministic
metrics~deterministic = .false
self~calculateMatchMetrics:super(metrics)
-- A node that handles the Greedy ? qualifier following a
-- group. This implements the ? matching symantics and
-- updates the group position accordingly
::class GreedyGroupQuestionNode subclass GroupQuestionNode
::method match
use arg context, position, target
info = self~getGroupReference(context)
-- if we match the optional part, and if we match the following part,
-- this is gold.
if self~optional~match(context, position, target) then do
-- update the group capture information
info~setMatch(target, position, context~matchEnd)
if self~wrappedMatchNext(context, context~matchEnd, target) then do
context~exitGroup -- we're done
return .true
end
end
else do
info~participated = .false -- We match if not there, but do not "participate"
end
-- we always match, even if it is nothing
info~setMatch(target, position, position)
-- try again, but without the optional section.
return self~matchNext(context, position, target)
-- A node that handles the Reluctant ? qualifier following a
-- group. This implements the ? matching symantics and
-- updates the group position accordingly
::class ReluctantGroupQuestionNode subclass QuestionNode
::method match
use arg context, position, target
info = self~getGroupReference(context)
-- we always match, even if it is nothing
info~setMatch(target, position, position)
-- first try for a match on the trailing part. If that matches, we ignore
-- the optional section
if self~wrappedMatchNext(context, position, target) then do
info~participated = .false -- We match if skipped, but do not "participate"
context~exitGroup -- we're done
return .true
end
-- try again, but with our optional section.
if \self~optional~match(context, position, target) then do
info~participated = .false -- We match if skipped, but do not "participate"
context~exitGroup -- we're done
return .false
end
-- update the group capture information
info~setMatch(target, position, context~matchEnd)
-- now try the final part
return self~matchNext(context, context~matchPosition, target)
-- A node that handles the Possessive ? qualifier following a
-- group. This implements the ? matching symantics and
-- updates the group position accordingly
::class PossessiveGroupQuestionNode subclass GroupQuestionNode
::method match
use arg context, position, target
info = self~getGroupReference(context)
-- we always match, even if it is nothing
info~setMatch(target, position, position)
-- try for the optional match...no backtracking if it is a match.
if self~optional~match(context, position, target) then do
-- update the group capture information
info~setMatch(target, position, context~matchEnd)
position = context~matchEnd
end
else do
info~participated = .false -- We match if skipped, but do not "participate"
end
return self~matchNext(context, position, target)
-- match a repetition of nodes
::class RepetitionNode subclass MatchNode
::method init
expose repNode min max
use arg repNode, min, max
self~init:super
repNode~terminate -- we need to ensure the chain ends in a terminator
-- common initial piece for all repetition nodes. The greedy/possessive/reluctant
-- parts are implemented in the recursiveMatch method that each subclass
-- implements
::method match
use arg context, position, target
current = position
repNode = self~repNode
-- if we have a minimum specified, we must get at least that, else we fail
do i = 1 to self~min
if \repNode~match(context, current, target) then do
return .false
end
current = context~matchEnd
end
return self~recursiveMatch(context, current, target, repNode, self~min, self~max)
::attribute repNode GET
::attribute min GET
::attribute max GET
::method calculateMatchMetrics
expose repNode min max
use arg metrics
-- get our repetition node values as if it was the only thing of interest
submetrics = self~calculateChildMatchMetrics(repNode)
metrics~addMin(min * submetrics~minLength)
metrics~addMax(max * submetrics~maxLength)
-- if the max and min are the same, then this is potentially deterministic
if max == min then do
metrics~deterministic = metrics~deterministic & submetrics~deterministic
end
else do
-- no go on the length predictions
metrics~deterministic = .false
end
-- send this along
self~calculateMatchMetrics:super(metrics)
-- a Greedy repetition of a pattern. This will match as
-- much as possible, but will back off in an attempt to match
-- any of the following pieces
::class GreedyRepetitionNode subclass RepetitionNode
-- implement greedy repetition matching logic
::method recursiveMatch
use arg context, position, target, repNode, matches, max
-- we hit the max count, now try to match the trailing bit
if matches >= max then do
return self~matchNext(context, position, target)
end
-- preserve matches, since that determines how much we can
-- back up
counter = matches
-- loop until we don't get a match on our search node
loop while repNode~match(context, position, target)
matchLength = context~matchEnd - position
-- if this is a zero length match, there's no point
-- in continuing
if matchLength == 0 then do
leave
end
-- count this occurrence and move up
counter += 1
position = context~matchEnd
-- now we need to consume as many as possible, up to
-- the maximum
loop while counter < max
-- test again
if \repNode~match(context, position, target) then do
-- we've eaten our fill, now see what happens
-- after this
leave
end
-- we matched, but if this match was a different
-- length from our working length, we need to recurse
-- to handle backing up
if position + matchLength \= context~matchEnd then do
if self~recursiveMatch(context, context~matchEnd, counter + 1, max) then do
return .true
end
-- go handle backing up from here. The backup position is
-- actually the previous match
leave
end
position = context~matchEnd
counter += 1
end
-- we can back up for the number of matches we've had
-- at this recursion level
loop while counter >= matches
-- if we hit a spot where our successor can match, we're
-- done
if self~matchNext(context, position, target) then do
return .true
end
-- step back the fixed length and decrement our counter
position -= matchLength
counter -= 1
end
return .false -- backed off as far as we can, but can't fit in the rest
end
-- we've matched as much as we can, now check the rest
return self~matchNext(context, position, target)
-- a node that implements reluctant repetition matches
::class ReluctantRepetitionNode subclass RepetitionNode
-- the initial part to match the minimum is performed
-- in the base class. The reluctant part of the algorithm is
-- done here
::method recursiveMatch
use arg context, position, target, repNode, matches, max
loop forever
-- check the successor without consuming any more of the
-- string. If it matches, we're done
if self~matchNext(context, position, target) then do
return .true
end
-- if we've hit the limit and there's no successor match,
-- this fails
if matches >= max then do
return .false
end
-- (reluctanly), we try to eat one leetle mint...
if \repNode~match(context, position, target) then do
-- we've eaten our fill, this is a failure
return .false
end
-- if we hit a zero-length match, there's no moving forward
-- from here. This is also a failure
if position == context~matchEnd then do
return .false
end
-- step forward, and try again
position = context~matchEnd
matches += 1
end
-- possessive repetition nodes...this sucks up all it can and will
-- never give anything back
::class PossessiveRepetitionNode subclass RepetitionNode
-- the initial part to match the minimum is performed
-- in the base class. The reluctant part of the algorithm is
-- done here
::method recursiveMatch
use arg context, position, target, repNode, matches, max
do i = self~min + 1 to self~max
-- match failure means we've got all we can get
if \repNode~match(context, position, target) then do
leave
end
-- a zero-length match also terminates matching
if position == context~matchEnd then do
leave
end
-- step over this
position = context~matchEnd
end
-- and try the next part
return self~matchNext(context, position, target)
-- Special logic for handling group repetitions
::class GroupRepetitionNode subclass MatchNode inherit GroupNodeMixin
::method init
expose repNode min max
use arg id, repNode, min, max
self~init:super
self~init:.GroupNodeMixin(id)
repNode~terminate -- we need to ensure the chain ends in a terminator
-- common initial piece for all repetition nodes. The greedy/possessive/reluctant
-- parts are implemented in the recursiveMatch method that each subclass
-- implements
::method match
expose id
use arg context, position, target
repNode = self~repNode
info = self~getGroupReference(context)
-- save the original state in case we need to back up
saved = info~saveMatch
-- if we have a minimum specified, we must get at least that, else we fail
do i = 1 to self~min
if \repNode~match(context, position, target) then do
-- restore the group state, we failed
info~restoreMatch(saved)
info~participated = .false -- We don't participate here either
context~exitGroup -- pop the group context
return .false
end
-- update the capture info to the current bit
info~setMatch(target, position, context~matchEnd)
position = context~matchEnd
end
-- The subclasses handle the match rules after the minimum
return self~recursiveMatch(context, info, position, target, repNode, self~min, self~max)
::attribute repNode GET
::attribute min GET
::attribute max GET
::method calculateMatchMetrics
expose repNode min max
use arg metrics
-- get our repetition node values as if it was the only thing of interest
submetrics = self~calculateChildMatchMetrics(repNode)
metrics~addMin(min * submetrics~minLength)
metrics~addMax(max * submetrics~maxLength)
-- if the max and min are the same, then this is potentially deterministic
-- if the children are deterministic.
if max == min then do
metrics~deterministic = metrics~deterministic & submetrics~deterministic
end
else do
-- no go on the length predictions
metrics~deterministic = .false
end
-- send this along
self~calculateMatchMetrics:super(metrics)
-- a Greedy repetition of a pattern. This will match as
-- much as possible, but will back off in an attempt to match
-- any of the following pieces
::class GreedyGroupRepetitionNode subclass GroupRepetitionNode
-- implement greedy repetition matching logic
::method recursiveMatch
use arg context, info, position, target, repNode, matches, max
-- save the original state in case we need to back up
saved = info~saveMatch
-- preserve matches, since that determines how much we can
-- back up
counter = matches
do label match
-- if reached the limit already, then quit
if counter >= max then do
leave match
end
-- if the first match fails, then quit immediately too
if \repNode~match(context, position, target) then do
leave match
end
matchLength = context~matchEnd - position
-- There are forms of groups that back up, so the length
-- can be negative.
if matchLength <= 0 then do
-- the match positions are reversed.
info~setMatch(target, context~matchEnd, position)
-- and this is our new position point
position = context~matchEnd
leave match -- no more matching here
end
loop forever
info~setMatch(target, position, position + matchLength)
-- step the match position to the end of the last
-- successful match
position = context~matchEnd
-- increment the counter now, and check for the max
counter += 1
if counter >= max then do
leave
end
-- no match, time to quit
if \repNode~match(context, position, target) then do
leave
end
-- if the length of the match has changed, then recurse
-- for the backups
if position + matchLength \= context~matchEnd then do
if self~recursiveMatch(context, info, context~matchEnd, counter + 1, max) then do
return .true
end
-- go handle backing up from here. The backup position is
-- actually the previous match
leave
end
end
-- we can back up for the number of matches we've had
-- at this recursion level
loop while counter >= matches
-- if we hit a spot where our successor can match, we're
-- done
if self~wrappedMatchNext(context, position, target) then do
-- if our match count was zero, then we don't participate
if counter == 0 then do
info~participated = .false
end
context~exitGroup
return .true
end
-- step back the fixed length and decrement our counter
position -= matchLength
-- update the group match
info~setMatch(target, position, position + matchLength)
counter -= 1
end
end
info~restoreMatch(saved) -- restore the match position
-- if our match count was zero, then we don't participate
if counter == 0 then do
info~participated = .false
end
-- we've matched as much as we can, now check the rest
return self~matchNext(context, position, target)
-- a node that implements reluctant repetition matches
::class ReluctantGroupRepetitionNode subclass GroupRepetitionNode
-- the initial part to match the minimum is performed
-- in the base class. The reluctant part of the algorithm is
-- done here
::method recursiveMatch
use arg context, info, position, target, repNode, matches, max
loop forever
-- check the successor without consuming any more of the
-- string. If it matches, we're done
if self~wrappedMatchNext(context, position, target) then do
-- if our match count was zero, then we don't participate
if matches == 0 then do
info~participated = .false
end
context~exitGroup
return .true
end
-- if we've hit the limit and there's no successor match,
-- this fails
if matches >= max then do
context~exitGroup
return .false
end
-- (reluctanly), we try to eat one leetle mint...
if \repNode~match(context, position, target) then do
-- we've eaten our fill, this is a failure
context~exitGroup
return .false
end
-- if we hit a zero-length match, there's no moving forward
-- from here. This is also a failure
if position == context~matchEnd then do
context~exitGroup
return .false
end
-- update the group information
info~setMatch(target, position, context~matchEnd)
-- step forward, and try again
position = context~matchEnd
matches += 1
end
-- possessive repetition nodes...this sucks up all it can and will
-- never give anything back
::class PossessiveGroupRepetitionNode subclass GroupRepetitionNode
-- the initial part to match the minimum is performed
-- in the base class. The reluctant part of the algorithm is
-- done here
::method recursiveMatch
use arg context, info, position, target, repNode, matches, max
do i = matches + 1 to self~max
-- match failure means we've got all we can get
if \repNode~match(context, position, target) then do
leave
end
-- update the group information
info~setMatch(target, position, context~matchEnd)
-- a zero-length match also terminates matching
if position == context~matchEnd then do
leave
end
-- step over this
position = context~matchEnd
end
-- if our match count was zero, then we don't participate
if i == 0 then do
info~participated = .false
end
-- and try the next part
return self~matchNext(context, position, target)
-- base class for all nodes that match back references
-- a back reference match
::class BackReferenceNode subclass MatchNode
-- main matching method for a back reference.
::method match
use arg context, position, target
-- get the match text defined for this type of back reference
-- if nothing is there, then this match fails
matchValue = self~matchText(context)
if matchValue == .nil then do
return .false
end
if context~checkEnd(position + matchValue~length - 1) then do
return .false
end
if \self~submatch(context, position, target, matchValue) then do
return .false
end
-- exhausted the max, so now search for the next
return self~matchNext(context, position + matchValue~length, target)
::method calculateMatchMetrics
use arg metrics
-- the maximum can no longer be trusted
metrics~validMaximum = .false
self~calculateMatchMetrics:super(metrics)
-- matches the current position for the same string value as
-- a back reference match
::class GroupBackReferenceNode subclass BackReferenceNode
::method init
expose ref
use arg ref
self~init:super
-- resolve the matching text for this back reference.
-- returns .nil if this cannot be located
::method matchText
expose ref
use arg context
-- retrieve the match result for our target back ref
refGroup = context~getBackReferenceResult(ref)
-- if the back reference did not match, then this is a
-- failure here too
if \refGroup~matched then do
return .nil
end
-- return the group's match text
return refGroup~matchText
-- simple method for performing the implementation specific
-- matching for a back reference. Intended to be overridden
::method submatch
use arg context, position, target, matchValue
return target~match(position, matchValue)
-- same as a back reference, but matching is done caselessly
::class CaselessGroupBackReferenceNode subclass GroupBackReferenceNode
-- simple method for performing the implementation specific
-- matching for a back reference. Intended to be overridden
::method submatch
use arg context, position, target, matchValue
return target~caselessMatch(position, matchValue)
-- a back reference node to handle more complex group/result resolution
::class ResultBackReferenceNode subclass BackReferenceNode
::method init
expose resultPath
-- the result path
use arg resultPath
self~init:super
-- run the resolution path to locate the target result or group.
-- returns .nil if there is a failure at any point in the matching
-- process
::method matchText
expose resultPath
use arg context
-- the first two matches here are a little different, since
-- there will a guarantee of 2 names and the first one comes
-- from the current matching context. After that, the
-- match results are used for retrieval
-- retrieve the match result for our target back ref
refGroup = context~getBackReferenceResult(resultPath[1])
result = refGroup~result(resultPath[2])
-- this might not be here, so return .nil for any failure
if result == .nil then do
return .nil
end
count = resultPath~items
-- resolution here is done in pairs, though there could be an odd
-- number
loop i = 3 by 2 while i < count
group = result~group(resultPath[i])
if group == .nil then do
return .nil
end
-- if this is the last item, the group value is the
-- desired text
if i == count then do
return group~text
end
-- step to the next result
result = group~result(resultPath[i + 1])
-- and fail it it is not there
if result == .nil then do
return .nil
end
end
-- we're after the result text now
return result~text
-- simple method for performing the implementation specific
-- matching for a back reference. Intended to be overridden
::method submatch
use arg context, position, target, matchValue
return target~match(position, matchValue)
-- same as a result back reference, but matching is done caselessly
::class CaselessResultBackReferenceNode subclass ResultBackReferenceNode
-- simple method for performing the implementation specific
-- matching for a back reference. Intended to be overridden
::method submatch
use arg context, position, target, matchValue
return target~caselessMatch(position, matchValue)
-- a normal group node with implicit numbering
::class GroupNode subclass MatchNode
::method init
expose id groupMatch
use arg id, groupMatch
self~init:super
::method match
expose id groupMatch
use arg context, position, target
info = context~getGroupReference(id)
-- if the pattern inside the group matches, then record
-- the match position inside group matches, record this
-- in the corresponding group information and continue
if groupMatch~match(context, position, target) then do
info~setMatch(target, position, context~matchEnd)
return self~matchNext(context, context~matchEnd, target)
end
else do
-- mark the group as non-matching
info~clearMatch
return .false
end
-- A back reference node used in conditionals to test if a
-- group node had participated in a match operation
::class BackReferenceTestNode subclass MatchNode
::method init
expose ref
use arg ref
self~init:super
-- perform the back reference test. A match here
-- is just an indicator that the group had participated
-- in a prior match. This does not forward to a successor
-- node
::method match
expose ref
use arg context, position, target
-- retrieve the match result for our target back ref
refGroup = context~getBackReferenceResult(ref)
-- and just return the matched indictor
return refGroup~participated
::method terminate
-- optimization override. This node does not require
-- a terminator, so turn this into a NOP when called
-- A back reference node used in conditionals to test if a
-- group result node had participated in a match operation
::class ResultBackReferenceTestNode subclass MatchNode
::method init
expose resultPath
-- the result path
use arg resultPath
self~init:super
-- run the resolution path to locate the target result or group.
-- returns .false if there is a failure at any point in the matching
-- process
::method match
expose resultPath
use arg context, position, target
-- the first two matches here are a little different, since
-- there will a guarantee of 2 names and the first one comes
-- from the current matching context. After that, the
-- match results are used for retrieval
-- retrieve the match result for our target back ref
refGroup = context~getBackReferenceResult(resultPath[1])
result = refGroup~result(resultPath[2])
-- this might not be here, so return .nil for any failure
if result == .nil then do
return .false
end
count = resultPath~items
-- resolution here is done in pairs, though there could be an odd
-- number
loop i = 3 by 2 while i < count
group = result~group(resultPath[i])
if group == .nil then do
return .false
end
-- if this is the last item, the group value is the
-- desired text
if i == count then do
return group~participated
end
-- step to the next result
result = group~result(resultPath[i + 1])
-- and fail it it is not there
if result == .nil then do
return .false
end
end
-- we're after the result match now
return result~matched
::method terminate
-- optimization override. This node does not require
-- a terminator, so turn this into a NOP when called
-- support for a (?(cond)then) node
::class IfThenNode subclass MatchNode
::method init
expose condition thenNode
use arg condition, thenNode
self~init:super
thenNode~terminate -- make sure the then node is terminated
condition~terminate -- and the condition also
::method match
expose condition thenNode
use arg context, position, target
-- if the condition succeeds, then attempt the then portion
if condition~match(context, position, target) then do
-- the condition is true, so attempt the conditional then part
-- using the original match position. The conditional never
-- changes the position
if \thenNode~match(context, position, target) then do
return .false
end
-- this succeed, so update the match position before
-- forwarding
position = context~matchEnd
end
-- either the condition was false or the then matched, so
-- forward along
return self~matchNext(context, position, target)
-- calculate match metrics for a conditional node
::method calculateMatchMetrics
expose thenNode
use arg metrics
-- calculate metrics for the then branch
submetrics = self~calculateChildMatchMetrics(thenNode)
-- since we don't necessary perform the then match,
-- our minimum successful match needs to be zero
submetrics~minLength = 0
-- we are not deterministic
submetrics~deterministic = .false
-- and merge into the full set
metrics~addMetrics(submetrics)
-- send this along
self~calculateMatchMetrics:super(metrics)
-- support for a (?(cond)then) node
::class IfThenElseNode subclass MatchNode
::method init
expose condition thenNode elseNode
use arg condition, thenNode, elseNode
self~init:super
thenNode~terminate -- make sure both nodes are terminated
elseNode~terminate
condition~terminate -- and the condition also
::method match
expose condition thenNode elseNode
use arg context, position, target
-- if the condition succeeds, then attempt the then portion
if condition~match(context, position, target) then do
-- the condition is true, so attempt the conditional then part
-- using the original match position. The conditional never
-- changes the position
if \thenNode~match(context, position, target) then do
return .false
end
-- this succeed, so update the match position before
-- forwarding
position = context~matchEnd
end
-- if the condition match is false, then take the else branch
else do
-- the condition is true, so attempt the conditional then part
-- using the original match position. The conditional never
-- changes the position
if \elseNode~match(context, position, target) then do
return .false
end
-- this succeed, so update the match position before
-- forwarding
position = context~matchEnd
end
-- we've had a match on either the then or else branch, so
-- forward along
return self~matchNext(context, position, target)
-- calculate match metrics for a conditional node
::method calculateMatchMetrics
expose thenNode
use arg metrics
-- calculate metrics for the then branch
submetrics = self~calculateChildMatchMetrics(thenNode)
elseMetrics = self~calculateChildMatchMetrics(elseNode)
-- get a merged set from the two branches
submetrics~mergeMetrics(elseMetrics)
submetrics~minLength = 0
-- we are not deterministic
submetrics~deterministic = .false
-- and merge into the full set
metrics~addMetrics(submetrics)
-- send this along
self~calculateMatchMetrics:super(metrics)
-- a group node with an explicit name
::class NamedGroupNode subclass MatchNode
::method init
expose id groupMatch
use arg id, groupMatch
self~init:super
::method match
expose id groupMatch
use arg context, position, target
info = context~namedGroupInfo(id)
if groupMatch~match(context, position, target) then do
info~setMatch(target, position, context~matchEnd)
return self~matchNext(context, context~matchEnd, target)
end
else do
info~clearMatch
return .false
end
-- base class for logical operations of class patterns
::class ClassLogicalNode subclass MatchNode
::method init
expose leftSide rightSide
use arg leftSide, rightSide
self~init:super
-- ensure these side branches have terminator elements
leftSide~terminate
rightSide~terminate
::method calculateMatchMetrics
expose leftSide rightSide
use arg metrics
leftMetrics = self~calculateChildMatchMetrics(leftSide)
rightMetrics = self~calculateChildMatchMetrics(rightSide)
-- merge this set of metrics into a combined result
leftMetrics~mergeMetrics(rightMetrics)
-- and add to the full metric set
metrics~addMetrics(leftMetrics)
self~calculateMatchMetrics:super(metrics)
::attribute leftSide
::attribute rightSide
-- class logical OR node
::class ClassOrNode subclass ClassLogicalNode
::method match
use arg context, position, target
if \context~checkEnd(position) then do
if self~leftSide~match(context, position, target) then do
return self~matchNext(context, context~matchEnd, target)
end
else if self~rightSide~match(context, position, target) then do
return self~matchNext(context, context~matchEnd, target)
end
end
return .false
-- class logical AND
::class ClassAndNode subclass ClassLogicalNode
::method match
use arg context, position, target
if \context~checkEnd(position) then do
if self~leftSide~match(context, position, target) then
if self~rightSide~match(context, position, target) then do
return self~matchNext(context, context~matchEnd, target)
end
end
return .false
-- base wrapper class for group operations. This holds all of
-- the pieces involved with a group and manages the wrappering
-- and management of the group
::class GroupEnvelope subclass MatchNode
::method init
expose terminator
-- The terminator handles end of group processing.
terminator = .GroupTerminator~new(self)
self~init:super
::method match
use arg context, position, target
-- our successor is our real node, but if it
-- matches, it will go through the GroupTerminator
-- node which will poke us to update the group state
-- however, since this is a non-capturing group, we don't
-- actually update anything
return self~matchNext(context, position, target)
::method terminator
expose terminator
return terminator
-- method for the group terminator to make a callback to indicate
-- a successful match. This is ignored for non-capturing nodes
::method setGroupEnd
-- nop in the base class
-- The terminator updates the match information before
-- calling its successor node in case there are back references.
-- If the successor does not match, it might need to rollback
-- the match information to a previous value. This will update the
-- information, but also return the previous information for saving
::method updateAndSaveMatch
-- nop in the base class, but we need a return value
return .true
-- this is the reverse of the previous. Restores the
-- start and end information using a previous saved state
::method restorePreviousMatch
-- nop in the base class
-- base class for capturing group interactions
::class CapturingGroupEnvelope subclass GroupEnvelope
::method init
expose id
-- capturing groups all have an id. This is either an
-- already allocated numeric or a string name
use arg id
self~init:super
::method match
use arg context, position, target
-- our successor is our real node, but if it
-- matches, it will go through the GroupTerminator
-- node which will poke us to update the group state
--save the current postion so we can retrieve it when
-- poked by the terminator
context~setLocal(self, position)
-- perform the match
ret = self~matchNext(context, position, target)
-- delete the local reference
context~removeLocal(self)
return ret
-- return the group reference information for a capturing group
::method getGroupReference
expose id
use arg context
return context~getGroupReference(id)
-- method for the group terminator to make a callback to indicate
-- a successful match. This uses the saved local information for
-- the position
::method setGroupEnd
use arg context, target, end
-- get the group information
info = getGroupReference(context)
-- and update with the current match information
info~setMatch(target, context~getLocal(self), end)
-- The terminator updates the match information before
-- calling its successor node in case there are back references.
-- If the successor does not match, it might need to rollback
-- the match information to a previous value. This will update the
-- information, but also return the previous information for saving
::method updateAndSaveMatch
use arg context, target, end
-- get the group information
info = self~getGroupReference(context)
save = .directory~new
save~start = info~start
save~end = info~end
-- and update with the current match information
info~setMatch(target, context~getLocal(self), end)
return save
-- this is the reverse of the previous. Restores the
-- start and end information using a previous saved state
::method restorePreviousMatch
use arg context, save
-- get the group information
info = self~getGroupReference(context)
info~start = save~start
info~end = save~end
-- special terminator for the end of a grouping
::class GroupTerminator subclass TerminatorNode
::method init
expose group
use arg group
self~init:super
::method match
expose group
use arg context, position, target
-- this will update the group information and return the
-- old information to us in case we need to revert
save = group~updateAndSaveMatch(context, target, position)
if self~matchNext(context, position, target) then do
-- good match, everything is ok
return .true
end
-- roll the info change back to the prior value
-- we did not get a complete and proper match
return .false
-- wrapper around a group to give atomic nature.
::class AtomicGroupNode subclass MatchNode
::method init
expose group
use arg group
self~init:super
-- The first match that comes out of the group will forward to
-- the terminator, which will tell it everything is good. At
-- that point, we unconditionally send this down the chain
group~terminate
::method match
expose group
use arg context, position, target
-- do the group match and accounting, then forward along.
if group~match(context, position, target) then do
return self~matchNext(context, context~matchEnd, target)
end
return .false
-- wrapper around a group to perform a positive lookahead.
-- Positive lookahead means this is true if the group
-- matches at the current position.
-- This only checks for a match, but does not consume
-- any text. If this matches, the same position
-- information is passed along to the successor node
::class PositiveLookaheadNode subclass MatchNode
::method init
expose group
use arg group
self~init:super
::method match
expose group
use arg context, position, target
-- do the group match and accounting, then forward along.
-- NOTE: both of these match the same position
if group~match(context, position, target) then do
return self~matchNext(context, position, target)
end
return .false
-- wrapper around a group to perform a negative lookahead.
-- Negative lookahead means this is true if the group
-- does NOT match at the current position.
-- This only checks for a match, but does not consume
-- any text. If this matches, the same position
-- information is passed along to the successor node
::class NegativeLookaheadNode subclass MatchNode
::method init
expose group
use arg group
self~init:super
::method match
expose group
use arg context, position, target
-- do the group match and accounting, then forward along.
-- NOTE: both of these match the same position
if \group~match(context, position, target) then do
return self~matchNext(context, position, target)
end
return .false
-- wrapper around a group to perform a positive lookbehind.
-- Positive lookbehind means this is true if the group
-- matches at prior position.
-- This only checks for a match, but does not consume
-- any text. If this matches, the same position
-- information is passed along to the successor node
::class PositiveLookBehindNode subclass MatchNode
::method init
expose group min max
use arg group, metrics
self~init:super
min = metrics~minLength
-- if there is a deterministic maximum, then
-- use it to optimize the search. Otherwise, set the
-- max to zero, which will force things to check everywhere.
if metrics~validMaximum then do
max = metrics~maxLength
end
else do
max = 0
end
::attribute group
::method match
expose group min max
use arg context, position, target
-- this is how much we back up for the first test
backPosition = position - min
-- if not enough room to test this, we fail
if \context~checkStart(backPosition) then do
return .false
end
-- no set maximum?
if max == 0 | max > position - context~startPosition then do
-- test all possible positions
startRange = context~startPosition
end
else do
-- we can cap this using the maximum
startRange = position - max
end
-- create a subcontext that restricts the possible match range
subContext = context~createSubContext(startRange, position)
-- mark this as requiring a complete match from the position to
-- the end. This will ensure this really is butted up against
-- the prior position
subContext~matchEndRequired = .true
return self~backMatch(context, position, target, subContext, backPosition)
-- backward matching method designed to be overridden by a subclass.
-- this version performs the positive match
::method backMatch
use arg context, position, target, subContext, backPosition
-- we need to test the shortest matches first
do i = backPosition by -1 while subContext~checkStart(i)
-- if we have a back match, then time to forward to the next bit
if self~group~match(subContext, i, target) then do
-- got a match, forward on using the original context
return self~matchNext(context, position, target)
end
end
-- no match
return .false
-- wrapper around a group to perform a negative lookbehind.
-- Negative lookbehind means this is true if the group
-- does NOT match at prior position.
-- This only checks for a match, but does not consume
-- any text. If this matches, the same position
-- information is passed along to the successor node
::class NegativeLookBehindNode subclass PositiveLookBehindNode
-- backward matching method designed to be overridden by a subclass.
-- this version performs the positive match
::method backMatch
use arg context, position, target, subContext, backPosition
-- we need to test the shortest matches first
do i = backPosition by -1 while subContext~checkStart(i)
-- if we have a back match, then this is a failure
if self~group~match(subContext, i, target) then do
return .false
end
end
-- no match, then this passes
return self~matchNext(context, position, target)
-- A matcher for beginning of text that works in
-- multiline mode. To match, this either must be
-- the beginning of the line or the first character after
-- a \r\n sequence
::class InternetMultilineCaretNode subclass MatchNode
::method match
use arg context, position, target
-- the end is always game over, even if preceeded by a newline
if context~checkEnd(position) then do
return .false
end
-- if at the real beginning, this is good
if context~atStart(position) then do
return self~matchNext(context, position, target)
end
-- Not enough space to test for a linend? This also fails ,
-- we need to see if we're positioned at a lineend
if \context~checkStart(position - 2) then do
return .false
end
-- must have a CRLF sequence before this to match
if \target~match(position - 2, '0d0a'x) then do
return .false
end
-- and go finish up
return self~matchNext(context, position, target)
-- A matcher for beginning of text that works in
-- multiline mode. To match, this either must be
-- the beginning of the line or the first character after
-- a \n sequence
::class UnixMultilineCaretNode subclass MatchNode
::method match
use arg context, position, target
-- the end is always game over, even if preceeded by a newline
if context~checkEnd(position) then do
return .false
end
-- if at the real beginning, this is good
if context~atStart(position) then do
return self~matchNext(context, position, target)
end
-- must have a CRLF sequence before this to match
if \target~match(position - 1, '0a'x) then do
return .false
end
-- and go finish up
return self~matchNext(context, position, target)
-- A terminal node for a full match chain. This does any
-- end-of-match processing.
::class TerminatorNode subclass MatchNode
::method match
use arg context, position, target
-- set the end match position
context~matchEnd = position
-- if we require a match with the end, then only return true
-- if our position is at the end
if context~matchEndRequired then do
return position == context~endPosition
end
-- this is always a successful match. This really just
-- records the last position of this branch segment.
return .true
-- add a .TerminatorNode terminator to a node that will
-- be used as part of a composite. This not process
-- the call, since a terminator node cannot have a
-- next element
::method terminate
-- Search nodes are not normally part of the pattern tree. These
-- are only instantiated when a find() operation is being done with
-- a pattern
::class SearchNode subclass MatchNode
::method init
expose minLength
use arg pattern
self~init:super
self~next = pattern -- this is our search pattern
-- to optimize, we scan the tree to figure out what the minium match
-- length will be. This will prevent making unnecessary probes on the
-- target once matches are no longer possible.
metrics = self~calculateChildMatchMetrics(pattern)
minLength = metrics~minLength
::method match
expose minLength
use arg context, position, target
-- NB, + 1 is needed because the start position is not
-- zero based. We might have exactly enough for a single test
probes = (context~endPosition - position) - minLength + 1
if probes <= 0 then do
return .false
end
do i = position for probes
if self~matchNext(context, i, target) then do
-- update the match information
context~setMatchPosition(i, context~matchEnd);
return .true
end
end
-- no matches possible
return .false
::method calculateMatchMetrics
use arg metrics
-- get the successor metrics, but we need to tweak them
self~calculateMatchMetrics:super(metrics)
-- because we slide, these are never valid
metrics~deterministic = .false
metrics~validMaximum = .false
-- A node that holds and executes an indirect match to another
-- pattern
::class PatternNode subclass MatchNode
::method init
expose name pattern
use arg name, pattern
::method match
expose name pattern
use arg context, position, target
-- create a new context to execute this
subcontext = context~createNestedPatternContext(pattern)
-- attempt a match from the current position
matchResult = subcontext~match(pattern, position)
-- record the result of this with the current group
context~addResult(name, matchResult)
-- if this matched, then foward along
if matchResult~matched then do
return self~matchNext(context, matchResult~end, target)
end
-- if it did not match, this is a failure
return .false
::method calculateMatchMetrics
expose pattern
use arg metrics
-- add in the metrics from the pattern
metrics~addMetrics(pattern~matchMetrics)
-- get the successor metrics, but we need to tweak them
self~calculateMatchMetrics:super(metrics)
-- base class for a match result from a group match. This is
-- similar to the MatchResult class, but lacks the ability to request
-- embedded group values
::class BaseMatchResult
::method init
expose regionStart regionEnd start end regionText
use strict arg regionText, regionStart, regionEnd, start, end
-- belt and braces...if the start is 0, make sure the end is zero also
if start == 0 then do
end = 0
end
-- return a response if the operation matched.
::method matched
expose start
return start > 0
-- individual match results
::attribute start GET
::attribute end GET
-- information about the string region we're matching on
::attribute regionText GET PRIVATE -- only available internally
::attribute regionStart GET
::attribute regionEnd GET
::attribute regionLength GET
expose regionStart regionEnd
return regionEnd - regionStart + 1 -- end position is Rexx-like last character
-- retrieve the length of the match string
::attribute length GET
expose end start
return end - start -- end position is one past the last match character
-- retrieves the match text
::attribute text GET
expose regionText start
-- return the match text
if start == 0 then do
return ''
end
-- extract the text subpiece
return regionText~substr(start, self~length)
-- retrieve the prefix string before the match, up to the start
-- of the match region
::attribute prefix GET
expose regionText start regionStart
-- no match is always a null string
if start == 0 then do
return ""
end
return regionText~substr(regionStart, start - regionStart)
-- retrieve any text following the match position, up to the end
-- of the match region
::attribute suffix GET
expose regionText start end regionStart regionEnd
-- no match is always the entire region string
if start == 0 then do
return regionText~substr(regionStart, regionEnd - regionStart)
end
return regionText~substr(end, regionEnd - end)
-- return the position of character after the match position. If
-- past the end of the match region, returns regionEnd + 1
::method nextMatch
expose end
-- NOTE: This is the correct result even if the match string
-- is zero-length
return end + 1
-- the class for a group result. This adds in the retrieval
-- of embedded match results from named pattern references
::class GroupMatchResult subclass BaseMatchResult
::method init
expose results
use strict arg regionText, regionStart, regionEnd, group
self~init:super(regionText, regionStart, regionEnd, group~start, group~end)
results = group~namedResults
-- retrieve a named result piece. This is the name used
-- in the \m{name} element used to invoke the piece
::method result
expose results
use strict arg id
-- make sure this is uppercase
id = id~upper
return results[id]
-- Information about an individual match. The match
-- may have embedded groups. The match information for
-- the embedded groups can also be retrieved
::class MatchResult subclass BaseMatchResult
::method init
expose groups
use strict arg regionText, regionStart, regionEnd, start, end, groups
self~init:super(regionText, regionStart, regionEnd, start, end)
-- retrieve a group. This is either a numeric id
-- or a symbolic name
::method group
expose groups
use strict arg id
-- make sure this is uppercase
id = id~upper
group = groups[id]
-- give a reasonable default rather than raising an error
if .nil == group then do
return .nil
end
-- this gets wrappered into a result item
return .GroupMatchResult~new(self~regionText, self~regionStart, self~regionEnd, group)
-- used for creating a MatchReplacementResult
::attribute groups GET PRIVATE
-- retrieve the text for a given group item in a match result
::method "[]"
expose groups
-- default is to retrieve the entire group match
use strict arg id = "0"
-- make sure this is uppercase
id = id~upper
group = groups[id]
-- unknown group, return the .nil default
if group == .nil then do
return .nil
end
-- return the match text (which will be null if not matched)
text = group~matchText
if text == .nil then do
return ""
end
return text
-- a combined match result that includes replacement string information
::class MatchReplacementResult public subclass MatchResult
::method init
expose resultText replacementLength replacementCount
use arg match, resultText, replacementLength, replacementCount
self~init:super(match~regionText, match~regionStart, match~regionEnd, match~start, match~end, match~groups)
-- the length of the replacement string
::attribute replacementLength GET
::attribute resultText GET
-- the current active context for a match operation. This
-- provides information to the matching filters and holds any
-- intermediate state required by the filters. This also
-- implements the matching operations.
::class MatchContext
::method init
expose text startPosition endPosition matchPosition matchEnd
use strict arg text, startPosition = 1, length = (text~length)
-- make sure the length is bounded. The end position is one
-- past the end
endPosition = min(text~length + 1, startPosition + length)
matchPosition = 0
matchEnd = 0
-- prepare for a match using a given pattern instance
::method prepareMatch private
expose root groups locals groupStack rootGroup
use arg pattern
-- get the pattern root and a copy of the groups information
root = pattern~root
groups = pattern~groups~copy
-- do a deep copy of the groups directory
-- to create a working groups list
do name over groups
groups[name] = groups[name]~copy
end
locals = .table~new -- this allows patterns to save/retrieve local state
groupStack = .queue~new -- create a stack for pushing and popping group usage
-- push the main group at the head of the stack (if it exists)
rootGroup = groups[0]
groupStack~push(rootGroup)
-- create a subcontext of the current context with a different start
-- and stop range. Used by lookbehind matchers to restrict the
-- search range of the filters
::method createSubContext
use arg start, end
-- just clone the context and update the bounds
copy = self~copy
copy~setRange(start, end)
return copy
-- create a new context for invoking a nested pattern
::method createNestedPatternContext
expose text startPosition endPosition
use arg pattern
-- create a context as if this was toplevel
return self~class~new(text, startPosition, endPosition - startPosition)
-- Retrieve the group reference item for a given group
::method getGroupReference
expose groups
use arg id
-- return the information inherited from the pattern
return groups[id]
-- record the entering of a group
::method enterGroup
expose groupStack
use arg group
groupStack~push(group)
-- perform exit clean up for group completion
::method exitGroup
expose groupStack
return groupStack~pull -- just pop this group instance off of the stack
-- add a named result object to the currently active group
::method addResult
expose groupStack
use arg name, result
group = groupStack~peek
group~addResult(name, result)
-- save a local value
::method setLocal
expose locals
use arg index, value
locals[index] = value
-- retrieve a local value
::method getLocal
expose locals
use arg index
return locals[index]
-- remove a given local value
::method removeLocal
expose locals
use arg index
locals~remove(index)
-- test if the pattern is an exact match for the entire region, from
-- beginning to end
::method matches
expose text startPosition matchPosition matchEndRequired root
use strict arg pattern
-- set up the context for matching
self~prepareMatch(pattern)
matchEndRequired = .true -- this must match exactly
-- this is the default result, and possibly checked by filters
-- that need to examine the starting match position
matchPosition = startPosition
if root~match(self, startPosition, text) then do
return .true -- good match, give the indicator
end
else do
matchPosition = 0 -- this needs to be cleared
return .false -- no match
end
-- test if the pattern is an exact match from the start of the match
-- region up to the end of the pattern. This does not need to match
-- to the end of the region
::method startsWith
expose text startPosition matchPosition matchEndRequired root
use strict arg pattern, start = (startPosition)
-- set up the context for matching
self~prepareMatch(pattern)
matchEndRequired = .false -- This does not need to match exactly
-- adjust the starting position to the bounds
start = max(startPosition, start)
-- this is the default result, and possibly checked by filters
-- that need to examine the starting match position
matchPosition = start
if root~match(self, startPosition, text) then do
return .true -- good match, give the indicator
end
else do
matchPosition = 0 -- this needs to be cleared
return .false -- no match
end
-- search the region for the first position with a pattern match. Returns
-- a match result object with the match result
::method find
expose startPosition root
-- the start is optional, but defalt to the beginning of the
-- region (typical)
use strict arg pattern, start = (startPosition)
-- set up the context for matching
self~prepareMatch(pattern)
-- forward to the common matching routine
-- this node implements a sliding search search of the pattern.
-- Not really part of the pattern tree, but it wrappers it
return self~performMatch(start, .SearchNode~new(root))
-- match the given (or starting position) for a match. Returns
-- a match result object with the match result
::method match
expose startPosition root
-- the start is optional, but defalt to the beginning of the
-- region (typical)
use strict arg pattern, start = (startPosition)
-- set up the context for matching
self~prepareMatch(pattern)
-- forward to the common matching routine
return self~performMatch(start, root)
-- match the given (or starting position) for a match. Returns
-- a match result object with the match result
::method performMatch private
expose text startPosition endPosition matchPosition matchEndRequired root
-- the start is optional, but defalt to the beginning of the
-- region (typical)
use strict arg start, pattern
-- adjust the starting position to the bounds
start = max(startPosition, start)
-- set the initial match position
matchPosition = start
if start > endPosition then do
matchPosition = 0
return self~matchResult -- give a match result object with the info
end
matchEndRequired = .false -- This does not need to match exactly
if \pattern~match(self, start, text) then do
matchPosition = 0 -- this needs to be cleared
end
return self~result -- give a match result object with the info
-- return a result object from the match result
::method result
expose text startPosition endPosition matchPosition matchEnd groups rootGroup
rootGroup~setMatch(text, matchPosition, matchEnd)
return .MatchResult~new(text, startPosition, endPosition, matchPosition, matchEnd, groups)
-- check if we're at the start position
::method atStart
expose startPosition
use arg test
return test == startPosition
-- test is a position is equal to or greater than the
-- start position. Used for checks where the matcher needs
-- to make tests prior to the current position
::method checkStart
expose startPosition
use arg test
return test >= startPosition
-- tests for whether a position is past the end of the range
::method checkEnd
expose endPosition
use arg test
if test >= endPosition then do
-- remember that we've hit the end of the pattern
return .true
end
return .false
-- the range positions
::attribute startPosition
::attribute endPosition
-- any set match positions
::attribute matchPosition
::attribute matchEnd
-- change the bounds of the search to a restricted range.
::method setRange private
expose startPosition endPosition
use arg startPosition, endPosition
-- indicates whether the pattern must exactly match the end
-- of the string (e.g., we're doing a match vs. a locate)
::attribute matchEndRequired
::method setMatchPosition
expose matchPosition matchEnd
use arg matchPosition, matchEnd
::method getBackReferenceResult
expose groups
use arg id
if groups == .nil then do
raise syntax 93.900 array("Back reference to unknown group" id);
end
groupRef = groups[id]
if groupRef == .nil then do
raise syntax 93.900 array("Back reference to unknown group" id);
end
return groupRef
-- return the offset of the given position. This will be
-- the number of characters from the start of the match
-- range to the given position.
::method matchOffset
expose startPosition
use arg position
return position - startPosition
-- the class for managing group information during a pattern match
::class GroupReference
::method init
expose id start end text participated namedResults
use arg id
start = 0
end = 0
text = .nil
namedResults = .nil -- This is only used when an embedded pattern is used
participated = .true -- participation is different from "matching"
-- the start and end match positions
::attribute start
::attribute end
-- indicates whether a group participated in a match
::attribute participated
-- the list of results from named patterns used inside this
-- group. Returns .nil if none were used (common)
::attribute namedResults
-- add a named result to this group
::method addResult
expose namedResults
use arg name, result
-- we create this lazily, since it's more common
-- that a group not have any of these
if namedResults == .nil then do
namedResults = .directory~new
end
-- add this to the directory table
namedResults[name] = result
-- retrieve a named result from the group information
::method result
expose namedResults
use arg name
if namedResults == .nil then do
return .nil
end
return namedResults[name]
-- indicates whether this match was a success or a failure
::method matched
expose start
return start > 0
-- set the match values
::method setMatch
expose text start end
use arg text, start, end
-- clear the match values
::method clearMatch
expose text start end
text = .nil
start = 0
end = 0
-- return the text that was matched. Returns .nil if
-- this match was not successful
::method matchText
expose text start end
if start > 0 then do
return text~substr(start, end - start)
end
return .nil
-- get a copy of the match positions
::method saveMatch
expose start end
r = .directory~new
r~start = start
r~end = end
return r
-- restore the match location from a saved copy
::method restoreMatch
expose start end
use arg r
start = r['START']
end = r~end
-- a general purpose parsing context that includes support for
-- regular expressions
::class parser public
::method init
expose string matchstart matchend sectionstart sectionend compiler matchResult
use strict arg string, compiler = (.RegexCompiler~new)
matchstart = 1; -- There is an implicit absolute trigger of 1 at the start
matchend = 1; -- All numeric movement triggers have a zero-length size
sectionstart = 1; -- The section also starts here
sectionend = string~length -- and is the length of the string
matchResult = .nil -- no match result at the start
-- return the current match position for the parsing context
::attribute matchStart GET
-- The end position of the match position. Note that this
-- will be located at matchStart + matchLength. The sectionStart
-- and matchEnd will be the same normally.
::attribute matchEnd GET
-- The length of the pattern match
::attribute matchLength GET
expose matchStart matchEnd
return matchEnd - matchStart
-- the text for the last section. All numeric triggers
-- have zero length. You can think of them as matching
-- in the space between matchStart and the previous character.
::attribute matchText GET
expose string matchStart matchEnd
return string~substr(matchStart, matchEnd - matchStart)
-- this is the current section of the parsed text that is
-- between the current match position and the previous match
-- end. For example, if you were working with the parse template
-- parse value '1234567890' with '3' x '9'
-- sectionstart would be 4, sectionend would be 8 after the
-- trigger '9' was applied
::attribute sectionStart GET
-- end of the equivalent section (see above). Note that this will
-- also be sectionStart + sectionLength. If the section is a null string,
-- then start and end will be the same
::attribute sectionEnd GET
-- length of the current section
::attribute sectionLength GET
expose sectionStart sectionEnd
return sectionEnd - sectionStart
-- the section text
::method section
expose string sectionstart sectionEnd
return string~substr(sectionstart, sectionEnd - sectionStart)
-- return the current section parsed into blank delimited words
::method sectionwords
section = self~section
count = section~words
wordlist = .array~new(count)
do i = 1 to count
wordlist[i] = section~word(i)
end
return wordlist
-- return the remainder of the string after the last
-- match position. Note that if backward movement is
-- used, the remainder will overlap with the last parsed
-- section
::method remainder
expose string matchend
return string~substr(matchend)
-- locate a needle in the current string, returning an
-- indicator of whether the string was located.
-- details of the match can be retrieved from the context.
::method find
expose string matchstart matchend sectionstart sectionEnd matchResult
use strict arg needle
temp = string~pos(needle, matchend)
-- NOTE: this differs from the PARSE instruction. If the
-- string is not found, the match positions will be unchanged.
-- This allows one to attempt a match, detect if it failed, and
-- maybe try other alternatives without needing to save and
-- restore the match position
if temp == 0 then do
return .false
end
else do
matchResult = .nil -- clear the old match result
matchStart = temp
sectionstart = matchend
matchend = matchstart + needle~length
sectionEnd = matchstart
return .true
end
-- locate a needle in the current string, returning an
-- indicator of whether the string was located.
-- details of the match can be retrieved from the context.
::method caselessFind
expose string matchstart matchend sectionstart sectionEnd matchEnd matchResult
use strict arg needle
temp = string~caselessPos(needle, matchend)
-- NOTE: this differs from the PARSE instruction. If the
-- string is not found, the match positions will be unchanged.
-- This allows one to attempt a match, detect if it failed, and
-- maybe try other alternatives without needing to save and
-- restore the match position
if temp == 0 then do
return .false
end
else do
matchResult = .nil -- clear the old match result
matchStart = temp
sectionstart = matchend
matchend = matchstart + needle~length
sectionEnd = matchstart
return .true
end
-- locate a needle in the current string, returning an
-- indicator of whether the string was located.
-- details of the match can be retrieved from the context.
-- the needle may be a string, which will be converted into
-- a regex pattern using the current compiler or a directly
-- provided pattern
::method findRegex
expose string matchstart matchend sectionstart sectionEnd compiler matchResult
use strict arg needle
-- the regular expression can be specified as a string or a
-- pattern instance. If this is a string, then compile it before
-- using
if needle~isa(.string) then do
needle = compiler~compile(needle)
end
-- now do a regex search on the string
result = needle~find(string, matchend, string~length)
-- NOTE: this differs from the PARSE instruction. If the
-- string is not found, the match positions will be unchanged.
-- This allows one to attempt a match, detect if it failed, and
-- maybe try other alternatives without needing to save and
-- restore the match position
if \result~matched then do
return .false
end
else do
matchResult = result -- save the result for retrieval, if needed
matchStart = result~start
sectionstart = matchend
matchend = matchstart + result~length
sectionEnd = matchstart
return .true
end
-- return a .MatchResult object that represents the last match
-- operation. This will either be a MatchResult returned from a
-- regex find operation or one constructed from the current parser
-- state that represents the prior operations
::attribute matchResult GET
expose methodResult string matchStart matchEnd
-- if the matchResult is not set, then construct one
if methodResult == .nil then do
methodResult = .MatchResult~new(string, 1, string~length, matchStart, matchEnd, .false, .nil)
end
return methodResult
-- relative postional movement of the pointer
::method move
expose string matchstart matchend sectionstart sectionlength
use strict arg delta
-- the section begins at the start of the movement
sectionstart = matchstart
matchstart = matchstart + delta
self~validateposition
-- absolute positional movement
::method moveTo
expose string matchstart matchend sectionstart sectionlength
sectionStart = matchStart
use arg matchStart
self~validateposition
-- Validate and adjust the positional values after a non-search
-- parse movement
::method validateposition private
expose string matchstart matchend sectionstart sectionlength matchResult
matchResult = .nil -- clear the old match result
-- keep the start within the bounds of the string
if matchstart < 1 then do
matchstart = 1
end
else if matchstart > string~length then do
matchstart = string~length + 1
end
-- if this moved backwards from the previous, then the
-- section goes to the end of the string
if matchstart <= sectionstart then do
sectionEnd = string~length + 1
end
else do
-- for forward movement, the sectionEnd is the same
-- as the matchStart position
sectionEnd = matchstart
end
-- for postional movement, the match string is always
-- zero-length, so these will be the same
matchend = matchstart
-- simple class used to accumulate matching metrics
::class MatchMetrics
::method init
expose minLength maxLength validMaximum deterministic
minLength = 0
maxLength = 0
validMaximum = .true -- indicates the max accumulator is good
deterministic = .true -- indicates whether calculations are even possible
::attribute minLength
::attribute maxLength
::attribute validMaximum
::attribute deterministic
-- bump both the min and max by the same value
::method addLength
expose minLength maxLength
use arg length
minLength += length
maxLength += length
::method addMin
expose minLength
use arg length
minLength += length
::method addMax
expose maxLength
use arg length
maxLength += length
-- add a node's metric set to our accumulated set
::method addMetrics
expose deterministic validMaximum
use arg other
-- add in the minumum and maximum
self~addMin(other~minLength)
self~addMax(other~maxLength)
-- or in the various flags
deterministic = deterministic & other~deterministic
validMaximum = validMaximum & other~validMaximum
-- like addMetrics, but this version will just calculate
-- the various max and min values between two sets of
-- metrics
::method mergeMetrics
expose minLength maxLength deterministic validMaximum
use arg other
-- calculate the new minimum and maximum
minLength = min(minLength, other~minLength)
maxLength = max(maxLength, other~maxLength)
-- or in the various flags
deterministic = deterministic & other~deterministic
validMaximum = validMaximum & other~validMaximum
-- base class for a string replacement node
::class ReplacementNode
-- abstract method that all replacement nodes need to override
::method getText Abstract
-- A node that returns the current
::class StringReplacementNode
::method init
expose text
use arg text
::method getText
expose text
return text
-- A node that returns the value of a match group.
-- if the match group does not exist
::class GroupReplacementNode
::method init
expose id
use arg id
::method getText
expose id
use arg result
group = result~group(id)
-- if this is there, return the text
if group \= .nil then do
return group~text
end
-- return a null string
return ""
-- A node that returns the entire match string
::class MatchReplacementNode
::method getText
use arg result
return result~text
-- A node that returns the prefix of the match string
::class PrefixReplacementNode
::method getText
use arg result
return result~prefix
-- A node that returns the suffix of the match string
::class SuffixReplacementNode
::method getText
use arg result
return result~suffix
-- A node that returns the value of an embedded match
-- pattern. Return null if the result does not exist
::class ResultReplacementNode
::method init
expose id
use arg id
::method getText
expose id
use arg result
subresult = result~result(id)
-- if this is there, return the text
if subresult \= .nil then do
return subresult~text
end
-- return a null string
return ""
-- A special type of pattern used for performing string replacements
::class ReplacementPattern public
::method compile class
-- the compiler is configurable, but there is a default
use strict arg pattern, compiler = (.RegexCompiler~new)
return compiler~compileReplacement(pattern)
::method init
expose pattern sections
use strict arg pattern, sections
::attribute pattern GET
::attribute stages GET
::method string
expose pattern
return pattern
-- perform a replacement operation within a mutable buffer instance
::method replace
expose sections
use arg buffer, matchResult
-- nothing to replace if there is no match
if \matchResult~matched then do
return 0
end
-- delete the information
buffer~delete(matchResult~start, matchResult~length)
position = matchResult~start -- replacement starts at the match begining
-- insert the text from each of the pieces into the buffer starting
-- at the match position
do section over sections
next = section~getText(matchResult)
buffer~insert(next, position)
position += next~length
end
-- return the length of the changed string
return position - matchResult~start