This file is indexed.

/usr/share/perl5/Regexp/Grammars.pm is in libregexp-grammars-perl 1.045-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
=encoding ISO8859-1
=cut

package Regexp::Grammars;
use re 'eval';

use warnings;
use strict;
use 5.010;
use vars ();

use Scalar::Util qw< blessed reftype >;
use Data::Dumper qw< Dumper  >;

our $VERSION = '1.045';

my $anon_scalar_ref = \do{my $var};
my $MAGIC_VARS = q{my ($CAPTURE, $CONTEXT, $DEBUG, $INDEX, $MATCH, %ARG, %MATCH);};

my $PROBLEM_WITH_5_18 = <<'END_ERROR_MSG';
Warning: Regexp::Grammars is unsupported
         under Perl 5.18.0 through 5.18.3 due to a bug
         in regex parsing under those versions.

         Please upgrade to Perl 5.18.4 or later, or revert to
         Perl 5.16 or earlier.
END_ERROR_MSG

# Load the module...
sub import {
    # Signal lexical scoping (active, unless something was exported)...
    $^H{'Regexp::Grammars::active'} = 1;

    # Process any regexes in module's active lexical scope...
    use overload;
    overload::constant(
        qr => sub {
            my ($raw, $cooked, $type) = @_;

            # In active scope and really a regex...
            if (_module_is_active() && $type =~ /qq?/) {
                return bless \$cooked, 'Regexp::Grammars::Precursor';
            }
            # Ignore everything else...
            else {
                return $cooked;
            }
        }
    );

    # Deal with 5.18 issues...
    if ($] >= 5.018) {
        # Issue warning...
        if ($] < 5.018004) {
            require Carp;
            Carp::croak($PROBLEM_WITH_5_18);
        }

        # Deal with cases where Perl 5.18+ complains about
        # the injection of (??{...}) and (?{...})
        require re;
        re->import('eval');

        # Sanctify the standard Regexp::Grammars pseudo-variables from
        # Perl 5.18's early enforcement of strictures...
        my $caller = caller;
        warnings->unimport('once');
        @_ = ( 'vars', '$CAPTURE', '$CONTEXT', '$DEBUG', '$INDEX', '$MATCH', '%ARG', '%MATCH' );
        goto &vars::import;
    }
}

# Deactivate module's regex effect when it is "anti-imported" with 'no'...
sub unimport {
    # Signal lexical (non-)scoping...
    $^H{'Regexp::Grammars::active'} = 0;
    require re;
    re->unimport('eval');
}

# Encapsulate the hoopy user-defined pragma interface...
sub _module_is_active {
    return (caller 1)[10]->{'Regexp::Grammars::active'};
}

my $RULE_HANDLER;
sub clear_rule_handler { undef $RULE_HANDLER; }

{
    package Regexp;

    sub with_actions {
        my ($self, $handler) = @_;
        $RULE_HANDLER = $handler;
        return $self;
    }
}

#=====[ COMPILE-TIME INTERIM REPRESENTATION OF GRAMMARS ]===================
{
    package Regexp::Grammars::Precursor;

    # Only translate precursors once...
    state %grammar_cache;

    use overload (
        # Concatenation/interpolation just concatenates to the precursor...
        q{.} => sub {
            my ($x, $y, $reversed) = @_;
            if (ref $x) { $x = ${$x} }
            if (ref $y) { $y = ${$y} }
            if ($reversed) { ($y,$x) = ($x,$y); }
            $x .= $y//q{};
            return bless \$x, 'Regexp::Grammars::Precursor';
        },

        # Using as a string (i.e. matching) preprocesses the precursor...
        q{""} => sub {
            my ($obj) = @_;
            return $grammar_cache{ overload::StrVal($$obj) }
                //= Regexp::Grammars::_build_grammar( ${$obj} );
        },

        # Everything else, as usual...
        fallback => 1,
    );
}


#=====[ SUPPORT FOR THE INTEGRATED DEBUGGER ]=========================

# All messages go to STDERR by default...
*Regexp::Grammars::LOGFILE = *STDERR{IO};

# Debugging levels indicate where to stop...
our %DEBUG_LEVEL = (
    same => undef,                           # No change in debugging mode
    off  => 0,                               # No more debugging
    run  => 1,   continue  => 1,             # Run to completion of regex match
                 match     => 2,   on => 2,  # Run to next successful submatch
    step => 3,   try       => 3,             # Run to next reportable event
);

# Debugging levels can be abbreviated to one character during interactions...
@DEBUG_LEVEL{ map {substr($_,0,1)} keys %DEBUG_LEVEL } = values %DEBUG_LEVEL;
$DEBUG_LEVEL{o} = $DEBUG_LEVEL{off};      # Not "on"
$DEBUG_LEVEL{s} = $DEBUG_LEVEL{step};     # Not "same"

# Width of leading context field in debugging messages is constrained...
my $MAX_CONTEXT_WIDTH = 20;
my $MIN_CONTEXT_WIDTH = 6;

sub set_context_width {
    { package Regexp::Grammars::ContextRestorer;
      sub new {
        my ($class, $old_context_width) = @_;
        bless \$old_context_width, $class;
      }
      sub DESTROY {
        my ($old_context_width_ref) = @_;
        $MAX_CONTEXT_WIDTH = ${$old_context_width_ref};
      }
    }

    my ($new_context_width) = @_;
    my $old_context_width = $MAX_CONTEXT_WIDTH;
    $MAX_CONTEXT_WIDTH = $new_context_width;
    if (defined wantarray) {
        return Regexp::Grammars::ContextRestorer->new($old_context_width);
    }
}

# Rewrite a string currently being matched, to make \n and \t visible
sub _show_metas {
    my $context_str = shift // q{};

    # Quote newlines (\n -> \\n, without using a regex)...
    my $index = index($context_str,"\n");
    while ($index >= 0) {
        substr($context_str, $index, 1, '\\n');
        $index = index($context_str,"\n",$index+2);
    }

    # Quote tabs (\t -> \\t, without using a regex)...
    $index = index($context_str,"\t");
    while ($index >= 0) {
        substr($context_str, $index, 1, '\\t');
        $index = index($context_str,"\t",$index+2);
    }

    return $context_str;
}

# Minimize whitespace in a string...
sub _squeeze_ws {
    my ($str) = @_;

    $str =~ tr/\n\t/ /;

    my $index = index($str,q{  });
    while ($index >= 0) {
        substr($str, $index, 2, q{ });
        $index = index($str,q{  },$index);
    }

    return $str;
}

# Prepare for debugging...
sub _init_try_stack {
    our (@try_stack, $last_try_pos, $last_context_str);

    # Start with a representation of the entire grammar match...
    @try_stack = ({
        subrule => '<grammar>',
        height  => 0,
        errmsg  => ' \\FAIL <grammar>',
    });

    # Initialize tracking of location and context...
    $last_try_pos     = -1;
    $last_context_str = q{};

    # Report...
    say {*Regexp::Grammars::LOGFILE} _debug_context('=>')
                . 'Trying <grammar> from position ' . pos();
}

# Create a "context string" showing where the regex is currently matching...
sub _debug_context {
    my ($fill_chars) = @_;

    # Determine minimal sufficient width for context field...
    my $field_width = length(_show_metas($_//q{}));
    if ($field_width > $MAX_CONTEXT_WIDTH) {
        $field_width = $MAX_CONTEXT_WIDTH;
    }
    elsif ($field_width < $MIN_CONTEXT_WIDTH) {
        $field_width = $MIN_CONTEXT_WIDTH;
    }

    # Get current matching position (and some additional trailing context)...
    my $context_str
        = substr(_show_metas(substr(($_//q{}).q{},pos()//0,$field_width)),0,$field_width);

    # Build the context string, handling special cases...
    our $last_context_str;
    if ($fill_chars) {
        # If caller supplied a 1- or 2-char fill sequence, use that instead...
        my $last_fill_char = length($fill_chars) > 1
                                ? substr($fill_chars,-1,1,q{})
                                : $fill_chars
                                ;
        $context_str = $fill_chars x ($field_width-1) . $last_fill_char;
    }
    else {
        # Make end-of-string visible in empty context string...
        if ($context_str eq q{}) {
            $context_str = '[eos]';
        }

        # Don't repeat consecutive identical context strings...
        if ($context_str eq $last_context_str) {
            $context_str = q{ } x $field_width;
        }
        else {
            # If not repeating, remember for next time...
            $last_context_str = $context_str;
        }
    }

    # Left justify and return context string...
    return sprintf("%-*s ",$field_width,$context_str);
}

# Show a debugging message (mainly used for compile-time errors and info)...
sub _debug_notify {
    # Single arg is a line to be printed with a null severity...
    my ($severity, @lines) = @_==1 ? (q{},@_) : @_;
    chomp @lines;

    # Formatting string for all lines...
    my $format = qq{%*s | %s\n};

    # Track previous severity and avoid repeating the same level...
    state $prev_severity = q{};
    if ($severity !~ /\S/) {
        # Do nothing
    }
    elsif ($severity eq 'info' && $prev_severity eq 'info' ) {
        $severity = q{};
    }
    else {
        $prev_severity = $severity;
    }

    # Display first line with severity indicator (unless same as previous)...
    printf {*Regexp::Grammars::LOGFILE} $format, $MIN_CONTEXT_WIDTH, $severity, shift @lines;

    # Display first line without severity indicator
    for my $next_line (@lines) {
        printf {*Regexp::Grammars::LOGFILE} $format, $MIN_CONTEXT_WIDTH, q{}, $next_line;
    }
}

# Handle user interactions during runtime debugging...
sub _debug_interact {
    my ($stack_height, $leader, $curr_frame_ref, $min_debug_level) = @_;

    our $DEBUG; # ...stores current debug level within regex

    # Only interact with terminals, and if debug level is appropriate...
    if (-t *Regexp::Grammars::LOGFILE
    &&  defined $DEBUG
    &&  ($DEBUG_LEVEL{$DEBUG}//0) >= $DEBUG_LEVEL{$min_debug_level}
    ) {
        local $/ = "\n";  # ...in case some caller is being clever
        INPUT:
        while (1) {
            my $cmd = readline // q{};
            chomp $cmd;

            # Input of 'd' means 'display current result frame'...
            if ($cmd eq 'd') {
                print {*Regexp::Grammars::LOGFILE} join "\n",
                    map { $leader . ($stack_height?'|   ':q{})
                        . '       : ' . $_
                        }
                        split "\n", q{ }x8 . substr(Dumper($curr_frame_ref),8);
                print "\t";
            }
            # Any other (valid) input changes debugging level and continues...
            else {
                if (defined $DEBUG_LEVEL{$cmd}) { $DEBUG = $cmd; }
                last INPUT;
            }
        }
    }
    # When interaction not indicated, just complete the debugging line...
    else {
        print {*Regexp::Grammars::LOGFILE} "\n";
    }
}

# Handle reporting of unsuccessful match attempts...
sub _debug_handle_failures {
    my ($stack_height, $subrule, $in_match) = @_;
    our @try_stack;

    # Unsuccessful match attempts leave "leftovers" on the attempt stack...
    CLEANUP:
    while (@try_stack && $try_stack[-1]{height} >= $stack_height) {
        # Grab record of (potentially) unsuccessful attempt...
        my $error_ref = pop @try_stack;

        # If attempt was the one whose match is being reported, go and report...
        last CLEANUP if $in_match
                     && $error_ref->{height} == $stack_height
                     && $error_ref->{subrule} eq $subrule;

        # Otherwise, report the match failure...
        say {*Regexp::Grammars::LOGFILE} _debug_context(q{ }) . $error_ref->{errmsg};
    }
}

# Handle attempts to call non-existent subrules...
sub _debug_fatal {
    my ($naughty_construct) = @_;

    print {*Regexp::Grammars::LOGFILE}
        "_________________________________________________________________\n",
        "Fatal error: Entire parse terminated prematurely while attempting\n",
        "             to call non-existent rule: $naughty_construct\n",
        "_________________________________________________________________\n";
    $@ = "Entire parse terminated prematurely while attempting to call non-existent rule: $naughty_construct";
}

# Handle objrules that don't return hashes...
sub _debug_non_hash {
    my ($obj, $name) = @_;

    # If the object is okay, no further action required...
    return q{} if reftype($obj) eq 'HASH';

    # Generate error messages...
    print {*Regexp::Grammars::LOGFILE}
    "_________________________________________________________________\n",
    "Fatal error: <objrule: $name> returned a non-hash-based object\n",
    "_________________________________________________________________\n";
    $@ = "<objrule: $name> returned a non-hash-based object";

    return '(*COMMIT)(*FAIL)';
}


# Print a <log:...> message in context...
sub _debug_logmsg {
    my ($stack_height, @msg) = @_;

    # Determine indent for messages...
    my $leader = _debug_context() . q{|   } x ($stack_height-1) . '|';

    # Report the attempt...
    print {*Regexp::Grammars::LOGFILE} map { "$leader$_\n" } @msg;
}

# Print a message indicating a (sub)match attempt...
sub _debug_trying {
    my ($stack_height, $curr_frame_ref, $subrule) = @_;

    # Clean up after any preceding unsuccessful attempts...
    _debug_handle_failures($stack_height, $subrule);

    # Determine indent for messages...
    my $leader = _debug_context() . q{|   } x ($stack_height-2);

    # Detect and report any backtracking prior to this attempt...
    our $last_try_pos //= 0;  #...Stores the pos() of the most recent match attempt?
    my $backtrack_distance = $last_try_pos - pos();
    if ($backtrack_distance > 0) {
        say {*Regexp::Grammars::LOGFILE} ' <' . q{~} x (length(_debug_context(q{ }))-3) . q{ }
                    . q{|   } x ($stack_height-2)
                    . qq{|...Backtracking $backtrack_distance char}
                    . ($backtrack_distance > 1 ? q{s} : q{})
                    . q{ and trying new match}
                    ;
    }

    # Report the attempt...
    print {*Regexp::Grammars::LOGFILE} $leader, "|...Trying $subrule\t";

    # Handle user interactions during debugging...
    _debug_interact($stack_height, $leader, $curr_frame_ref, 'step');

    # Record the attempt, for later error handling in _debug_matched()...
    if ($subrule ne 'next alternative') {
        our @try_stack;
        push @try_stack, {
            height  => $stack_height,
            subrule => $subrule,
            # errmsg should align under:              |...Trying $subrule\t
            errmsg  => q{|   } x ($stack_height-2) . "|    \\FAIL $subrule",
        };
    }
    $last_try_pos = pos();
}

# Print a message indicating a successful (sub)match...
sub _debug_matched {
    my ($stack_height, $curr_frame_ref, $subrule, $matched_text) = @_;

    # Clean up any intervening unsuccessful attempts...
    _debug_handle_failures($stack_height, $subrule, 'in match');

    # Build debugging message...
    my $debug_context = _debug_context();
    my $leader  = $debug_context . q{|   } x ($stack_height-2);
    my $message = ($stack_height ? '|   ' : q{})
                . " \\_____$subrule matched ";
    my $filler  = $stack_height
                    ? '|   ' . q{ } x (length($message)-4)
                    :          q{ } x  length($message);

    our $last_try_pos //= 0;  #...Stores the pos() of the most recent match attempt?

    # Report if match required backtracking...
    my $backtrack_distance = $last_try_pos - (pos()//0);
    if ($backtrack_distance > 0) {
        say {*Regexp::Grammars::LOGFILE} ' <' . q{~} x (length(_debug_context(q{ }))-3) . q{ }
                    . q{|   } x ($stack_height-2)
                    . qq{|...Backtracking $backtrack_distance char}
                    . ($backtrack_distance > 1 ? q{s} : q{})
                    . qq{ and rematching $subrule}
                    ;
    }
    $last_try_pos = pos();

    # Format match text (splitting multi-line texts and indent them correctly)...
    $matched_text =  defined($matched_text)
        ? $matched_text = q{'} . join("\n$leader$filler", split "\n", $matched_text) . q{'}
        : q{};

    # Print match message...
    print {*Regexp::Grammars::LOGFILE} $leader . $message . $matched_text . qq{\t};

    # Check for user interaction...
    _debug_interact($stack_height, $leader, $curr_frame_ref, $stack_height ?  'match' : 'run');
}

# Print a message indicating a successful (sub)match...
sub _debug_require {
    my ($stack_height, $condition, $succeeded) = @_;

    # Build debugging message...
    my $debug_context = _debug_context();
    my $leader  = $debug_context . q{|   } x ($stack_height-1);
    my $message1 = ($stack_height ? '|...' : q{})
                 . "Testing condition: $condition"
                 ;
    my $message2 = ($stack_height ? '|   ' : q{})
                 . " \\_____"
                 . ($succeeded ? 'Satisified' : 'FAILED')
                 ;

    # Report if match required backtracking...
    our $last_try_pos;
    my $backtrack_distance = $last_try_pos - pos();
    if ($backtrack_distance > 0) {
        say {*Regexp::Grammars::LOGFILE} ' <' . q{~} x (length(_debug_context(q{ }))-3) . q{ }
                    . q{|   } x ($stack_height-1)
                    . qq{|...Backtracking $backtrack_distance char}
                    . ($backtrack_distance > 1 ? q{s} : q{})
                    . qq{ and rematching}
                    ;
    }

    # Remember where the condition was tried...
    $last_try_pos = pos();

    # Print match message...
    say {*Regexp::Grammars::LOGFILE} $leader . $message1;
    say {*Regexp::Grammars::LOGFILE} $leader . $message2;
}

# Print a message indicating a successful store-result-of-code-block...
sub _debug_executed {
    my ($stack_height, $curr_frame_ref, $subrule, $value) = @_;

    # Build message...
    my $leader   = _debug_context() . q{|   } x ($stack_height-2);
    my $message  = "|...Action $subrule\n";
    my $message2 = "|   saved value: '";
    $message    .= $leader . $message2;
    my $filler   = q{ } x length($message2);

    # Split multiline results over multiple lines (properly indented)...
    $value = join "\n$leader$filler", split "\n", $value;

    # Report the action...
    print {*Regexp::Grammars::LOGFILE} $leader . $message . $value . qq{'\t};

    # Check for user interaction...
    _debug_interact($stack_height, $leader, $curr_frame_ref, 'match');
}

# Create the code to be inserted into the regex to facilitate debugging...
sub _build_debugging_statements {
    my ($debugging_active, $subrule, $extra_pre_indent) = @_;

    return (q{}, q{}) if ! $debugging_active;;

    $extra_pre_indent //= 0;

    $subrule = "q{$subrule}";

    return (
      qq{ Regexp::Grammars::_debug_trying(\@Regexp::Grammars::RESULT_STACK+$extra_pre_indent, \$Regexp::Grammars::RESULT_STACK[-2+$extra_pre_indent], $subrule)
            if \$Regexp::Grammars::DEBUG_LEVEL{\$Regexp::Grammars::DEBUG};
        },
      qq{ Regexp::Grammars::_debug_matched(\@Regexp::Grammars::RESULT_STACK+1, \$Regexp::Grammars::RESULT_STACK[-1], $subrule, \$^N)
            if \$Regexp::Grammars::DEBUG_LEVEL{\$Regexp::Grammars::DEBUG};
        },
    );
}

sub _build_raw_debugging_statements {
    my ($debugging_active, $subpattern, $extra_pre_indent) = @_;

    return (q{}, q{}) if ! $debugging_active;

    $extra_pre_indent //= 0;

    if ($subpattern eq '|') {
        return (
        q{},
        qq{
            (?{;Regexp::Grammars::_debug_trying(\@Regexp::Grammars::RESULT_STACK+$extra_pre_indent,
              \$Regexp::Grammars::RESULT_STACK[-2+$extra_pre_indent], 'next alternative')
                if \$Regexp::Grammars::DEBUG_LEVEL{\$Regexp::Grammars::DEBUG};})
            },
        );
    }
    else {
        return (
        qq{
            (?{;Regexp::Grammars::_debug_trying(\@Regexp::Grammars::RESULT_STACK+$extra_pre_indent,
              \$Regexp::Grammars::RESULT_STACK[-2+$extra_pre_indent], q{subpattern /$subpattern/}, \$^N)
                if \$Regexp::Grammars::DEBUG_LEVEL{\$Regexp::Grammars::DEBUG};})
            },
        qq{
            (?{;Regexp::Grammars::_debug_matched(\@Regexp::Grammars::RESULT_STACK+1,
              \$Regexp::Grammars::RESULT_STACK[-1], q{subpattern /$subpattern/}, \$^N)
                if \$Regexp::Grammars::DEBUG_LEVEL{\$Regexp::Grammars::DEBUG};})
            },
        );
    }
}


#=====[ SUPPORT FOR AUTOMATIC TIMEOUTS ]=========================

sub _test_timeout {
    our ($DEBUG, $TIMEOUT);

    return q{} if time() < $TIMEOUT->{'limit'};

    my $duration = "$TIMEOUT->{duration} second"
                 . ( $TIMEOUT->{duration} == 1 ? q{} : q{s} );

    if (defined($DEBUG) && $DEBUG ne 'off') {
        my $leader   = _debug_context(q{ });
        say {*LOGFILE} $leader . '|';
        say {*LOGFILE} $leader . "|...Invoking <timeout: $TIMEOUT->{duration}>";
        say {*LOGFILE} $leader . "|   \\_____No match after $duration";
        say {*LOGFILE} $leader . '|';
        say {*LOGFILE} $leader . " \\FAIL <grammar>";
    }

    if (! @!) {
        @! = "Internal error: Timed out after $duration (as requested)";
    }
    return q{(*COMMIT)(*FAIL)};
}


#=====[ SUPPORT FOR UPDATING THE RESULT STACK ]=========================

# Create a clone of the current result frame with an new key/value...
sub _extend_current_result_frame_with_scalar {
    my ($stack_ref, $key, $value) = @_;

    # Autovivify null stacks (only occur when grammar invokes no subrules)...
    if (!@{$stack_ref}) {
        $stack_ref = [{}];
    }

    # Copy existing frame, appending new value so it overwrites any old value...
    my $cloned_result_frame = {
        %{$stack_ref->[-1]},
        $key => $value,
    };

    # Make the copy into an object, if the original was one...
    if (my $class = blessed($stack_ref->[-1])) {
        bless $cloned_result_frame, $class;
    }

    return $cloned_result_frame;
}

# Create a clone of the current result frame with an additional key/value
# (As above, but preserving the "listiness" of the key being added to)...
sub _extend_current_result_frame_with_list {
    my ($stack_ref, $key, $value) = @_;

    # Copy existing frame, appending new value to appropriate element's list...
    my $cloned_result_frame = {
        %{$stack_ref->[-1]},
        $key => [
            @{$stack_ref->[-1]{$key}//[]},
            $value,
        ],
    };

    # Make the copy into an object, if the original was one...
    if (my $class = blessed($stack_ref->[-1])) {
        bless $cloned_result_frame, $class;
    }

    return $cloned_result_frame;
}

# Pop current result frame and add it to a clone of previous result frame
# (flattening it if possible, and preserving any blessing)...
sub _pop_current_result_frame {
    my ($stack_ref, $key, $original_name, $value) = @_;

    # Where are we in the stack?
    my $curr_frame   = $stack_ref->[-1];
    my $caller_frame = $stack_ref->[-2];

    # Track which frames are objects...
    my $is_blessed_curr   = blessed($curr_frame);
    my $is_blessed_caller = blessed($caller_frame);

    # Remove "private" captures (i.e. those starting with _)...
    delete @{$curr_frame}{grep {substr($_,0,1) eq '_'} keys %{$curr_frame} };

    # Remove "nocontext" marker...
    my $nocontext = delete $curr_frame->{'~'};

    # Build a clone of the current frame...
    my $cloned_result_frame
        = exists $curr_frame->{'='}                                  ? $curr_frame->{'='}
        : $is_blessed_curr || length(join(q{}, keys %{$curr_frame})) ? { q{} => $value, %{$curr_frame} }
        : keys %{$curr_frame}                                        ? $curr_frame->{q{}}
        :                                                              $value
        ;

    # Apply any appropriate handler...
    if ($RULE_HANDLER) {
        if ($RULE_HANDLER->can($original_name) || $RULE_HANDLER->can('AUTOLOAD')) {
            my $replacement_result_frame
                = $RULE_HANDLER->$original_name($cloned_result_frame);
            if (defined $replacement_result_frame) {
                $cloned_result_frame = $replacement_result_frame;
            }
        }
    }

    # Remove capture if not requested...
    if ($nocontext && ref $cloned_result_frame eq 'HASH' && keys %{$cloned_result_frame} > 1) {
        delete $cloned_result_frame->{q{}};
    }

    # Nest a clone of current frame inside a clone of the caller frame...
    my $cloned_caller_frame = {
        %{$caller_frame//{}},
        $key => $cloned_result_frame,
    };

    # Make the copies into objects, if the originals were...
    if ($is_blessed_curr && !exists $curr_frame->{'='} ) {
        bless $cloned_caller_frame->{$key}, $is_blessed_curr;
    }
    if ($is_blessed_caller) {
        bless $cloned_caller_frame, $is_blessed_caller;
    }

    return $cloned_caller_frame;
}

# Pop current result frame and add it to a clone of previous result frame
# (flattening it if possible, and preserving any blessing)
# (As above, but preserving listiness of key being added to)...
sub _pop_current_result_frame_with_list {
    my ($stack_ref, $key, $original_name, $value) = @_;

    # Where are we in the stack?
    my $curr_frame   = $stack_ref->[-1];
    my $caller_frame = $stack_ref->[-2];

    # Track which frames are objects...
    my $is_blessed_curr = blessed($curr_frame);
    my $is_blessed_caller = blessed($caller_frame);

    # Remove "private" captures (i.e. those starting with _)...
    delete @{$curr_frame}{grep {substr($_,0,1) eq '_'} keys %{$curr_frame} };

    # Remove "nocontext" marker...
    my $nocontext = delete $curr_frame->{'~'};

    # Clone the current frame...
    my $cloned_result_frame
        = exists $curr_frame->{'='}                                  ? $curr_frame->{'='}
        : $is_blessed_curr || length(join(q{}, keys %{$curr_frame})) ? { q{} => $value, %{$curr_frame} }
        : keys %{$curr_frame}                                        ? $curr_frame->{q{}}
        :                                                              $value
        ;

    # Apply any appropriate handler...
    if ($RULE_HANDLER) {
        if ($RULE_HANDLER->can($original_name) || $RULE_HANDLER->can('AUTOLOAD')) {
            my $replacement_result_frame
                = $RULE_HANDLER->$original_name($cloned_result_frame);
            if (defined $replacement_result_frame) {
                $cloned_result_frame = $replacement_result_frame;
            }
        }
    }

    # Remove capture if not requested...
    if ($nocontext && ref $cloned_result_frame eq 'HASH' && keys %{$cloned_result_frame} > 1) {
        delete $cloned_result_frame->{q{}};
    }

    # Append a clone of current frame inside a clone of the caller frame...
    my $cloned_caller_frame = {
            %{$caller_frame},
            $key => [
                @{$caller_frame->{$key}//[]},
                $cloned_result_frame,
            ],
        };

    # Make the copies into objects, if the originals were...
    if ($is_blessed_curr && !exists $curr_frame->{'='} ) {
        bless $cloned_caller_frame->{$key}[-1], $is_blessed_curr;
    }
    if ($is_blessed_caller) {
        bless $cloned_caller_frame, $is_blessed_caller;
    }

    return $cloned_caller_frame;
}


#=====[ MISCELLANEOUS CONSTANTS ]=========================

# Namespace in which grammar inheritance occurs...
my $CACHE = 'Regexp::Grammars::_CACHE_::';
my $CACHE_LEN = length $CACHE;
my %CACHE; #...for subrule tracking

# This code inserted at the start of every grammar regex
#    (initializes the result stack cleanly and backtrackably, via local)...
my $PROLOGUE = q{((?{; @! = () if !pos;
                       local @Regexp::Grammars::RESULT_STACK
                           = (@Regexp::Grammars::RESULT_STACK, {});
                       local $Regexp::Grammars::TIMEOUT = { limit => -1>>1 };
                       local $Regexp::Grammars::DEBUG = 'off' }) };

# This code inserted at the end of every grammar regex
#    (puts final result in %/. Also defines default <ws>, <hk>, etc.)...
my $EPILOGUE = q{)(?{; $Regexp::Grammars::RESULT_STACK[-1]{q{}} //= $^N;;
         local $Regexp::Grammars::match_frame = pop @Regexp::Grammars::RESULT_STACK;
         delete @{$Regexp::Grammars::match_frame}{
                    '~', grep {substr($_,0,1) eq '_'} keys %{$Regexp::Grammars::match_frame}
                };
         if (exists $Regexp::Grammars::match_frame->{'='}) {
            if (ref($Regexp::Grammars::match_frame->{'='}) eq 'HASH') {
                $Regexp::Grammars::match_frame
                    = $Regexp::Grammars::match_frame->{'='};
            }
         }
         if (@Regexp::Grammars::RESULT_STACK) {
            $Regexp::Grammars::RESULT_STACK[-1]{'(?R)'}
                = $Regexp::Grammars::match_frame;
         }
         Regexp::Grammars::clear_rule_handler();
         */ = $Regexp::Grammars::match_frame;
    })|\Z(?{Regexp::Grammars::clear_rule_handler();})(?!)(?(DEFINE)
        (?<ws__implicit__> \\s* )
        (?<ws>
                (?{$Regexp::Grammars::RESULT_STACK[-1]{'!'}=$#{!};})
                \\s*
                (?{;$#{!}=delete($Regexp::Grammars::RESULT_STACK[-1]{'!'})//0;
                           delete($Regexp::Grammars::RESULT_STACK[-1]{'@'});
                })
        )
        (?<hk__implicit__> \\S+ )
        (?<hk>
                (?{$Regexp::Grammars::RESULT_STACK[-1]{'!'}=$#{!};})
                \\S+
                (?{;$#{!}=delete($Regexp::Grammars::RESULT_STACK[-1]{'!'})//0;
                           delete($Regexp::Grammars::RESULT_STACK[-1]{'@'});
                })
        )
        (?<matchpos> (?{; $Regexp::Grammars::RESULT_STACK[-1]{"="} = pos; }) )
        (?<matchline> (?{; $Regexp::Grammars::RESULT_STACK[-1]{"="} = 1 + substr($_,0,pos) =~ tr/\n/\n/; }) )
    )
};
my $EPILOGUE_NC = $EPILOGUE;
   $EPILOGUE_NC =~ s{ ; .* ;;}{;}xms;


#=====[ MISCELLANEOUS PATTERNS THAT MATCH USEFUL THINGS ]========

# Match an identifier...
my $IDENT     = qr{ [^\W\d] \w*+ }xms;
my $QUALIDENT = qr{ (?: $IDENT :: )*+ $IDENT }xms;

# Match balanced parentheses, taking into account \-escapes and []-escapes...
my $PARENS = qr{
    (?&VAR_PARENS)
    (?(DEFINE)
        (?<VAR_PARENS> \( (?: \\. | (?&VAR_PARENS) | (?&CHARSET) | [^][()\\]++)*+ \) )
        (?<CHARSET> \[ \^?+ \]?+ (?: \[:\w+:\] | \\. | [^]])*+ \] )

    )
}xms;

# Match a <ws:...> directive within rules...
my $WS_PATTERN = qr{<ws: ((?: \\. | [^\\()>]++ | $PARENS )*+) >}xms;


#=====[ UTILITY SUBS FOR ERROR AND WARNING MESSAGES ]========

sub _uniq {
    my %seen;
    return grep { defined $_ && !$seen{$_}++ } @_;
}

# Default translator for error messages...
my $ERRORMSG_TRANSLATOR = sub {
    my ($errormsg, $rulename, $context) = @_;

    $rulename   = 'valid input' if $rulename eq q{};
    $context  //= '<end of string>';

    # Unimplemented subrule when rulename starts with '-'...
    if (substr($rulename,0,1) eq '-') {
        $rulename = substr($rulename,1);
        return "Can't match subrule <$rulename> (not implemented)";
    }

    # Empty message converts to a "Expected...but found..." message...
    if ($errormsg eq q{}) {
        $rulename =~ tr/_/ /;
        $rulename = lc($rulename);
        return "Expected $rulename, but found '$context' instead";
    }

    # "Expecting..." messages get "but found" added...
    if (lc(substr($errormsg,0,6)) eq 'expect') {
        return "$errormsg, but found '$context' instead";
    }

    # Everything else stays "as is"...
    return $errormsg;
};

# Allow user to set translation...
sub set_error_translator {
    { package Regexp::Grammars::TranslatorRestorer;
      sub new {
        my ($class, $old_translator) = @_;
        bless \$old_translator, $class;
      }
      sub DESTROY {
        my ($old_translator_ref) = @_;
        $ERRORMSG_TRANSLATOR = ${$old_translator_ref};
      }
    }

    my ($translator_ref) = @_;
    die "Usage: set_error_translator(\$subroutine_reference)\n"
        if ref($translator_ref) ne 'CODE';

    my $old_translator_ref = $ERRORMSG_TRANSLATOR;
    $ERRORMSG_TRANSLATOR = $translator_ref;

    return defined wantarray
        ? Regexp::Grammars::TranslatorRestorer->new($old_translator_ref)
        : ();
}

# Dispatch to current translator for error messages...
sub _translate_errormsg {
    goto &{$ERRORMSG_TRANSLATOR};
}

#=====[ SUPPORT FOR TRANSLATING GRAMMAR-ENHANCED REGEX TO NATIVE REGEX ]====

# Store any specified grammars...
my %user_defined_grammar;

my %REPETITION_DESCRIPTION_FOR = (
    '+'  => 'once or more',
    '*'  => 'any number of times',
    '?'  => 'if possible',
    '+?' => 'as few times as possible',
    '*?' => 'as few times as possible',
    '??' => 'if necessary',
    '++' => 'as many times as possible',
    '*+' => 'as many times as possible',
    '?+' => 'if possible',
);

sub _translate_raw_regex {
    my ($regex, $debug_build, $debug_runtime) = @_;

    my $is_comment =  substr($regex, 0, 1) eq q{#}
                   || substr($regex, 0, 3) eq q{(?#};
    my $visible_regex = _squeeze_ws($regex);

    # Report how regex was interpreted, if requested to...
    if ($debug_build && $visible_regex ne q{} && $visible_regex ne q{ }) {
        _debug_notify( info =>
                           "   |",
                           "   |...Treating '$visible_regex' as:",
            ($is_comment ? "   |       \\ a comment (which will be ignored)"
                         : "   |       \\ normal Perl regex syntax"
            ),
        );
    }

    return q{} if $is_comment;

    # Generate run-time debugging code (if any)...
    my ($debug_pre, $debug_post)
        = _build_raw_debugging_statements($debug_runtime,$visible_regex, +1);

    # Replace negative lookahead with one that works under R::G...
    $regex =~ s{\(\?!}{(?!(?!)|}gxms;
    # ToDo: Also replace positive lookahead with one that works under R::G...
    #       This replacement should be of the form:
    #           $regex =~ s{\(\?!}{(?!(?!)|(?!(?!)|}gxms;
    #       but need to find a way to insert the extra ) at the other end

    return $debug_runtime && $regex eq '|'   ?  $regex . $debug_post
         : $debug_runtime && $regex =~ /\S/  ?  "(?:$debug_pre($regex)$debug_post)"
         :                                      $regex;
}

# Report and convert a debugging directive...
sub _translate_debug_directive {
    my ($construct, $cmd, $debug_build) = @_;

    # Report how directive was interpreted, if requested to...
    if ($debug_build) {
        _debug_notify( info =>
            "   |",
            "   |...Treating $construct as:",
            "   |       \\ Change run-time debugging mode to '$cmd'",
        );
    }

    return qq{(?{; local \$Regexp::Grammars::DEBUG = q{$cmd}; }) };
}

# Report and convert a timeout directive...
sub _translate_timeout_directive {
    my ($construct, $timeout, $debug_build) = @_;

    # Report how directive was interpreted, if requested to...
    if ($debug_build) {
        _debug_notify( info =>
            "   |",
            "   |...Treating $construct as:",
         ($timeout > 0
          ? "   |       \\ Cause the entire parse to fail after $timeout second" .  ($timeout==1 ? q{} : q{s})
          : "   |       \\ Cause the entire parse to fail immediately"
         ),
        );
    }

    return $timeout > 0
            ? qq{(?{; local \$Regexp::Grammars::TIMEOUT = { duration => $timeout, limit => time() + $timeout }; }) }
            : qq{(*COMMIT)(*FAIL)};
}

# Report and convert a <require:...> directive...
sub _translate_require_directive {
    my ($construct, $condition, $debug_build) = @_;

    $condition = substr($condition, 3, -2);

    # Report how directive was interpreted, if requested to...
    if ($debug_build) {
        _debug_notify( info =>
            "   |",
            "   |...Treating $construct as:",
            "   |       \\ Require that {$condition} is true",
        );
    }

    my $quoted_condition = $condition;
    $quoted_condition =~ s{\$}{}xms;

    return qq{(?(?{;$condition})
        (?{;Regexp::Grammars::_debug_require(
            scalar \@Regexp::Grammars::RESULT_STACK, q{$quoted_condition}, 1)
                if \$Regexp::Grammars::DEBUG_LEVEL{\$Regexp::Grammars::DEBUG}})
      | (?{;Regexp::Grammars::_debug_require(
            scalar \@Regexp::Grammars::RESULT_STACK, q{$quoted_condition}, 0)
                if \$Regexp::Grammars::DEBUG_LEVEL{\$Regexp::Grammars::DEBUG}})(?!))
    };
}


# Report and convert a <minimize:> directive...
sub _translate_minimize_directive {
    my ($construct, $debug_build) = @_;

    # Report how directive was interpreted, if requested to...
    if ($debug_build) {
        _debug_notify( info =>
            "   |",
            "   |...Treating $construct as:",
            "   |       \\ Minimize result value if possible",
        );
    }

    return q{(?{;
        if (1 == grep { $_ ne '!' && $_ ne '@' && $_ ne '~' } keys %MATCH) { # ...single alnum key
            local %Regexp::Grammars::matches = %MATCH;
            delete @Regexp::Grammars::matches{'!', '@', '~'};
            local ($Regexp::Grammars::only_key) = keys %Regexp::Grammars::matches;
            local $Regexp::Grammars::array_ref  = $MATCH{$Regexp::Grammars::only_key};
            if (ref($Regexp::Grammars::array_ref) eq 'ARRAY' && 1 == @{$Regexp::Grammars::array_ref}) {
                $MATCH = $Regexp::Grammars::array_ref->[0];
            }
        }
    })};
}

# Report and convert a debugging directive...
sub _translate_error_directive {
    my ($construct, $type, $msg, $debug_build, $subrule_name) = @_;
    $subrule_name //= 'undef';

    # Determine severity...
    my $severity = ($type eq 'error') ? 'fail' : 'non-fail';

    # Determine fatality (and build code to invoke it)...
    my $fatality = ($type eq 'fatal') ? '(*COMMIT)(*FAIL)' : q{};

    # Unpack message...
    if (substr($msg,0,3) eq '(?{') {
        $msg = 'do'. substr($msg,2,-1);
    }
    else {
        $msg = quotemeta $msg;
        $msg = qq{qq{$msg}};
    }

    # Report how directive was interpreted, if requested to...
    if ($debug_build) {
        _debug_notify( info => "   |",
                               "   |...Treating $construct as:",
            ( $type eq 'log' ? "   |       \\ Log a message to the logfile"
                             : "   |       \\ Append a $severity error message to \@!"
            ),
        );
    }

    # Generate the regex...
    return $type eq 'log'
        ? qq{(?{Regexp::Grammars::_debug_logmsg(scalar \@Regexp::Grammars::RESULT_STACK,$msg)
                if \$Regexp::Grammars::DEBUG_LEVEL{\$Regexp::Grammars::DEBUG}
          })}

        : qq{(?:(?{;local \$Regexp::Grammar::_memopos=pos();})
              (?>\\s*+((?-s).{0,$MAX_CONTEXT_WIDTH}+))
              (?{; pos() = \$Regexp::Grammar::_memopos;
              @! = Regexp::Grammars::_uniq(
                @!,
                Regexp::Grammars::_translate_errormsg($msg,q{$subrule_name},\$CONTEXT)
              ) }) (?!)|}
        . ($severity eq 'fail' ? q{(?!)} : $fatality)
        . q{)}
        ;
}

sub _translate_subpattern {
    my ($construct, $alias, $subpattern, $savemode, $postmodifier, $debug_build, $debug_runtime, $timeout, $backref)
        = @_;

    # Determine save behaviour...
    my $is_noncapturing   = $savemode eq 'noncapturing';
    my $is_listifying     = $savemode eq 'list';
    my $is_codeblock      = substr($subpattern,0,3) eq '(?{';
    my $value_saved       = $is_codeblock  ? '$^R'                    : '$^N';
    my $do_something_with = $is_codeblock  ? 'execute the code block' : 'match the pattern';
    my $result            = $is_codeblock  ? 'result'                 : 'matched substring';
    my $description       = $is_codeblock    ? substr($subpattern,2,-1)
                          : defined $backref ? $backref
                          :                    $subpattern;
    my $debug_construct
        = $is_codeblock ?  '<' . substr($alias,1,-1) . '= (?{;' . substr($subpattern,3,-2) . '})>'
        :                  $construct
        ;

    # Report how construct was interpreted, if requested to...
    my $repeatedly = $REPETITION_DESCRIPTION_FOR{$postmodifier} // q{};
    my $results  = $is_listifying && $postmodifier    ? "each $result"
                 : substr($postmodifier,0,1) eq '?'   ? "any $result"
                 : $postmodifier && !$is_noncapturing ? "only the final $result"
                 :                                      "the $result"
                 ;
    if ($debug_build) {
        _debug_notify( info =>
                                 "   |",
                                 "   |...Treating $construct as:",
                                 "   |      |  $do_something_with $description $repeatedly",
            ( $is_noncapturing ? "   |       \\ but don't save $results"
            : $is_listifying   ? "   |       \\ appending $results to \@{\$MATCH{$alias}}"
            :                    "   |       \\ saving $results in \$MATCH{$alias}"
            )
        );
    }

    # Generate run-time debugging code (if any)...
    my ($debug_pre, $debug_post)
        = _build_debugging_statements($debug_runtime,$debug_construct, +1);

    # Generate post-match result-capturing code, if match captures...
    my $post_action = $is_noncapturing
        ? q{}
        : qq{local \@Regexp::Grammars::RESULT_STACK = (
                \@Regexp::Grammars::RESULT_STACK[0..\@Regexp::Grammars::RESULT_STACK-2],
                Regexp::Grammars::_extend_current_result_frame_with_$savemode(
                    \\\@Regexp::Grammars::RESULT_STACK, $alias, $value_saved
                ),
            );}
        ;

    # Generate timeout test...
    my $timeout_test = $timeout ? q{(??{;Regexp::Grammars::_test_timeout()})} : q{};

    # Translate to standard regex code...
    return qq{$timeout_test(?{;local \@Regexp::Grammars::RESULT_STACK
                    = \@Regexp::Grammars::RESULT_STACK;$debug_pre})
                (?:($subpattern)(?{;$post_action$debug_post}))$postmodifier};
}


sub _translate_hashmatch {
    my ($construct, $alias, $hashname, $keypat, $savemode, $postmodifier, $debug_build, $debug_runtime, $timeout)
        = @_;

    # Empty or missing keypattern defaults to <.hk>...
    if (!defined $keypat || $keypat !~ /\S/) {
        $keypat = '(?&hk__implicit__)'
    }
    else {
        $keypat = substr($keypat, 1, -1);
    }

    # Determine save behaviour...
    my $is_noncapturing   = $savemode eq 'noncapturing';
    my $is_listifying     = $savemode eq 'list';

    # Convert hash to hash lookup...
    my $hash_lookup = '$' . substr($hashname, 1). '{$^N}';

    # Report how construct was interpreted, if requested to...
    my $repeatedly = $REPETITION_DESCRIPTION_FOR{$postmodifier} // q{};
    my $results  = $is_listifying && $postmodifier    ? 'each matched key'
                 : substr($postmodifier,0,1) eq '?'   ? 'any matched key'
                 : $postmodifier && !$is_noncapturing ? 'only the final matched key'
                 :                                      'the matched key'
                 ;
    if ($debug_build) {
        _debug_notify( info =>
                                 "   |",
                                 "   |...Treating $construct as:",
                                 "   |      |  match a key from the hash $hashname $repeatedly",
            ( $is_noncapturing ? "   |       \\ but don't save $results"
            : $is_listifying   ? "   |       \\ appending $results to \$MATCH{$alias}"
            :                    "   |       \\ saving $results in \$MATCH{$alias}"
            )
        );
    }

    # Generate run-time debugging code (if any)...
    my ($debug_pre, $debug_post)
        = _build_debugging_statements($debug_runtime,$construct, +1);

    # Generate post-match result-capturing code, if match captures...
    my $post_action = $is_noncapturing
        ? q{}
        : qq{local \@Regexp::Grammars::RESULT_STACK = (
                \@Regexp::Grammars::RESULT_STACK[0..\@Regexp::Grammars::RESULT_STACK-2],
                Regexp::Grammars::_extend_current_result_frame_with_$savemode(
                    \\\@Regexp::Grammars::RESULT_STACK, $alias, \$^N
                ),
            );}
        ;

    # Generate timeout test...
    my $timeout_test = $timeout ? q{(??{;Regexp::Grammars::_test_timeout()})} : q{};

    # Translate to standard regex code...
    return qq{$timeout_test(?:(?{;local \@Regexp::Grammars::RESULT_STACK
                    = \@Regexp::Grammars::RESULT_STACK;$debug_pre})
                (?:($keypat)(??{exists $hash_lookup ? q{} : q{(?!)}})(?{;$post_action$debug_post})))$postmodifier};
}


# Convert a "<rule><qualifier> % <rule>" construct to pure Perl 5.10...
sub _translate_separated_list {
    my ($term, $op, $separator, $term_trans, $sep_trans,
        $ws, $debug_build, $debug_runtime, $timeout) = @_;

    # This insertion ensures backtracking upwinds the stack correctly...
    state $CHECKPOINT = q{(?{;@Regexp::Grammars::RESULT_STACK = @Regexp::Grammars::RESULT_STACK;})};

    # Translate meaningful whitespace...
    $ws = length($ws) ? q{(?&ws__implicit__)} : q{};

    # Generate timeout test...
    my $timeout_test = $timeout ? q{(??{;Regexp::Grammars::_test_timeout()})} : q{};

    # Report how construct was interpreted, if requested to...
    if ($debug_build) {
        _debug_notify( info =>
            "   |",
            "   |...Treating $term $op $separator as:",
            "   |      |  repeatedly match the subrule $term",
            "   |       \\ as long as the matches are separated by matches of $separator",
        );
    }

    #  One-or-more...
    return qq{$timeout_test(?:$ws$CHECKPOINT$sep_trans$ws$term_trans)*$+}
        if $op =~ m{ [*][*]() | [+]([+?]?) \s* % | \{ 1, \}([+?]?) \s* % }xms;

    #  Zero-or-more...
    return qq{{0}$timeout_test$ws(?:$term_trans(?:$ws$CHECKPOINT$sep_trans$ws$term_trans)*$+)?$+}
        if $op =~ m{ [*]([+?]?) \s* % | \{ 0, \}([+?]?) \s* % }xms;

    #  One-or-zero...
    return qq{?$+}
        if $op =~ m{ [?]([+?]?) \s* % | \{ 0,1 \}([+?]?) \s* % }xms;

    #  Zero exactly...
    return qq{{0}$ws}
        if $op =~ m{ \{ 0 \}[+?]? \s* % }xms;

    #  N exactly...
    if ($op =~ m{ \{ (\d+) \}([+?]?) \s* % }xms ) {
        my $min = $1-1;
        return qq{{0}$timeout_test$ws(?:$term_trans(?:$ws$CHECKPOINT$sep_trans$ws$term_trans){$min}$+)}
    }

    #  Zero-to-N...
    if ($op =~ m{ \{ 0,(\d+) \}([+?]?) \s* % }xms ) {
        my $max = $1-1;
        return qq{{0}$timeout_test$ws(?:$term_trans(?:$ws$CHECKPOINT$sep_trans$ws$term_trans){0,$max}$+)?$+}
    }

    #  M-to-N and M-to-whatever...
    if ($op =~ m{ \{ (\d+),(\d*) \} ([+?]?) \s* % }xms ) {
        my $min = $1-1;
        my $max = $2 ? $2-1 : q{};
        return qq{{0}$timeout_test$ws(?:$term_trans(?:$ws$CHECKPOINT$sep_trans$ws$term_trans){$min,$max}$+)}
    }

    # Somehow we missed a case (this should never happen)...
    die "Internal error: missing case in separated list handler";
}

sub _translate_subrule_call {
    my ($source_line, $source_file, $rulename, $grammar_name, $construct, $alias,
        $subrule, $args, $savemode, $postmodifier,
        $debug_build, $debug_runtime, $timeout, $valid_subrule_names_ref, $nocontext)
            = @_;

    # Translate arg list, if provided...
    my $arg_desc;
    if ($args eq q{}) {
        $args = q{()};
    }
    elsif (substr($args,0,3) eq '(?{') {
        # Turn parencode into do block...
        $arg_desc = substr($args,3,-2);
        substr($args,1,1) = 'do';
    }
    else {
        # Turn abbreviated format into a key=>value list...
        $args =~ s{ [(,] \s* \K : (\w+) (?= \s* [,)] ) }{$1 => \$MATCH{'$1'}}gxms;
        $arg_desc = substr($args,1,-1);
    }

    # Transform qualified subrule names...
    my $simple_subrule = $subrule;
    my $start_grammar = (($simple_subrule =~ s{(.*)::}{}xms) ? $1 : "");
    if ($start_grammar !~ /^NEXT$|::/) {
        $start_grammar = caller(3).'::'.$start_grammar;
    }

    my @candidates = $start_grammar eq 'NEXT' ? _ancestry_of($grammar_name)
                   :                            _ancestry_of($start_grammar);

    # Rename fully-qualified rule call, if to ancestor grammar...
    RESOLVING:
    for my $parent_class (@candidates) {
        my $inherited_subrule = $parent_class.'::'.$simple_subrule;
        if ($CACHE{$inherited_subrule}) {
            $subrule = $inherited_subrule;
            last RESOLVING;
        }
    }

    # Replace package separators, which regex engine can't handle...
    my $internal_subrule = $subrule;
    $internal_subrule =~ s{::}{_88_}gxms;

    # Shortcircuit if unknown subrule invoked...
    if (!$valid_subrule_names_ref->{$subrule}) {
        _debug_notify( error =>
            qq{Found call to $construct inside definition of $rulename},
            qq{near $source_file line $source_line.},
            qq{But no <rule: $subrule> or <token: $subrule> was defined in the grammar},
            qq{(Did you misspell $construct? Or forget to define the rule?)},
            q{},
        );
        return "(?{Regexp::Grammars::_debug_fatal('$construct')})(*COMMIT)(*FAIL)";
    }

    # Determine save behaviour...
    my $is_noncapturing = $savemode =~ /noncapturing|lookahead/;
    my $is_listifying   = $savemode eq 'list';

    my $save_code =
       $is_noncapturing?
          q{ @Regexp::Grammars::RESULT_STACK[0..@Regexp::Grammars::RESULT_STACK-2] }
     : $is_listifying?
         qq{ \@Regexp::Grammars::RESULT_STACK[0..\@Regexp::Grammars::RESULT_STACK-3],
              Regexp::Grammars::_pop_current_result_frame_with_list(
                  \\\@Regexp::Grammars::RESULT_STACK, $alias, '$simple_subrule', \$^N
              ),
         }
     :
         qq{ \@Regexp::Grammars::RESULT_STACK[0..\@Regexp::Grammars::RESULT_STACK-3],
              Regexp::Grammars::_pop_current_result_frame(
                   \\\@Regexp::Grammars::RESULT_STACK, $alias, '$simple_subrule', \$^N
              ),
        }
     ;

    # Report how construct was interpreted, if requested to...
    my $repeatedly = $REPETITION_DESCRIPTION_FOR{$postmodifier} // q{};
    my $results  = $is_listifying && $postmodifier    ? 'each match'
                 : substr($postmodifier,0,1) eq '?'   ? 'any match'
                 :                                      'the match'
                 ;
    my $do_something_with = $savemode eq 'neglookahead' ? 'lookahead for anything except'
                          : $savemode eq 'poslookahead' ? 'lookahead for'
                          :                               'match'
                          ;
    if ($debug_build) {
        _debug_notify( info =>
                                 "   |",
                                 "   |...Treating $construct as:",
                                 "   |      |  $do_something_with the subrule <$subrule> $repeatedly",
            (defined $arg_desc ? "   |      |  passing the args: ($arg_desc)"
            :                    ()
            ),
            ( $is_noncapturing ? "   |       \\ but don't save anything"
            : $is_listifying   ? "   |       \\ appending $results to \$MATCH{$alias}"
            :                    "   |       \\ saving $results in \$MATCH{$alias}"
            ),
        );
    }

    # Generate post-match result-capturing code, if match captures...
    my ($debug_pre, $debug_post)
        = _build_debugging_statements($debug_runtime, $construct);

    # Generate timeout test...
    my $timeout_test = $timeout ? q{(??{;Regexp::Grammars::_test_timeout()})} : q{};

    # Translate to standard regex code...
    return qq{(?:$timeout_test(?{;
            local \@Regexp::Grammars::RESULT_STACK = (\@Regexp::Grammars::RESULT_STACK, {'\@'=>{$args}});
            \$Regexp::Grammars::RESULT_STACK[-2]{'~'} = $nocontext
                if \@Regexp::Grammars::RESULT_STACK >= 2;
            $debug_pre})((?&$internal_subrule))(?{;
                local \@Regexp::Grammars::RESULT_STACK = (
                    $save_code
                );$debug_post
    }))$postmodifier};
}

sub _translate_rule_def {
    my ($type, $qualifier, $name, $callname, $qualname, $body, $objectify, $local_ws) = @_;
    $qualname =~ s{::}{_88_}gxms;

    # Return object if requested...
    my $objectification =
        $objectify ? qq{(??{; local \@Regexp::Grammars::RESULT_STACK = \@Regexp::Grammars::RESULT_STACK;
                            \$Regexp::Grammars::RESULT_STACK[-1] = '$qualifier$name'->can('new')
                                ? '$qualifier$name'->new(\$Regexp::Grammars::RESULT_STACK[-1])
                                : bless \$Regexp::Grammars::RESULT_STACK[-1], '$qualifier$name';
                            Regexp::Grammars::_debug_non_hash(\$Regexp::Grammars::RESULT_STACK[-1],'$name');
                        })}
                   : q{};

    # Each rule or token becomes a DEFINE'd Perl 5.10 named capture...
    my $implicit_version
        = ($callname eq 'ws' || $callname eq 'hk')
            ? qq{(?<${callname}__implicit__> $body) }
            : qq{};
    return qq{
        (?(DEFINE) $local_ws
            (?<$qualname>
            (?<$callname>
                (?{\$Regexp::Grammars::RESULT_STACK[-1]{'!'}=\$#{!};})
                (?:$body) $objectification
                (?{;\$#{!}=delete(\$Regexp::Grammars::RESULT_STACK[-1]{'!'})//0;
                           delete(\$Regexp::Grammars::RESULT_STACK[-1]{'\@'});
                })
            ))
            $implicit_version
        )
    };
}


# Locate any valid <...> sequences and replace with native regex code...
sub _translate_subrule_calls {
    my ($source_file, $source_line,
        $grammar_name,
        $grammar_spec,
        $compiletime_debugging_requested,
        $runtime_debugging_requested,
        $timeout_requested,
        $pre_match_debug,
        $post_match_debug,
        $rule_name,
        $subrule_names_ref,
        $magic_ws,
        $nocontext,
    ) = @_;

    my $pretty_rule_name = $rule_name ? ($magic_ws ? '<rule' : '<token') . ": $rule_name>"
                                      : 'main regex (before first rule)';

    # Remember the preceding construct, so as to implement the +% etc. operators...
    my $prev_construct   = q{};
    my $prev_translation = q{};
    my $curr_line_num = 1;

    # Translate all other calls (MAIN GRAMMAR FOR MODULE)...
    $grammar_spec =~ s{
      (?<list_marker> (?<ws1> \s*+)  (?<op> (?&SEPLIST_OP) ) (?<ws2> \s*+) )?
      (?<construct>
        (?<! \(\? )
        <
        (?:
            (?<self_subrule_scalar_nocap>
                   \.                            \s* (?<subrule>(?&QUALIDENT)) \s* (?<args>(?&ARGLIST)) \s*
            )
          | (?<self_subrule_lookahead>
                   (?<sign> \? | \! )            \s* (?<subrule>(?&QUALIDENT)) \s* (?<args>(?&ARGLIST)) \s*
            )
          | (?<self_subrule_scalar>
                                                 \s* (?<subrule>(?&QUALIDENT)) \s* (?<args>(?&ARGLIST)) \s*

            )
          | (?<self_subrule_list>
                   \[                            \s* (?<subrule>(?&QUALIDENT)) \s* (?<args>(?&ARGLIST)) \s* \]
            )
          | (?<alias_subrule_scalar>
                       (?<alias>(?&IDENT)) \s* = \s* (?<subrule>(?&QUALIDENT)) \s* (?<args>(?&ARGLIST)) \s*

            )
          | (?<alias_subrule_list>
                   \[  (?<alias>(?&IDENT)) \s* = \s* (?<subrule>(?&QUALIDENT)) \s* (?<args>(?&ARGLIST)) \s* \]
            )

          | (?<self_argrule_scalar>
                                                 \s* : (?<subrule>(?&QUALIDENT)) \s*
            )
          | (?<alias_argrule_scalar>
                       (?<alias>(?&IDENT)) \s* = \s* : (?<subrule>(?&QUALIDENT)) \s*
            )
          | (?<alias_argrule_list>
                   \[  (?<alias>(?&IDENT)) \s* = \s* : (?<subrule>(?&QUALIDENT)) \s*  \]
            )

          | (?<alias_parens_scalar_nocap>
                   \.  (?<alias>(?&IDENT)) \s* = \s* (?<pattern>(?&PARENCODE)|(?&PARENS)|(?&LITERAL)) \s*
            )
          | (?<alias_parens_scalar>
                       (?<alias>(?&IDENT)) \s* = \s* (?<pattern>(?&PARENCODE)|(?&PARENS)|(?&LITERAL)) \s*
            )
          | (?<alias_parens_list>
                   \[  (?<alias>(?&IDENT)) \s* = \s* (?<pattern>(?&PARENCODE)|(?&PARENS)|(?&LITERAL)) \s* \]
            )
          | (?<alias_hash_scalar_nocap>
                                                     (?<varname>(?&HASH)) \s* (?<keypat>(?&BRACES))?  \s*
            )
          | (?<alias_hash_scalar>
                       (?<alias>(?&IDENT)) \s* = \s* (?<varname>(?&HASH)) \s* (?<keypat>(?&BRACES))?  \s*
            )
          | (?<alias_hash_list>
                   \[  (?<alias>(?&IDENT)) \s* = \s* (?<varname>(?&HASH)) \s* (?<keypat>(?&BRACES))?  \s* \]
            )
          | (?<backref>
                                                 \s* (?<slash> \\  | /) (?<subrule> [:] (?&QUALIDENT))  \s*
                |                                \s* (?<slash> \\_ | /) (?<subrule>     (?&QUALIDENT))  \s*
            )
          | (?<alias_backref>
                       (?<alias>(?&IDENT)) \s* = \s* (?<slash> \\  | /) (?<subrule> [:] (?&QUALIDENT))  \s*
                |      (?<alias>(?&IDENT)) \s* = \s* (?<slash> \\_ | /) (?<subrule>     (?&QUALIDENT))  \s*
            )
          | (?<alias_backref_list>
                   \[  (?<alias>(?&IDENT)) \s* = \s* (?<slash> \\  | /) (?<subrule> [:] (?&QUALIDENT))  \s* \]
                |  \[  (?<alias>(?&IDENT)) \s* = \s* (?<slash> \\_ | /) (?<subrule>     (?&QUALIDENT))  \s* \]
            )
          |
            (?<minimize_directive>
                    minimize \s* : \s*
            )
          |
            (?<require_directive>
                    require \s* : \s* (?<condition> (?&PARENCODE) ) \s*
            )
          |
            (?<debug_directive>
                    debug \s* : \s* (?<cmd> run | match | step | try | off | on) \s*
            )
          |
            (?<timeout_directive>
                    timeout \s* : \s* (?<timeout> \d+) \s*
            )
          |
            (?<context_directive>
                    context \s* : \s*
            )
          |
            (?<nocontext_directive>
                    nocontext \s* : \s*
            )
          |
            (?<yadaerror_directive>
                    [.][.][.]
                  | [!][!][!]
                  | [?][?][?]
            )
          |
            (?<autoerror_directive>
                    (?<error_type> error | fatal ) \s*+ : \s*+
            )
          |
            (?<error_directive>
                    (?<error_type> log | error | warning | fatal )
                    \s*+ : \s*+
                    (?<msg> (?&PARENCODE) | .+? )
                    \s*+
            )
        )
        > (?<modifier> \s* (?! (?&SEPLIST_OP) ) [?+*][?+]? | )
      |
        (?<ws_directive>
            $WS_PATTERN
        )
      |
        (?<raw_regex>
            \(\?\<\w+\>
        )
      |
        (?<incomplete_request>
            < [^>\n]* [>\n]
        )
      |
        (?<loose_quantifier>
            (?<! \| ) \s++ (?&QUANTIFIER)
          | (?<! \A ) \s++ (?&QUANTIFIER)
        )
      |
        (?<reportable_raw_regex>
            (?: \\[^shv]
            |   (?! (?&PARENCODE) ) (?&PARENS)
            |   (?&CHARSET)
            |   \w++
            |   \|
            )
            (?&QUANTIFIER)?
        )
      |
        (?<raw_regex>
              \s++
            | \\. (?&QUANTIFIER)?
            | \(\?!
            | \(\?\# [^)]* \)   # (?# -> old style inline comment)
            | (?&PARENCODE)
            | \# [^\n]*+
            | [^][\s()<>#\\]++
        )
    )

    (?(DEFINE)
        (?<SEPLIST_OP> \*\* | [*+?][+?]?\s*% | \{ \d+(,\d*)? \} [+?]?\s*%                                          )
        (?<PARENS>    \( (?:[?]<[=!])? (?: \\. | (?&PARENCODE) | (?&PARENS) | (?&CHARSET) | [^][()\\<>]++ )*+ \)   )
        (?<BRACES>    \{     (?: \\. | (?&BRACES)    | [^{}\\]++   )*+                              \}   )
        (?<PARENCODE> \(\?[{] (?: \\. | (?&BRACES)    | [^{}\\]++   )*+ [}]\)                            )
        (?<HASH>      \% (?&IDENT) (?: :: (?&IDENT) )*                                                   )
        (?<CHARSET>   \[ \^?+ \]?+ (?: \[:\w+:\] | \\. | [^]] )*+                                   \]   )
        (?<IDENT>     [^\W\d]\w*+                                                                        )
        (?<QUALIDENT> (?: [^\W\d]\w*+ :: )*  [^\W\d]\w*+                                                 )
        (?<LITERAL>   (?&NUMBER) | (?&STRING) | (?&VAR)                                                  )
        (?<NUMBER>    [+-]? \d++ (?:\. \d++)? (?:[eE] [+-]? \d++)?                                       )
        (?<STRING>    ' [^\\']++ (?: \\. [^\\']++ )* '                                                   )
        (?<ARGLIST>   (?&PARENCODE) | \( \s* (?&ARGS)? \s* \) | (?# NOTHING )                            )
        (?<ARGS>      (?&ARG) \s* (?: , \s* (?&ARG) \s* )*  ,?                                           )
        (?<ARG>       (?&VAR)  |  (?&KEY) \s* => \s* (?&LITERAL)                                         )
        (?<VAR>       : (?&IDENT)                                                                        )
        (?<KEY>       (?&IDENT) | (?&LITERAL)                                                            )
        (?<QUANTIFIER> [*+?][+?]? | \{ \d+,?\d* \} [+?]?                                                 )
    )
    }{
        my $curr_construct   = $+{construct};
        my $list_marker      = $+{list_marker} // q{};
        my $alias            = ($+{alias}//'MATCH') eq 'MATCH' ? q{'='} : qq{'$+{alias}'};

        # Determine and remember the necessary translation...
        my $curr_translation = do{

        # Translate subrule calls of the form: <ALIAS=(...)>...
            if (defined $+{alias_parens_scalar}) {
                my $pattern = substr($+{pattern},0,1) eq '(' ? $+{pattern} : "(?{$+{pattern}})";
                _translate_subpattern(
                    $curr_construct, $alias, $pattern, 'scalar', $+{modifier},
                    $compiletime_debugging_requested,
                    $runtime_debugging_requested, $timeout_requested,
                );
            }
            elsif (defined $+{alias_parens_scalar_nocap}) {
                my $pattern = substr($+{pattern},0,1) eq '(' ? $+{pattern} : "(?{$+{pattern}})";
                _translate_subpattern(
                    $curr_construct, $alias, $pattern, 'noncapturing', $+{modifier},
                    $compiletime_debugging_requested,
                    $runtime_debugging_requested, $timeout_requested,
                );
            }
            elsif (defined $+{alias_parens_list}) {
                my $pattern = substr($+{pattern},0,1) eq '(' ? $+{pattern} : "(?{$+{pattern}})";
                _translate_subpattern(
                    $curr_construct, $alias, $pattern, 'list', $+{modifier},
                    $compiletime_debugging_requested,
                    $runtime_debugging_requested, $timeout_requested,
                );
            }

        # Translate subrule calls of the form: <ALIAS=%HASH>...
            elsif (defined $+{alias_hash_scalar}) {
                _translate_hashmatch(
                    $curr_construct, $alias, $+{varname}, $+{keypat}, 'scalar', $+{modifier},
                    $compiletime_debugging_requested,
                    $runtime_debugging_requested,
                    $timeout_requested,
                );
            }
            elsif (defined $+{alias_hash_scalar_nocap}) {
                _translate_hashmatch(
                    $curr_construct, $alias, $+{varname}, $+{keypat}, 'noncapturing', $+{modifier},
                    $compiletime_debugging_requested,
                    $runtime_debugging_requested,
                    $timeout_requested,
                );
            }
            elsif (defined $+{alias_hash_list}) {
                _translate_hashmatch(
                    $curr_construct, $alias, $+{varname}, $+{keypat}, 'list', $+{modifier},
                    $compiletime_debugging_requested,
                    $runtime_debugging_requested,
                    $timeout_requested,
                );
            }

        # Translate subrule calls of the form: <ALIAS=RULENAME>...
            elsif (defined $+{alias_subrule_scalar}) {
                _translate_subrule_call(
                    $source_line, $source_file,
                    $pretty_rule_name,
                    $grammar_name,
                    $curr_construct, $alias, $+{subrule}, $+{args}, 'scalar', $+{modifier},
                    $compiletime_debugging_requested,
                    $runtime_debugging_requested,
                    $timeout_requested,
                    $subrule_names_ref,
                    $nocontext,
                );
            }
            elsif (defined $+{alias_subrule_list}) {
                _translate_subrule_call(
                    $source_line, $source_file,
                    $pretty_rule_name,
                    $grammar_name,
                    $curr_construct, $alias, $+{subrule}, $+{args}, 'list', $+{modifier},
                    $compiletime_debugging_requested,
                    $runtime_debugging_requested,
                    $timeout_requested,
                    $subrule_names_ref,
                    $nocontext,
                );
            }

        # Translate subrule calls of the form: <?RULENAME> and <!RULENAME>...
            elsif (defined $+{self_subrule_lookahead}) {

                # Determine type of lookahead, and work around capture problem...
                my ($type, $pre, $post) = ( 'neglookahead', '(?!(?!)|', ')' );
                if (defined $+{sign} eq '?') {
                    $type = 'poslookahead';
                    $pre  x= 2;
                    $post x= 2;
                }

                $pre . _translate_subrule_call(
                    $source_line, $source_file,
                    $pretty_rule_name,
                    $grammar_name,
                    $curr_construct, qq{'$+{subrule}'}, $+{subrule}, $+{args}, $type, q{},
                    $compiletime_debugging_requested,
                    $runtime_debugging_requested,
                    $timeout_requested,
                    $subrule_names_ref,
                    $nocontext,
                  )
                . $post;
            }
            elsif (defined $+{self_subrule_scalar_nocap}) {
                _translate_subrule_call(
                    $source_line, $source_file,
                    $pretty_rule_name,
                    $grammar_name,
                    $curr_construct, qq{'$+{subrule}'}, $+{subrule}, $+{args}, 'noncapturing', $+{modifier},
                    $compiletime_debugging_requested,
                    $runtime_debugging_requested,
                    $timeout_requested,
                    $subrule_names_ref,
                    $nocontext,
                );
            }
            elsif (defined $+{self_subrule_scalar}) {
                _translate_subrule_call(
                    $source_line, $source_file,
                    $pretty_rule_name,
                    $grammar_name,
                    $curr_construct, qq{'$+{subrule}'}, $+{subrule}, $+{args}, 'scalar', $+{modifier},
                    $compiletime_debugging_requested,
                    $runtime_debugging_requested,
                    $timeout_requested,
                    $subrule_names_ref,
                    $nocontext,
                );
            }
            elsif (defined $+{self_subrule_list}) {
                _translate_subrule_call(
                    $source_line, $source_file,
                    $pretty_rule_name,
                    $grammar_name,
                    $curr_construct, qq{'$+{subrule}'}, $+{subrule}, $+{args}, 'list', $+{modifier},
                    $compiletime_debugging_requested,
                    $runtime_debugging_requested,
                    $timeout_requested,
                    $subrule_names_ref,
                    $nocontext,
                );
            }

        # Translate subrule calls of the form: <ALIAS=:ARGNAME>...
            elsif (defined $+{alias_argrule_scalar}) {
                my $pattern = qq{(??{;\$Regexp::Grammars::RESULT_STACK[-1]{'\@'}{'$+{subrule}'} // '(?!)'})};
                _translate_subpattern(
                    $curr_construct, $alias, $pattern, 'scalar', $+{modifier},
                    $compiletime_debugging_requested, $runtime_debugging_requested, $timeout_requested,
                    "in \$ARG{'$+{subrule}'}"
                );
            }
            elsif (defined $+{alias_argrule_list}) {
                my $pattern = qq{(??{;\$Regexp::Grammars::RESULT_STACK[-1]{'\@'}{'$+{subrule}'} // '(?!)'})};
                _translate_subpattern(
                    $curr_construct, $alias, $pattern, 'list', $+{modifier},
                    $compiletime_debugging_requested, $runtime_debugging_requested, $timeout_requested,
                    "in \$ARG{'$+{subrule}'}"
                );
            }

        # Translate subrule calls of the form: <:ARGNAME>...
            elsif (defined $+{self_argrule_scalar}) {
                my $pattern = qq{(??{;\$Regexp::Grammars::RESULT_STACK[-1]{'\@'}{'$+{subrule}'} // '(?!)'})};
                _translate_subpattern(
                    $curr_construct, qq{'$+{subrule}'}, $pattern, 'noncapturing', $+{modifier},
                    $compiletime_debugging_requested, $runtime_debugging_requested, $timeout_requested,
                    "in \$ARG{'$+{subrule}'}"
                );
            }

        # Translate subrule calls of the form: <\IDENT> or </IDENT>...
            elsif (defined $+{backref} || $+{alias_backref} || $+{alias_backref_list}) {
                # Use "%ARGS" if subrule names starts with a colon...
                my $subrule = $+{subrule};
                if (substr($subrule,0,1) eq ':') {
                    substr($subrule,0,1,"\@'}{'");
                }

                my $backref = qq{\$Regexp::Grammars::RESULT_STACK[-1]{'$subrule'}};
                my $quoter  = $+{slash} eq '\\' || $+{slash} eq '\\_'
                                    ? "quotemeta($backref)"
                                    : "Regexp::Grammars::_invert_delim($backref)"
                                    ;
                my $pattern = qq{ (??{ defined $backref ? $quoter : q{(?!)}})};
                my $type = $+{backref}            ? 'noncapturing'
                         : $+{alias_backref}      ? 'scalar'
                         :                          'list'
                         ;
                _translate_subpattern(
                    $curr_construct, $alias, $pattern, $type, $+{modifier},
                    $compiletime_debugging_requested, $runtime_debugging_requested, $timeout_requested,
                    "in \$MATCH{'$subrule'}"
                );
            }

        # Translate reportable raw regexes (add debugging support)...
            elsif (defined $+{reportable_raw_regex}) {
                _translate_raw_regex(
                    $+{reportable_raw_regex}, $compiletime_debugging_requested, $runtime_debugging_requested
                );
            }

        # Translate non-reportable raw regexes (leave as is)...
            elsif (defined $+{raw_regex}) {
                _translate_raw_regex(
                    $+{raw_regex}, $compiletime_debugging_requested
                );
            }

        # Translate directives...
            elsif (defined $+{require_directive}) {
                _translate_require_directive(
                    $curr_construct, $+{condition}, $compiletime_debugging_requested
                );
            }
            elsif (defined $+{minimize_directive}) {
                _translate_minimize_directive(
                    $curr_construct, $+{condition}, $compiletime_debugging_requested
                );
            }
            elsif (defined $+{debug_directive}) {
                _translate_debug_directive(
                    $curr_construct, $+{cmd}, $compiletime_debugging_requested
                );
            }
            elsif (defined $+{timeout_directive}) {
                _translate_timeout_directive(
                    $curr_construct, $+{timeout}, $compiletime_debugging_requested
                );
            }
            elsif (defined $+{error_directive}) {
                _translate_error_directive(
                    $curr_construct, $+{error_type}, $+{msg},
                    $compiletime_debugging_requested, $rule_name
                );
            }
            elsif (defined $+{autoerror_directive}) {
                _translate_error_directive(
                    $curr_construct, $+{error_type}, q{},
                    $compiletime_debugging_requested, $rule_name
                );
            }
            elsif (defined $+{yadaerror_directive}) {
                _translate_error_directive(
                    $curr_construct,
                    ($+{yadaerror_directive} eq '???' ?  'warning' : 'error'),
                    q{},
                    $compiletime_debugging_requested, -$rule_name
                );
            }
            elsif (defined $+{context_directive}) {
                $nocontext = 0;
                if ($compiletime_debugging_requested) {
                    _debug_notify( info => "   |",
                                           "   |...Treating $curr_construct as:",
                                           "   |       \\ Turn on context-saving for the current rule"
                    );
                }
                q{};  # Remove the directive
            }
            elsif (defined $+{nocontext_directive}) {
                $nocontext = 1;
                if ($compiletime_debugging_requested) {
                    _debug_notify( info => "   |",
                                           "   |...Treating $curr_construct as:",
                                           "   |       \\ Turn off context-saving for the current rule"
                    );
                }
                q{};  # Remove the directive
            }
            elsif (defined $+{ws_directive}) {
                if ($compiletime_debugging_requested) {
                    _debug_notify( info => "   |",
                                           "   |...Treating $curr_construct as:",
                                           "   |       \\ Change whitespace matching for the current rule"
                    );
                }
                $curr_construct;
            }

        # Something that looks like a rule call or directive, but isn't...
            elsif (defined $+{incomplete_request}) {
                my $request = $+{incomplete_request};
                my $inferred_type = $request =~ /:/ ? 'directive' : 'subrule call';
                    _debug_notify( warn =>
                        qq{Possible failed attempt to specify a $inferred_type:},
                        qq{    $request},
                        qq{near $source_file line $source_line},
                        qq{(If you meant to match literally, use: \\$request)},
                        q{},
                    );
                $request;
            }

        # A quantifier that isn't quantifying anything...
            elsif (defined $+{loose_quantifier}) {
                my $quant = $+{loose_quantifier};
                   $quant =~ s{^\s+}{};
                my $literal = quotemeta($quant);
                _debug_notify( fatal =>
                    qq{Quantifier that doesn't quantify anything: $quant},
                    qq{in declaration of $pretty_rule_name},
                    qq{near $source_file line $source_line},
                    qq{(Did you mean to match literally? If so, try: $literal)},
                    q{},
                );
                exit(1);
            }

        # There shouldn't be any other possibility...
            else {
                die qq{Internal error: this shouldn't happen!\n},
                    qq{Near '$curr_construct' in $pretty_rule_name\n};
            }
        };

        # Handle the **/*%/+%/{n,m}%/etc operators...
        if ($list_marker) {
            my $ws = $magic_ws ? $+{ws1} . $+{ws2} : q{};
            my $op = $+{op};

            $curr_translation = _translate_separated_list(
                $prev_construct,   $op, $curr_construct,
                $prev_translation, $curr_translation, $ws,
                $compiletime_debugging_requested,
                $runtime_debugging_requested, $timeout_requested,
            );
            $curr_construct = qq{$prev_construct $op $curr_construct};
        }

        # Finally, remember this latest translation, and return it...
        $prev_construct   = $curr_construct;
        $prev_translation = $curr_translation;;
    }exmsg;

    # Translate magic hash accesses...
    $grammar_spec =~ s{\$(?:\:\:)?MATCH (?= \s*\{) }
                      {\$Regexp::Grammars::RESULT_STACK[-1]}xmsg;
    $grammar_spec =~ s{\$(?:\:\:)?ARG (?= \s*\{) }
                      {\$Regexp::Grammars::RESULT_STACK[-1]{'\@'}}xmsg;

    # Translate magic scalars and hashes...
    state $translate_scalar = {
        q{%$MATCH}  => q{%{$Regexp::Grammars::RESULT_STACK[-1]{q{=}}}},
        q{@$MATCH}  => q{@{$Regexp::Grammars::RESULT_STACK[-1]{q{=}}}},
        q{$MATCH}   => q{$Regexp::Grammars::RESULT_STACK[-1]{q{=}}},
        q{%MATCH}   => q{%{$Regexp::Grammars::RESULT_STACK[-1]}},
        q{$CAPTURE} => q{$^N},
        q{$CONTEXT} => q{$^N},
        q{$DEBUG}   => q{$Regexp::Grammars::DEBUG},
        q{$INDEX}   => q{${\\pos()}},
        q{%ARG}     => q{%{$Regexp::Grammars::RESULT_STACK[-1]{'@'}}},

        q{%$::MATCH}  => q{%{$Regexp::Grammars::RESULT_STACK[-1]{q{=}}}},
        q{@$::MATCH}  => q{@{$Regexp::Grammars::RESULT_STACK[-1]{q{=}}}},
        q{$::MATCH}   => q{$Regexp::Grammars::RESULT_STACK[-1]{q{=}}},
        q{%::MATCH}   => q{%{$Regexp::Grammars::RESULT_STACK[-1]}},
        q{$::CAPTURE} => q{$^N},
        q{$::CONTEXT} => q{$^N},
        q{$::DEBUG}   => q{$Regexp::Grammars::DEBUG},
        q{$::INDEX}   => q{${\\pos()}},
        q{%::ARG}     => q{%{$Regexp::Grammars::RESULT_STACK[-1]{'@'}}},

    };
    state $translatable_scalar
        = join '|', map {quotemeta $_}
                        sort {length $b <=> length $a}
                             keys %{$translate_scalar};

    $grammar_spec =~ s{ ($translatable_scalar) (?! \s* (?: \[ | \{) ) }
                      {$translate_scalar->{$1}}oxmsg;

    return $grammar_spec;
}

# Generate a "decimal timestamp" and insert in a template...
sub _timestamp {
    my ($template) = @_;

    # Generate and insert any timestamp...
    if ($template =~ /%t/) {
        my ($sec, $min, $hour, $day, $mon,   $year) = localtime;
                                     $mon++; $year+=1900;
        my $timestamp = sprintf("%04d%02d%02d.%02d%02d%02d",
                                $year, $mon, $day, $hour, $min, $sec);
        $template =~ s{%t}{$timestamp}xms;;
    }

    return $template;
}

# Open (or re-open) the requested log file...
sub _autoflush {
    my ($fh) = @_;
    my $originally_selected = select $fh;
    $|=1;
    select $originally_selected;
}

sub _open_log {
    my ($mode, $filename, $from_where) = @_;
    $from_where //= q{};

    # Special case: '-' --> STDERR
    if ($filename eq q{-}) {
        return *STDERR{IO};
    }
    # Otherwise, just open the named file...
    elsif (open my $fh, $mode, $filename) {
        _autoflush($fh);
        return $fh;
    }
    # Otherwise, generate a warning and default to STDERR...
    else {
        local *Regexp::Grammars::LOGFILE = *STDERR{IO};
        _debug_notify( warn =>
            qq{Unable to open log file '$filename'},
            ($from_where ? $from_where : ()),
            qq{($!)},
            qq{Defaulting to STDERR instead.},
            q{},
        );
        return *STDERR{IO};
    }
}

sub _invert_delim {
    my ($delim) = @_;
    $delim = reverse $delim;
    $delim =~ tr/<>[]{}()«»`'/><][}{)(»«'`/;
    return quotemeta $delim;
}

# Regex to detect if other regexes contain a grammar specification...
my $GRAMMAR_DIRECTIVE
    = qr{ < grammar: \s* (?<grammar_name> $QUALIDENT ) \s* > }xms;

# Regex to detect if other regexes contain a grammar inheritance...
my $EXTENDS_DIRECTIVE
    = qr{ < extends: \s* (?<base_grammar_name> $QUALIDENT ) \s* > }xms;

# Cache of rule/token names within defined grammars...
my %subrule_names_for;

# Build list of ancestors for a given grammar...
sub _ancestry_of {
    my ($grammar_name) = @_;

    return () if !$grammar_name;

    use mro;
    return map { substr($_, $CACHE_LEN) } @{mro::get_linear_isa($CACHE.$grammar_name, 'c3')};
}

# Detect and translate any requested grammar inheritances...
sub _extract_inheritances {
    my ($source_line, $source_file, $regex, $compiletime_debugging_requested, $derived_grammar_name) = @_;


    # Detect and remove inheritance requests...
    while ($regex =~ s{$EXTENDS_DIRECTIVE}{}xms) {
        # Normalize grammar name and report...
        my $orig_grammar_name = $+{base_grammar_name};
        my $grammar_name = $orig_grammar_name;
        if ($grammar_name !~ /::/) {
            $grammar_name = caller(2).'::'.$grammar_name;
        }

        if (exists $user_defined_grammar{$grammar_name}) {
            if ($compiletime_debugging_requested) {
                _debug_notify( info =>
                    "Processing inheritance request for $grammar_name...",
                    q{},
                );
            }

            # Specify new relationship...
            no strict 'refs';
            push @{$CACHE.$derived_grammar_name.'::ISA'}, $CACHE.$grammar_name;
        }
        else {
            _debug_notify( fatal =>
                "Inheritance from unknown grammar requested",
                "by <extends: $grammar_name> directive",
                "in regex grammar declared at $source_file line $source_line",
                q{},
            );
            exit(1);
        }
    }

    # Retrieve ancestors (but not self) in C3 dispatch order...
    my (undef, @ancestors) = _ancestry_of($derived_grammar_name);

    # Extract subrule names and implementations for ancestors...
    my %subrule_names = map { %{$subrule_names_for{$_}} } @ancestors;
    $_ = -1 for values %subrule_names;
    my $implementation
        = join "\n", map { $user_defined_grammar{$_} } @ancestors;

    return $implementation, \%subrule_names;
}

# Transform grammar-augmented regex into pure Perl 5.10 regex...
sub _build_grammar {
    my ($grammar_spec) = @_;
    $grammar_spec .= q{};

    # Check for lack of Regexp::Grammar-y constructs and short-circuit...
    if ($grammar_spec !~ m{ < (?: [.?![:%\\/]? [^\W\d]\w* [^>]* | [.?!]{3} ) > }xms) {
        return $grammar_spec;
    }

    # Remember where we parked...
    my ($source_file, $source_line) = (caller 1)[1,2];
    $source_line -= $grammar_spec =~ tr/\n//;

    # Check for dubious repeated <SUBRULE> constructs that throw away captures...
    my $dubious_line = $source_line;
    while ($grammar_spec =~ m{
           (.*?)
           (
            < (?! \[ )                     # not <[SUBRULE]>
                ( $IDENT (?: = [^>]*)? )   # but <SUBRULE> or <SUBRULE=*>
            > \s*
            (                              # followed by a quantifier...
                [+*][?+]?                  #    either symbolic
              | \{\d+(?:,\d*)?\}[?+]?      #    or numeric
            )
           )
        }gxms) {
            my ($prefix, $match, $rule, $qual) = ($1, $2, $3, $4);
            $dubious_line += $prefix =~ tr/\n//;
            _debug_notify( warn =>
                qq{Repeated subrule <$rule>$qual},
                qq{at $source_file line $dubious_line},
                qq{will only capture its final match},
                qq{(Did you mean <[$rule]>$qual instead?)},
                q{},
            );
            $dubious_line += $match =~ tr/\n//;
    }

    # Check for dubious non-backtracking <SUBRULE> constructs...
    $dubious_line = $source_line;
    while (
        $grammar_spec =~ m{
            (.*?)
            (
                <
                    (?! (?:obj)? (?:rule: | token ) )
                    ( [^>]+ )
                >
                \s*
                ( [?+*][+] | \{.*\}[+] )
            )
        }gxms) {
            my ($prefix, $match, $rule, $qual) = ($1, $2, $3, $4);
            $dubious_line += $prefix =~ tr/\n//;
            my $safe_qual = substr($qual,0,-1);
            _debug_notify( warn =>
                qq{Non-backtracking subrule call <$rule>$qual},
                qq{at $source_file line $dubious_line},
                qq{may not revert correctly during backtracking.},
                qq{(If grammar does not work, try <$rule>$safe_qual instead)},
                q{},
            );
            $dubious_line += $match =~ tr/\n//;
    }

    # Check whether a log file was specified...
    my $compiletime_debugging_requested;
    local *Regexp::Grammars::LOGFILE = *Regexp::Grammars::LOGFILE;
    my $logfile = q{-};

    my $log_where = "for regex grammar defined at $source_file line $source_line";
    $grammar_spec =~ s{ ^ [^#]* < logfile: \s* ([^>]+?) \s* > }{
        $logfile = _timestamp($1);

        # Presence of <logfile:...> implies compile-time logging...
        $compiletime_debugging_requested = 1;
        *Regexp::Grammars::LOGFILE = _open_log('>',$logfile, $log_where );

        # Delete <logfile:...> directive...
        q{};
    }gexms;

    # Look ahead for any run-time debugging or timeout requests...
    my $runtime_debugging_requested
        = $grammar_spec =~ m{
              ^ [^#]*
              < debug: \s* (run | match | step | try | on | same ) \s* >
            | \$DEBUG (?! \s* (?: \[ | \{) )
        }xms;

    my $timeout_requested
        = $grammar_spec =~ m{
              ^ [^#]*
              < timeout: \s* \d+ \s* >
        }xms;


    # Standard actions set up and clean up any regex debugging...
    # Before entire match, set up a stack of attempt records and report...
    my $pre_match_debug
        = $runtime_debugging_requested
            ? qq{(?{; *Regexp::Grammars::LOGFILE
                        = Regexp::Grammars::_open_log('>>','$logfile', '$log_where');
                      Regexp::Grammars::_init_try_stack(); })}
            : qq{(?{; *Regexp::Grammars::LOGFILE
                        = Regexp::Grammars::_open_log('>>','$logfile', '$log_where'); })}
            ;

    # After entire match, report whether successful or not...
    my $post_match_debug
        = $runtime_debugging_requested
            ? qq{(?{;Regexp::Grammars::_debug_matched(0,\\%/,'<grammar>',\$^N)})
                |(?>(?{;Regexp::Grammars::_debug_handle_failures(0,'<grammar>'); }) (?!))
                }
            : q{}
            ;

    # Remove comment lines...
    $grammar_spec =~ s{^ ([^#\n]*) \s \# [^\n]* }{$1}gxms;

    # Subdivide into rule and token definitions, preparing to process each...
    # REWRITE THIS, USING (PROBABLY NEED TO REFACTOR ALL GRAMMARS TO REUSe
    # THESE COMPONENTS:
    #   (?<PARAMLIST> \( \s* (?&PARAMS)? \s* \) | (?# NOTHING )                                          )
    #   (?<PARAMS>    (?&PARAM) \s* (?: , \s* (?&PARAM) \s* )*  ,?                                       )
    #   (?<PARAM>     (?&VAR) (?: \s* = \s* (?: (?&LITERAL) | (?&PARENCODE) ) )?                         )
    #   (?<LITERAL>   (?&NUMBER) | (?&STRING) | (?&VAR)                                                  )
    #   (?<VAR>       : (?&IDENT)                                                                        )
    my @defns = split m{
            (< (obj|)(rule|token) \s*+ :
              \s*+ ((?:${IDENT}::)*+) (?: ($IDENT) \s*+ = \s*+ )?+
              ($IDENT)
            \s* >)
        }xms, $grammar_spec;

    # Extract up list of names of defined rules/tokens...
    # (Name is every 6th item out of every seven, skipping the first item)
    my @subrule_names = @defns[ map { $_ * 7 + 6 } 0 .. ((@defns-1)/7-1) ];
    my @defns_copy = @defns[1..$#defns];
    my %subrule_names;

    # Build a look-up table of subrule names, checking for duplicates...
    my $defn_line = $source_line + $defns[0] =~ tr/\n//;
    my %first_decl_explanation;
    for my $subrule_name (@subrule_names) {
        my ($full_decl, $objectify, $type, $qualifier, $name, $callname, $body) = splice(@defns_copy, 0, 7);
        if (++$subrule_names{$subrule_name} > 1) {
            _debug_notify( warn =>
                "Redeclaration of <$objectify$type: $subrule_name>",
                "at $source_file line $defn_line",
                "will be ignored.",
                @{ $first_decl_explanation{$subrule_name} },
                q{},
            );
        }
        else {
            $first_decl_explanation{$subrule_name} = [
                "(Hidden by the earlier declaration of <$objectify$type: $subrule_name>",
                " at $source_file line $defn_line)"
            ];
        }
        $defn_line += ($full_decl.$body) =~ tr/\n//;
    }

    # Add the built-ins...
    @subrule_names{'ws', 'hk', 'matchpos', 'matchline'} = (1) x 4;

    # An empty main rule will never match anything...
    my $main_regex = shift @defns;
    if ($main_regex =~ m{\A (?: \s++ | \(\?\# [^)]* \) | \# [^\n]++ )* \z}xms) {
        _debug_notify( error =>
            "No main regex specified before rule definitions",
            "in regex grammar declared at $source_file line $source_line",
            "Grammar will never match anything.",
            "(Or did you forget a <grammar:...> specification?)",
            q{},
        );
    }

    # Compile the regex or grammar...
    my $regex = q{};
    my $grammar_name;
    my $is_grammar;

    # Is this a grammar specification?
    if ($main_regex =~ $GRAMMAR_DIRECTIVE) {
        # Normalize grammar name and report...
        $grammar_name = $+{grammar_name};
        if ($grammar_name !~ /::/) {
            $grammar_name = caller(1) . "::$grammar_name";
        }
        $is_grammar = 1;

        # Add subrule definitions to namespace...
        for my $subrule_name (@subrule_names) {
            $CACHE{$grammar_name.'::'.$subrule_name} = 1;
        }
    }
    else {
        state $dummy_grammar_index = 0;
        $grammar_name = '______' . $dummy_grammar_index++;
    }

    # Extract any inheritance information...
    my ($inherited_rules, $inherited_subrule_names)
        = _extract_inheritances(
            $source_line, $source_file,
            $main_regex,
            $compiletime_debugging_requested,
            $grammar_name
          );

    # Remove <extends:...> requests...
    $main_regex =~ s{ $EXTENDS_DIRECTIVE }{}gxms;

    # Add inherited subrule names to allowed subrule names;
    @subrule_names{ keys %{$inherited_subrule_names} }
        = values %{$inherited_subrule_names};

    # Remove comments from top-level grammar...
    $main_regex =~ s{
          \(\?\# [^)]* \)
        | (?<! \\ ) [#] [^\n]+
    }{}gxms;

    # Remove any top-level nocontext directive...
                    # 1 2     3     4
    $main_regex =~ s{^( (.*?) (\\*) (\# [^\n]*) )$}{length($3) % 2 ? $1 : $2.substr($3,0,-1)}gexms;
    my $nocontext = ($main_regex =~ s{ < nocontext \s* : \s* > }{}gxms) ? 1
                  : ($main_regex =~ s{ <   context \s* : \s* > }{}gxms) ? 0
                  :                                                       0;

    # If so, set up to save the grammar...
    if ($is_grammar) {
        # Normalize grammar name and report...
        if ($grammar_name !~ /::/) {
            $grammar_name = caller(1) . "::$grammar_name";
        }
        if ($compiletime_debugging_requested) {
            _debug_notify( info =>
                "Processing definition of grammar $grammar_name...",
                q{},
            );
        }

        # Remove the grammar directive...
        $main_regex =~ s{
            ( $GRAMMAR_DIRECTIVE
            | < debug: \s* (run | match | step | try | on | off | same ) \s* >
            )
        }{$source_line += $1 =~ tr/\n//; q{}}gexms;

        # Check for anything else in the main regex...
        if ($main_regex =~ /\A(\s*)\S/) {
            $source_line += $1 =~ tr/\n//;
            _debug_notify( warn =>
                "Unexpected item before first subrule specification",
                "in definition of <grammar: $grammar_name>",
                "at $source_file line $source_line:",
                map({ "    $_"} grep /\S/, split "\n", $main_regex),
                "(this will be ignored when defining the grammar)",
                q{},
            );
        }

        # Remember set of valid subrule names...
        $subrule_names_for{$grammar_name}
            = {
                map({ ($_ => 1) } keys %subrule_names),
                map({ ($grammar_name.'::'.$_ => 1) } grep { !/::/ } keys %subrule_names),
              };
    }
    else { #...not a grammar specification
        # Report how main regex was interpreted, if requested to...
        if ($compiletime_debugging_requested) {
            _debug_notify( info =>
                "Processing the main regex before any rule definitions",
            );
        }

        # Any actual regex is processed first...
        $regex = _translate_subrule_calls(
            $source_file, $source_line,
            $grammar_name,
            $main_regex,
            $compiletime_debugging_requested,
            $runtime_debugging_requested,
            $timeout_requested,
            $pre_match_debug,
            $post_match_debug,
            q{},                        # Expected...what?
            \%subrule_names,
            0,                          # Whitespace isn't magical
            $nocontext,
        );

        # Wrap the main regex (to ensure |'s don't segment pre and # post commands)...
        $regex = "(?:$regex)";

        # Report how construct was interpreted, if requested to...
        if ($compiletime_debugging_requested) {
            _debug_notify( q{} =>
                q{   |},
                q{    \\___End of main regex},
                q{},
            );
        }
    }

    # Update line number...
    $source_line += $main_regex =~ tr/\n//;

    #  Then iterate any following rule definitions...
    while (@defns) {
        # Grab details of each rule defn (as extracted by previous split)...
        my ($full_decl, $objectify, $type, $qualifier, $name, $callname, $body) = splice(@defns, 0, 7);
        $name //= $callname;
        my $qualified_name = $grammar_name.'::'.$callname;

        # Report how construct was interpreted, if requested to...
        if ($compiletime_debugging_requested) {
            _debug_notify( info =>
                "Defining a $type: <$callname>",
                "   |...Returns: " . ($objectify ? "an object of class '$qualifier$name'" : "a hash"),
            );
        }

        # Translate any nested <...> constructs...
        my $trans_body = _translate_subrule_calls(
            $source_file, $source_line,
            $grammar_name,
            $body,
            $compiletime_debugging_requested,
            $runtime_debugging_requested,
            $timeout_requested,
            $pre_match_debug,
            $post_match_debug,
            $callname,                # Expected...what?
            \%subrule_names,
            $type eq 'rule',          # Is whitespace magical?
            $nocontext,               # Start with the global nocontextuality
        );

        # Report how construct was interpreted, if requested to...
        if ($compiletime_debugging_requested) {
            _debug_notify( q{} =>
                q{   |},
                q{    \\___End of rule definition},
                q{},
            );
        }

        # Make allowance for possible local whitespace definitions...
        my $local_ws_defn = q{};
        my $local_ws_call = q{(?&ws__implicit__)};

        # Rules make non-code literal whitespace match textual whitespace...
        if ($type eq 'rule') {
            # Implement any local whitespace definition...
            my $first_ws = 1;
            WS_DIRECTIVE:
            while ($trans_body =~ s{$WS_PATTERN}{}oxms) {
                my $defn = $1;
                if ($defn !~ m{\S}xms) {
                    _debug_notify( warn =>
                        qq{Ignoring useless empty <ws:> directive},
                        qq{in definition of <rule: $name>},
                        qq{near $source_file line $source_line},
                        qq{(Did you mean <ws> instead?)},
                        q{},
                    );
                    next WS_DIRECTIVE;
                }
                elsif (!$first_ws) {
                    _debug_notify( warn =>
                        qq{Ignoring useless extra <ws:$defn> directive},
                        qq{in definition of <rule: $name>},
                        qq{at $source_file line $source_line},
                        qq{(No more than one is permitted per rule!)},
                        q{},
                    );
                    next WS_DIRECTIVE;
                }
                else {
                    $first_ws = 0;
                }
                state $ws_counter = 0;
                $ws_counter++;
                $local_ws_defn = qq{(?<__RG_ws_$ws_counter> $defn)};
                $local_ws_call = qq{(?&__RG_ws_$ws_counter)};
            }

            # Implement auto-whitespace...
            state $CODE_OR_SPACE = qr{
                (?<ignorable_space>          # These are not magic...
                    \( \?\?? (?&BRACED) \)   #     Embedded code blocks
                  | \s++                     #     Whitespace not followed by...
                    (?= \|                   #         ...an OR
                      | (?: \) \s* )? \z     #         ...the end of the rule
                      | \(\(?\?\&ws\)        #         ...an explicit ws match
                      | \(\?\??\{            #         ...an embedded code block
                      | \\s                  #         ...an explicit space match
                    )
                )
                |
                (?<magic_space> \s++ )       # All other whitespace is magic

                (?(DEFINE) (?<BRACED> \{ (?: \\. | (?&BRACED) | [^{}] )* \} ) )
            }xms;
            $trans_body =~ s{($CODE_OR_SPACE)}{ $+{ignorable_space} // $local_ws_call }exmsg;
        }
        else {
            while ($trans_body =~ s{$WS_PATTERN}{}oxms) {
                _debug_notify( warn =>
                    qq{Ignoring useless <ws:$1> directive},
                    qq{in definition of <token: $name>},
                    qq{at $source_file line $source_line},
                    qq{(Did you need to define <rule: $name> instead of <token: $name>?)},
                    q{},
                );
            }
        }

        $regex
            .= "\n###############[ $source_file line $source_line ]###############\n"
            .  _translate_rule_def(
                 $type, $qualifier, $name, $callname, $qualified_name, $trans_body, $objectify, $local_ws_defn
               );

        # Update line number...
        $source_line += ($full_decl.$body) =~ tr/\n//;
    }

    # Insert checkpoints into any user-defined code block...
    $regex =~ s{ \( \?\?? \{ \K (?!;) }{
        local \@Regexp::Grammars::RESULT_STACK = \@Regexp::Grammars::RESULT_STACK;
    }xmsg;

    # Check for any suspicious left-overs from the start of the regex...
    pos $regex = 0;

    # If a grammar definition, save grammar and return a placeholder...
    if ($is_grammar) {
        $user_defined_grammar{$grammar_name} = $regex;
        return qq{(?{
            warn "Can't match directly against a pure grammar: <grammar: $grammar_name>\n";
        })(*COMMIT)(?!)};
    }
    # Otherwise, aggregrate the final grammar...
    else {
        return _complete_regex($regex.$inherited_rules, $pre_match_debug, $post_match_debug, $nocontext);
    }
}

sub _complete_regex {
    my ($regex, $pre_match_debug, $post_match_debug, $nocontext) = @_;

    return $nocontext ? qq{(?x)$pre_match_debug$PROLOGUE$regex$EPILOGUE_NC$post_match_debug}
                      : qq{(?x)$pre_match_debug$PROLOGUE$regex$EPILOGUE$post_match_debug};
}

1; # Magic true value required at end of module

__END__

=head1 NAME

Regexp::Grammars - Add grammatical parsing features to Perl 5.10 regexes


=head1 VERSION

This document describes Regexp::Grammars version 1.045


=head1 SYNOPSIS

    use Regexp::Grammars;

    my $parser = qr{
        (?:
            <Verb>               # Parse and save a Verb in a scalar
            <.ws>                # Parse but don't save whitespace
            <Noun>               # Parse and save a Noun in a scalar

            <type=(?{ rand > 0.5 ? 'VN' : 'VerbNoun' })>
                                 # Save result of expression in a scalar
        |
            (?:
                <[Noun]>         # Parse a Noun and save result in a list
                                     (saved under the key 'Noun')
                <[PostNoun=ws]>  # Parse whitespace, save it in a list
                                 #   (saved under the key 'PostNoun')
            )+

            <Verb>               # Parse a Verb and save result in a scalar
                                     (saved under the key 'Verb')

            <type=(?{ 'VN' })>   # Save a literal in a scalar
        |
            <debug: match>       # Turn on the integrated debugger here
            <.Cmd= (?: mv? )>    # Parse but don't capture a subpattern
                                     (name it 'Cmd' for debugging purposes)
            <[File]>+            # Parse 1+ Files and save them in a list
                                     (saved under the key 'File')
            <debug: off>         # Turn off the integrated debugger here
            <Dest=File>          # Parse a File and save it in a scalar
                                     (saved under the key 'Dest')
        )

        ################################################################

        <token: File>              # Define a subrule named File
            <.ws>                  #  - Parse but don't capture whitespace
            <MATCH= ([\w-]+) >     #  - Parse the subpattern and capture
                                   #    matched text as the result of the
                                   #    subrule

        <token: Noun>              # Define a subrule named Noun
            cat | dog | fish       #  - Match an alternative (as usual)

        <rule: Verb>               # Define a whitespace-sensitive subrule
            eats                   #  - Match a literal (after any space)
            <Object=Noun>?         #  - Parse optional subrule Noun and
                                   #    save result under the key 'Object'
        |                          #  Or else...
            <AUX>                  #  - Parse subrule AUX and save result
            <part= (eaten|seen) >  #  - Match a literal, save under 'part'

        <token: AUX>               # Define a whitespace-insensitive subrule
            (has | is)             #  - Match an alternative and capture
            (?{ $MATCH = uc $^N }) #  - Use captured text as subrule result

    }x;

    # Match the grammar against some text...
    if ($text =~ $parser) {
        # If successful, the hash %/ will have the hierarchy of results...
        process_data_in( %/ );
    }



=head1 QUICKSTART CHEATSHEET

=head2 In your program...

    use Regexp::Grammars;    Allow enhanced regexes in lexical scope
    %/                       Result-hash for successful grammar match

=head2 Defining and using named grammars...

    <grammar:  GRAMMARNAME>  Define a named grammar that can be inherited
    <extends:  GRAMMARNAME>  Current grammar inherits named grammar's rules

=head2 Defining rules in your grammar...

    <rule:     RULENAME>     Define rule with magic whitespace
    <token:    RULENAME>     Define rule without magic whitespace

    <objrule:  CLASS= NAME>  Define rule that blesses return-hash into class
    <objtoken: CLASS= NAME>  Define token that blesses return-hash into class

    <objrule:  CLASS>        Shortcut for above (rule name derived from class)
    <objtoken: CLASS>        Shortcut for above (token name derived from class)


=head2 Matching rules in your grammar...

    <RULENAME>               Call named subrule (may be fully qualified)
                             save result to $MATCH{RULENAME}

    <RULENAME(...)>          Call named subrule, passing args to it

    <!RULENAME>              Call subrule and fail if it matches
    <!RULENAME(...)>         (shorthand for (?!<.RULENAME>) )

    <:IDENT>                 Match contents of $ARG{IDENT} as a pattern
    <\:IDENT>                Match contents of $ARG{IDENT} as a literal
    </:IDENT>                Match closing delimiter for $ARG{IDENT}

    <%HASH>                  Match longest possible key of hash
    <%HASH {PAT}>            Match any key of hash that also matches PAT

    </IDENT>                 Match closing delimiter for $MATCH{IDENT}
    <\_IDENT>                Match the literal contents of $MATCH{IDENT}

    <ALIAS= RULENAME>        Call subrule, save result in $MATCH{ALIAS}
    <ALIAS= %HASH>           Match a hash key, save key in $MATCH{ALIAS}
    <ALIAS= ( PATTERN )>     Match pattern, save match in $MATCH{ALIAS}
    <ALIAS= (?{ CODE })>     Execute code, save value in $MATCH{ALIAS}
    <ALIAS= 'STR' >          Save specified string in $MATCH{ALIAS}
    <ALIAS= 42 >             Save specified number in $MATCH{ALIAS}
    <ALIAS= /IDENT>          Match closing delim, save as $MATCH{ALIAS}
    <ALIAS= \_IDENT>         Match '$MATCH{IDENT}', save as $MATCH{ALIAS}

    <.SUBRULE>               Call subrule (one of the above forms),
                             but don't save the result in %MATCH


    <[SUBRULE]>              Call subrule (one of the above forms), but
                             append result instead of overwriting it

    <SUBRULE1>+ % <SUBRULE2> Match one or more repetitions of SUBRULE1
                             as long as they're separated by SUBRULE2
    <SUBRULE1> ** <SUBRULE2> Same (only for backwards compatibility)

    <SUBRULE1>* % <SUBRULE2> Match zero or more repetitions of SUBRULE1
                             as long as they're separated by SUBRULE2


=head2 In your grammar's code blocks...

    $CAPTURE    Alias for $^N (the most recent paren capture)
    $CONTEXT    Another alias for $^N
    $INDEX      Current index of next matching position in string
    %MATCH      Current rule's result-hash
    $MATCH      Magic override value (returned instead of result-hash)
    %ARG        Current rule's argument hash
    $DEBUG      Current match-time debugging mode

=head2 Directives...

    <require: (?{ CODE })   >  Fail if code evaluates false
    <timeout: INT           >  Fail after specified number of seconds
    <debug:   COMMAND       >  Change match-time debugging mode
    <logfile: LOGFILE       >  Change debugging log file (default: STDERR)
    <fatal:   TEXT|(?{CODE})>  Queue error message and fail parse
    <error:   TEXT|(?{CODE})>  Queue error message and backtrack
    <warning: TEXT|(?{CODE})>  Queue warning message and continue
    <log:     TEXT|(?{CODE})>  Explicitly add a message to debugging log
    <ws:      PATTERN       >  Override automatic whitespace matching
    <minimize:>                Simplify the result of a subrule match
    <context:>                 Switch on context substring retention
    <nocontext:>               Switch off context substring retention



=head1 DESCRIPTION

This module adds a small number of new regex constructs that can be used
within Perl 5.10 patterns to implement complete recursive-descent parsing.

Perl 5.10 already supports recursive=descent I<matching>, via the new
C<< (?<name>...) >> and C<< (?&name) >> constructs. For example, here is
a simple matcher for a subset of the LaTeX markup language:

    $matcher = qr{
        (?&File)

        (?(DEFINE)
            (?<File>     (?&Element)* )

            (?<Element>  \s* (?&Command)
                      |  \s* (?&Literal)
            )

            (?<Command>  \\ \s* (?&Literal) \s* (?&Options)? \s* (?&Args)? )

            (?<Options>  \[ \s* (?:(?&Option) (?:\s*,\s* (?&Option) )*)? \s* \])

            (?<Args>     \{ \s* (?&Element)* \s* \}  )

            (?<Option>   \s* [^][\$&%#_{}~^\s,]+     )

            (?<Literal>  \s* [^][\$&%#_{}~^\s]+      )
        )
    }xms

This technique makes it possible to use regexes to recognize complex,
hierarchical--and even recursive--textual structures. The problem is
that Perl 5.10 doesn't provide any support for extracting that
hierarchical data into nested data structures. In other words, using
Perl 5.10 you can I<match> complex data, but not I<parse> it into an
internally useful form.

An additional problem when using Perl 5.10 regexes to match complex data
formats is that you have to make sure you remember to insert
whitespace-matching constructs (such as C<\s*>) at every possible position
where the data might contain ignorable whitespace. This reduces the
readability of such patterns, and increases the chance of errors (typically
caused by overlooking a location where whitespace might appear).

The Regexp::Grammars module solves both those problems.

If you import the module into a particular lexical scope, it
preprocesses any regex in that scope, so as to implement a number of
extensions to the standard Perl 5.10 regex syntax. These extensions
simplify the task of defining and calling subrules within a grammar, and
allow those subrule calls to capture and retain the components of they
match in a proper hierarchical manner.

For example, the above LaTeX matcher could be converted to a full LaTeX parser
(and considerably tidied up at the same time), like so:

    use Regexp::Grammars;
    $parser = qr{
        <File>

        <rule: File>       <[Element]>*

        <rule: Element>    <Command> | <Literal>

        <rule: Command>    \\  <Literal>  <Options>?  <Args>?

        <rule: Options>    \[  <[Option]>+ % (,)  \]

        <rule: Args>       \{  <[Element]>*  \}

        <rule: Option>     [^][\$&%#_{}~^\s,]+

        <rule: Literal>    [^][\$&%#_{}~^\s]+
    }xms

Note that there is no need to explicitly place C<\s*> subpatterns throughout
the rules; that is taken care of automatically.

If the Regexp::Grammars version of this regex were successfully matched
against some appropriate LaTeX document, each rule would call the
subrules specified within it, and then return a hash containing whatever
result each of those subrules returned, with each result indexed by the
subrule's name.

That is, if the rule named C<Command> were invoked, it would first try
to match a backslash, then it would call the three subrules
C<< <Literal> >>, C<< <Options> >>, and C<< <Args> >> (in that sequence). If
they all matched successfully, the C<Command> rule would then return a
hash with three keys: C<'Literal'>, C<'Options'>, and C<'Args'>. The value
for each of those hash entries would be whatever result-hash the
subrules themselves had returned when matched.

In this way, each level of the hierarchical regex can generate hashes
recording everything its own subrules matched, so when the entire pattern
matches, it produces a tree of nested hashes that represent the
structured data the pattern matched.

For example, if the previous regex grammar were matched against a string
containing:

    \documentclass[a4paper,11pt]{article}
    \author{D. Conway}

it would automatically extract a data structure equivalent to the
following (but with several extra "empty" keys, which are described in
L<Subrule results>):

    {
        'file' => {
            'element' => [
                {
                    'command' => {
                        'literal' => 'documentclass',
                        'options' => {
                            'option'  => [ 'a4paper', '11pt' ],
                        },
                        'args'    => {
                            'element' => [ 'article' ],
                        }
                    }
                },
                {
                    'command' => {
                        'literal' => 'author',
                        'args' => {
                            'element' => [
                                {
                                    'literal' => 'D.',
                                },
                                {
                                    'literal' => 'Conway',
                                }
                            ]
                        }
                    }
                }
            ]
        }
    }

The data structure that Regexp::Grammars produces from a regex match
is available to the surrounding program in the magic variable C<%/>.

Regexp::Grammars provides many features that simplify the extraction of
hierarchical data via a regex match, and also some features that can
simplify the processing of that data once it has been extracted. The
following sections explain each of those features, and some of the
parsing techniques they support.


=head2 Setting up the module

Just add:

    use Regexp::Grammars;

to any lexical scope. Any regexes within that scope will automatically now
implement the new parsing constructs:

    use Regexp::Grammars;

    my $parser = qr/ regex with $extra <chocolatey> grammar bits /;

Note that you do not to use the C</x> modifier when declaring a regex
grammar (though you certainly may). But even if you don't, the module
quietly adds a C</x> to every regex within the scope of its usage.
Otherwise, the default I<"a whitespace character matches exactly that
whitespace character"> behaviour of Perl regexes would mess up your
grammar's parsing. If you need the non-C</x> behaviour, you can still
use the C<(?-x)> of C<(?-x:...)> directives to switch of C</x> within
one or more of your grammar's components.

Once the grammar has been processed, you can then match text against the
extended regexes, in the usual manner (i.e. via a C<=~> match):

    if ($input_text =~ $parser) {
        ...
    }

After a successful match, the variable C<%/> will contain a series of
nested hashes representing the structured hierarchical data captured
during the parse.

=head2 Structure of a Regexp::Grammars grammar

A Regexp::Grammars specification consists of a I<start-pattern> (which
may include both standard Perl 5.10 regex syntax, as well as special
Regexp::Grammars directives), followed by one or more rule or token
definitions.

For example:

    use Regexp::Grammars;
    my $balanced_brackets = qr{

        # Start-pattern...
        <paren_pair> | <brace_pair>

        # Rule definition...
        <rule: paren_pair>
            \(  (?: <escape> | <paren_pair> | <brace_pair> | [^()] )*  \)

        # Rule definition...
        <rule: brace_pair>
            \{  (?: <escape> | <paren_pair> | <brace_pair> | [^{}] )*  \}

        # Token definition...
        <token: escape>
            \\ .
    }xms;

The start-pattern at the beginning of the grammar acts like the
"top" token of the grammar, and must be matched completely for the
grammar to match.

This pattern is treated like a token for whitespace
matching behaviour (see L<"Tokens vs rules (whitespace handling)">).
That is, whitespace in the start-pattern is treated like whitespace
in any normal Perl regex.

The rules and tokens are declarations only and they are not directly matched.
Instead, they act like subroutines, and are invoked by name from the
initial pattern (or from within a rule or token).

Each rule or token extends from the directive that introduces it up to either
the next rule or token directive, or (in the case of the final rule or token)
to the end of the grammar.


=head2 Tokens vs rules (whitespace handling)

The difference between a token and a rule is that a token treats any
whitespace within it exactly as a normal Perl regular expression would.
That is, a sequence of whitespace in a token is ignored if the C</x>
modifier is in effect, or else matches the same literal sequence of
whitespace characters (if C</x> is not in effect).

In a rule, most sequences of whitespace are treated as matching the
implicit subrule C<< <.ws> >>, which is automatically predefined to
match optional whitespace (i.e. C<\s*>).

Exceptions to this behaviour are whitespaces before a C<|> or a code
block or an explicit space-matcher (such as C<< <ws> >> or C<\s>),
or at the very end of the rule)

You can explicitly define a C<< <ws> >> token to change that default
behaviour. For example, you could alter the definition of "whitespace" to
include Perlish comments, by adding an explicit C<< <token: ws> >>:

    <token: ws>
        (?: \s+ | #[^\n]* )*

But be careful not to define C<< <ws> >> as a rule, as this will lead to
all kinds of infinitely recursive unpleasantness.


=head3 Per-rule whitespace handling

Redefining the C<< <ws> >> token changes its behaviour throughout the
entire grammar, within every rule definition. Usually that's appropriate,
but sometimes you need finer-grained control over whitespace handling.

So Regexp::Grammars provides the C<< <ws:> >> directive, which allows
you to override the implicit whitespace-matches-whitespace behaviour
only within the current rule.

Note that this directive does I<not> redefined C<< <ws> >> within the
rule; it simply specifies what to replace each whitespace sequence with
(instead of replacing each with a C<< <ws> >> call).

For example, if a language allows one kind of comment between statements
and another within statements, you could parse it with:

    <rule: program>
        # One type of comment between...
        <ws: (\s++ | \# .*? \n)* >

        # ...colon-separated statements...
        <[statement]>+ % ( ; )


    <rule: statement>
        # Another type of comment...
        <ws: (\s*+ | \#{ .*? }\# )* >

        # ...between comma-separated commands...
        <cmd>  <[arg]>+ % ( , )


Note that each directive only applies to the rule in which it is
specified. In every other rule in the grammar, whitespace would still
match the usual C<< <ws> >> subrule.



=head2 Calling subrules

To invoke a rule to match at any point, just enclose the rule's name in angle
brackets (like in Perl 6). There must be no space between the opening bracket
and the rulename. For example::

    qr{
        file:             # Match literal sequence 'f' 'i' 'l' 'e' ':'
        <name>            # Call <rule: name>
        <options>?        # Call <rule: options> (it's okay if it fails)

        <rule: name>
            # etc.
    }x;

If you need to match a literal pattern that would otherwise look like a
subrule call, just backslash-escape the leading angle:

    qr{
        file:             # Match literal sequence 'f' 'i' 'l' 'e' ':'
        \<name>           # Match literal sequence '<' 'n' 'a' 'm' 'e' '>'
        <options>?        # Call <rule: options> (it's okay if it fails)

        <rule: name>
            # etc.
    }x;


=head2 Subrule results

If a subrule call successfully matches, the result of that match is a
reference to a hash. That hash reference is stored in the current rule's
own result-hash, under the name of the subrule that was invoked. The
hash will, in turn, contain the results of any more deeply nested
subrule calls, each stored under the name by which the nested
subrule was invoked.

In other words, if the rule C<sentence> is defined:

    <rule: sentence>
        <noun> <verb> <object>

then successfully calling the rule:

    <sentence>

causes a new hash entry at the current nesting level. That entry's key will be
C<'sentence'> and its value will be a reference to a hash, which in turn will
have keys: C<'noun'>, C<'verb'>, and C<'object'>.

In addition each result-hash has one extra key: the empty string. The
value for this key is whatever substring the entire subrule call matched.
This value is known as the I<context substring>.

So, for example, a successful call to C<< <sentence> >> might add
something like the following to the current result-hash:

    sentence => {
        ""     => 'I saw a dog',
        noun   => 'I',
        verb   => 'saw',
        object => {
            ""      => 'a dog',
            article => 'a',
            noun    => 'dog',
        },
    }

Note, however, that if the result-hash at any level contains I<only>
the empty-string key (i.e. the subrule did not call any sub-subrules or
save any of their nested result-hashes), then the hash is "unpacked"
and just the context substring itself is returned.

For example, if C<< <rule: sentence> >> had been defined:

    <rule: sentence>
        I see dead people

then a successful call to the rule would only add:

    sentence => 'I see dead people'

to the current result-hash.

This is a useful feature because it prevents a series of nested subrule
calls from producing very unwieldy data structures. For example, without
this automatic unpacking, even the simple earlier example:

    <rule: sentence>
        <noun> <verb> <object>

would produce something needlessly complex, such as:

    sentence => {
        ""     => 'I saw a dog',
        noun   => {
            "" => 'I',
        },
        verb   => {
            "" => 'saw',
        },
        object => {
            ""      => 'a dog',
            article => {
                "" => 'a',
            },
            noun    => {
                "" => 'dog',
            },
        },
    }


=head3 Turning off the context substring

The context substring is convenient for debugging and for generating
error messages but, in a large grammar, or when parsing a long string,
the capture and storage of many nested substrings may quickly become
prohibitively expensive.

So Regexp::Grammars provides a directive to prevent context substrings
from being retained. Any rule or token that includes the directive
C<< <nocontext:> >> anywhere in the rule's body will not retain any
context substring it matches...unless that substring would be the only
entry in its result hash (which only happens within objrules and
objtokens).

If a C<< <nocontext:> >> directive appears I<before> the first rule or
token definition (i.e. as part of the main pattern), then the entire grammar
will discard all context substrings from every one of its rules
and tokens.

However, you can override this universal prohibition with a second
directive: C<< <context:> >>. If this directive appears in any rule or
token, that rule or token I<will> save its context substring, even if a
global C<< <nocontext:> >> is in effect.

This means that this grammar:

    qr{
        <Command>

        <rule: Command>
            <nocontext:>
            <Keyword> <arg=(\S+)>+ % <.ws>

        <token: Keyword>
            <Move> | <Copy> | <Delete>

        # etc.
    }x

and this grammar:

    qr{
        <nocontext:>
        <Command>

        <rule: Command>
            <Keyword> <arg=(\S+)>+ % <.ws>

        <token: Keyword>
            <context:>
            <Move> | <Copy> | <Delete>

        # etc.
    }x

will behave identically (saving context substrings for keywords, but not
for commands), except that the first version will also retain the global
context substring (i.e. $/{""}), whereas the second version will not.

Note that C<< <context:> >> and C<< <nocontext:> >> have no effect on,
or even any interaction with, the various
L<result distillation|"Result distillation"> mechanisms,
which continue to work in the usual way when either or both of the
directives is used.


=head2 Renaming subrule results

It is not always convenient to have subrule results stored under the
same name as the rule itself. Rule names should be optimized for
understanding the behaviour of the parser, whereas result names should
be optimized for understanding the structure of the data. Often those
two goals are identical, but not always; sometimes rule names need to
describe what the data looks like, while result names need to describe
what the data means.

For example, sometimes you need to call the same rule twice, to match
two syntactically identical components whose positions give then semantically
distinct meanings:

    <rule: copy_cmd>
        copy <file> <file>

The problem here is that, if the second call to C<< <file> >> succeeds, its
result-hash will be stored under the key C<'file'>, clobbering the data that
was returned from the first call to C<< <file> >>.

To avoid such problems, Regexp::Grammars allows you to I<alias> any subrule
call, so that it is still invoked by the original name, but its result-hash is
stored under a different key. The syntax for that is:
C<<< <I<alias>=I<rulename>> >>>. For example:

    <rule: copy_cmd>
        copy <from=file> <to=file>

Here, C<< <rule: file> >> is called twice, with the first result-hash being
stored under the key C<'from'>, and the second result-hash being stored under
the key C<'to'>.

Note, however, that the alias before the C<=> must be a proper
identifier (i.e. a letter or underscore, followed by letters, digits,
and/or underscores). Aliases that start with an underscore and aliases named
C<MATCH> have special meaning (see L<Private subrule calls> and
L<Result distillation> respectively).

Aliases can also be useful for normalizing data that may appear in different
formats and sequences. For example:

    <rule: copy_cmd>
        copy <from=file>        <to=file>
      | dup    <to=file>  as  <from=file>
      |      <from=file>  ->    <to=file>
      |        <to=file>  <-  <from=file>

Here, regardless of which order the old and new files are specified, the
result-hash always gets:

    copy_cmd => {
        from => 'oldfile',
          to => 'newfile',
    }


=head2 List-like subrule calls

If a subrule call is quantified with a repetition specifier:

    <rule: file_sequence>
        <file>+

then each repeated match overwrites the corresponding entry in the
surrounding rule's result-hash, so only the result of the final
repetition will be retained. That is, if the above example matched
the string C<S<"foo.pl bar.py baz.php">>, then the result-hash would contain:

    file_sequence {
        ""   => 'foo.pl bar.py baz.php',
        file => 'baz.php',
    }

Usually, that's not the desired outcome, so Regexp::Grammars provides
another mechanism by which to call a subrule; one that saves I<all>
repetitions of its results.

A regular subrule call consists of the rule's name surrounded by angle
brackets. If, instead, you surround the rule's name with C<< <[...]> >>
(angle I<and> square brackets) like so:

    <rule: file_sequence>
        <[file]>+

then the rule is invoked in exactly the same way, but the result of that
submatch is pushed onto an array nested inside the appropriate result-hash
entry. In other words, if the above example matched the same
C<S<"foo.pl bar.py baz.php">> string, the result-hash would contain:

    file_sequence {
        ""   => 'foo.pl bar.py baz.php',
        file => [ 'foo.pl', 'bar.py', 'baz.php' ],
    }

This "listifying subrule call" can also be useful for non-repeated subrule
calls, if the same subrule is invoked in several places in a grammar. For
example if a cmdline option could be given either one or two values, you
might parse it:

    <rule: size_option>
        -size <[size]> (?: x <[size]> )?

The result-hash entry for C<'size'> would then always contain an array,
with either one or two elements, depending on the input being parsed.

Listifying subrules can also be given L<aliases|"Renaming subrule results">,
just like ordinary subrules. The alias is always specified inside the square
brackets:

    <rule: size_option>
        -size <[size=pos_integer]> (?: x <[size=pos_integer]> )?

Here, the sizes are parsed using the C<pos_integer> rule, but saved in the
result-hash in an array under the key C<'size'>.


=head2 Parametric subrules

When a subrule is invoked, it can be passed a set of named arguments
(specified as I<key>C<< => >>I<values> pairs). This argument list is
placed in a normal Perl regex code block and must appear immediately
after the subrule name, before the closing angle bracket.

Within the subrule that has been invoked, the arguments can be accessed
via the special hash C<%ARG>. For example:

    <rule: block>
        <tag>
            <[block]>*
        <end_tag(?{ tag=>$MATCH{tag} })>  # ...call subrule with argument

    <token: end_tag>
        end_ (??{ quotemeta $ARG{tag} })

Here the C<block> rule first matches a C<< <tag> >>, and the corresponding
substring is saved in C<$MATCH{tag}>. It then matches any number of nested
blocks. Finally it invokes the C<< <end_tag> >> subrule, passing it an
argument whose name is C<'tag'> and whose value is the current value of
C<$MATCH{tag}> (i.e. the original opening tag).

When it is thus invoked, the C<end_tag> token first matches C<'end_'>,
then interpolates the literal value of the C<'tag'> argument and
attempts to match it.

Any number of named arguments can be passed when a subrule is invoked.
For example, we could generalize the C<end_tag> rule to allow any prefix
(not just C<'end_'>), and also to allow for 'if...fi'-style reversed
tags, like so:

    <rule: block>
        <tag>
            <[block]>*
        <end_tag (?{ prefix=>'end', tag=>$MATCH{tag} })>

    <token: end_tag>
        (??{ $ARG{prefix} // q{(?!)} })      # ...prefix as pattern
        (??{ quotemeta $ARG{tag} })          # ...tag as literal
      |
        (??{ quotemeta reverse $ARG{tag} })  # ...reversed tag


Note that, if you do not need to interpolate values (such as
C<$MATCH{tag}>) into a subrule's argument list, you can
use simple parentheses instead of C<(?{...})>, like so:

        <end_tag( prefix=>'end', tag=>'head' )>

The only types of values you can use in this simplified
syntax are numbers and single-quote-delimited strings.
For anything more complex, put the argument list
in a full C<(?{...})>.

As the earlier examples show, the single most common
type of argument is one of the form:
I<IDENTIFIER> C<< => $MATCH{ >>I<IDENTIFIER>C<}>. That is,
it's a common requirement to pass an element of C<%MATCH>
into a subrule, named with its own key.

Because this is such a common usage, Regexp::Grammars
provides a shortcut. If you use simple parentheses (instead
of C<(?{...})> parentheses) then instead of a pair, you can
specify an argument using a colon followed by an identifier.
This argument is replaced by a named argument whose name
is the identifier and whose value is the corresponding item
from C<%MATCH>. So, for example, instead of:

        <end_tag(?{ prefix=>'end', tag=>$MATCH{tag} })>

you can just write:

        <end_tag( prefix=>'end', :tag )>

Note that, from Perl 5.20 onwards, due to changes in the way that
Perl parses regexes, Regexp::Grammars does not support explicitly passing
elements of C<%MATCH> as argument values within a list subrule
(yeah, it's a very specific and obscure edge-case):

        <[end_tag(?{ prefix=>'end', tag=>$MATCH{tag} })]>   # Does not work

Note, however, that the shortcut:

        <[end_tag( prefix=>'end', :tag )]>

still works correctly.


=head3 Accessing subrule arguments more cleanly

As the preceding examples illustrate, using subrule arguments
effectively generally requires the use of run-time interpolated
subpatterns via the C<(??{...})> construct.

This produces ugly rule bodies such as:

    <token: end_tag>
        (??{ $ARG{prefix} // q{(?!)} })      # ...prefix as pattern
        (??{ quotemeta $ARG{tag} })          # ...tag as literal
      |
        (??{ quotemeta reverse $ARG{tag} })  # ...reversed tag

To simplify these common usages, Regexp::Grammars provides
three convenience constructs.

A subrule call of the form C<< <: >>I<identifier>C<< > >>
is equivalent to:

    (??{ $ARG{'identifier'} // q{(?!)} })

Namely: I<"Match the contents of C<$ARG{'identifier'}>,
treating those contents as a pattern.">

A subrule call of the form C<< <\: >>I<identifier>C<< > >>
(that is: a L<matchref|"Rematching subrule results">
with a colon after the backslash) is equivalent to:

    (??{ defined $ARG{'identifier'}
            ? quotemeta($ARG{'identifier'})
            : '(?!)'
    })

Namely: I<"Match the contents of C<$ARG{'identifier'}>,
treating those contents as a literal.">

A subrule call of the form C<< </: >>I<identifier>C<< > >>
(that is: an L<invertref|"Rematching balanced delimiters">
with a colon after the forward slash) is equivalent to:

    (??{ defined $ARG{'identifier'}
            ? quotemeta(reverse $ARG{'identifier'})
            : '(?!)'
    })

Namely: I<"Match the closing delimiter corresponding to
the contents of C<$ARG{'identifier'}>, as if it were a literal">.

The availability of these three constructs mean that we could rewrite
the above C<< <end_tag> >> token much more cleanly as:

    <token: end_tag>
        <:prefix>      # ...prefix as pattern
        <\:tag>        # ...tag as a literal
      |
        </:tag>        # ...reversed tag

In general these constructs mean that, within a subrule,
if you want to match an argument passed to that subrule,
you use C<< <: >>I<ARGNAME>C<< > >> (to match the argument
as a pattern) or C<< <\: >>I<ARGNAME>C<< > >> (to match
the argument as a literal).

Note the consistent mnemonic in these various subrule-like
interpolations of named arguments: the name is always prefixed by a
colon.

In other words, the C<< <:ARGNAME> >> form works just like
a C<< <RULENAME> >>, except that the leading colon tells
Regexp::Grammars to use the contents of C<$ARG{'ARGNAME'}>
as the subpattern, instead of the contents of C<(?&RULENAME)>

Likewise, the C<< <\:ARGNAME> >> and C<< </:ARGNAME> >> constructs work
exactly like C<< <\_MATCHNAME> >> and C<< </INVERTNAME> >> respectively,
except that the leading colon indicates that the matchref or invertref
should be taken from C<%ARG> instead of from C<%MATCH>.


=head2 Pseudo-subrules

Aliases can also be given to standard Perl subpatterns, as well as to
code blocks within a regex. The syntax for subpatterns is:

    <ALIAS= (SUBPATTERN) >

In other words, the syntax is exactly like an aliased subrule call, except
that the rule name is replaced with a set of parentheses containing the
subpattern. Any parentheses--capturing or non-capturing--will do.

The effect of aliasing a standard subpattern is to cause whatever that
subpattern matches to be saved in the result-hash, using the alias as
its key. For example:

    <rule: file_command>

        <cmd=(mv|cp|ln)>  <from=file>  <to=file>

Here, the C<< <cmd=(mv|cp|ln)> >> is treated exactly like a regular
C<(mv|cp|ln)>, but whatever substring it matches is saved in the result-hash
under the key C<'cmd'>.

The syntax for aliasing code blocks is:

    <ALIAS= (?{ your($code->here) }) >

Note, however, that the code block must be specified in the standard Perl 5.10
regex notation: C<(?{...})>. A common mistake is to write:

    <ALIAS= { your($code->here } >

instead, which will attempt to interpolate C<$code> before
the regex is even compiled, as such variables are only "protected" from
interpolation inside a C<< (?{...}) >>.

When correctly specified, this construct executes the code in the block
and saves the result of that execution in the result-hash, using the
alias as its key. Aliased code blocks are useful for adding semantic
information based on which branch of a rule is executed. For example,
consider the C<copy_cmd> alternatives shown earlier:

    <rule: copy_cmd>
        copy <from=file>        <to=file>
      | dup    <to=file>  as  <from=file>
      |      <from=file>  ->    <to=file>
      |        <to=file>  <-  <from=file>

Using aliased code blocks, you could add an extra field to the result-
hash to describe which form of the command was detected, like so:

    <rule: copy_cmd>
        copy <from=file>        <to=file>  <type=(?{ 'std' })>
      | dup    <to=file>  as  <from=file>  <type=(?{ 'rev' })>
      |      <from=file>  ->    <to=file>  <type=(?{  +1   })>
      |        <to=file>  <-  <from=file>  <type=(?{  -1   })>

Now, if the rule matched, the result-hash would contain something like:

    copy_cmd => {
        from => 'oldfile',
          to => 'newfile',
        type => 'fwd',
    }

Note that, in addition to the semantics described above, aliased
subpatterns and code blocks also become visible to Regexp::Grammars'
integrated debugger (see L<Debugging>).


=head2 Aliased literals

As the previous example illustrates, it is inconveniently verbose to
assign constants via aliased code blocks. So Regexp::Grammars provides a
short-cut. It is possible to directly alias a numeric literal or a
single-quote delimited literal string, without putting either inside a code
block. For example, the previous example could also be written:

    <rule: copy_cmd>
        copy <from=file>        <to=file>  <type='std'>
      | dup    <to=file>  as  <from=file>  <type='rev'>
      |      <from=file>  ->    <to=file>  <type= +1  >
      |        <to=file>  <-  <from=file>  <type= -1  >

Note that only these two forms of literal are supported in this
abbreviated syntax.


=head2 Amnesiac subrule calls

By default, every subrule call saves its result into the result-hash, either
under its own name, or under an alias.

However, sometimes you may want to refactor some literal part of a rule
into one or more subrules, without having those submatches added to the
result-hash. The syntax for calling a subrule, but ignoring its return value
is:

    <.SUBRULE>

(which is stolen directly from Perl 6).

For example, you may prefer to rewrite a rule such as:

    <rule: paren_pair>

        \(
            (?: <escape> | <paren_pair> | <brace_pair> | [^()] )*
        \)

without any literal matching, like so:

    <rule: paren_pair>

        <.left_paren>
            (?: <escape> | <paren_pair> | <brace_pair> | <.non_paren> )*
        <.right_paren>

    <token: left_paren>   \(
    <token: right_paren>  \)
    <token: non_paren>    [^()]

Moreover, as the individual components inside the parentheses probably
aren't being captured for any useful purpose either, you could further
optimize that to:

    <rule: paren_pair>

        <.left_paren>
            (?: <.escape> | <.paren_pair> | <.brace_pair> | <.non_paren> )*
        <.right_paren>


Note that you can also use the dot modifier on an aliased subpattern:

    <.Alias= (SUBPATTERN) >

This seemingly contradictory behaviour (of giving a subpattern a name,
then deliberately ignoring that name) actually does make sense in one
situation. Providing the alias makes the subpattern visible to the
debugger, while using the dot stops it from affecting the result-hash.
See L<"Debugging non-grammars"> for an example of this usage.


=head2 Private subrule calls

If a rule name (or an alias) begins with an underscore:

     <_RULENAME>       <_ALIAS=RULENAME>
    <[_RULENAME]>     <[_ALIAS=RULENAME]>

then matching proceeds as normal, and any result that is returned is
stored in the current result-hash in the usual way.

However, when any rule finishes (and just before it returns) it first
filters its result-hash, removing any entries whose keys begin with an
underscore. This means that any subrule with an underscored name (or
with an underscored alias) remembers its result, but only until the end
of the current rule. Its results are effectively private to the current
rule.

This is especially useful in conjunction with
L<result distillation|"Result distillation">.


=head2 Lookahead (zero-width) subrules

Non-capturing subrule calls can be used in normal lookaheads:

    <rule: qualified_typename>
        # A valid typename and has a :: in it...
        (?= <.typename> )  [^\s:]+ :: \S+

    <rule: identifier>
        # An alpha followed by alnums (but not a valid typename)...
        (?! <.typename> )    [^\W\d]\w*

but the syntax is a little unwieldy. More importantly, an internal
problem with backtracking causes positive lookaheads to mess up
the module's named capturing mechanism.

So Regexp::Grammars provides two shorthands:

    <!typename>        same as: (?! <.typename> )
    <?typename>        same as: (?= <.typename> ) ...but works correctly!

These two constructs can also be called with arguments, if necessary:

    <rule: Command>
        <Keyword>
        (?:
            <!Terminator(:Keyword)>  <Args=(\S+)>
        )?
        <Terminator(:Keyword)>

Note that, as the above equivalences imply, neither of these forms of a
subroutine call ever captures what it matches.


=head2 Matching separated lists

One of the commonest tasks in text parsing is to match a list of unspecified
length, in which items are separated by a fixed token. Things like:

    1, 2, 3 , 4 ,13, 91        # Numbers separated by commas and spaces

    g-c-a-g-t-t-a-c-a          # DNA bases separated by dashes

    /usr/local/bin             # Names separated by directory markers

    /usr:/usr/local:bin        # Directories separated by colons

The usual construct required to parse these kinds of structures is either:

    <rule: list>

        <item> <separator> <list>     # recursive definition
      | <item>                        # base case

or, if you want to allow zero-or-more items instead of requiring one-or-more:

    <rule: list_opt>
        <list>?                       # entire list may be missing

    <rule: list>                      # as before...
        <item> <separator> <list>     #   recursive definition
      | <item>                        #   base case


Or, more efficiently, but less prettily:

    <rule: list>
        <[item]> (?: <separator> <[item]> )*           # one-or-more

    <rule: list_opt>
        (?: <[item]> (?: <separator> <[item]> )* )?    # zero-or-more

Because separated lists are such a common component of grammars,
Regexp::Grammars provides cleaner ways to specify them:

    <rule: list>
        <[item]>+ % <separator>      # one-or-more

    <rule: list_zom>
        <[item]>* % <separator>      # zero-or-more

Note that these are just regular repetition qualifiers (i.e. C<+>
and C<*>) applied to a subriule (C<< <[item]> >>), with a C<%>
modifier after them to specify the required separator between the
repeated matches.

The number of repetitions matched is controlled both by the nature of
the qualifier (C<+> vs C<*>) and by the subrule specified after the C<%>.
The qualified subrule will be repeatedly matched
for as long as its qualifier allows, provided that the second subrule
also matches I<between> those repetitions.

For example, you can match a parenthesized sequence of one-or-more
numbers separated by commas, such as:

    (1, 2, 3, 4, 13, 91)        # Numbers separated by commas (and spaces)

with:

    <rule: number_list>

        \(  <[number]>+ % <comma>  \)

    <token: number>  \d+
    <token: comma>   ,

Note that any spaces round the commas will be ignored because
C<< <number_list> >> is specified as a rule and the C<+%> specifier
has spaces within and around it. To disallow spaces around the commas,
make sure there are no spaces in or around the C<+%>:

    <rule: number_list_no_spaces>

        \( <[number]>+%<comma> \)

(or else specify the rule as a token instead).

Because the C<%> is a modifier applied to a qualifier, you can modify
I<any> other repetition qualifier in the same way. For example:

    <[item]>{2,4} % <sep>   # two-to-four items, separated

    <[item]>{7}   % <sep>   # exactly 7 items, separated

    <[item]>{10,}? % <sep>   # minimum of 10 or more items, separated

You can even do this:

    <[item]>? % <sep>       # one-or-zero items, (theoretically) separated

though the separator specification is, of course, meaningless in that case
as it will never be needed to separate a maximum of one item.

If a C<%> appears anywhere else in a grammar (i.e. I<not> immediately after a
repetition qualifier), it is treated normally (i.e. as a self-matching literal
character):

    <token: perl_hash>
        % <ident>                # match "%foo", "%bar", etc.

    <token: perl_mod>
        <expr> % <expr>          # match "$n % 2", "($n+3) % ($n-1)", etc.

If you need to match a literal C<%> immediately after a repetition, either
quote it:

    <token: percentage>
        \d{1,3} \% solution                  # match "7% solution", etc.

or refactor the C<%> character:

    <token: percentage>
        \d{1,3} <percent_sign> solution      # match "7% solution", etc.

    <token: percent_sign>
        %

Note that it's usually necessary to use the C<< <[...]> >> form for the
repeated items being matched, so that all of them are saved in the
result hash. You can also save all the separators (if they're important)
by specifying them as a list-like subrule too:

    \(  <[number]>* % <[comma]>  \)  # save numbers *and* separators

The repeated item I<must> be specified as a subrule call of some kind
(i.e. in angles), but the separators may be specified either as a
subrule or as a raw bracketed pattern. For example:

    <[number]>* % ( , | : )    # Numbers separated by commas or colons

    <[number]>* % [,:]         # Same, but more efficiently matched

The separator should always be specified within matched delimiters of
some kind: either matching C<< <...> >> or matching C<(...)> or matching
C<[...]>. Simple, non-bracketed separators will sometimes also work:

    <[number]>+ % ,

but not always:

    <[number]>+ % ,\s+     # Oops! Separator is just: ,

This is because of the limited way in which the module internally parses
ordinary regex components (i.e. without full understanding of their
implicit precedence). As a consequence, consistently placing brackets
around any separator is a much safer approach:

    <[number]>+ % (,\s+)


You can also use a simple pattern on the left of the C<%> as the item
matcher, but in this case it I<must always> be aliased into a
list-collecting subrule, like so:

    <[item=(\d+)]>* % [,]


Note that, for backwards compatibility with earlier versions of
Regexp::Grammars, the C<+%> operator can also be written: C<**>.
However, there can be no space between the two asterisks of this
variant. That is:

    <[item]> ** <sep>      # same as <[item]>* % <sep>

    <[item]>* * <sep>      # error (two * qualifiers in a row)


=head2 Matching hash keys

In some situations a grammar may need a rule that matches dozens,
hundreds, or even thousands of one-word alternatives. For example, when
matching command names, or valid userids, or English words. In such
cases it is often impractical (and always inefficient) to list all the
alternatives between C<|> alterators:

    <rule: shell_cmd>
        a2p | ac | apply | ar | automake | awk | ...
        # ...and 400 lines later
        ... | zdiff | zgrep | zip | zmore | zsh

    <rule: valid_word>
        a | aa | aal | aalii | aam | aardvark | aardwolf | aba | ...
        # ...and 40,000 lines later...
        ... | zymotize | zymotoxic | zymurgy | zythem | zythum

To simplify such cases, Regexp::Grammars provides a special construct
that allows you to specify all the alternatives as the keys of a normal
hash. The syntax for that construct is simply to put the hash name
inside angle brackets (with no space between the angles and the hash name).

Which means that the rules in the previous example could also be written:

    <rule: shell_cmd>
        <%cmds>

    <rule: valid_word>
        <%dict>

provided that the two hashes (C<%cmds> and C<%dict>) are visible in the scope
where the grammar is created.

Matching a hash key in this way is typically I<significantly> faster
than matching a large set of alternations. Specifically, it is
I<O(length of longest potential key) ^ 2>, instead of I<O(number of keys)>.

Internally, the construct is converted to something equivalent to:

    <rule: shell_cmd>
        (<.hk>)  <require: (?{ exists $cmds{$CAPTURE} })>

    <rule: valid_word>
        (<.hk>)  <require: (?{ exists $dict{$CAPTURE} })>

The special C<< <hk> >> rule is created automatically, and defaults to
C<\S+>, but you can also define it explicitly to handle other kinds of
keys. For example:

    <rule: hk>
        [^\n]+        # Key may be any number of chars on a single line

    <rule: hk>
        [ACGT]{10,}   # Key is a base sequence of at least 10 pairs

Alternatively, you can specify a different key-matching pattern for
each hash you're matching, by placing the required pattern in braces
immediately after the hash name. For example:

    <rule: client_name>
        # Valid keys match <.hk> (default or explicitly specified)
        <%clients>

    <rule: shell_cmd>
        # Valid keys contain only word chars, hyphen, slash, or dot...
        <%cmds { [\w-/.]+ }>

    <rule: valid_word>
        # Valid keyss contain only alphas or internal hyphen or apostrophe...
        <%dict{ (?i: (?:[a-z]+[-'])* [a-z]+ ) }>

    <rule: DNA_sequence>
        # Valid keys are base sequences of at least 10 pairs...
        <%sequences{[ACGT]{10,}}>

This second approach to key-matching is preferred, because it localizes
any non-standard key-matching behaviour to each individual hash.

Note that changes in the compilation process from Perl 5.18 onwards
mean that in some cases the C<< <%hash> >> construct only works
reliably if the hash itself is declared at the outermost lexical scope
(i.e. file scope).

Specifically, if the regex grammar does not include any interpolated
scalars or arrays I<and> the hash was declared within a subroutine (even
within the same subroutine as the regex grammar that uses it), the regex
will not be able to "see" the hash variable at compile-time. This will
produce a I<"Global symbol "%hash" requires explicit package name">
compile-time error. For example:

    sub build_keyword_parser {
        # Hash declared inside subroutine...
        my %keywords = (foo => 1, bar => 1);

        # ...then used in <%hash> construct within uninterpolated regex...
        return qr{
                    ^<keyword>$
                    <rule: keyword> <%keywords>
                 }x;

        # ...produces compile-time error
    }

The solution is to place the hash outside the subroutine containing the
grammar:

    # Hash declared OUTSIDE subroutine...
    my %keywords = (foo => 1, bar => 1);

    sub build_keyword_parser {
        return qr{
                    ^<keyword>$
                    <rule: keyword> <%keywords>
                 }x;
    }


...or else to explicitly interpolate at least one scalar (even 
just a scalar containing an empty string):

    sub build_keyword_parser {
        my %keywords = (foo => 1, bar => 1);
        my $DEFER_REGEX_COMPILATION = "";

        return qr{
                    ^<keyword>$
                    <rule: keyword> <%keywords>

                    $DEFER_REGEX_COMPILATION
                 }x;
    }


=head2 Rematching subrule results

Sometimes it is useful to be able to rematch a string that has previously
been matched by some earlier subrule. For example, consider a rule to
match shell-like control blocks:

    <rule: control_block>
          for   <expr> <[command]>+ endfor
        | while <expr> <[command]>+ endwhile
        | if    <expr> <[command]>+ endif
        | with  <expr> <[command]>+ endwith

This would be much tidier if we could factor out the command names
(which are the only differences between the four alternatives). The
problem is that the obvious solution:

    <rule: control_block>
        <keyword> <expr>
            <[command]>+
        end<keyword>

doesn't work, because it would also match an incorrect input like:

    for 1..10
        echo $n
        ls subdir/$n
    endif

We need some way to ensure that the C<< <keyword> >> matched immediately
after "end" is the same C<< <keyword> >> that was initially matched.

That's not difficult, because the first C<< <keyword> >> will have
captured what it matched into C<$MATCH{keyword}>, so we could just
write:

    <rule: control_block>
        <keyword> <expr>
            <[command]>+
        end(??{quotemeta $MATCH{keyword}})

This is such a useful technique, yet so ugly, scary, and prone to error,
that Regexp::Grammars provides a cleaner equivalent:

    <rule: control_block>
        <keyword> <expr>
            <[command]>+
        end<\_keyword>

A directive of the form C<<< <\_I<IDENTIFIER>> >>> is known as a
"matchref" (an abbreviation of "%MATCH-supplied backreference").
Matchrefs always attempt to match, as a literal, the current value of
C<<< $MATCH{I<IDENTIFIER>} >>>.

By default, a matchref does not capture what it matches, but you
can have it do so by giving it an alias:

    <token: delimited_string>
        <ldelim=str_delim>  .*?  <rdelim=\_ldelim>

    <token: str_delim> ["'`]

At first glance this doesn't seem very useful as, by definition,
C<$MATCH{ldelim}> and C<$MATCH{rdelim}> must necessarily
always end up with identical values. However, it can be useful
if the rule also has other alternatives and you want to create a
consistent internal representation for those alternatives, like so:

    <token: delimited_string>
          <ldelim=str_delim>  .*?  <rdelim=\_ldelim>
        | <ldelim=( \[ )      .*?  <rdelim=( \] )
        | <ldelim=( \{ )      .*?  <rdelim=( \} )
        | <ldelim=( \( )      .*?  <rdelim=( \) )
        | <ldelim=( \< )      .*?  <rdelim=( \> )

You can also force a matchref to save repeated matches
as a nested array, in the usual way:

    <token: marked_text>
        <marker> <text> <[endmarkers=\_marker]>+

Be careful though, as the following will not do as you may expect:

        <[marker]>+ <text> <[endmarkers=\_marker]>+

because the value of C<$MATCH{marker}> will be an array reference, which
the matchref will flatten and concatenate, then match the
resulting string as a literal, which will mean the previous example will
match endmarkers that are exact multiples of the complete start marker,
rather than endmarkers that consist of any number of repetitions of the
individual start marker delimiter. So:

        ""text here""
        ""text here""""
        ""text here""""""

but not:

        ""text here"""
        ""text here"""""

Uneven start and end markers such as these are extremely unusual, so
this problem rarely arises in practice.


I<B<Note:> Prior to Regexp::Grammars version 1.020, the syntax for matchrefs
was C<<< <\I<IDENTIFIER>> >>> instead of C<<< <\_I<IDENTIFIER>> >>>. This
created problems when the identifier started with any of C<l>, C<u>, C<L>,
C<U>, C<Q>, or C<E>, so the syntax has had to be altered in a backwards
incompatible way. It will not be altered again.
>

=head2 Rematching balanced delimiters

Consider the example in the previous section:

    <token: delimited_string>
          <ldelim=str_delim>  .*?  <rdelim=\_ldelim>
        | <ldelim=( \[ )      .*?  <rdelim=( \] )
        | <ldelim=( \{ )      .*?  <rdelim=( \} )
        | <ldelim=( \( )      .*?  <rdelim=( \) )
        | <ldelim=( \< )      .*?  <rdelim=( \> )

The repeated pattern of the last four alternatives is gauling,
but we can't just refactor those delimiters as well:

    <token: delimited_string>
          <ldelim=str_delim>  .*?  <rdelim=\_ldelim>
        | <ldelim=bracket>    .*?  <rdelim=\_ldelim>

because that would incorrectly match:

    { delimited content here {

while failing to match:

    { delimited content here }

To refactor balanced delimiters like those, we need a second
kind of matchref; one that's a little smarter.

Or, preferably, a lot smarter...because there are many other kinds of
balanced delimiters, apart from single brackets. For example:

      {{{ delimited content here }}}
       /* delimited content here */
       (* delimited content here *)
       `` delimited content here ''
       if delimited content here fi

The common characteristic of these delimiter pairs is that the closing
delimiter is the I<inverse> of the opening delimiter: the sequence of
characters is reversed and certain characters (mainly brackets, but also
single-quotes/backticks) are mirror-reflected.

Regexp::Grammars supports the parsing of such delimiters with a
construct known as an I<invertref>, which is specified using the
C<<< </I<IDENT>> >>> directive. An invertref acts very like a
L<matchref|"Rematching subrule results">, except that it does not
convert to:

    (??{ quotemeta( $MATCH{I<IDENT>} ) })

but rather to:

    (??{ quotemeta( inverse( $MATCH{I<IDENT> ))} })

With this directive available, the balanced delimiters of the previous
example can be refactored to:

    <token: delimited_string>
          <ldelim=str_delim>  .*?  <rdelim=\_ldelim>
        | <ldelim=( [[{(<] )  .*?  <rdelim=/ldelim>

Like matchrefs, invertrefs come in the usual range of flavours:

    </ident>            # Match the inverse of $MATCH{ident}
    <ALIAS=/ident>      # Match inverse and capture to $MATCH{ident}
    <[ALIAS=/ident]>    # Match inverse and push on @{$MATCH{ident}}

The character pairs that are reversed during mirroring are: C<{> and C<}>,
C<[> and C<]>, C<(> and C<)>, C<< < >> and C<< > >>, C<«> and C<»>,
C<`> and C<'>.

The following mnemonics may be useful in distinguishing inverserefs from
backrefs: a backref starts with a C<\> (just like the standard Perl
regex backrefs C<\1> and C<\g{-2}> and C<< \k<name> >>), whereas an
inverseref starts with a C</> (like an HTML or XML closing tag). Or
just remember that C<< <\_IDENT> >> is "match the same again", and if you
want "the same again, only mirrored" instead, just mirror the C<\>
to get C<< </IDENT> >>.


=head2 Rematching parametric results and delimiters

The C<< <\I<IDENTIFIER>> >> and C<< </I<IDENTIFIER>> >> mechanisms
normally locate the literal to be matched by looking in
C<$MATCH{I<IDENTIFIER>}>.

However, you can cause them to look in C<$ARG{I<IDENTIFIER>}> instead,
by prefixing the identifier with a single C<:>. This is especially
useful when refactoring subrules. For example, instead of:

    <rule: Command>
        <Keyword>  <CommandBody>  end_ <\_Keyword>

    <rule: Placeholder>
        <Keyword>    \.\.\.   end_ <\_Keyword>

you could parameterize the Terminator rule, like so:

    <rule: Command>
        <Keyword>  <CommandBody>  <Terminator(:Keyword)>

    <rule: Placeholder>
        <Keyword>    \.\.\.   <Terminator(:Keyword)>

    <token: Terminator>
        end_ <\:Keyword>


=head2 Tracking and reporting match positions

Regexp::Grammars automatically predefines a special token that makes it
easy to track exactly where in its input a particular subrule matches.
That token is: C<< <matchpos> >>.

The C<< <matchpos> >> token implements a zero-width match that never
fails. It always returns the current index within the string that the
grammar is matching.

So, for example you could have your C<< <delimited_text> >> subrule
detect and report unterminated text like so:

    <token: delimited_text>
        qq? <delim> <text=(.*?)> </delim>
    |
        <matchpos> qq? <delim>
        <error: (?{"Unterminated string starting at index $MATCH{matchpos}"})>

Matching C<< <matchpos> >> in the second alternative causes
C<$MATCH{matchpos}> to contain the position in the string at which the
C<< <matchpos> >> subrule was matched (in this example: the start of the
unterminated text).

If you want the line number instead of the string index, use the
predefined C<< <matchline> >> subrule instead:

    <token: delimited_text>
              qq? <delim> <text=(.*?)> </delim>
    |   <matchline> qq? <delim>
        <error: (?{"Unterminated string starting at line $MATCH{matchline}"})>

Note that the line numbers returned by C<< <matchline> >> start at 1
(not at zero, as with C<< <matchpos> >>).

The C<< <matchpos> >> and C<< <matchline> >> subrules are just like any
other subrules; you can alias them (C<< <started_at=matchpos> >>) or
match them repeatedly ( C<< (?: <[matchline]> <[item]> )++ >>), etc.


=head1 Autoactions

The module also supports event-based parsing. You can specify a grammar
in the usual way and then, for a particular parse, layer a collection of
call-backs (known as "autoactions") over the grammar to handle the data
as it is parsed.

Normally, a grammar rule returns the result hash it has accumulated
(or whatever else was aliased to C<MATCH=> within the rule). However,
you can specify an autoaction object before the grammar is matched.

Once the autoaction object is specified, every time a rule succeeds
during the parse, its result is passed to the object via one of its
methods; specifically it is passed to the method whose name is the same
as the rule's.

For example, suppose you had a grammar that recognizes simple algebraic
expressions:

    my $expr_parser = do{
        use Regexp::Grammars;
        qr{
            <Expr>

            <rule: Expr>       <[Operand=Mult]>+ % <[Op=(\+|\-)]>

            <rule: Mult>       <[Operand=Pow]>+  % <[Op=(\*|/|%)]>

            <rule: Pow>        <[Operand=Term]>+ % <Op=(\^)>

            <rule: Term>          <MATCH=Literal>
                       |       \( <MATCH=Expr> \)

            <token: Literal>   <MATCH=( [+-]? \d++ (?: \. \d++ )?+ )>
        }xms
    };

You could convert this grammar to a calculator, by installing a set of
autoactions that convert each rule's result hash to the corresponding
value of the sub-expression that the rule just parsed. To do that, you
would create a class with methods whose names match the rules whose
results you want to change. For example:

    package Calculator;
    use List::Util qw< reduce >;

    sub new {
        my ($class) = @_;

        return bless {}, $class
    }

    sub Answer {
        my ($self, $result_hash) = @_;

        my $sum = shift @{$result_hash->{Operand}};

        for my $term (@{$result_hash->{Operand}}) {
            my $op = shift @{$result_hash->{Op}};
            if ($op eq '+') { $sum += $term; }
            else            { $sum -= $term; }
        }

        return $sum;
    }

    sub Mult {
        my ($self, $result_hash) = @_;

        return reduce { eval($a . shift(@{$result_hash->{Op}}) . $b) }
                      @{$result_hash->{Operand}};
    }

    sub Pow {
        my ($self, $result_hash) = @_;

        return reduce { $b ** $a } reverse @{$result_hash->{Operand}};
    }


Objects of this class (and indeed the class itself) now have methods
corresponding to some of the rules in the expression grammar. To
apply those methods to the results of the rules (as they parse) you
simply install an object as the "autoaction" handler, immediately
before you initiate the parse:

    if ($text ~= $expr_parser->with_actions(Calculator->new)) {
        say $/{Answer};   # Now prints the result of the expression
    }

The C<with_actions()> method expects to be passed an object or
classname. This object or class will be installed as the autoaction
handler for the next match against any grammar. After that match, the
handler will be uninstalled. C<with_actions()> returns the grammar it's
called on, making it easy to call it as part of a match (which is the
recommended idiom).

With a C<Calculator> object set as the autoaction handler, whenever
the C<Answer>, C<Mult>, or C<Pow> rule of the grammar matches, the
corresponding C<Answer>, C<Mult>, or C<Pow> method of the
C<Calculator> object will be called (with the rule's result value
passed as its only argument), and the result of the method will be
used as the result of the rule.

Note that nothing new happens when a C<Term> or C<Literal> rule matches,
because the C<Calculator> object doesn't have methods with those names.

The overall effect, then, is to allow you to specify a grammar without
rule-specific bahaviours and then, later, specify a set of final actions
(as methods) for some or all of the rules of the grammar.

Note that, if a particular callback method returns C<undef>, the result
of the corresponding rule will be passed through without modification.


=head1 Named grammars

All the grammars shown so far are confined to a single regex. However,
Regexp::Grammars also provides a mechanism that allows you to defined
named grammars, which can then be imported into other regexes. This
gives the a way of modularizing common grammatical components.

=head2 Defining a named grammar

You can create a named grammar using the C<< <grammar:...> >>
directive. This directive must appear before the first rule definition
in the grammar, and instead of any start-rule. For example:

    qr{
        <grammar: List::Generic>

        <rule: List>
            <MATCH=[Item]>+ % <Separator>

        <rule: Item>
            \S++

        <token: Separator>
            \s* , \s*
    }x;

This creates a grammar named C<List::Generic>, and installs it in the module's
internal caches, for future reference.

Note that there is no need (or reason) to assign the resulting regex to
a variable, as the named grammar cannot itself be matched against.


=head2 Using a named grammar

To make use of a named grammar, you need to incorporate it into another
grammar, by inheritance. To do that, use the C<< <extends:...> >>
directive, like so:

    my $parser = qr{
        <extends: List::Generic>

        <List>
    }x;

The C<< <extends:...> >> directive incorporates the rules defined in the
specified grammar into the current regex. You can then call any of those
rules in the start-pattern.


=head2 Overriding an inherited rule or token

Subrule dispatch within a grammar is always polymorphic. That is, when a
subrule is called, the most-derived rule of the same name within the
grammar's hierarchy is invoked.

So, to replace a particular rule within grammar, you simply need to inherit
that grammar and specify new, more-specific versions of any rules you
want to change. For example:

    my $list_of_integers = qr{
        <List>

        # Inherit rules from base grammar...
        <extends: List::Generic>

        # Replace Item rule from List::Generic...
        <rule: Item>
            [+-]? \d++
    }x;

You can also use C<< <extends:...> >> in other named grammars, to create
hierarchies:

    qr{
        <grammar: List::Integral>
        <extends: List::Generic>

        <token: Item>
            [+-]? <MATCH=(<.Digit>+)>

        <token: Digit>
            \d
    }x;

    qr{
        <grammar: List::ColonSeparated>
        <extends: List::Generic>

        <token: Separator>
            \s* : \s*
    }x;

    qr{
        <grammar: List::Integral::ColonSeparated>
        <extends: List::Integral>
        <extends: List::ColonSeparated>
    }x;

As shown in the previous example, Regexp::Grammars allows you
to multiply inherit two (or more) base grammars. For example, the
C<List::Integral::ColonSeparated> grammar takes the definitions of
C<List> and C<Item> from the C<List::Integral> grammar, and the
definition of C<Separator> from C<List::ColonSeparated>.

Note that grammars dispatch subrule calls using C3 method lookup, rather
than Perl's older DFS lookup. That's why C<List::Integral::ColonSeparated>
correctly gets the more-specific C<Separator> rule defined in
C<List::ColonSeparated>, rather than the more-generic version defined in
C<List::Generic> (via C<List::Integral>). See C<perldoc mro> for more
discussion of the C3 dispatch algorithm.


=head2 Augmenting an inherited rule or token

Instead of replacing an inherited rule, you can augment it.

For example, if you need a grammar for lists of hexademical
numbers, you could inherit the behaviour of C<List::Integral>
and add the hex digits to its C<Digit> token:

    my $list_of_hexadecimal = qr{
        <List>

        <extends: List::Integral>

        <token: Digit>
            <List::Integral::Digit>
          | [A-Fa-f]
    }x;

If you call a subrule using a fully qualified name (such as
C<< <List::Integral::Digit> >>), the grammar calls that
version of the rule, rather than the most-derived version.


=head2 Debugging named grammars

Named grammars are independent of each other, even when inherited. This
means that, if debugging is enabled in a derived grammar, it will not be
active in any rules inherited from a base grammar, unless the base
grammar also included a C<< <debug:...> >> directive.

This is a deliberate design decision, as activating the debugger adds a
significant amount of code to each grammar's implementation, which is
detrimental to the matching performance of the resulting regexes.

If you need to debug a named grammar, the best approach is to include a
C<< <debug: same> >> directive at the start of the grammar. The presence
of this directive will ensure the necessary extra debugging code is
included in the regex implementing the grammar, while setting C<same>
mode will ensure that the debugging mode isn't altered when the matcher
uses the inherited rules.


=head1 Common parsing techniques

=head2 Result distillation

Normally, calls to subrules produce nested result-hashes within the
current result-hash. Those nested hashes always have at least one
automatically supplied key (C<"">), whose value is the entire substring
that the subrule matched.

If there are no other nested captures within the subrule, there will be
no other keys in the result-hash. This would be annoying as a typical
nested grammar would then produce results consisting of hashes of
hashes, with each nested hash having only a single key (C<"">). This in
turn would make postprocessing the result-hash (in C<%/>) far more
complicated than it needs to be.

To avoid this behaviour, if a subrule's result-hash doesn't contain any keys
except C<"">, the module "flattens" the result-hash, by replacing it with
the value of its single key.

So, for example, the grammar:

    mv \s* <from> \s* <to>

    <rule: from>   [\w/.-]+
    <rule: to>     [\w/.-]+

I<doesn't> return a result-hash like this:

    {
        ""     => 'mv /usr/local/lib/libhuh.dylib  /dev/null/badlib',
        'from' => { "" => '/usr/local/lib/libhuh.dylib' },
        'to'   => { "" => '/dev/null/badlib'            },
    }

Instead, it returns:

    {
        ""     => 'mv /usr/local/lib/libhuh.dylib  /dev/null/badlib',
        'from' => '/usr/local/lib/libhuh.dylib',
        'to'   => '/dev/null/badlib',
    }

That is, because the C<'from'> and C<'to'> subhashes each have only a single
entry, they are each "flattened" to the value of that entry.

This flattening also occurs if a result-hash contains only "private" keys
(i.e. keys starting with underscores). For example:

    mv \s* <from> \s* <to>

    <rule: from>   <_dir=path>? <_file=filename>
    <rule: to>     <_dir=path>? <_file=filename>

    <token: path>      [\w/.-]*/
    <token: filename>  [\w.-]+

Here, the C<from> rule produces a result like this:

    from => {
          "" => '/usr/local/bin/perl',
        _dir => '/usr/local/bin/',
       _file => 'perl',
    }

which is automatically stripped of "private" keys, leaving:

    from => {
          "" => '/usr/local/bin/perl',
    }

which is then automatically flattened to:

    from => '/usr/local/bin/perl'


=head3 List result distillation

A special case of result distillation occurs in a separated
list, such as:

    <rule: List>

        <[Item]>+ % <[Sep=(,)]>

If this construct matches just a single item, the result hash will
contain a single entry consisting of a nested array with a single
value, like so:

    { Item => [ 'data' ] }

Instead of returning this annoyingly nested data structure, you can tell
Regexp::Grammars to flatten it to just the inner data with a special
directive:

    <rule: List>

        <[Item]>+ % <[Sep=(,)]>

        <minimize:>

The C<< <minimize:> >> directive examines the result hash (i.e.
C<%MATCH>). If that hash contains only a single entry, which is a
reference to an array with a single value, then the directive assigns
that single value directly to C<$MATCH>, so that it will be returned
instead of the usual result hash.

This means that a normal separated list still results in a hash
containing all elements and separators, but a "degenerate" list of only
one item results in just that single item.


=head3 Manual result distillation

Regexp::Grammars also offers full manual control over the distillation
process. If you use the reserved word C<MATCH> as the alias for
a subrule call:

    <MATCH=filename>

or a subpattern match:

    <MATCH=( \w+ )>

or a code block:

    <MATCH=(?{ 42 })>

then the current rule will treat the return value of that subrule,
pattern, or code block as its complete result, and return that value
instead of the usual result-hash it constructs. This is the case even if
the result has other entries that would normally also be returned.

For example, in a rule like:

    <rule: term>
          <MATCH=literal>
        | <left_paren> <MATCH=expr> <right_paren>

The use of C<MATCH> aliases causes the rule to return either whatever
C<< <literal> >> returns, or whatever C<< <expr> >> returns (provided
it's between left and right parentheses).

Note that, in this second case, even though C<< <left_paren> >> and
C<< <right_paren> >> I<are> captured to the result-hash, they are
not returned, because the C<MATCH> alias overrides the normal "return
the result-hash" semantics and returns only what its associated
subrule (i.e. C<< <expr> >>) produces.


=head3 Programmatic result distillation

It's also possible to control what a rule returns from within a code block.
Regexp::Grammars provides a set of reserved variables that give direct
access to the result-hash.

The result-hash itself can be accessed as C<%MATCH> within any code block
inside a rule. For example:

    <rule: sum>
        <X=product> \+ <Y=product>
            <MATCH=(?{ $MATCH{X} + $MATCH{Y} })>

Here, the rule matches a product (aliased C<'X'> in the result-hash),
then a literal C<'+'>, then another product (aliased to C<'Y'> in the
result-hash). The rule then executes the code block, which accesses the two
saved values (as C<$MATCH{X}> and C<$MATCH{Y}>), adding them together.
Because the block is itself aliased to C<MATCH>, the sum produced by the block
becomes the (only) result of the rule.

It is also possible to set the rule result from within a code block (instead
of aliasing it). The special "override" return value is represented by the
special variable C<$MATCH>. So the previous example could be rewritten:

    <rule: sum>
        <X=product> \+ <Y=product>
            (?{ $MATCH = $MATCH{X} + $MATCH{Y} })

Both forms are identical in effect. Any assignment to C<$MATCH> overrides the
normal "return all subrule results" behaviour.

Assigning to C<$MATCH> directly is particularly handy if the result
may not always be "distillable", for example:

    <rule: sum>
        <X=product> \+ <Y=product>
            (?{ if (!ref $MATCH{X} && !ref $MATCH{Y}) {
                    # Reduce to sum, if both terms are simple scalars...
                    $MATCH = $MATCH{X} + $MATCH{Y};
                }
                else {
                    # Return full syntax tree for non-simple case...
                    $MATCH{op} = '+';
                }
            })

Note that you can also partially override the subrule return behaviour.
Normally, the subrule returns the complete text it matched as its context
substring (i.e. under the "empty key") in its result-hash. That is, of
course, C<$MATCH{""}>, so you can override just that behaviour by
directly assigning to that entry.

For example, if you have a rule that matches key/value pairs from a
configuration file, you might prefer that any trailing comments not be
included in the "matched text" entry of the rule's result-hash. You could
hide such comments like so:

    <rule: config_line>
        <key> : <value>  <comment>?
            (?{
                # Edit trailing comments out of "matched text" entry...
                $MATCH = "$MATCH{key} : $MATCH{value}";
            })

Some more examples of the uses of C<$MATCH>:

    <rule: FuncDecl>
      # Keyword  Name               Keep return the name (as a string)...
        func     <Identifier> ;     (?{ $MATCH = $MATCH{'Identifier'} })


    <rule: NumList>
      # Numbers in square brackets...
        \[
            ( \d+ (?: , \d+)* )
        \]

      # Return only the numbers...
        (?{ $MATCH = $CAPTURE })


    <token: Cmd>
      # Match standard variants then standardize the keyword...
        (?: mv | move | rename )      (?{ $MATCH = 'mv'; })


=head2 Parse-time data processing

Using code blocks in rules, it's often possible to fully process data as
you parse it. For example, the C<< <sum> >> rule shown in the previous section
might be part of a simple calculator, implemented entirely in a single
grammar. Such a calculator might look like this:


    my $calculator = do{
        use Regexp::Grammars;
        qr{
            <Answer>

            <rule: Answer>
                ( <.Mult>+ % <.Op=([+-])> )
                    <MATCH= (?{ eval $CAPTURE })>

            <rule: Mult>
                ( <.Pow>+ % <.Op=([*/%])> )
                    <MATCH= (?{ eval $CAPTURE })>

            <rule: Pow>
                <X=Term> \^ <Y=Pow>
                    <MATCH= (?{ $MATCH{X} ** $MATCH{Y}; })>
              |
                    <MATCH=Term>

            <rule: Term>
                    <MATCH=Literal>
              | \(  <MATCH=Answer>  \)

            <token: Literal>
                    <MATCH= ( [+-]? \d++ (?: \. \d++ )?+ )>
        }xms
    };

    while (my $input = <>) {
        if ($input =~ $calculator) {
            say "--> $/{Answer}";
        }
    }

Because every rule computes a value using the results of the subrules
below it, and aliases that result to its C<MATCH>, each rule returns a
complete evaluation of the subexpression it matches, passing that back
to higher-level rules, which then do the same.

Hence, the result returned to the very top-level rule (i.e. to C<<
<Answer> >>) is the complete evaluation of the entire expression that
was matched. That means that, in the very process of having matched a
valid expression, the calculator has also computed the value of that
expression, which can then simply be printed directly.

It is often possible to have a grammar fully (or sometimes at least
partially) evaluate or transform the data it is parsing, and this
usually leads to very efficient and easy-to-maintain implementations.

The main limitation of this technique is that the data has to be in a
well-structured form, where subsets of the data can be evaluated using
only local information. In cases where the meaning of the data is
distributed through that data non-hierarchically, or relies on global
state, or on external information, it is often better to have the grammar
simply construct a complete syntax tree for the data first, and then evaluate
that syntax tree separately, after parsing is complete. The following section
describes a feature of Regexp::Grammars that can make this second style of
data processing simpler and more maintainable.


=head2 Object-oriented parsing

When a grammar has parsed successfully, the C<%/> variable will contain a
series of nested hashes (and possibly arrays) representing the hierarchical
structure of the parsed data.

Typically, the next step is to walk that tree, extracting or
converting or otherwise processing that information. If the tree has nodes of
many different types, it can be difficult to build a recursive subroutine that
can navigate it easily.

A much cleaner solution is possible if the nodes of the tree are proper
objects.  In that case, you just define a C<process()> or C<traverse()> method
for eah of the classes, and have every node call that method on each of its
children. For example, if the parser were to return a tree of nodes
representing the contents of a LaTeX file, then you could define the following
methods:

    sub Latex::file::explain
    {
        my ($self, $level) = @_;
        for my $element (@{$self->{element}}) {
            $element->explain($level);
        }
    }

    sub Latex::element::explain {
        my ($self, $level) = @_;
        (  $self->{command} || $self->{literal})->explain($level)
    }

    sub Latex::command::explain {
        my ($self, $level) = @_;
        say "\t"x$level, "Command:";
        say "\t"x($level+1), "Name: $self->{name}";
        if ($self->{options}) {
            say "\t"x$level, "\tOptions:";
            $self->{options}->explain($level+2)
        }

        for my $arg (@{$self->{arg}}) {
            say "\t"x$level, "\tArg:";
            $arg->explain($level+2)
        }
    }

    sub Latex::options::explain {
        my ($self, $level) = @_;
        $_->explain($level) foreach @{$self->{option}};
    }

    sub Latex::literal::explain {
        my ($self, $level, $label) = @_;
        $label //= 'Literal';
        say "\t"x$level, "$label: ", $self->{q{}};
    }

and then simply write:

    if ($text =~ $LaTeX_parser) {
        $/{LaTeX_file}->explain();
    }

and the chain of C<explain()> calls would cascade down the nodes of the tree,
each one invoking the appropriate C<explain()> method according to the type of
node encountered.

The only problem is that, by default, Regexp::Grammars returns a tree of
plain-old hashes, not LaTeX::Whatever objects. Fortunately, it's easy to
request that the result hashes be automatically blessed into the appropriate
classes, using the C<< <objrule:...> >> and C<< <objtoken:...> >> directives.

These directives are identical to the C<< <rule:...> >> and C<<
<token:...> >> directives (respectively), except that the rule or token
they create will also convert the hash it normally returns into an
object of a specified class. This conversion is done by passing the result
hash to the class's constructor:

    $class->new(\%result_hash)

if the class has a constructor method named C<new()>, or else (if
the class doesn't provide a constructor) by directly blessing the
result hash:

    bless \%result_hash, $class

Note that, even if object is constructed via its own constructor, the
module still expects the new object to be hash-based, and will fail if
the object is anything but a blessed hash. The module issues an
error in this case.

The generic syntax for these types of rules and tokens is:

    <objrule:  CLASS::NAME = RULENAME  >
    <objtoken: CLASS::NAME = TOKENNAME >

For example:

    <objrule: LaTeX::Element=component>
        # ...Defines a rule that can be called as <component>
        # ...and which returns a hash-based LaTeX::Element object

    <objtoken: LaTex::Literal=atom>
        # ...Defines a token that can be called as <atom>
        # ...and which returns a hash-based LaTeX::Literal object

Note that, just as in L<aliased subrule calls|"Renaming subrule results">,
the name by which something is referred to outside the grammar (in this
case, the class name) comes I<before> the C<=>, whereas the name that it
is referred to inside the grammar comes I<after> the C<=>.

You can freely mix object-returning and plain-old-hash-returning rules
and tokens within a single grammar, though you have to be careful not to
subsequently try to call a method on any of the unblessed nodes.

=head4 An important caveat regarding OO rules

Prior to Perl 5.14.0, Perl's regex engine was not fully re-entrant.
This means that in older versions of Perl, it is not possible to
re-invoke the regex engine when already inside the regex engine.

This means that you need to be careful that the C<new()>
constructors that are called by your object-rules do not themselves
use regexes in any way, unless you're running under Perl 5.14 or later
(in which case you can ignore what follows).

The two ways this is most likely to happen are:

=over

=item 1.

If you're using a class built on Moose, where one or more of the C<has>
uses a type constraint (such as C<'Int'>) that is implemented via regex
matching. For example:

    has 'id' => (is => 'rw', isa => 'Int');

The workaround (for pre-5.14 Perls) is to replace the type
constraint with one that doesn't use a regex. For example:

    has 'id' => (is => 'rw', isa => 'Num');

Alternatively, you could define your own type constraint that
avoids regexes:

    use Moose::Util::TypeConstraints;

    subtype 'Non::Regex::Int',
         as 'Num',
      where { int($_) == $_ };

    no Moose::Util::TypeConstraints;

    # and later...

    has 'id' => (is => 'rw', isa => 'Non::Regex::Int');

=item 2.

If your class uses an C<AUTOLOAD()> method to implement its constructor
and that method uses the typical:

    $AUTOLOAD =~ s/.*://;

technique. The workaround here is to achieve the same effect without a
regex. For example:

    my $last_colon_pos = rindex($AUTOLOAD, ':');
    substr $AUTOLOAD, 0, $last_colon_pos+1, q{};

=back

Note that this caveat against using nested regexes also applies to any
code blocks executed inside a rule or token (whether or not those rules
or tokens are object-oriented).

=head3 A naming shortcut

If an C<< <objrule:...> >> or C<< <objtoken:...> >> is defined with a
class name that is I<not> followed by C<=> and a rule name, then the
rule name is determined automatically from the classname.
Specifically, the final component of the classname (i.e. after the last
C<::>, if any) is used.

For example:

    <objrule: LaTeX::Element>
        # ...Defines a rule that can be called as <Element>
        # ...and which returns a hash-based LaTeX::Element object

    <objtoken: LaTex::Literal>
        # ...Defines a token that can be called as <Literal>
        # ...and which returns a hash-based LaTeX::Literal object

    <objtoken: Comment>
        # ...Defines a token that can be called as <Comment>
        # ...and which returns a hash-based Comment object


=head1 Debugging

Regexp::Grammars provides a number of features specifically designed to help
debug both grammars and the data they parse.

All debugging messages are written to a log file (which, by default, is
just STDERR). However, you can specify a disk file explicitly by placing a
C<< <logfile:...> >> directive at the start of your grammar:

    $grammar = qr{

        <logfile: LaTeX_parser_log >

        \A <LaTeX_file> \Z    # Pattern to match

        <rule: LaTeX_file>
            # etc.
    }x;

You can also explicitly specify that messages go to the terminal:

        <logfile: - >


=head2 Debugging grammar creation with C<< <logfile:...> >>

Whenever a log file has been directly specified,
Regexp::Grammars automatically does verbose static analysis of your grammar.
That is, whenever it compiles a grammar containing an explicit
C<< <logfile:...> >> directive it logs a series of messages explaining how it
has interpreted the various components of that grammar. For example, the
following grammar:

    <logfile: parser_log >

    <cmd>

    <rule: cmd>
        mv <from=file> <to=file>
      | cp <source> <[file]>  <.comment>?

would produce the following analysis in the 'parser_log' file:

    info | Processing the main regex before any rule definitions
         |    |
         |    |...Treating <cmd> as:
         |    |      |  match the subrule <cmd>
         |    |       \ saving the match in $MATCH{'cmd'}
         |    |
         |     \___End of main regex
         |
    info | Defining a rule: <cmd>
         |    |...Returns: a hash
         |    |
         |    |...Treating ' mv ' as:
         |    |       \ normal Perl regex syntax
         |    |
         |    |...Treating <from=file> as:
         |    |      |  match the subrule <file>
         |    |       \ saving the match in $MATCH{'from'}
         |    |
         |    |...Treating <to=file> as:
         |    |      |  match the subrule <file>
         |    |       \ saving the match in $MATCH{'to'}
         |    |
         |    |...Treating ' | cp ' as:
         |    |       \ normal Perl regex syntax
         |    |
         |    |...Treating <source> as:
         |    |      |  match the subrule <source>
         |    |       \ saving the match in $MATCH{'source'}
         |    |
         |    |...Treating <[file]> as:
         |    |      |  match the subrule <file>
         |    |       \ appending the match to $MATCH{'file'}
         |    |
         |    |...Treating <.comment>? as:
         |    |      |  match the subrule <comment> if possible
         |    |       \ but don't save anything
         |    |
         |     \___End of rule definition

This kind of static analysis is a useful starting point in debugging a
miscreant grammar, because it enables you to see what you actually
specified (as opposed to what you I<thought> you'd specified).


=head2 Debugging grammar execution with C<< <debug:...> >>

Regexp::Grammars also provides a simple interactive debugger, with which you
can observe the process of parsing and the data being collected in any
result-hash.

To initiate debugging, place a C<< <debug:...> >> directive anywhere in your
grammar. When parsing reaches that directive the debugger will be activated,
and the command specified in the directive immediately executed. The available
commands are:

    <debug: on>    - Enable debugging, stop when a rule matches
    <debug: match> - Enable debugging, stop when a rule matches
    <debug: try>   - Enable debugging, stop when a rule is tried
    <debug: run>   - Enable debugging, run until the match completes
    <debug: same>  - Continue debugging (or not) as currently
    <debug: off>   - Disable debugging and continue parsing silently

    <debug: continue> - Synonym for <debug: run>
    <debug: step>     - Synonym for <debug: try>

These directives can be placed anywhere within a grammar and take effect
when that point is reached in the parsing. Hence, adding a
C<< <debug:step> >> directive is very much like setting a breakpoint at that
point in the grammar. Indeed, a common debugging strategy is to turn
debugging on and off only around a suspect part of the grammar:

    <rule: tricky>   # This is where we think the problem is...
        <debug:step>
        <preamble> <text> <postscript>
        <debug:off>

Once the debugger is active, it steps through the parse, reporting rules
that are tried, matches and failures, backtracking and restarts, and the
parser's location within both the grammar and the text being matched. That
report looks like this:

    ===============> Trying <grammar> from position 0
    > cp file1 file2 |...Trying <cmd>
                     |   |...Trying <cmd=(cp)>
                     |   |    \FAIL <cmd=(cp)>
                     |    \FAIL <cmd>
                      \FAIL <grammar>
    ===============> Trying <grammar> from position 1
     cp file1 file2  |...Trying <cmd>
                     |   |...Trying <cmd=(cp)>
     file1 file2     |   |    \_____<cmd=(cp)> matched 'cp'
    file1 file2      |   |...Trying <[file]>+
     file2           |   |    \_____<[file]>+ matched 'file1'
                     |   |...Trying <[file]>+
    [eos]            |   |    \_____<[file]>+ matched ' file2'
                     |   |...Trying <[file]>+
                     |   |    \FAIL <[file]>+
                     |   |...Trying <target>
                     |   |   |...Trying <file>
                     |   |   |    \FAIL <file>
                     |   |    \FAIL <target>
     <~~~~~~~~~~~~~~ |   |...Backtracking 5 chars and trying new match
    file2            |   |...Trying <target>
                     |   |   |...Trying <file>
                     |   |   |    \____ <file> matched 'file2'
    [eos]            |   |    \_____<target> matched 'file2'
                     |    \_____<cmd> matched ' cp file1 file2'
                      \_____<grammar> matched ' cp file1 file2'

The first column indicates the point in the input at which the parser is
trying to match, as well as any backtracking or forward searching it may
need to do. The remainder of the columns track the parser's hierarchical
traversal of the grammar, indicating which rules are tried, which
succeed, and what they match.


Provided the logfile is a terminal (as it is by default), the debugger
also pauses at various points in the parsing process--before trying a
rule, after a rule succeeds, or at the end of the parse--according to
the most recent command issued. When it pauses, you can issue a new
command by entering a single letter:

    m       - to continue until the next subrule matches
    t or s  - to continue until the next subrule is tried
    r or c  - to continue to the end of the grammar
    o       - to switch off debugging

Note that these are the first letters of the corresponding
C<< <debug:...> >> commands, listed earlier. Just hitting ENTER while the
debugger is paused repeats the previous command.

While the debugger is paused you can also type a 'd', which will display
the result-hash for the current rule. This can be useful for detecting
which rule isn't returning the data you expected.


=head3 Resizing the context string

By default, the first column of the debugger output (which shows the
current matching position within the string) is limited to a width of
20 columns.

However, you can change that limit calling the
C<Regexp::Grammars::set_context_width()> subroutine. You have to specify
the fully qualified name, however, as Regexp::Grammars does not export
this (or any other) subroutine.

C<set_context_width()> expects a single argument: a positive integer
indicating the maximal allowable width for the context column. It issues
a warning if an invalid value is passed, and ignores it.

If called in a void context, C<set_context_width()> changes the context
width permanently throughout your application. If called in a scalar or
list context, C<set_context_width()> returns an object whose destructor
will cause the context width to revert to its previous value. This means
you can temporarily change the context width within a given block with
something like:

    {
        my $temporary = Regexp::Grammars::set_context_width(50);

        if ($text =~ $parser) {
            do_stuff_with( %/ );
        }

    } # <--- context width automagically reverts at this point

and the context width will change back to its previous value when
C<$temporary> goes out of scope at the end of the block.


=head2 User-defined logging with C<< <log:...> >>

Both static and interactive debugging send a series of predefined log messages
to whatever log file you have specified. It is also possible to send
additional, user-defined messages to the log, using the C<< <log:...> >>
directive.

This directive expects either a simple text or a codeblock as its single
argument. If the argument is a code block, that code is expected to
return the text of the message; if the argument is anything else, that
something else I<is> the literal message. For example:

    <rule: ListElem>

        <Elem=   ( [a-z]\d+) >
            <log: Checking for a suffix, too...>

        <Suffix= ( : \d+   ) >?
            <log: (?{ "ListElem: $MATCH{Elem} and $MATCH{Suffix}" })>

User-defined log messages implemented using a codeblock can also specify
a severity level. If the codeblock of a C<< <log:...> >> directive
returns two or more values, the first is treated as a log message
severity indicator, and the remaining values as separate lines of text
to be logged. For example:

    <rule: ListElem>
        <Elem=   ( [a-z]\d+) >
        <Suffix= ( : \d+   ) >?

            <log: (?{
                warn => "Elem was: $MATCH{Elem}",
                        "Suffix was $MATCH{Suffix}",
            })>

When they are encountered, user-defined log messages are interspersed
between any automatic log messages (i.e. from the debugger), at the correct
level of nesting for the current rule.


=head2 Debugging non-grammars

I<[Note that, with the release in 2012 of the Regexp::Debugger module (on
CPAN) the techniques described below are unnecessary. If you need to
debug plain Perl regexes, use Regexp::Debugger instead.]>

It is possible to use Regexp::Grammars without creating I<any> subrule
definitions, simply to debug a recalcitrant regex. For example, if the
following regex wasn't working as expected:

    my $balanced_brackets = qr{
        \(             # left delim
        (?:
            \\         # escape or
        |   (?R)       # recurse or
        |   .          # whatever
        )*
        \)             # right delim
    }xms;

you could instrument it with aliased subpatterns and then debug it
step-by-step, using Regexp::Grammars:

    use Regexp::Grammars;

    my $balanced_brackets = qr{
        <debug:step>

        <.left_delim=  (  \(  )>
        (?:
            <.escape=  (  \\  )>
        |   <.recurse= ( (?R) )>
        |   <.whatever=(  .   )>
        )*
        <.right_delim= (  \)  )>
    }xms;

    while (<>) {
        say 'matched' if /$balanced_brackets/;
    }

Note the use of L<amnesiac aliased subpatterns|"Amnesiac subrule calls">
to avoid needlessly building a result-hash. Alternatively, you could use
listifying aliases to preserve the matching structure as an additional
debugging aid:

    use Regexp::Grammars;

    my $balanced_brackets = qr{
        <debug:step>

        <[left_delim=  (  \(  )]>
        (?:
            <[escape=  (  \\  )]>
        |   <[recurse= ( (?R) )]>
        |   <[whatever=(  .   )]>
        )*
        <[right_delim= (  \)  )]>
    }xms;

    if ( '(a(bc)d)' =~ /$balanced_brackets/) {
        use Data::Dumper 'Dumper';
        warn Dumper \%/;
    }

=head1 Handling errors when parsing

Assuming you have correctly debugged your grammar, the next source of problems
will probably be invalid input (especially if that input is being provided
interactively). So Regexp::Grammars also provides some support for detecting
when a parse is likely to fail...and informing the user why.

=head2 Requirements

The C<< <require:...> >> directive is useful for testing conditions
that it's not easy (or even possible) to check within the syntax of the
the regex itself. For example:

    <rule: IPV4_Octet_Decimal>
        # Up three digits...
        <MATCH= ( \d{1,3}+ )>

        # ...but less than 256...
        <require: (?{ $MATCH <= 255 })>

A require expects a regex codeblock as its argument and succeeds if the final
value of that codeblock is true. If the final value is false, the directive
fails and the rule starts backtracking.

Note, in this example that the digits are matched with C< \d{1,3}+ >. The
trailing C<+> prevents the C<{1,3}> repetition from backtracking to a smaller
number of digits if the C<< <require:...> >> fails.


=head2 Handling failure

The module has limited support for error reporting from within a grammar,
in the form of the C<< <error:...> >> and C<< <warning:...> >> directives
and their shortcuts: C<< <...> >>, C<< <!!!> >>, and C<< <???> >>

=head3 Error messages

The C<< <error: MSG> >> directive queues a I<conditional> error message
within C<@!> and then fails to match (that is, it is equivalent to a
C<(?!)> when matching). For example:

    <rule: ListElem>
        <SerialNumber>
      | <ClientName>
      | <error: (?{ $errcount++ . ': Missing list element' })>

So a common code pattern when using grammars that do this kind of error
detection is:

    if ($text =~ $grammar) {
        # Do something with the data collected in %/
    }
    else {
        say {*STDERR} $_ for @!;   # i.e. report all errors
    }

Each error message is conditional in the sense that, if any surrounding rule
subsequently matches, the message is automatically removed from C<@!>. This
implies that you can queue up as many error messages as you wish, but they
will only remain in C<@!> if the match ultimately fails. Moreover, only those
error messages originating from rules that actually contributed to the
eventual failure-to-match will remain in C<@!>.

If a code block is specified as the argument, the error message is whatever
final value is produced when the block is executed. Note that this final value
does not have to be a string (though it does have to be a scalar).

    <rule: ListElem>
        <SerialNumber>
      | <ClientName>
      | <error: (?{
            # Return a hash, with the error information...
            { errnum => $errcount++, msg => 'Missing list element' }
        })>

If anything else is specified as the argument, it is treated as a
literal error string (and may not contain an unbalanced C<< '<' >>
or C<< '>' >>, nor any interpolated variables).

However, if the literal error string begins with "Expected " or
"Expecting ", then the error string automatically has the following
"context suffix" appended:

    , but found '$CONTEXT' instead

For example:

    qr{ <Arithmetic_Expression>                # ...Match arithmetic expression
      |                                        # Or else
        <error: Expected a valid expression>   # ...Report error, and fail

        # Rule definitions here...
    }xms;

On an invalid input this example might produce an error message like:

    "Expected a valid expression, but found '(2+3]*7/' instead"

The value of the special $CONTEXT variable is found by looking ahead in
the string being matched against, to locate the next sequence of non-blank
characters after the current parsing position. This variable may also be
explicitly used within the C<< <error: (?{...})> >> form of the directive.

As a special case, if you omit the message entirely from the directive,
it is supplied automatically, derived from the name of the current rule.
For example, if the following rule were to fail to match:

    <rule: Arithmetic_expression>
          <Multiplicative_Expression>+ % ([+-])
        | <error:>

the error message queued would be:

    "Expected arithmetic expression, but found 'one plus two' instead"

Note however, that it is still essential to include the colon in the
directive. A common mistake is to write:

    <rule: Arithmetic_expression>
          <Multiplicative_Expression>+ % ([+-])
        | <error>

which merely attempts to call C<< <rule: error> >> if the first
alternative fails.

=head3 Warning messages

Sometimes, you want to detect problems, but not invalidate the entire
parse as a result. For those occasions, the module provides a "less stringent"
form of error reporting: the C<< <warning:...> >> directive.

This directive is exactly the same as an C<< <error:...> >> in every respect
except that it does not induce a failure to match at the point it appears.

The directive is, therefore, useful for reporting I<non-fatal> problems
in a parse. For example:

    qr{ \A            # ...Match only at start of input
        <ArithExpr>   # ...Match a valid arithmetic expression

        (?:
            # Should be at end of input...
            \s* \Z
          |
            # If not, report the fact but don't fail...
            <warning: Expected end-of-input>
            <warning: (?{ "Extra junk at index $INDEX: $CONTEXT" })>
        )

        # Rule definitions here...
    }xms;

Note that, because they do not induce failure, two or more
C<< <warning:...> >> directives can be "stacked" in sequence,
as in the previous example.

=head3 Stubbing

The module also provides three useful shortcuts, specifically to
make it easy to declare, but not define, rules and tokens.

The C<< <...> >> and C<< <???> >> directives are equivalent to
the directive:

    <error: Cannot match RULENAME (not implemented)>

The C<< <???> >> is equivalent to the directive:

    <warning: Cannot match RULENAME (not implemented)>

For example, in the following grammar:

    <grammar: List::Generic>

    <rule: List>
        <[Item]>+ % (\s*,\s*)

    <rule: Item>
        <...>

the C<Item> rule is declared but not defined. That means the grammar
will compile correctly, (the C<List> rule won't complain about a call to
a non-existent C<Item>), but if the C<Item> rule isn't overridden in
some derived grammar, a match-time error will occur when C<List> tries
to match the C<< <...> >> within C<Item>.


=head3 Localizing the (semi-)automatic error messages

Error directives of any of the following forms:

    <error: Expecting identifier>

    <error: >

    <...>

    <!!!>

or their warning equivalents:

    <warning: Expecting identifier>

    <warning: >

    <???>

each autogenerate part or all of the actual error message they produce.
By default, that autogenerated message is always produced in English.

However, the module provides a mechanism by which you can
intercept I<every> error or warning that is queued to C<@!>
via these directives...and localize those messages.

To do this, you call C<Regexp::Grammars::set_error_translator()>
(with the full qualification, since Regexp::Grammars does not
export it...nor anything else, for that matter).

The C<set_error_translator()> subroutine expect as single
argument, which must be a reference to another subroutine.
This subroutine is then called whenever an error or warning
message is queued to C<@!>.

The subroutine is passed three arguments:

=over

=item *

the message string,

=item *

the name of the rule from which the error or warning was queued, and

=item *

the value of C<$CONTEXT> when the error or warning was encountered

=back

The subroutine is expected to return the final version of the message
that is actually to be appended to C<@!>. To accomplish this it may make
use of one of the many internationalization/localization modules
available in Perl, or it may do the conversion entirely by itself.

The first argument is always exactly what appeared as a message in the
original directive (regardless of whether that message is supposed to
trigger autogeneration, or is just a "regular" error message).
That is:

    Directive                         1st argument

    <error: Expecting identifier>     "Expecting identifier"
    <warning: That's not a moon!>     "That's not a moon!"
    <error: >                         ""
    <warning: >                       ""
    <...>                             ""
    <!!!>                             ""
    <???>                             ""

The second argument always contains the name of the rule in which the
directive was encountered. For example, when invoked from within
C<< <rule: Frinstance> >> the following directives produce:

    Directive                         2nd argument

    <error: Expecting identifier>     "Frinstance"
    <warning: That's not a moon!>     "Frinstance"
    <error: >                         "Frinstance"
    <warning: >                       "Frinstance"
    <...>                             "-Frinstance"
    <!!!>                             "-Frinstance"
    <???>                             "-Frinstance"

Note that the "unimplemented" markers pass the rule name with a
preceding C<'-'>. This allows your translator to distinguish between
"empty" messages (which should then be generated automatically) and the
"unimplemented" markers (which should report that the rule is not yet
properly defined).

If you call C<Regexp::Grammars::set_error_translator()> in a void
context, the error translator is permanently replaced (at least,
until the next call to C<set_error_translator()>).

However, if you call C<Regexp::Grammars::set_error_translator()> in a
scalar or list context, it returns an object whose destructor will
restore the previous translator. This allows you to install a
translator only within a given scope, like so:

    {
        my $temporary
            = Regexp::Grammars::set_error_translator(\&my_translator);

        if ($text =~ $parser) {
            do_stuff_with( %/ );
        }
        else {
            report_errors_in( @! );
        }

    } # <--- error translator automagically reverts at this point


B<Warning>: any error translation subroutine you install will be
called during the grammar's parsing phase (i.e. as the grammar's regex
is matching). You should therefore ensure that your translator does
not itself use regular expressions, as nested evaluations of regexes
inside other regexes are extremely problematical (i.e. almost always
disastrous) in Perl.


=head2 Restricting how long a parse runs

Like the core Perl 5 regex engine on which they are built, the grammars
implemented by Regexp::Grammars are essentially top-down parsers. This
means that they may occasionally require an exponentially long time to
parse a particular input. This usually occurs if a particular grammar
includes a lot of recursion or nested backtracking, especially if the
grammar is then matched against a long string.

The judicious use of non-backtracking repetitions (i.e. C<x*+> and
C<x++>) can significantly improve parsing performance in many such
cases. Likewise, carefully reordering any high-level alternatives
(so as to test simple common cases first) can substantially reduce
parsing times.

However, some languages are just intrinsically slow to parse using
top-down techniques (or, at least, may have slow-to-parse corner cases).

To help cope with this constraint, Regexp::Grammars provides a mechanism
by which you can limit the total effort that a given grammar will expend
in attempting to match. The C<< <timeout:...> >> directive allows you
to specify how long a grammar is allowed to continue trying to match
before giving up. It expects a single argument, which must be an
unsigned integer, and it treats this integer as the number of seconds
to continue attempting to match.

For example:

    <timeout: 10>    # Give up after 10 seconds

indicates that the grammar should keep attempting to match for another
10 seconds from the point where the directive is encountered during a
parse. If the complete grammar has not matched in that time, the entire
match is considered to have failed, the matching process is immediately
terminated, and a standard error message
(C<'Internal error: Timed out after 10 seconds (as requested)'>)
is returned in C<@!>.

A C<< <timeout:...> >> directive can be placed anywhere in a grammar,
but is most usually placed at the very start, so that the entire grammar
is governed by the specified time limit. The second most common alternative
is to place the timeout at the start of a particular subrule that is known
to be potentially very slow.

A common mistake is to put the timeout specification at the top level
of the grammar, but place it I<after> the actual subrule to be matched,
like so:

    my $grammar = qr{

        <Text_Corpus>      # Subrule to be matched
        <timeout: 10>      # Useless use of timeout

        <rule: Text_Corpus>
            # et cetera...
    }xms;

Since the parser will only reach the C<< <timeout: 10> >> directive
I<after> it has completely matched C<< <Text_Corpus> >>, the timeout is
only initiated at the very end of the matching process and so does not
limit that process in any useful way.


=head3 Immediate timeouts

As you might expect, a C<< <timeout: 0> >> directive tells the parser to
keep trying for only zero more seconds, and therefore will immediately
cause the entire surrounding grammar to fail (no matter how deeply
within that grammar the directive is encountered).

This can occasionally be exteremely useful. If you know that detecting a
particular datum means that the grammar will never match, no matter how
many other alternatives may subsequently be tried, you can short-circuit
the parser by injecting a C<< <timeout: 0> >> immediately after the
offending datum is detected.

For example, if your grammar only accepts certain versions of the
language being parsed, you could write:

    <rule: Valid_Language_Version>
            vers = <%AcceptableVersions>
        |
            vers = <bad_version=(\S++)>
            <warning: (?{ "Cannot parse language version $MATCH{bad_version}" })>
            <timeout: 0>

In fact, this C<< <warning: MSG> <timeout: 0> >> sequence
is sufficiently useful, sufficiently complex, and sufficiently easy
to get wrong, that Regexp::Grammars provides a handy shortcut for it:
the C<< <fatal:...> >> directive. A C<< <fatal:...> >> is exactly
equivalent to a C<< <warning:...> >> followed by a zero-timeout,
so the previous example could also be written:

    <rule: Valid_Language_Version>
            vers = <%AcceptableVersions>
        |
            vers = <bad_version=(\S++)>
            <fatal: (?{ "Cannot parse language version $MATCH{bad_version}" })>

Like C<< <error:...> >> and C<< <warning:...> >>, C<< <fatal:...> >> also
provides its own failure context in C<$CONTEXT>, so the previous example
could be further simplified to:

    <rule: Valid_Language_Version>
            vers = <%AcceptableVersions>
        |
            vers = <fatal:(?{ "Cannot parse language version $CONTEXT" })>

Also like C<< <error:...> >>, C<< <fatal:...> >> can autogenerate an
error message if none is provided, so the example could be still further
reduced to:

    <rule: Valid_Language_Version>
            vers = <%AcceptableVersions>
        |
            vers = <fatal:>

In this last case, however, the error message returned in C<@!> would no
longer be:

    Cannot parse language version 0.95

It would now be:

    Expected valid language version, but found '0.95' instead


=head1 Scoping considerations

If you intend to use a grammar as part of a larger program that contains
other (non-grammatical) regexes, it is more efficient--and less
error-prone--to avoid having Regexp::Grammars process those regexes as
well. So it's often a good idea to declare your grammar in a C<do>
block, thereby restricting the scope of the module's effects.

For example:

    my $grammar = do {
        use Regexp::Grammars;
        qr{
            <file>

            <rule: file>
                <prelude>
                <data>
                <postlude>

            <rule: prelude>
                # etc.
        }x;
    };

Because the effects of Regexp::Grammars are lexically scoped, any regexes
defined outside that C<do> block will be unaffected by the module.



=head1 INTERFACE

=head2 Perl API

=over 4

=item C<use Regexp::Grammars;>

Causes all regexes in the current lexical scope to be compile-time processed
for grammar elements.

=item C<$str =~ $grammar>

=item C<$str =~ /$grammar/>

Attempt to match the grammar against the string, building a nested data
structure from it.

=item C<%/>

This hash is assigned the nested data structure created by any successful
match of a grammar regex.

=item C<@!>

This array is assigned the queue of error messages created by any
unsuccessful match attempt of a grammar regex.

=back


=head2 Grammar syntax

=head3 Directives

=over 4

=item C<< <rule: IDENTIFIER> >>

Define a rule whose name is specified by the supplied identifier.

Everything following the C<< <rule:...> >> directive
(up to the next C<< <rule:...> >> or C<< <token:...> >> directive) is
treated as part of the rule being defined.

Any whitespace in the rule is replaced by a call to the C<< <.ws> >>
subrule (which defaults to matching C<\s*>, but may be explicitly redefined).


=item C<< <token: IDENTIFIER> >>

Define a rule whose name is specified by the supplied identifier.

Everything following the C<< <token:...> >> directive (up to the next
C<< <rule:...> >> or C<< <token:...> >> directive) is treated as part
of the rule being defined.

Any whitespace in the rule is ignored (under the C</x> modifier), or
explicitly matched (if C</x> is not used).

=item C<< <objrule:  IDENTIFIER> >>

=item C<< <objtoken: IDENTIFIER> >>

Identical to a C<< <rule: IDENTIFIER> >> or C<< <token: IDENTIFIER> >>
declaration, except that the rule or token will also bless the hash it
normally returns, converting it to an object of a class whose name is
the same as the rule or token itself.


=item C<< <require: (?{ CODE }) > >>

The code block is executed and if its final value is true, matching continues
from the same position. If the block's final value is false, the match fails at
that point and starts backtracking.


=item C<< <error: (?{ CODE })  > >>

=item C<< <error: LITERAL TEXT > >>

=item C<< <error: > >>

This directive queues a I<conditional> error message within the global
special variable C<@!> and then fails to match at that point (that is,
it is equivalent to a C<(?!)> or C<(*FAIL)> when matching).

=item C<< <fatal: (?{ CODE })  > >>

=item C<< <fatal: LITERAL TEXT > >>

=item C<< <fatal: > >>

This directive is exactly the same as an C<< <error:...> >> in every
respect except that it immediately causes the entire surrounding
grammar to fail, and parsing to immediate cease.

=item C<< <warning: (?{ CODE })  > >>

=item C<< <warning: LITERAL TEXT > >>

This directive is exactly the same as an C<< <error:...> >> in every
respect except that it does not induce a failure to match at the point
it appears. That is, it is equivalent to a C<(?=)> ["succeed and
continue matching"], rather than a C<(?!)> ["fail and backtrack"].



=item C<< <debug: COMMAND > >>

During the matching of grammar regexes send debugging and warning
information to the specified log file (see C<< <logfile: LOGFILE> >>).

The available C<COMMAND>'s are:

    <debug: continue>    ___ Debug until end of complete parse
    <debug: run>         _/

    <debug: on>          ___ Debug until next subrule match
    <debug: match>       _/

    <debug: try>         ___ Debug until next subrule call or match
    <debug: step>        _/

    <debug: same>        ___ Maintain current debugging mode

    <debug: off>         ___ No debugging

See also the C<$DEBUG> special variable.


=item C<< <logfile: LOGFILE> >>

=item C<< <logfile:    -   > >>

During the compilation of grammar regexes, send debugging and warning
information to the specified LOGFILE (or to C<*STDERR> if C<-> is
specified).

If the specified LOGFILE name contains a C<%t>, it is replaced with a
(sortable) "YYYYMMDD.HHMMSS" timestamp. For example:

    <logfile: test-run-%t >

executed at around 9.30pm on the 21st of March 2009, would generate a
log file named: C<test-run-20090321.213056>


=item C<< <log: (?{ CODE })  > >>

=item C<< <log: LITERAL TEXT > >>

Append a message to the log file. If the argument is a code block,
that code is expected to return the text of the message; if the
argument is anything else, that something else I<is> the literal
message.

If the block returns two or more values, the first is treated as a log
message severity indicator, and the remaining values as separate lines
of text to be logged.

=item C<< <timeout: INT > >>

Restrict the match-time of the parse to the specified number of seconds.
Queues a error message and terminates the entire match process
if the parse does not complete within the nominated time limit.

=back


=head3 Subrule calls

=over 4

=item C<< <IDENTIFIER> >>

Call the subrule whose name is IDENTIFIER.

If it matches successfully, save the hash it returns in the current
scope's result-hash, under the key C<'IDENTIFIER'>.


=item C<< <IDENTIFIER_1=IDENTIFIER_2> >>

Call the subrule whose name is IDENTIFIER_1.

If it matches successfully, save the hash it returns in the current
scope's result-hash, under the key C<'IDENTIFIER_2'>.

In other words, the C<IDENTIFIER_1=> prefix changes the key under which the
result of calling a subrule is stored.


=item C<< <.IDENTIFIER> >>

Call the subrule whose name is IDENTIFIER.
Don't save the hash it returns.

In other words, the "dot" prefix disables saving of subrule results.


=item C<< <IDENTIFIER= ( PATTERN )> >>

Match the subpattern PATTERN.

If it matches successfully, capture the substring it matched and save
that substring in the current scope's result-hash, under the key
'IDENTIFIER'.


=item C<< <.IDENTIFIER= ( PATTERN )> >>

Match the subpattern PATTERN.
Don't save the substring it matched.


=item C<< <IDENTIFIER= %HASH> >>

Match a sequence of non-whitespace then verify that the sequence is a
key in the specified hash

If it matches successfully, capture the sequence it matched and save
that substring in the current scope's result-hash, under the key
'IDENTIFIER'.


=item C<< <%HASH> >>

Match a key from the hash.
Don't save the substring it matched.


=item C<< <IDENTIFIER= (?{ CODE })> >>

Execute the specified CODE.

Save the result (of the final expression that the CODE evaluates) in the
current scope's result-hash, under the key C<'IDENTIFIER'>.


=item C<< <[IDENTIFIER]> >>

Call the subrule whose name is IDENTIFIER.

If it matches successfully, append the hash it returns to a nested array
within the current scope's result-hash, under the key <'IDENTIFIER'>.


=item C<< <[IDENTIFIER_1=IDENTIFIER_2]> >>

Call the subrule whose name is IDENTIFIER_1.

If it matches successfully, append the hash it returns to a nested array
within the current scope's result-hash, under the key C<'IDENTIFIER_2'>.


=item C<< <ANY_SUBRULE>+ % <ANY_OTHER_SUBRULE> >>

=item C<< <ANY_SUBRULE>* % <ANY_OTHER_SUBRULE> >>

=item C<< <ANY_SUBRULE>+ % (PATTERN) >>

=item C<< <ANY_SUBRULE>* % (PATTERN) >>

Repeatedly call the first subrule.
Keep matching as long as the subrule matches, provided successive
matches are separated by matches of the second subrule or the pattern.

In other words, match a list of ANY_SUBRULE's separated by
ANY_OTHER_SUBRULE's or PATTERN's.

Note that, if a pattern is used to specify the separator, it must be
specified in some kind of matched parentheses. These may be capturing
[C<(...)>], non-capturing [C<(?:...)>], non-backtracking [C<< (?>...) >>],
or any other construct enclosed by an opening and closing paren.

=back

=head2 Special variables within grammar actions

=over 4

=item C<$CAPTURE>

=item C<$CONTEXT>

These are both aliases for the built-in read-only C<$^N> variable, which
always contains the substring matched by the nearest preceding C<(...)>
capture. C<$^N> still works perfectly well, but these are provided to
improve the readability of code blocks and error messages respectively.

=item C<$INDEX>

This variable contains the index at which the next match will be attempted
within the string being parsed. It is most commonly used in C<< <error:...> >>
or C<< <log:...> >> directives:

    <rule: ListElem>
        <log: (?{ "Trying words at index $INDEX" })>
        <MATCH=( \w++ )>
      |
        <log: (?{ "Trying digits at index $INDEX" })>
        <MATCH=( \d++ )>
      |
        <error: (?{ "Missing ListElem near index $INDEX" })>



=item C<%MATCH>

This variable contains all the saved results of any subrules called from the
current rule. In other words, subrule calls like:

    <ListElem>  <Separator= (,)>

stores their respective match results in C<$MATCH{'ListElem'}> and
C<$MATCH{'Separator'}>.


=item C<$MATCH>

This variable is an alias for C<$MATCH{"="}>. This is the C<%MATCH>
entry for the special "override value". If this entry is defined, its
value overrides the usual "return \%MATCH" semantics of a successful
rule.


=item C<%ARG>

This variable contains all the key/value pairs that were passed into
a particular subrule call.

    <Keyword>  <Command>  <Terminator(:Keyword)>

the C<Terminator> rule could get access to the text matched by
C<< <Keyword> >> like so:

    <token: Terminator>
        end_ (??{ $ARG{'Keyword'} })

Note that to match against the calling subrules 'Keyword' value, it's
necessary to use either a deferred interpolation (C<(??{...})>) or
a qualified matchref:

    <token: Terminator>
        end_ <\:Keyword>

A common mistake is to attempt to directly interpolate the argument:

    <token: Terminator>
        end_ $ARG{'Keyword'}

This evaluates C<$ARG{'Keyword'}> when the grammar is
compiled, rather than when the rule is matched.


=item C<$_>

At the start of any code blocks inside any regex, the variable C<$_> contains
the complete string being matched against. The current matching position
within that string is given by: C<pos($_)>.

=item C<$DEBUG>

This variable stores the current debugging mode (which may be any of:
C<'off'>, C<'on'>, C<'run'>, C<'continue'>, C<'match'>, C<'step'>, or
C<'try'>). It is set automatically by the C<< <debug:...> >> command, but may
also be set manually in a code block (which can be useful for conditional
debugging). For example:

    <rule: ListElem>
        <Identifier>

        # Conditionally debug if 'foobar' encountered...
        (?{ $DEBUG = $MATCH{Identifier} eq 'foobar' ? 'step' : 'off' })

        <Modifier>?

See also: the C<< <log: LOGFILE> >> and C<< <debug: DEBUG_CMD> >> directives.

=back


=head1 IMPORTANT CONSTRAINTS AND LIMITATIONS

=over 4

=item *

Prior to Perl 5.14, the Perl 5 regex engine as not reentrant. So any
attempt to perform a regex match inside a C<(?{ ... })> or C<(??{
... })> under Perl 5.12 or earlier will almost certainly lead to either
weird data corruption or a segfault.

The same calamities can also occur in any constructor called by
C<< <objrule:> >>. If the constructor invokes another regex in any
way, it will most likely fail catastrophically. In particular, this
means that Moose constructors will frequently crash and burn within
a Regex::Grammars grammar (for example, if the Moose-based class
declares an attribute type constraint such as 'Int', which Moose
checks using a regex).


=item *

The additional regex constructs this module provides are implemented by
rewriting regular expressions. This is a (safer) form of source
filtering, but still subject to all the same limitations and
fallibilities of any other macro-based solution.

=item *

In particular, rewriting the macros involves the insertion of (a lot of)
extra capturing parentheses. This means you can no longer assume that
particular capturing parens correspond to particular numeric variables:
i.e. to C<$1>, C<$2>, C<$3> etc. If you want to capture directly use
Perl 5.10's named capture construct:

    (?<name> [^\W\d]\w* )

Better still, capture the data in its correct hierarchical context
using the module's "named subpattern" construct:

    <name= ([^\W\d]\w*) >


=item *

No recursive descent parser--including those created with
Regexp::Grammars--can directly handle left-recursive grammars with rules
of the form:

    <rule: List>
        <List> , <ListElem>

If you find yourself attempting to write a left-recursive grammar (which
Perl 5.10 may or may not complain about, but will never successfully
parse with), then you probably need to use the "separated list"
construct instead:

    <rule: List>
        <[ListElem]>+ % (,)

=item *

Grammatical parsing with Regexp::Grammars can fail if your grammar
places "non-backtracking" directives (i.e. the C<< (?>...) >> block or
the C<?+>, C<*+>, or C<++> repetition specifiers) around a subrule call.
The problem appears to be that preventing the regex from backtracking
through the in-regex actions that Regexp::Grammars adds causes the
module's internal stack to fall out of sync with the regex match.

For the time being, you need to make sure that grammar rules don't appear
inside a "non-backtracking" directive.

=item *

Similarly, parsing with Regexp::Grammars will fail if your grammar
places a subrule call within a positive look-ahead, since
these don't play nicely with the data stack.

This seems to be an internal problem with perl itself.
Investigations, and attempts at a workaround, are proceeding.

For the time being, you need to make sure that grammar rules don't appear
inside a positive lookahead or use the
L<<< C<< <?RULENAME> >> construct | "Lookahead (zero-width) subrules" >>>
instead

=back

=head1 DIAGNOSTICS

Note that (because the author cannot find a way to throw exceptions from
within a regex) none of the following diagnostics actually throws an
exception.

Instead, these messages are simply written to the specified parser logfile
(or to C<*STDERR>, if no logfile is specified).

However, any fatal match-time message will immediately terminate the
parser matching and will still set C<$@> (as if an exception had been
thrown and caught at that point in the code). You then have the option
to check C<$@> immediately after matching with the grammar, and rethrow if
necessary:

    if ($input =~ $grammar) {
        process_data_in(\%/);
    }
    else {
        die if $@;
    }

=over

=item C<< Found call to %s, but no %s was defined in the grammar >>

You specified a call to a subrule for which there was no definition in
the grammar. Typically that's either because you forget to define the
rule, or because you misspelled either the definition or the subrule
call. For example:

    <file>

    <rule: fiel>            <---- misspelled rule
        <lines>             <---- used but never defined

Regexp::Grammars converts any such subrule call attempt to an instant
catastrophic failure of the entire parse, so if your parser ever
actually tries to perform that call, Very Bad Things will happen.


=item C<< Entire parse terminated prematurely while attempting to call non-existent rule: %s >>

You ignored the previous error and actually tried to call to a subrule
for which there was no definition in the grammar. Very Bad Things are
now happening. The parser got very upset, took its ball, and went home.
See the preceding diagnostic for remedies.

This diagnostic should throw an exception, but can't. So it sets C<$@>
instead, allowing you to trap the error manually if you wish.


=item C<< Fatal error: <objrule: %s> returned a non-hash-based object >>

An <objrule:> was specified and returned a blessed object that wasn't
a hash. This will break the behaviour of the grammar, so the module
immediately reports the problem and gives up.

The solution is to use only hash-based classes with <objrule:>


=item C<< Can't match against <grammar: %s> >>

The regex you attempted to match against defined a pure grammar, using
the C<< <grammar:...> >> directive. Pure grammars have no start-pattern
and hence cannot be matched against directly.

You need to define a matchable grammar that inherits from your pure
grammar and then calls one of its rules. For example, instead of:

    my $greeting = qr{
        <grammar: Greeting>

        <rule: greet>
            Hi there
            | Hello
            | Yo!
    }xms;

you need:

    qr{
        <grammar: Greeting>

        <rule: greet>
            Hi there
          | Hello
          | Yo!
    }xms;

    my $greeting = qr{
        <extends: Greeting>
        <greet>
    }xms;


=item C<< Inheritance from unknown grammar requested by <%s> >>

You used an C<< <extends:...> >> directive to request that your
grammar inherit from another, but the grammar you asked to
inherit from doesn't exist.

Check the spelling of the grammar name, and that it's already been
defined somewhere earlier in your program.


=item C<< Redeclaration of <%s> will be ignored >>

You defined two or more rules or tokens with the same name.
The first one defined in the grammar will be used;
the rest will be ignored.

To get rid of the warning, get rid of the extra definitions
(or, at least, comment them out or rename the rules).


=item C<< Possible invalid subrule call %s >>

Your grammar contained something of the form:

    <identifier
    <.identifier
    <[identifier

which you might have intended to be a subrule call, but which didn't
correctly parse as one. If it was supposed to be a Regexp::Grammars
subrule call, you need to check the syntax you used. If it wasn't
supposed to be a subrule call, you can silence the warning by rewriting
it and quoting the leading angle:

    \<identifier
    \<.identifier
    \<[identifier


=item C<< Possible failed attempt to specify a directive: %s >>

Your grammar contained something of the form:

    <identifier:...

but which wasn't a known directive like C<< <rule:...> >>
or C<< <debug:...> >>. If it was supposed to be a Regexp::Grammars
directive, check the spelling of the directive name. If it wasn't
supposed to be a directive, you can silence the warning by rewriting it
and quoting the leading angle:

    \<identifier:

=item C<< Possible failed attempt to specify a subrule call %s >>

Your grammar contained something of the form:

    <identifier...

but which wasn't a call to a known subrule like C<< <ident> >> or C<<
<name> >>. If it was supposed to be a Regexp::Grammars subrule call,
check the spelling of the rule name in the angles. If it wasn't supposed
to be a subrule call, you can silence the warning by rewriting it and
quoting the leading angle:

    \<identifier...


=item C<< Repeated subrule %s will only capture its final match >>

You specified a subrule call with a repetition qualifier, such as:

    <ListElem>*

or:

    <ListElem>+

Because each subrule call saves its result in a hash entry of the same name,
each repeated match will overwrite the previous ones, so only the last match
will ultimately be saved. If you want to save all the matches, you need to
tell Regexp::Grammars to save the sequence of results as a nested array within
the hash entry, like so:

    <[ListElem]>*

or:

    <[ListElem]>+

If you really did intend to throw away every result but the final one, you can
silence the warning by placing the subrule call inside any kind of
parentheses. For example:

    (<ListElem>)*

or:

    (?: <ListElem> )+


=item C<< Unable to open log file '$filename' (%s) >>

You specified a C<< <logfile:...> >> directive but the
file whose name you specified could not be opened for
writing (for the reason given in the parens).

Did you misspell the filename, or get the permissions wrong
somewhere in the filepath?


=item C<< Non-backtracking subrule %s may not revert correctly during backtracking >>

Because of inherent limitations in the Perl regex engine,
non-backtracking constructs like C<++>, C<*+>, C<?+>,
and C<< (?>...) >> do not always work correctly when applied to
subrule calls, especially in earlier versions of Perl.

If the grammar doesn't work properly, replace the offending constructs
with regular backtracking versions instead. If the grammar does work,
you can silence the warning by enclosing the subrule call in any
kind of parentheses. For example, change:

    <[ListElem]>++

to:

    (?: <[ListElem]> )++


=item C<< Unexpected item before first subrule specification in definition of <grammar: %s> >>

Named grammar definitions must consist only of rule and token definitions.
They cannot have patterns before the first definitions.
You had some kind of pattern before the first definition, which will be
completely ignored within the grammar.

To silence the warning, either comment out or delete whatever is before
the first rule/token definition.


=item C<< No main regex specified before rule definitions >>

You specified an unnamed grammar (i.e. no C<< <grammar:...> >> directive),
but didn't specify anything for it to actually match, just some rules
that you don't actually call. For example:

    my $grammar = qr{

        <rule: list>    \( <item> +% [,] \)

        <token: item>   <list> | \d+
    }x;

You have to provide something before the first rule to start the matching
off. For example:

    my $grammar = qr{

        <list>   # <--- This tells the grammar how to start matching

        <rule: list>    \( <item> +% [,] \)

        <token: item>   <list> | \d+
    }x;


=item C<< Ignoring useless empty <ws:> directive >>

The C<< <ws:...> >> directive specifies what whitespace matches within the
current rule. An empty C<< <ws:> >> directive would cause whitespace
to match nothing at all, which is what happens in a token definition,
not in a rule definition.

Either put some subpattern inside the empty C<< <ws:...> >> or, if you
really do want whitespace to match nothing at all, remove the directive
completely and change the rule definition to a token definition.


=item C<< Ignoring useless <ws: %s > directive in a token definition >>

The C<< <ws:...> >> directive is used to specify what whitespace matches
within a rule. Since whitespace never matches anything inside tokens,
putting a C<< <ws:...> >> directive in a token is a waste of time.

Either remove the useless directive, or else change the surrounding
token definition to a rule definition.

=item C<< Quantifier that doesn't quantify anything: <%s> >>

You specified a rule or token something like:

    <token: star>  *

or:

    <rule: add_op>  plus | add | +

but the C<*> and C<+> in those examples are both regex meta-operators:
quantifiers that usually cause what precedes them to match repeatedly.
In these cases however, nothing is preceding the quantifier, so it's a
Perl syntax error.

You almost certainly need to escape the meta-characters in some way.
For example:

    <token: star>  \*

    <rule: add_op>  plus | add | [+]

=back


=head1 CONFIGURATION AND ENVIRONMENT

Regexp::Grammars requires no configuration files or environment variables.


=head1 DEPENDENCIES

This module only works under Perl 5.10 or later.


=head1 INCOMPATIBILITIES

This module is likely to be incompatible with any other module that
automagically rewrites regexes. For example it may conflict with
Regexp::DefaultFlags, Regexp::DeferredExecution, or Regexp::Extended.


=head1 BUGS

No bugs have been reported.

Please report any bugs or feature requests to
C<bug-regexp-grammars@rt.cpan.org>, or through the web interface at
L<http://rt.cpan.org>.


=head1 AUTHOR

Damian Conway  C<< <DCONWAY@CPAN.org> >>


=head1 LICENCE AND COPYRIGHT

Copyright (c) 2009, Damian Conway C<< <DCONWAY@CPAN.org> >>. All rights reserved.

This module is free software; you can redistribute it and/or
modify it under the same terms as Perl itself. See L<perlartistic>.


=head1 DISCLAIMER OF WARRANTY

BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH
YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
NECESSARY SERVICING, REPAIR, OR CORRECTION.

IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE
LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL,
OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE
THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.