Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 16343x 32655x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 9x 9x 13x 3x 10x 5x 5x 5x 1x 47x 47x 47x 47x 47x 47x 47x 516x 21x 21x 160x 3x 3x 3x 3x 3x 3x 7x 7x 3x 3x 3x 3x 17x 17x 140x 21x 21x 8x 8x 8x 8x 8x 8x 5x 5x 5x 5x 5x 1x 1x 1x 5x 5x 13x 13x 13x 13x 7x 7x 7x 7x 456x 456x 47x 47x 47x 238294x 238294x 2686x 238294x 20x 20x 238294x 84918x 4x 84914x 84914x 84914x 1031x 1031x 1031x 83883x 83883x 83883x 82433x 72321x 7389x 72321x 11562x 11562x 11562x 52x 11510x 11510x 11521x 11x 11510x 11x 11510x 11510x 11562x 11562x 11562x 11562x 11562x 11562x 10095x 10095x 11562x 11562x 10002x 10002x 4764x 10002x 10002x 6497x 6497x 6497x 6497x 10002x 10002x 9977x 10002x 10002x 10002x 9979x 23x 23x 10002x 10002x 10002x 9979x 10002x 13x 13x 13x 13x 13x 13x 13x 10x 10x 13x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11546x 11546x 5795x 5751x 2781x 11546x 11546x 11546x 11546x 187160x 11546x 11546x 11537x 11537x 11537x 11537x 11537x 126x 126x 11537x 11546x 8292x 8297x 8297x 8297x 6821x 5833x 2977x 2856x 1352x 1476x 78x 144x 144x 144x 144x 14x 130x 130x 64x 66x 66x 66x 8297x 34x 34x 34x 34x 34x 19021x 346x 34x 34x 8263x 8263x 7246x 2049x 2049x 1017x 8297x 202x 186x 186x 186x 16x 16x 16x 202x 130x 8x 8x 2x 6x 6x 6x 6x 122x 130x 130x 130x 9983x 9983x 9983x 9983x 5239x 5239x 9983x 3333x 3333x 3333x 3333x 3333x 3333x 3333x 3450x 3450x 3450x 594x 594x 2856x 3450x 3200x 3200x 1671x 1671x 3200x 3200x 485x 485x 2715x 3200x 9983x 2645x 2645x 9983x 118x 118x 118x 118x 1537x 4x 4x 4x 4x 1537x 1537x 57821x 57633x 57834x 57834x 57834x 53462x 57834x 5589x 5589x 5589x 5589x 17352x 1609x 15743x 13616x 13616x 13616x 11679x 13616x 13616x 13616x 12498x 17352x 17352x 17352x 7041x 2893x 2893x 4148x 781x 781x 781x 3367x 1345x 1345x 1345x 824x 3367x 2543x 21x 21x 21x 2543x 2543x 2543x 2543x 2543x 521x 521x 521x 40x 824x 824x 824x 4148x 7039x 2893x 2893x 4146x 4081x 4146x 4146x 4146x 4146x 1604x 2542x 2542x 2542x 4146x 4146x 1604x 4146x 2x 2x 2x 2894x 2894x 1457x 1437x 734x 703x 2894x 2894x 2894x 14x 14x 14x 13x 13x 13x 13x 1x 14x 7742x 7742x 7058x 3552x 3552x 3506x 1790x 1790x 7742x 7742x 7742x 7742x 15x 15x 15x 15x 15x 194x 15x 15x 8x 8x 8x 8x 8x 6x 6x 2x 4x 4x 4x 4x 6x 6x 5924x 5924x 5924x 2x 2x 2x 75x 75x 75x 47x 47x 36x 36x 47x 47x 47x 47x 47x 47x 335167x 38406x 7239x 7235x 7235x 9x 7239x 7239x 38406x 38406x 38406x 73446x 73446x 27564x 27564x 1999x 193752x 28875x 17314x 11561x 11561x 11561x 11561x 11561x 11561x 164877x 7246x 7246x 157631x 186506x 47x 7x 6x 6x 7x 47x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 852214x 42x 852172x 852172x 152653x 223681x 63459x 37917x 2419x 264x 2155x 2155x 372043x 212905x 159138x 159138x 820142x 28553x 28553x 55277x 28535x 28553x 18x 28535x 1450x 1450x 5025x 1449x 3576x 1450x 265x 1185x 63985x 63985x 63985x 63985x 177x 177x 3940x 3940x 3940x 59868x 59868x 63985x 63985x 33150x 33150x 33122x 41536x 41536x 30756x 36984x 1757x 35227x 34484x 34484x 34484x 743x 743x 743x 91x 75x 91x 91x 91x 91x 91x 91x 39x 52x 52x 91x 322772x 322772x 1016x 1016x 1015x 1x 1x 1016x 322772x 5388x 5388x 26358x 26358x 26358x 26358x 291026x 164877x 291026x 164877x 1016x 1016x 163861x 163861x 265x 91x 163861x 163861x 163861x 126149x 126149x 290010x 94x 3x 91x 3x 88x 250500x 250500x 88x 88x 88x 43x 45x 45x 197x 45x 14415x 14415x 304937x 304937x 14415x 11561x 11561x 11561x 13x 13x 13x 11548x 11561x 11561x 127769x 126149x 29870x 26358x 16x 26358x 10115x 10115x 169x 169x 326x 222x 104x 100x 169x 169x 169x 169x 100x 9946x 16x 25465x 25465x 25465x 25465x 25465x 23599x 25465x 22536x 19323x 8353x 22536x 3885x 25465x 502267x 502267x 87972x 7194x 7194x 7194x 9598x 9598x 6188x 3410x 3410x 6188x 12155x 12155x 12155x 12155x 6902x 6902x 2926x 985x 3x 982x 982x 266240x 266240x 266240x 20247x 16745x 6971x 6971x 9774x 13276x 13276x 38x 38x 88010x 88010x 88010x 88010x 6676x 2833x 97x 2736x 6579x 8358x 1748x 5252x 5252x 4764x 8358x 8358x 8358x 1273x 1273x 3309x 3309x 3309x 4x 4x 2858x 2858x 2858x 584x 584x 193x 193x 196x 196x 194x 194x 193x 193x 192x 192x 196x 196x 1110x 2858x 248x 248x 248x 248x 248x 199x 199x 199x 199x 199x 24754x 15x 24754x 24754x 19991x 19534x 19991x 19991x 18774x 13409x 13409x 19991x 6582x 19991x 19991x 47x 329x 329x 15x 6582x 2711x 2711x 328x 2383x 2711x 3871x 3871x 17280x 17280x 17280x 3871x 3871x 3871x 3871x 3871x 17280x 17280x 17280x 17280x 17280x 12763x 17280x 17280x 17280x 17280x 17280x 86511x 17280x 17280x 17280x 69231x 69231x 11946x 11946x 11143x 11143x 1803x 44339x 4782x 1002x 1002x 1002x 1002x 1002x 3780x 3740x 3740x 39557x 44339x 17280x 376761x 23145x 353616x 17280x 34x 34x 34x 34x 34x 412x 34x 11x 6x 11x 11x 5x 6x 34x 34x 10x 10x 10x 24x 34x 34x 34x 139x 2524x 295x 295x 295x 2524x 2524x 139x 34x 105x 2501x 105x 105x 100x 100x 66x 58x 8x 34x 18x 16x 3x 105x 16x 14x 16x 16x 105x 34x 34x 34x 11x 34x 34x | /*
* This file is released under the MIT license.
* Copyright (c) 2016, 2022, Mike Lischke
*
* See LICENSE file for more info.
*/
import { IFormattingOptions } from "./types";
import { Token } from "antlr4ts";
import { Interval } from "antlr4ts/misc";
import { ANTLRv4Lexer } from "../parser/ANTLRv4Lexer";
// Insert markers are what the output pipeline (see below) is made of (if not direct token indices).
enum InsertMarker {
// Token markers.
// EOF is -1
LineBreak = -2,
Space = -3,
Tab = -4,
// Markers for a group of elements.
Whitespace = -100,
Comment = -101,
// Action markers.
WhitespaceEraser = -102, // Marker for any future whitespace to be ignored.
Error = -103,
// Block markers.
Range = -100000, // Indirect index into the range list.
Alignment = -200000, // Indirect index into the alignment groups list.
WhitespaceBlock = -300000, // Indirect index into the whitespace list.
}
const formatIntroducer = "$antlr-format";
/**
* Tests if the marker belongs to the range block.
*
* @param marker The marker to test.
*
* @returns True if the marker is a range marker.
*/
const isRangeBlock = (marker: InsertMarker): boolean => {
return (marker <= InsertMarker.Range) && (marker > InsertMarker.Alignment);
};
/**
* Tests if the marker belongs to the whitespace block.
*
* @param marker The marker to test.
*
* @returns True if the marker is a whitespace marker.
*/
const isWhitespaceBlock = (marker: InsertMarker): boolean => { return (marker <= InsertMarker.WhitespaceBlock); };
// Enum used to address a specific alignment status in the alignment map.
enum AlignmentType {
Colon,
FirstToken,
Label,
LexerCommand,
Action,
TrailingComment,
Trailers // Align all of label, action, trailing comment and lexer command (whatever comes first).
}
// All alignments in the order they will be evaluated.
const allAlignments = [
AlignmentType.Colon, AlignmentType.FirstToken, AlignmentType.Label, AlignmentType.Action,
AlignmentType.LexerCommand, AlignmentType.TrailingComment, AlignmentType.Trailers,
];
// Holds line number and group index for a specific alignment. For each alignment type there's an own
// status, to allow multiple alignments per line and ordered processing.
interface IAlignmentStatus {
lastLine: number; // The line number of the last alignment entry in the current group (if there's one currently).
groups: number[][]; // A list of output pipeline indices for groups of alignments.
}
export class GrammarFormatter {
private options: IFormattingOptions;
// The pipeline contains markers for constructing the final text.
// A marker is either an index in the token list (if >= 0) or one of the special markers
// (when < 0), like space, line break, alignment and range markers.
private outputPipeline: InsertMarker[];
private currentIndentation: number;
private formattingDisabled: boolean; // When true no formatting takes place.
private currentLine: number;
private currentColumn: number;
// When a block has been determined to fit as a whole on a single line (relevant only if
// allowShortBlocksOnASingleLine is true), this var directs line break handling.
// Note: counting begins on the most outer block that can be formatted on a single line, which is not necessarily
// the rule itself.
private singleLineBlockNesting: number;
// A list of index pairs describing start and end of a token sequence in the original token stream.
// This is mostly used to avoid having to place a large list of action tokens in the generated list.
private ranges: Array<[InsertMarker, InsertMarker]>;
private currentRangeIndex: InsertMarker; // When scanning a range this contains the start token index.
private rangeStart: number; // Holds the start index of a range when collecting.
// For each possible alignment type (colon, first token, trailing predicate, trailing comment etc.)
// there's one status record in this map.
private alignments = new Map<AlignmentType, IAlignmentStatus>();
private whitespaceList: string[]; // A list of strings containing whitespaces to insert for alignment.
public constructor(private tokens: Token[]) { }
/**
* This is the main formatting routine.
*
* @param options Options that control the formatting process. Can be overridden in the code.
* @param start The character index in the input to start from.
* @param stop The character index in the input to end with.
* @returns A tuple containing the formatted text as well as new start/stop indices that should be used
* to replace the old text range.
*/
public formatGrammar(options: IFormattingOptions, start: number, stop: number): [string, number, number] {
Iif (this.tokens.length === 0) {
return ["", -1, -1];
}
this.setDefaultOptions();
this.options = Object.assign(this.options, options); // Overwrite default values with passed in values.
Iif (this.options.columnLimit! <= 0) {
this.options.columnLimit = 1e30;
}
this.outputPipeline = [];
this.currentIndentation = 0;
this.singleLineBlockNesting = 0;
this.ranges = [];
this.currentRangeIndex = 0;
this.rangeStart = -1;
this.alignments.clear();
this.whitespaceList = [];
// Position info of the target text.
this.currentColumn = 0;
this.currentLine = 1;
this.formattingDisabled = false;
let coalesceWhitespaces = false; // Set in situations where we don't want multiple consecutive whitespaces.
let inBraces = false; // Set between {} (e.g. in options).
let inRule = false; // Set when we are processing a lexer or parser rule.
let inNamedAction = false; // Ditto for a named action.
let inLexerCommand = false; // Ditto for a lexer command (the part starting with ->).
let inCatchFinally = false; // Ditto for catch/finally blocks.
let inSingleLineRule = false; // Set when an entire rule is placed on a single line.
let minLineInsertionPending = false; // Set when the min line setting must be enforced after next line break.
// Start by determining the actual formatting range. This is specified for the unformatted text,
// which allows the caller to use it directly to replace the old text.
let startIndex = this.tokenFromIndex(start, true);
const endIndex = this.tokenFromIndex(stop, false);
// Adjust the start index if we are within a single line comment which is part of a comment block
// and we are reflowing comment text. Include all single line comment entries of that block.
// For other comment types this is not necessary, as they are blocks by nature.
if (this.options.reflowComments && this.tokens[startIndex].type === ANTLRv4Lexer.LINE_COMMENT) {
let runningIndex = startIndex;
while (runningIndex > 0) {
if (this.tokens[runningIndex--].text!.indexOf(formatIntroducer) >= 0) {
break; // Don't include comment lines containing (potential) formatting instructions.
}
// The comment must be the only non-whitespace token on the line.
if (this.tokens[runningIndex].type !== ANTLRv4Lexer.WS
|| this.tokens[runningIndex].line + 1 !== this.tokens[runningIndex + 1].line) {
break;
}
startIndex = runningIndex + 1;
if (this.tokens[--runningIndex].type !== ANTLRv4Lexer.LINE_COMMENT) {
break;
}
}
}
let targetStart = this.tokens[startIndex].startIndex;
let startRow = this.tokens[startIndex].line;
const targetStop = this.tokens[endIndex].stopIndex;
// If the start token doesn't begin at the first column walk back in the text to ensure the target
// range starts directly after a line break, to allow fixing the indentation on the start line.
targetStart -= this.tokens[startIndex].charPositionInLine;
// Next step is to determine the context the start token is in.
let run = startIndex;
let done = false;
while (run > 0 && !done) {
switch (this.tokens[run].type) {
case ANTLRv4Lexer.SEMI: {
// Top level or options block.
let localRun = run;
while (localRun-- > 0 && !done) {
switch (this.tokens[localRun].type) {
case ANTLRv4Lexer.LBRACE: {
// In an options {} rule. Increase indentation if the token is not
// on the same line as the start token (in which case we would do that
// in the main formatting loop then).
if (this.tokens[localRun].line < startRow) {
++this.currentIndentation;
inBraces = true;
}
// Determine if we are in an assignment or between them.
localRun = startIndex;
let type = 0;
do {
type = this.tokens[localRun].type;
if (type !== ANTLRv4Lexer.WS
&& type !== ANTLRv4Lexer.LINE_COMMENT
&& type !== ANTLRv4Lexer.BLOCK_COMMENT
&& type !== ANTLRv4Lexer.DOC_COMMENT) {
break;
}
} while (localRun-- > 0);
coalesceWhitespaces = type !== ANTLRv4Lexer.SEMI;
done = true;
break;
}
// These are indicators for not being in a braced block.
case ANTLRv4Lexer.BEGIN_ACTION:
case ANTLRv4Lexer.END_ACTION:
case ANTLRv4Lexer.COLON:
case ANTLRv4Lexer.COLONCOLON:
case ANTLRv4Lexer.OR: {
done = true;
break;
}
default: {
break;
}
}
}
done = true;
break;
}
case ANTLRv4Lexer.COLON: // Also pretty clear. We are in a rule.
if (this.tokens[run].line < startRow) {
++this.currentIndentation;
inRule = true;
coalesceWhitespaces = true;
}
done = true;
break;
case ANTLRv4Lexer.AT: // A named action. Want this to be formatted as a whole.
startRow = this.tokens[run].line;
startIndex = run;
targetStart = this.tokens[run].startIndex;
done = true;
break;
case ANTLRv4Lexer.LBRACE:
case ANTLRv4Lexer.BEGIN_ACTION:
// A braced block (e.g. tokens, channels etc.).
Iif (this.tokens[run].line < startRow) {
++this.currentIndentation;
inBraces = true;
}
done = true;
break;
case ANTLRv4Lexer.RBRACE:
case ANTLRv4Lexer.END_ACTION:
done = true;
break;
case ANTLRv4Lexer.LPAREN:
if (this.tokens[run].line < startRow) {
++this.currentIndentation;
}
--run;
break;
case ANTLRv4Lexer.RPAREN:
if (this.tokens[run].line < startRow) {
--this.currentIndentation;
}
--run;
break;
default:
--run;
break;
}
}
// Here starts the main formatting loop.
this.currentLine = startRow;
this.pushCurrentIndentation();
for (let i = startIndex; i <= endIndex; ++i) {
const token = this.tokens[i];
// If no whitespace is coming up we don't need the eraser marker anymore.
if (token.type !== ANTLRv4Lexer.WS && this.lastEntryIs(InsertMarker.WhitespaceEraser)) {
this.outputPipeline.pop();
}
if (minLineInsertionPending && token.type !== ANTLRv4Lexer.WS && token.type !== ANTLRv4Lexer.LINE_COMMENT) {
minLineInsertionPending = false;
this.ensureMinEmptyLines();
}
switch (token.type) {
case ANTLRv4Lexer.WS: {
if (i === 0 || this.formattingDisabled) {
// Ignore leading whitespaces at the beginning of the grammar.
break;
}
const nextType = this.tokens[i + 1].type;
const localCommentAhead = (nextType === ANTLRv4Lexer.LINE_COMMENT
|| nextType === ANTLRv4Lexer.BLOCK_COMMENT || nextType === ANTLRv4Lexer.DOC_COMMENT);
if (this.lastEntryIs(InsertMarker.WhitespaceEraser)) {
// And ignore these incoming whitespaces if there is an eraser marker
// (unless comments after a line break follow, which we want to stay on their line).
this.outputPipeline.pop();
if (!localCommentAhead) {
break;
}
}
// Analyze whitespaces, we can have a mix of tab/space and line breaks here.
const text = token.text!.replace("\r\n", "\n");
const hasLineBreaks = text.indexOf("\n") >= 0;
if (!localCommentAhead || !hasLineBreaks) {
if (!hasLineBreaks || coalesceWhitespaces || this.singleLineBlockNesting > 0) {
if (!this.lastEntryIs(InsertMarker.Whitespace)) {
this.addSpace();
}
break;
}
}
const parts = text.split("\n");
let breakCount = 0;
// Limit the number of line breaks before a comment right after a left parenthesis.
if (localCommentAhead && this.lastCodeTokenIs(ANTLRv4Lexer.LPAREN)
&& !this.options.keepEmptyLinesAtTheStartOfBlocks) {
breakCount = 1;
} else {
// Take into account any line breaks that are already in the pipeline.
let j = this.outputPipeline.length - 1;
while (j >= 0) {
if (this.entryIs(j, InsertMarker.LineBreak)) {
++breakCount;
} else {
break;
}
--j;
}
breakCount = Math.max(breakCount, parts.length - 1);
breakCount = Math.min(breakCount, this.options.maxEmptyLinesToKeep! + 1);
}
this.removeTrailingWhitespaces();
const lineBreaks: number[] = Array(breakCount).fill(InsertMarker.LineBreak);
this.outputPipeline.push(...lineBreaks);
this.currentLine += breakCount;
this.currentColumn = 0;
// Ensure empty lines only if still have something to format.
if (i < endIndex && minLineInsertionPending) {
minLineInsertionPending = false;
this.ensureMinEmptyLines();
}
this.pushCurrentIndentation();
break;
}
case ANTLRv4Lexer.SEMI: {
this.removeTrailingWhitespaces();
// Single line mode here can be caused by 2 situations:
// single line block from the last alt or single line rule.
// In the first case we have to end single line mode now, otherwise
// after the alignment handling.
if (!inSingleLineRule) {
this.singleLineBlockNesting = 0;
}
// Even if the rule is on a single line we have to check for semicolon placement,
// because in case of a hanging colon only the body of the rule is on a single line,
// while name and semicolon are placed on own lines.
const canAlignSemicolon = !inSingleLineRule || this.options.alignColons === "hanging";
if (canAlignSemicolon && !inBraces && inRule) {
switch (this.options.alignSemicolons) {
case "none": {
break;
}
case "ownLine": {
const forceNewLine = !this.options.singleLineOverrulesHangingColon
&& this.options.alignColons === "hanging";
this.addLineBreak(forceNewLine);
break;
}
case "hanging": {
this.addLineBreak();
this.pushCurrentIndentation();
break;
}
default: {
break;
}
}
}
this.add(i);
if (!inBraces && this.currentIndentation > 0) {
--this.currentIndentation;
}
// Now we can end single line mode in any case (if not done yet above).
this.singleLineBlockNesting = 0;
inSingleLineRule = false;
if (this.currentIndentation === 0) {
minLineInsertionPending = true;
} else {
this.addLineBreak();
this.pushCurrentIndentation();
}
coalesceWhitespaces = false;
inLexerCommand = false;
if (!inBraces) {
inRule = false;
}
break;
}
case ANTLRv4Lexer.LBRACE: {
Iif (this.singleLineBlockNesting === 0 && this.options.breakBeforeBraces) {
this.removeTrailingWhitespaces();
this.addLineBreak();
this.pushCurrentIndentation();
this.add(i);
} else {
this.removeTrailingWhitespaces();
this.addSpace();
this.add(i);
}
++this.currentIndentation;
inBraces = true;
if (!this.nonBreakingTrailerAhead(i)) {
this.addLineBreak();
this.pushCurrentIndentation();
}
break;
}
case ANTLRv4Lexer.RBRACE: {
this.removeTrailingWhitespaces();
this.addLineBreak();
if (this.currentIndentation > 0) {
--this.currentIndentation;
}
this.pushCurrentIndentation();
this.add(i);
minLineInsertionPending = this.currentIndentation === 0;
inBraces = false;
coalesceWhitespaces = false;
inRule = false;
break;
}
case ANTLRv4Lexer.BEGIN_ACTION: {
Iif (this.formattingDisabled) {
break;
}
if (this.options.alignTrailers) {
this.addAlignmentEntry(AlignmentType.Trailers);
} else if (this.options.alignActions) {
this.addAlignmentEntry(AlignmentType.Action);
}
this.add(i++);
Iif (inCatchFinally && this.tokens[i].text !== "\n") {
this.addLineBreak();
}
// Find the action end token (or the last in the given source range).
const actionStart = i;
while (i <= endIndex
&& this.tokens[i].type !== Token.EOF
&& this.tokens[i].type !== ANTLRv4Lexer.END_ACTION) {
++i;
}
// Add a new range for the action code.
this.addRaw(actionStart, i - 1);
if (i <= endIndex) {
Iif (inCatchFinally && this.tokens[i - 1].text !== "\n") {
this.addLineBreak();
}
this.add(i);
this.addSpace();
minLineInsertionPending = this.currentIndentation === 0;
if (!inRule) {
inNamedAction = false;
coalesceWhitespaces = false;
}
inCatchFinally = false;
}
break;
}
case ANTLRv4Lexer.LINE_COMMENT:
case ANTLRv4Lexer.BLOCK_COMMENT: {
this.processFormattingCommands(i);
// [falls-through]
}
case ANTLRv4Lexer.DOC_COMMENT: {
// If this comment is the first non-whitespace entry on the current line
// some extra processing is required.
const hasLineContent = this.lineHasNonWhitespaceContent();
let comment = token.text!;
if (hasLineContent) {
if (token.type === ANTLRv4Lexer.LINE_COMMENT) {
// There's something before the comment on the current line.
// Trigger normal alignment handling then.
if (this.options.alignTrailers) {
this.addAlignmentEntry(AlignmentType.Trailers);
} else if (this.options.alignTrailingComments) {
this.addAlignmentEntry(AlignmentType.TrailingComment);
}
}
} else if (comment.indexOf(formatIntroducer) < 0
&& this.options.reflowComments
&& token.type === ANTLRv4Lexer.LINE_COMMENT) {
// Scan forward and collect all consecutive single line comments lines
// which stand alone on a line.
while (true) {
let nextToken = this.tokens[i + 1];
Iif (nextToken.type === ANTLRv4Lexer.EOF) {
break;
}
const content = nextToken.text!; // Must be whitespaces.
if (content.split("\n").length > 2) { // More than a single line break. Stop here.
break;
}
nextToken = this.tokens[i + 2];
if (nextToken.type !== ANTLRv4Lexer.LINE_COMMENT
|| nextToken.text!.indexOf(formatIntroducer) >= 0) {
break;
}
comment += "\n" + nextToken.text!;
i += 2;
this.processFormattingCommands(i);
}
}
if (this.options.reflowComments && comment.indexOf("\n") > 0) {
const formatted = this.reflowComment(comment, token.type);
const whitespaceIndex = InsertMarker.WhitespaceBlock - this.whitespaceList.length;
this.outputPipeline.push(whitespaceIndex);
this.whitespaceList.push(formatted);
// Update the current line member.
for (const char of formatted) {
if (char === "\n") {
++this.currentLine;
}
}
this.addLineBreak();
this.pushCurrentIndentation();
} else {
this.add(i);
if (token.type === ANTLRv4Lexer.LINE_COMMENT) {
if (this.currentIndentation > 0) {
this.addLineBreak();
this.pushCurrentIndentation();
}
} else {
this.addSpace();
}
}
break;
}
case ANTLRv4Lexer.ASSIGN:
case ANTLRv4Lexer.PLUS_ASSIGN: {
if (this.options.spaceBeforeAssignmentOperators) {
Iif (!this.lastEntryIs(InsertMarker.Whitespace)) {
this.addSpace();
}
this.add(i);
this.addSpace();
} else {
if (this.lastEntryIs(InsertMarker.Whitespace)) {
this.removeLastEntry();
}
this.add(i);
}
break;
}
case ANTLRv4Lexer.AT: {
if (inRule) {
this.removeTrailingWhitespaces();
if (this.options.ruleInternalsOnSingleLine) {
this.addSpace();
} else {
this.addLineBreak();
++this.currentIndentation;
this.pushCurrentIndentation();
--this.currentIndentation;
}
} else {
inNamedAction = true;
}
this.add(i);
this.add(InsertMarker.WhitespaceEraser);
break;
}
case ANTLRv4Lexer.COLON: {
++this.currentIndentation;
let { singleLineLength } = this.getBlockInfo(i, new Set([ANTLRv4Lexer.SEMI]));
singleLineLength += this.currentColumn;
if (this.options.allowShortRulesOnASingleLine
&& singleLineLength <= (2 * this.options.columnLimit! / 3)) {
++this.singleLineBlockNesting;
inSingleLineRule = true;
}
switch (this.options.alignColons) {
case "hanging": {
this.removeTrailingWhitespaces();
const forceNewLine = !this.options.singleLineOverrulesHangingColon;
this.addLineBreak(forceNewLine);
this.pushCurrentIndentation(forceNewLine);
this.add(i);
this.addSpace();
break;
}
case "none": {
this.removeTrailingWhitespaces();
this.add(i);
if (!this.nonBreakingTrailerAhead(i) && !inSingleLineRule) {
this.addLineBreak();
this.pushCurrentIndentation();
} else {
this.addSpace();
}
break;
}
case "trailing": {
this.removeTrailingWhitespaces();
if (this.singleLineBlockNesting > 0) {
this.addAlignmentEntry(AlignmentType.Colon);
this.add(InsertMarker.WhitespaceEraser);
}
this.add(i);
if (!this.nonBreakingTrailerAhead(i) && !inSingleLineRule) {
this.addLineBreak();
this.pushCurrentIndentation();
} else {
this.addSpace();
}
break;
}
default: {
break;
}
}
// Aligning the first token only makes sense if the entire rule is on a single line.
if (this.options.alignFirstTokens && inSingleLineRule) {
this.addAlignmentEntry(AlignmentType.FirstToken);
this.add(InsertMarker.WhitespaceEraser);
}
break;
}
case ANTLRv4Lexer.COLONCOLON:
this.removeTrailingWhitespaces();
this.add(i);
this.add(InsertMarker.WhitespaceEraser);
break;
case ANTLRv4Lexer.IMPORT:
case ANTLRv4Lexer.LEXER:
case ANTLRv4Lexer.PARSER:
case ANTLRv4Lexer.GRAMMAR:
case ANTLRv4Lexer.MODE: {
if (!inNamedAction && !inRule) {
// We increase the current indentation here only to have an easier time
// when handling the ending semicolon. Otherwise we would have to add
// extra checks to know which command the semicolon ends.
++this.currentIndentation;
inSingleLineRule = true;
coalesceWhitespaces = true;
inRule = true;
}
this.add(i);
break;
}
case ANTLRv4Lexer.FRAGMENT:
case ANTLRv4Lexer.PRIVATE:
case ANTLRv4Lexer.PROTECTED:
case ANTLRv4Lexer.PUBLIC:
case ANTLRv4Lexer.TOKEN_REF:
case ANTLRv4Lexer.RULE_REF: {
if (!inNamedAction && !inBraces) {
inRule = true;
}
// [falls-through]
}
case ANTLRv4Lexer.OPTIONS:
case ANTLRv4Lexer.TOKENS:
case ANTLRv4Lexer.CHANNELS: {
coalesceWhitespaces = true;
this.add(i);
if (!inLexerCommand) {
this.addSpace();
}
break;
}
case ANTLRv4Lexer.PLUS:
case ANTLRv4Lexer.QUESTION:
case ANTLRv4Lexer.STAR: {
this.removeTrailingWhitespaces();
this.add(i);
this.addSpace();
break;
}
case ANTLRv4Lexer.OR: {
// Starts a new alt. If we are in the first single line nesting level
// (not to be confused with block nesting, we can have the first single line block
// at, say, block nesting 10), we have to end the current single line block
// (which is the previous alt) and see if we can start a new one.
if (this.singleLineBlockNesting > 1) {
this.addSpace();
} else {
if (!inSingleLineRule) {
// If we are in a single line rule block it means we are not ending a
// single line alt block.
this.singleLineBlockNesting = 0;
this.removeTrailingTabsAndSpaces();
if (this.outputPipeline.length > 0 && !this.lastEntryIs(InsertMarker.LineBreak)) {
this.addLineBreak();
}
this.pushCurrentIndentation();
const { containsAlts, singleLineLength } = this.getBlockInfo(i,
new Set([ANTLRv4Lexer.OR, ANTLRv4Lexer.SEMI]));
// See if we should enter single line mode.
if ((!containsAlts || this.options.allowShortBlocksOnASingleLine)
&& singleLineLength <= (this.options.columnLimit! / 2 + 3)) {
++this.singleLineBlockNesting;
}
}
}
this.add(i);
this.addSpace();
break;
}
case ANTLRv4Lexer.LPAREN: {
if (inLexerCommand) {
this.add(i);
break;
}
if (this.singleLineBlockNesting > 0) {
// If we are already in single line mode add a nesting level.
// It's impossible to have a multi line block within a single line block.
// The other way around it's well possible, though.
// See a few lines below why we increase by 2.
this.singleLineBlockNesting += 2;
++this.currentIndentation;
this.add(i);
} else {
// First check if we can put the entire block on a single line (if the block option is set).
if (this.options.allowShortBlocksOnASingleLine) {
let { singleLineLength } = this.getBlockInfo(i, new Set([ANTLRv4Lexer.RPAREN]));
singleLineLength += this.currentColumn;
if (singleLineLength <= (2 * this.options.columnLimit! / 3)) {
// Increase by 2: one for the block and one for the first alt.
// We increase for the alt even if there's no content or only a single alt.
// Doing that simplifies handling when closing the block.
this.singleLineBlockNesting += 2;
}
}
if (this.singleLineBlockNesting === 0) {
if (this.options.breakBeforeParens) {
this.removeTrailingWhitespaces();
this.addLineBreak();
this.pushCurrentIndentation();
}
this.add(i);
++this.currentIndentation;
this.addLineBreak();
this.pushCurrentIndentation();
if (this.options.allowShortBlocksOnASingleLine) {
// If the entire block is too long, see if the first alt would fit on a single line.
let { singleLineLength } = this.getBlockInfo(i,
new Set([ANTLRv4Lexer.OR, ANTLRv4Lexer.RPAREN]));
singleLineLength += this.currentColumn;
if (singleLineLength <= (this.options.columnLimit! / 2 + 3)) {
++this.singleLineBlockNesting;
}
}
} else {
this.add(i);
this.add(InsertMarker.WhitespaceEraser);
++this.currentIndentation;
}
}
break;
}
case ANTLRv4Lexer.RPAREN: {
if (inLexerCommand) {
this.add(i);
break;
}
if (this.singleLineBlockNesting > 0) {
// If we are in single line mode when we end an alt it means
// the nesting counter was increased for it. Hence we can count down here.
--this.singleLineBlockNesting;
}
if (this.currentIndentation > 0) {
--this.currentIndentation;
}
this.removeTrailingWhitespaces();
// If the single line counter is still > 0 it means the entire block is
// to be formatted on a single line.
if (this.singleLineBlockNesting > 0) {
this.add(i);
} else {
this.addLineBreak();
this.pushCurrentIndentation();
this.add(i);
}
this.addSpace();
if (this.singleLineBlockNesting > 0) {
// Now decrease single line block counter for the closing parenthesis too.
--this.singleLineBlockNesting;
}
break;
}
case ANTLRv4Lexer.GT: {
this.removeTrailingWhitespaces();
this.add(i);
break;
}
case ANTLRv4Lexer.RARROW: {
inLexerCommand = true;
if (this.options.alignTrailers) {
this.addAlignmentEntry(AlignmentType.Trailers);
} else if (this.options.alignLexerCommands) {
this.addAlignmentEntry(AlignmentType.LexerCommand);
} else {
Iif (!this.lastEntryIs(InsertMarker.Space)) {
this.addSpace();
}
}
this.add(i);
this.addSpace();
break;
}
case ANTLRv4Lexer.COMMA: {
this.removeTrailingWhitespaces();
this.add(i);
if (inBraces) {
coalesceWhitespaces = false; // For tokens block.
if (!this.nonBreakingTrailerAhead(i)) {
this.addLineBreak();
this.pushCurrentIndentation();
}
} else {
this.addSpace();
}
break;
}
case ANTLRv4Lexer.POUND: {
// Starting a label. They are not trailing per se, but we treat them so
// if not in single line mode, as they look similar like trailing comments.
let willUseAlignment = false;
if (!inSingleLineRule) {
// Labels can only be specified for top level alts, hence we test on the entire
// rule if we are in single line mode, not the current alt's mode.
if (this.options.alignTrailers) {
willUseAlignment = true;
this.addAlignmentEntry(AlignmentType.Trailers);
} else if (this.options.alignLabels) {
willUseAlignment = true;
this.addAlignmentEntry(AlignmentType.Label);
}
}
Iif (!willUseAlignment && !this.lastEntryIs(InsertMarker.Space)) {
this.addSpace();
}
this.add(i);
this.addSpace();
break;
}
case ANTLRv4Lexer.BEGIN_ARGUMENT: {
Iif (this.formattingDisabled) {
break;
}
this.removeTrailingWhitespaces();
this.add(i++);
// Find the argument end token.
const argumentStartIndex = i;
while (this.tokens[i].type !== Token.EOF && this.tokens[i].type !== ANTLRv4Lexer.END_ARGUMENT) {
++i;
}
// Add a new range for the action code.
this.addRaw(argumentStartIndex, i);
break;
}
case ANTLRv4Lexer.CATCH:
case ANTLRv4Lexer.FINALLY: {
inCatchFinally = true;
this.removeTrailingWhitespaces();
this.addLineBreak();
this.add(i);
break;
}
case ANTLRv4Lexer.RETURNS:
case ANTLRv4Lexer.LOCALS: {
this.removeTrailingWhitespaces();
if (this.options.ruleInternalsOnSingleLine) {
this.addSpace();
} else {
this.addLineBreak();
++this.currentIndentation;
this.pushCurrentIndentation();
--this.currentIndentation;
}
this.add(i);
break;
}
case ANTLRv4Lexer.STRING_LITERAL:
this.add(i);
this.addSpace();
break;
case Token.EOF:
// Ensure a line break at the end of the text.
this.removeTrailingWhitespaces();
this.addLineBreak();
break;
default:
coalesceWhitespaces = true;
this.add(i);
break;
}
}
Iif (this.lastEntryIs(InsertMarker.WhitespaceEraser)) {
this.removeLastEntry();
}
// If we ended with an alignment entry, we apply it only if the selected range ends in whitespaces.
if (this.tokens[endIndex].type !== ANTLRv4Lexer.WS) {
// If the end index is not at a whitespace then we neither apply any trailing alignments nor
// keep trailing whitespaces in our output pipeline.
Iif (this.lastEntryIs(InsertMarker.Alignment)) {
this.removeLastEntry();
}
this.removeTrailingWhitespaces();
}
// If formatting was disabled and never enabled again we have to add the raw text to
// output pipeline as well.
Iif (this.formattingDisabled && this.rangeStart > -1) {
this.addRaw(this.rangeStart, endIndex);
}
// Output phase: compose all collected entries into a result string.
// Start with computing all alignments.
this.computeAlignments();
let result = "";
let pendingLineComment = -1;
let hadErrorOnLine = false;
for (const entry of this.outputPipeline) {
switch (entry) {
case InsertMarker.LineBreak:
if (pendingLineComment > 0) {
if (result.length > 0) {
const lastChar = result[result.length - 1];
if (lastChar !== " " && lastChar !== "\t" && lastChar !== "\n") {
result += " ";
}
}
result += this.tokens[pendingLineComment].text;
pendingLineComment = -1;
}
result += "\n";
hadErrorOnLine = false;
break;
case InsertMarker.Space:
result += " ";
break;
case InsertMarker.Tab:
result += "\t";
break;
case InsertMarker.WhitespaceEraser: // Ignore.
break;
case InsertMarker.Error:
Iif (!hadErrorOnLine) { // Don't output more than one error per line.
result += "<<Unexpected input or wrong formatter command>>";
hadErrorOnLine = true;
}
break;
default:
if (entry < 0) {
// One of the block markers. Alignment blocks are removed at this point and
// replaced by whitespace indices.
if (isWhitespaceBlock(entry)) {
result += this.whitespaceList[-(entry - InsertMarker.WhitespaceBlock)];
} else if (isRangeBlock(entry)) {
// Copy an entire block.
const rangeIndex = -(entry - InsertMarker.Range);
const tokenStart = this.ranges[rangeIndex][0];
const tokenEnd = this.ranges[rangeIndex][1];
const interval = Interval.of(this.tokens[tokenStart].startIndex,
this.tokens[tokenEnd].stopIndex);
result += this.tokens[0].inputStream!.getText(interval);
}
} else {
if (this.tokens[entry].type === ANTLRv4Lexer.LINE_COMMENT) {
// Ensure we don't print out a line comment before anything
// but a line break.
pendingLineComment = entry;
break;
}
result += this.tokens[entry].text;
}
break;
}
}
if (pendingLineComment > 0) {
if (result.length > 0) {
const lastChar = result[result.length - 1];
Iif (lastChar !== " " && lastChar !== "\t" && lastChar !== "\n") {
result += " ";
}
}
result += this.tokens[pendingLineComment].text;
}
return [result, targetStart, targetStop];
}
private setDefaultOptions() {
this.options = {};
this.options.alignTrailingComments = false;
this.options.allowShortBlocksOnASingleLine = true;
this.options.breakBeforeBraces = false;
this.options.columnLimit = 100;
this.options.indentWidth = 4;
this.options.continuationIndentWidth = this.options.indentWidth;
this.options.keepEmptyLinesAtTheStartOfBlocks = false;
this.options.maxEmptyLinesToKeep = 1;
this.options.reflowComments = true;
this.options.spaceBeforeAssignmentOperators = true;
this.options.tabWidth = 4;
this.options.useTab = true;
this.options.alignColons = "none";
this.options.allowShortRulesOnASingleLine = true;
this.options.alignSemicolons = "ownLine";
this.options.singleLineOverrulesHangingColon = true;
this.options.breakBeforeParens = false;
this.options.ruleInternalsOnSingleLine = false;
this.options.minEmptyLines = 0;
this.options.groupedAlignments = true;
this.options.alignFirstTokens = false;
this.options.alignLexerCommands = false;
this.options.alignActions = false;
this.options.alignLabels = true;
this.options.alignTrailers = false;
}
/**
* Is the value at the given index in the token list of the given type?
*
* @param index The index for the value.
* @param marker The marker type for which to test.
*
* @returns True if the value is of the given type.
*/
private entryIs(index: number, marker: InsertMarker): boolean {
if (index < 0 || index >= this.outputPipeline.length) {
return false;
}
const entry = this.outputPipeline[index];
switch (marker) {
case InsertMarker.Whitespace: {
return entry === InsertMarker.LineBreak || entry === InsertMarker.Space || entry === InsertMarker.Tab;
}
case InsertMarker.Space: {
return entry === InsertMarker.Space;
}
case InsertMarker.Tab: {
return entry === InsertMarker.Tab;
}
case InsertMarker.LineBreak: {
return entry === InsertMarker.LineBreak;
}
case InsertMarker.Comment: {
if (entry < 0) {
return false;
}
const token = this.tokens[entry];
return token.type === ANTLRv4Lexer.BLOCK_COMMENT || token.type === ANTLRv4Lexer.LINE_COMMENT
|| token.type === ANTLRv4Lexer.DOC_COMMENT;
}
default: {
if (entry < 0) {
return entry === marker;
}
const token = this.tokens[entry];
return token.type === marker;
}
}
}
private lastEntryIs(marker: InsertMarker): boolean {
return this.entryIs(this.outputPipeline.length - 1, marker);
}
private lineHasNonWhitespaceContent(): boolean {
let index = this.outputPipeline.length;
while (--index > 0) {
if (this.outputPipeline[index] !== InsertMarker.Space
&& this.outputPipeline[index] !== InsertMarker.Tab) {
break;
}
}
if (index <= 0) {
return false;
}
return this.outputPipeline[index] !== InsertMarker.LineBreak;
}
/**
* Skips over all comments and whitespaces backwards and checks the value of the value after that.
*
* @param marker The marker type for which to test.
*
* @returns True if the last non-whitespace token is of the given type.
*/
private lastCodeTokenIs(marker: InsertMarker): boolean {
let i = this.outputPipeline.length - 1;
while (i >= 0) {
if (!this.entryIs(i, InsertMarker.WhitespaceEraser)
&& !this.entryIs(i, InsertMarker.Whitespace)
&& !this.entryIs(i, InsertMarker.LineBreak)
&& !this.entryIs(i, InsertMarker.Comment)) {
break;
}
--i;
}
if (i < 0 || this.outputPipeline[i] < 0) {
return false;
}
return this.tokens[this.outputPipeline[i]].type === marker;
}
private removeLastEntry() {
Iif (this.formattingDisabled) {
return;
}
const lastEntry = this.outputPipeline[this.outputPipeline.length - 1];
this.outputPipeline.pop();
switch (lastEntry) {
case InsertMarker.WhitespaceEraser:
break; // Ignore.
case InsertMarker.LineBreak:
--this.currentLine;
break;
case InsertMarker.Tab: {
const offset = this.currentColumn % this.options.tabWidth!;
this.currentColumn -= (offset > 0 ? offset : this.options.tabWidth!);
break;
}
default:
--this.currentColumn;
break;
}
console.assert(this.currentLine >= 0, "Current line can never be less than 0");
console.assert(this.currentColumn >= 0, "Current column can never be less than 0");
}
/**
* Scans backwards and removes any pipeline entry up to the first non-space entry.
*/
private removeTrailingTabsAndSpaces() {
Iif (this.formattingDisabled) {
return;
}
while (this.lastEntryIs(InsertMarker.Space) || this.lastEntryIs(InsertMarker.Tab)) {
this.removeLastEntry();
}
}
/**
* Scans backwards and removes any pipeline entry up to the first non-whitespace entry.
*/
private removeTrailingWhitespaces() {
Iif (this.formattingDisabled) {
return;
}
while (this.lastEntryIs(InsertMarker.Whitespace)) {
this.removeLastEntry();
}
}
private pushCurrentIndentation(force = false) {
if (this.formattingDisabled || (!force && this.singleLineBlockNesting > 0)) {
return;
}
if (this.options.useTab) {
const tabs: number[] = Array(this.currentIndentation).fill(InsertMarker.Tab);
this.outputPipeline.push(...tabs);
this.currentColumn = this.currentIndentation * this.options.tabWidth!;
} else {
const spaces: number[] = Array(this.currentIndentation * (this.options.indentWidth ?? 4))
.fill(InsertMarker.Space);
this.outputPipeline.push(...spaces);
this.currentColumn = this.currentIndentation * this.options.indentWidth!;
}
}
private applyLineContinuation() {
while (this.lastEntryIs(InsertMarker.Space) || this.lastEntryIs(InsertMarker.Tab)) {
this.removeLastEntry();
}
if (!this.lastEntryIs(InsertMarker.LineBreak)) {
this.outputPipeline.push(InsertMarker.LineBreak);
++this.currentLine;
}
this.currentColumn = 0;
this.pushCurrentIndentation(true);
if (this.options.useTab) {
this.outputPipeline.push(InsertMarker.Tab);
} else {
const spaces: number[] = Array(this.options.continuationIndentWidth).fill(InsertMarker.Space);
this.outputPipeline.push(...spaces);
}
this.currentColumn += this.options.continuationIndentWidth!;
}
/**
* Adds the given marker to the output pipeline and updates current line + column.
*
* @param marker The emarker to add.
*/
private add(marker: InsertMarker) {
Iif (this.formattingDisabled) {
return;
}
/**
* Helper function to insert a block with embedded line breaks.
*
* @param token The token for which to enter the block.
*/
const insertBlock = (token: Token): void => {
const parts = token.text!.split("\n");
if (parts.length === 1) {
this.currentColumn += token.text!.length;
} else {
this.currentLine += parts.length - 1;
this.currentColumn = this.computeLineLength(parts[parts.length - 1]);
}
this.outputPipeline.push(marker);
};
switch (marker) {
case InsertMarker.WhitespaceEraser: { // Doesn't move current position.
this.outputPipeline.push(marker);
return;
}
case InsertMarker.LineBreak: {
this.outputPipeline.push(marker);
++this.currentLine;
this.currentColumn = 0;
return;
}
default: {
let token: Token | undefined;
if (marker >= 0) {
token = this.tokens[marker];
}
if (token) {
switch (token.type) {
case ANTLRv4Lexer.BLOCK_COMMENT: {
insertBlock(token);
return;
}
case ANTLRv4Lexer.ACTION_CONTENT: { // Action content can contain line breaks.
insertBlock(this.tokens[marker]);
return;
}
default: {
const tokenLength = token.stopIndex - token.startIndex + 1;
if (this.currentColumn + tokenLength > this.options.columnLimit!) {
// Note: this implementation works on non-aligned content and allows alignments
// after the word wrapping.
// In cases where alignment moves text beyond the column limit, we don't do
// another word wrapping round. Instead we let alignments overrule the column limit.
// The same applies for exceeding of the column limit caused by deep/large indentation,
// where the indentation already goes beyond that limit.
if (this.lineHasNonWhitespaceContent()) {
this.applyLineContinuation();
}
}
this.currentColumn += tokenLength;
this.outputPipeline.push(marker);
break;
}
}
} else {
++this.currentColumn;
this.outputPipeline.push(marker);
}
break;
}
}
}
/**
* Returns the index for the token which covers the given character index.
* If no token can be found for that position return the EOF token index.
*
* @param charIndex The character index to examine.
* @param first If this is true the search behavior is changed and returns the first token on the line
* where the found token is on.
*
* @returns The index of the token as requested.
*/
private tokenFromIndex(charIndex: number, first: boolean): number {
// Sanity checks first.
if (charIndex < 0) {
return 0;
}
if (charIndex >= this.tokens[0].inputStream!.size) {
return this.tokens.length - 1;
}
for (let i = 0; i < this.tokens.length; ++i) {
const token = this.tokens[i];
if (token.startIndex > charIndex) {
Iif (i === 0) {
return i;
}
--i;
if (!first) {
return i;
}
const row = this.tokens[i].line;
while (i > 0 && this.tokens[i - 1].line === row) {
--i;
}
return i;
}
}
return this.tokens.length - 1;
}
/**
* Computes the length of the given text, with tab stops.
* There must be no line breaks in the text.
*
* @param text The line for which to return the length.
*
* @returns The computed length, which is equal to the line length if there are no tabs in the text.
*/
private computeLineLength(text: string): number {
let length = 0;
for (const char of text) {
Iif (char === "\t") {
// Round up column offset to next tab stop.
const offsetToNextTabStop = this.options.tabWidth! - (this.currentColumn % this.options.tabWidth!);
length += offsetToNextTabStop;
} else {
++length;
}
}
return length;
}
/**
* Used only for real tokens (indices), e.g. in non-formatting mode.
* Inserts a range for the given start and end markers.
* No processing takes place, except for line/column updates.
*
* @param start The start index for the raw range.
* @param stop The end index for the raw range.
*/
private addRaw(start: InsertMarker, stop: InsertMarker): void {
const interval = Interval.of(this.tokens[start].startIndex, this.tokens[stop].stopIndex);
const text = this.tokens[0].inputStream!.getText(interval);
if (text.indexOf("\n") >= 0) {
const parts = text.split("\n");
this.currentLine += parts.length - 1;
this.currentColumn = this.computeLineLength(parts[parts.length - 1]);
} else {
this.currentColumn += this.computeLineLength(text);
}
this.ranges.push([start, stop]);
this.outputPipeline.push(InsertMarker.Range - this.currentRangeIndex++);
}
private addSpace() {
if (this.outputPipeline.length > 0
&& !this.lastEntryIs(InsertMarker.Space)
&& !this.lastEntryIs(ANTLRv4Lexer.LINE_COMMENT)) {
this.add(InsertMarker.Space);
}
}
private addLineBreak(force = false) {
if (this.singleLineBlockNesting === 0 || force) {
// If the current line ends with tabs/spaces, remove them first.
while (this.lastEntryIs(InsertMarker.Space) || this.lastEntryIs(InsertMarker.Tab)) {
this.removeLastEntry();
}
this.add(InsertMarker.LineBreak);
}
}
/**
* Ensure there are at least as many empty lines as specified in the options,
* but not more than max empty lines.
*/
private ensureMinEmptyLines(): void {
Iif (this.formattingDisabled) {
return;
}
if (this.options.minEmptyLines! > 0) {
let lineBreakCount = Math.min(this.options.minEmptyLines!, this.options.maxEmptyLinesToKeep!) + 1;
for (let i = this.outputPipeline.length - 1; i > 0 && lineBreakCount > 0; --i) {
if (this.entryIs(i, InsertMarker.LineBreak)) {
--lineBreakCount;
} else if (!this.entryIs(i, InsertMarker.Whitespace)) {
break;
}
}
const lineBreaks: number[] = Array(lineBreakCount).fill(InsertMarker.LineBreak);
this.outputPipeline.push(...lineBreaks);
this.currentLine += lineBreakCount;
if (lineBreakCount > 0) {
this.currentColumn = 0;
}
} else if (!this.lastEntryIs(InsertMarker.LineBreak)) {
this.addLineBreak();
}
}
/**
* Starting from position i this methods scans forward in the input token list to determine
* if the current block contains alternatives and how long it would be (in characters) if the block would be
* formatted on a single line.
* If there's a single line comment before the stoppers we cannot put the block on a single line.
* If there's one after the stopper account for that too.
*
* @param i The position to start scanning from. Should point to either a colon or an opening parenthesis.
* @param stoppers A set of token types that make the scan stop.
*
* @returns An object containing a flag the indicates if the given block contains alternatives and a number
* that gives the length of the block if it was to be formatted all on a single line.
*/
private getBlockInfo(i: number, stoppers: Set<number>): { containsAlts: boolean; singleLineLength: number } {
let containsAlts = false;
let singleLineLength = 1;
let nestingLevel = 0;
let token = this.tokens[i];
if (token.type === ANTLRv4Lexer.COLON || token.type === ANTLRv4Lexer.OR) {
++singleLineLength; // One for the space after these two.
}
const checkTrailingComment = () => {
while (this.tokens[++i].type === ANTLRv4Lexer.WS) {
if (this.tokens[i].text!.indexOf("\n") >= 0) {
break;
}
}
if (this.tokens[i].type === ANTLRv4Lexer.LINE_COMMENT) {
singleLineLength += this.tokens[i].text!.length;
}
};
while (++i < this.tokens.length) {
token = this.tokens[i];
switch (token.type) {
case ANTLRv4Lexer.WS: {
// Ignore whitespaces here. We pretend there is always a single space char
// between tokens and we will add them below (except for certain tokens).
break;
}
case ANTLRv4Lexer.LPAREN: {
++nestingLevel;
++singleLineLength;
break;
}
case ANTLRv4Lexer.RPAREN: {
// No need to add a space here (we have one from the previous token).
++singleLineLength;
if (nestingLevel > 0) {
--nestingLevel;
} else {
// No check here if RPAREN is in the list of stoppers.
// If it is we return. If not and we got an RPAREN at nesting level 0
// we found an unbalanced block and return also.
checkTrailingComment();
return { containsAlts, singleLineLength };
}
break;
}
case ANTLRv4Lexer.SEMI: {
++singleLineLength;
if (stoppers.has(ANTLRv4Lexer.SEMI)) {
checkTrailingComment();
return { containsAlts, singleLineLength };
}
break;
}
case ANTLRv4Lexer.QUESTION:
case ANTLRv4Lexer.STAR:
case ANTLRv4Lexer.PLUS: {
++singleLineLength; // No addition for a space. That happened already.
break;
}
case ANTLRv4Lexer.LINE_COMMENT: {
// Single line comments cannot be formatted on a single line (they would hide what follows).
// Signal that by a large overall length.
return { containsAlts, singleLineLength: 1e100 };
}
case ANTLRv4Lexer.BLOCK_COMMENT:
case ANTLRv4Lexer.DOC_COMMENT: {
// If the comment contains a line break we cannot format the block as single line.
if (token.text!.indexOf("\n") >= 0) {
return { containsAlts, singleLineLength: 1e100 };
} else {
singleLineLength += token.text!.length + 1;
}
break;
}
case ANTLRv4Lexer.BEGIN_ACTION:
case ANTLRv4Lexer.ACTION_CONTENT:
case ANTLRv4Lexer.END_ACTION: {
// No extra space. These are entire blocks we take over as they are.
Iif (token.text === "\n") {
return { containsAlts, singleLineLength: 1e100 };
} else {
++singleLineLength;
}
break;
}
case ANTLRv4Lexer.OR: {
if (nestingLevel === 0) {
if (stoppers.has(ANTLRv4Lexer.OR)) {
checkTrailingComment();
return { containsAlts, singleLineLength };
}
containsAlts = true;
}
singleLineLength += 2;
break;
}
case ANTLRv4Lexer.NOT: {
++singleLineLength; // Unary NOT, no space after that.
break;
}
default:
if (token.text) {
singleLineLength += token.text.length;
}
++singleLineLength; // Add one for a space char which must follow this token.
break;
}
}
// We should never arrive here, since we bail out above when the block end was found.
return { containsAlts, singleLineLength };
}
/**
* Determines if there is an element after the given position which should go
* on the current line (line comment, lexer commands).
*
* @param i The position to start from.
*
* @returns True if there's something should be kept on the same line.
*/
private nonBreakingTrailerAhead(i: number): boolean {
if (this.tokens[++i].type === ANTLRv4Lexer.WS) {
if (this.tokens[i].text!.indexOf("\n") >= 0) {
return false;
}
++i;
}
return this.tokens[i].type === ANTLRv4Lexer.LINE_COMMENT
|| this.tokens[i].type === ANTLRv4Lexer.RARROW
|| this.tokens[i].type === ANTLRv4Lexer.LPAREN;
}
/**
* Scans the given comment for any of the formatter commands and parses them out.
*
* @param index The index of the comment token.
*/
private processFormattingCommands(index: number): void {
const resetAlignmentStatus = (alignments: AlignmentType[]): void => {
for (const type of alignments) {
const status = this.alignments.get(type);
if (status) {
status.lastLine = -1;
}
}
};
let text = this.tokens[index].text!;
text = text.substr(2, text.length - 2).trim();
if (text.startsWith(formatIntroducer)) {
const entries = text.substr(formatIntroducer.length + 1, text.length).split(",");
for (const entry of entries) {
const groups = /(\w+)(?:(?:\s*:)?\s*)?(\w+|[0-9]+)?/i.exec(entry.trim());
if (groups) {
switch (groups[1]) {
case "reset": {
this.setDefaultOptions();
break;
}
case "on":
case "true": {
this.formattingDisabled = false;
Iif (this.rangeStart > -1) {
this.addRaw(this.rangeStart, index - 1);
}
break;
}
case "off":
case "false": {
this.formattingDisabled = true;
this.rangeStart = index;
break;
}
case "alignTrailingComments":
case "allowShortBlocksOnASingleLine":
case "breakBeforeBraces":
case "keepEmptyLinesAtTheStartOfBlocks":
case "reflowComments":
case "spaceBeforeAssignmentOperators":
case "useTab":
case "allowShortRulesOnASingleLine":
case "singleLineOverrulesHangingColon":
case "breakBeforeParens":
case "ruleInternalsOnSingleLine":
case "groupedAlignments":
case "alignFirstTokens":
case "alignLexerCommands":
case "alignActions":
case "alignLabels":
case "alignTrailers": {
if ((
groups.length > 2 && (groups[2] === "true" || groups[2] === "false")
)
|| groups[2] === "on"
|| groups[2] === "off") {
this.options[groups[1]] = (groups[2] === "true" || groups[2] === "on");
// Some additional handling for alignments. Switching an alignment means
// that the alignment group for that alignment is finished.
switch (groups[1]) {
case "groupedAlignments": {
resetAlignmentStatus(allAlignments);
break;
}
case "alignTrailingComments": {
resetAlignmentStatus([AlignmentType.TrailingComment]);
break;
}
case "alignFirstTokens": {
resetAlignmentStatus([AlignmentType.FirstToken]);
break;
}
case "alignLexerCommands": {
resetAlignmentStatus([AlignmentType.LexerCommand]);
break;
}
case "alignActions": {
resetAlignmentStatus([AlignmentType.Action]);
break;
}
case "alignLabels": {
resetAlignmentStatus([AlignmentType.Label]);
break;
}
case "alignTrailers": {
resetAlignmentStatus([AlignmentType.Trailers]);
break;
}
default: {
break;
}
}
} else E{
this.add(InsertMarker.Error);
}
break;
}
case "columnLimit":
case "continuationIndentWidth":
case "indentWidth":
case "maxEmptyLinesToKeep":
case "tabWidth":
case "minEmptyLines": {
if (groups.length > 2) {
const value = parseInt(groups[2], 10);
if (value !== undefined) {
this.options[groups[1]] = value;
} else E{
this.add(InsertMarker.Error);
}
} else E{
this.add(InsertMarker.Error);
}
break;
}
case "alignColons": {
if (groups.length > 2) {
const value = groups[2];
if (value === "none" || value === "trailing" || value === "hanging") {
this.options.alignColons = value;
} else E{
this.add(InsertMarker.Error);
}
} else E{
this.add(InsertMarker.Error);
}
break;
}
case "alignSemicolons": {
if (groups.length > 2) {
const value = groups[2];
if (value === "none" || value === "ownLine" || value === "hanging") {
this.options.alignSemicolons = value;
} else {
this.add(InsertMarker.Error);
}
} else {
this.add(InsertMarker.Error);
}
break;
}
default: {
this.add(InsertMarker.Error);
break;
}
}
}
}
}
}
/**
* Inserts an alignment marker for the current alignment group for the given type.
* If there's currently no active group a new one is started. This happens also if the current
* position does not qualify for the current group.
*
* @param type The type of the alignment to add.
*/
private addAlignmentEntry(type: AlignmentType): void {
if (!this.alignments.has(type)) {
this.alignments.set(type, { lastLine: -1, groups: [] });
}
const status = this.alignments.get(type)!;
// While we allow multiple different alignment types on a single line, we don't want the same type
// more than once on a line.
if (status.lastLine !== this.currentLine) {
if (this.lineHasNonWhitespaceContent()) {
// Don't remove any indentation.
this.removeTrailingTabsAndSpaces();
}
let startNewGroup = true;
if (status.lastLine > -1) {
// There's an active group. See if we can append the new entry to it.
if (!this.options.groupedAlignments || status.lastLine + 1 === this.currentLine) {
// We can extend the active group.
startNewGroup = false;
// Groups consist of indices into the output pipeline.
status.groups[status.groups.length - 1].push(this.outputPipeline.length);
}
}
if (startNewGroup) {
status.groups.push([this.outputPipeline.length]);
}
this.outputPipeline.push(InsertMarker.Alignment);
status.lastLine = this.currentLine;
}
}
/**
* Goes through the alignment groups for each alignment type. Each member is examined to find the column to
* align to. The alignment markers in the output pipeline are replaced by indices into our whitespace list, which
* gets the text to insert for a specific position. This way we don't change the output pipeline (which would
* invalidate group indices).
*/
private computeAlignments(): void {
for (const type of allAlignments) {
const alignment = this.alignments.get(type);
if (alignment) {
for (const group of alignment.groups) {
// If the group only consists of a single member then ignore it.
if (group.length === 1) {
if (group[0] < this.outputPipeline.length) {
if (this.entryIs(group[0] - 1, InsertMarker.Whitespace)
|| this.entryIs(group[0] - 1, ANTLRv4Lexer.LPAREN)) {
this.outputPipeline[group[0]] = InsertMarker.WhitespaceEraser;
} else {
this.outputPipeline[group[0]] = InsertMarker.Space;
}
}
continue;
}
const columns: number[] = [];
for (const member of group) {
// For partial formatting it can happen we removed the last alignment entry
// in the pipeline. However the associated alignment group still exists and
// may here try to access a non-existing pipeline entry.
if (member < this.outputPipeline.length) {
console.assert(this.outputPipeline[member] <= InsertMarker.Alignment);
columns.push(this.columnForEntry(member));
}
}
// Determine the largest column and bring this up to the next tab stop (if we are using tabs)
// or add a single space to the highest column value and align all others to this position.
const useTabs = this.options.useTab;
let maxColumn = Math.max(...columns);
if (useTabs) {
maxColumn += this.options.tabWidth! - (maxColumn % this.options.tabWidth!);
} else E{
++maxColumn;
}
// Compute required whitespace inserts and store them in the whitespace list.
// Replace the alignment markers in the current group with the indices in that list.
for (let i = 0; i < group.length; ++i) {
const whitespaceIndex = InsertMarker.WhitespaceBlock - this.whitespaceList.length;
this.outputPipeline[group[i]] = whitespaceIndex;
let whitespaces;
if (useTabs) {
let tabCount = Math.floor((maxColumn - columns[i]) / this.options.tabWidth!);
if ((maxColumn - columns[i]) % this.options.tabWidth! !== 0) {
++tabCount;
}
whitespaces = Array(tabCount).fill("\t").join("");
} else E{
whitespaces = Array(maxColumn - columns[i]).fill(" ").join("");
}
this.whitespaceList.push(whitespaces);
}
}
}
}
}
/**
* Determines the column offset of the given entry in the output pipeline.
*
* @param offset The offset for which to return the column.
*
* @returns The computed column.
*/
private columnForEntry(offset: number): number {
let result = 0;
// Scan back to last line break.
let run = offset;
while (--run > -1) {
if (this.outputPipeline[run] === InsertMarker.LineBreak) {
break;
}
}
// Now sum up the individual entries. Need to collect text here since ranges
// as well as lexer tokens can contain tabs.
let text = "";
while (++run < offset) {
const entry = this.outputPipeline[run];
switch (entry) {
case InsertMarker.Space:
text += " ";
break;
case InsertMarker.Tab:
text += "\t";
break;
case InsertMarker.WhitespaceEraser: // Ignore.
case InsertMarker.Error:
break;
default:
// We cannot see alignment markers here (as we are currently processing one),
// nor whitespace blocks (we are inserting them afterwards).
if (entry < 0) {
if (isRangeBlock(entry)) {
// Copy an entire block.
const rangeIndex = -(entry - InsertMarker.Range);
const startIndex = this.ranges[rangeIndex][0];
const endIndex = this.ranges[rangeIndex][1];
const interval = Interval.of(this.tokens[startIndex].startIndex,
this.tokens[endIndex].stopIndex);
text += this.tokens[0].inputStream!.getText(interval);
} else if (isWhitespaceBlock(entry)) {
const whitespaceIndex = -(entry - InsertMarker.WhitespaceBlock);
text += this.whitespaceList[whitespaceIndex];
}
} else {
text += this.tokens[entry].text;
}
break;
}
}
for (const char of text) {
if (char === "\t") {
result += this.options.tabWidth! - (result % this.options.tabWidth!);
} else {
++result;
}
}
return result;
}
/**
* Reformats the given comment so that it does not go beyond the column limit, but fills the available space.
* It will fix indentation as well as leading * on block/doc comments. Lines starting with a dash will be kept
* on an own line, to avoid breaking lists/enumerations (but the column limit is still enforced).
*
* The function should only be called for comments spanning at least 2 lines.
*
* @param comment The comment to reformat.
* @param type Specifies what type of comment we have (a collection of single line comments or a block/doc comment).
* @returns The formatted comment.
*/
private reflowComment(comment: string, type: number): string {
const result: string[] = [];
let lineIntroducer = (type === ANTLRv4Lexer.LINE_COMMENT) ? "// " : " * ";
const lines = comment.split("\n");
let lineIndex = 0;
let pipeline = lines[lineIndex++].split(/ |\t/).filter((entry: string) => {
return entry.length > 0;
});
let line: string;
// We use a leading star only if the second line has one. Otherwise they are all removed (if any).
if (type !== ANTLRv4Lexer.LINE_COMMENT) {
if (!lines[1].trim().startsWith("*")) {
lineIntroducer = " ";
}
const last = lines[lines.length - 1].trim().slice(0, -2);
if (last.length === 0) {
lines.pop();
} else {
lines[lines.length - 1] = last;
}
}
// Take over everything unchanged until the first space or line break.
// If there's only the comment introducer on the first line, keep it that way and start
// on the next line with the processing.
let isFirst = false;
if (pipeline.length === 1) {
result.push(pipeline[0]);
line = lineIntroducer;
isFirst = true;
} else {
line = pipeline[0] + " ";
}
let index = 1;
let column = this.computeLineLength(line);
while (true) {
while (index < pipeline.length) {
if (this.currentColumn + column + pipeline[index].length > this.options.columnLimit!) {
// Don't push the trailing space we added before.
result.push(line.slice(0, -1));
line = lineIntroducer;
column = this.computeLineLength(line);
}
line += pipeline[index++] + " ";
column = this.computeLineLength(line);
}
// Pipeline exhausted. Load next source line.
if (lineIndex === lines.length) {
break;
}
pipeline = lines[lineIndex++].split(/ |\t/).filter((entry: string) => {
return entry.length > 0;
});
index = 0;
if (pipeline.length > 0) {
// Remove line introducer (if there's one). Can make the pipeline empty if it only consists of that.
const first = pipeline[0];
if (type === ANTLRv4Lexer.LINE_COMMENT) {
if (first === "//") {
pipeline = pipeline.slice(1);
} else {
pipeline[0] = first.substr(2);
}
} else {
if (first === "*") {
pipeline = pipeline.slice(1);
} else {
if (first.startsWith("*")) {
pipeline[0] = first.substr(1);
}
}
}
}
if (pipeline.length === 0) {
// Keep empty lines. Push the current line only if this is not still the first line
// (because we already pushed it already).
if (!isFirst) {
result.push(line.slice(0, -1));
}
result.push(lineIntroducer);
line = lineIntroducer;
}
isFirst = false;
}
if (line.length > 0) {
result.push(line.slice(0, -1));
}
if (type !== ANTLRv4Lexer.LINE_COMMENT) {
result.push(" */");
}
const indentation = (this.options.useTab)
? "\t".repeat(this.currentIndentation)
: " ".repeat(this.currentIndentation * this.options.indentWidth!);
return result.join("\n" + indentation);
}
}
|