All files / src/rules downport.ts

92.52% Statements 4073/4402
80.08% Branches 1552/1938
100% Functions 102/102
92.52% Lines 4073/4402

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 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 44031x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 1x 1x 1x 1x 1x 1x 292x 292x 1x 1x 5x 5x 5x 5x 9x     9x 5x 5x 5x 12x 12x 5x 12x 7x 7x 12x 5x 5x 5x 1x 1x 6x 6x 6x 16x 16x 6x 6x 20x 14x 14x 14x 14x 14x 12x 12x 14x 20x 6x 1x 1x 2x 2x 2x 2x 1x 6x 6x 1x 1x 218x 218x 5x 5x 213x 218x 150x 150x 6x 6x 150x 207x 207x 207x 1x 1x 68x 68x 68x 17x 17x 68x 68x     68x 68x 1x 1x 1x 15888x 15888x 15888x 15888x 15888x 15888x 15888x 15888x 76702x 76702x 76702x 76702x 76702x 76702x 76702x 76702x 76702x 76702x 76702x 76702x 76702x 76702x 76702x 76702x 76702x 76702x 76702x 76702x 76702x 76702x 76702x 76702x 76702x 76702x 76702x 76702x 76702x 76702x 76702x 76702x 76702x 76702x 76702x 76702x 76702x 76702x 76702x 76702x 76702x 76702x 15888x 15888x 14908x 14908x 15888x 15888x 264x 264x 15888x 15888x 1078x 1078x 1078x 813x 813x 1078x 1078x 15888x 15888x 1x     1x 1x 1x 1x 1x 1x 15888x 15888x 813x 813x 6117x 1x 1x 6117x 813x     813x 812x 812x 812x 15888x 15888x 1175x 1175x 1175x 1175x 1175x 362x 1175x     813x 813x 1175x     813x 813x 813x 1175x 1x 1x 812x 812x 1175x 1x 1x     1x 1x     1x 1x 812x 812x 812x 812x 812x 812x     812x 812x 812x 812x                       812x 812x 812x 812x 812x 812x 812x 812x 6108x 6108x 6108x 6108x 618x 618x 618x 618x 618x 575x 618x 36x 36x 6x 6x 36x 618x 618x 7x 5x 5x 7x 2x 2x 7x 618x 6108x 810x 812x 25x 25x 199x 199x 21x 21x 5x 5x 21x 199x 25x 810x 812x 10x 78x 78x 78x 8x 8x 78x 10x 810x 810x 810x 810x 812x 299x 2707x 2707x 3x 3x 3x 2707x 299x 810x 810x 810x 812x 296x 2657x 2657x 2x 2x 2x 2657x 296x 810x 810x 810x 812x 294x 2646x     2646x 2646x 3x 3x 3x 2646x 294x 810x 810x 810x 812x 291x 2620x 2620x 2620x 2620x 8x 8x 2620x 291x 810x 810x 812x 283x 283x 812x 812x 810x 810x 810x 15888x 15888x 15888x 15888x 15888x 36x 8x 8x 28x 28x 36x 22x 5x     5x 5x 5x 19x 19x 19x 5x 5x 1x 1x 1x 5x 21x 21x 6x 6x 6x 6x 6x     6x 6x 6x 5x 5x 5x 6x 1x 1x 1x 15888x 15888x 15888x 813x 813x 813x 813x 813x 813x 813x 813x 813x 813x 840x 841x   841x 841x 841x 841x 840x 813x 813x 813x 15888x 15888x 15888x 618x 618x     618x 618x 618x 618x 618x 618x 618x 618x 618x 618x 618x 2x 2x 616x 616x 618x 2x 2x 614x 614x 618x 1x 1x 613x 613x 618x 5x 5x 608x 608x 618x 7x 7x 601x 601x 618x 6x 6x 595x 595x 618x 6x 6x 589x 589x 618x 14x 14x 575x 575x 618x 2x 2x 573x 573x 618x 5x 5x 568x 568x 618x 1x 1x 567x 567x 618x 7x 7x 560x 560x 618x 4x 4x 556x 556x 618x 1x 1x 555x 555x 618x 2x 2x 553x 553x 618x 11x 11x 542x 542x 618x 2x 2x 540x 540x 618x 8x 8x 532x 532x 618x 16x 16x 516x 516x 618x 1x 1x 515x 515x 618x 1x 1x 514x 514x 618x 8x 8x 506x 506x 618x 64x 64x 442x 442x 618x 1x 1x 441x 441x 618x 43x 43x 398x 398x 398x 398x 398x 618x 7x 7x 7x   7x 7x 7x 7x 398x 618x 391x 391x 72x 72x 391x 324x 324x 324x 324x 23x 23x 324x 299x 299x 618x 6x 6x 293x 293x 618x 9x 9x 284x 284x 618x 4x 4x 280x 280x 618x 2x 2x 278x 278x 618x 3x 3x 275x 275x 618x 25x 25x 250x 250x 618x 17x 17x 232x 232x 618x 1x 1x 231x 231x 618x 7x 7x 224x 224x 618x 29x 29x 195x 195x 618x 5x 5x 190x 190x 618x 51x 51x 139x 139x 618x 12x 12x 127x 127x 618x 23x 23x 104x 104x 618x 7x 7x 97x 97x 618x 19x 19x 78x 78x 618x     78x 78x 618x 1x 1x 77x 77x 618x 2x 2x 75x 75x 618x 21x 21x 52x 52x 618x 2x 2x 50x 50x 618x 9x 9x 41x 41x 618x 1x 1x 40x 40x 618x 3x 3x 37x 37x 618x 1x 1x 36x 36x 36x 15888x 15888x 15888x 15888x 15888x 15888x 15888x 15888x 3134x 3134x 3054x 3054x 80x 80x 3134x 3134x 14x 14x 66x 66x 3134x 12x 12x 54x 54x 3134x 52x 52x 3134x 26x 26x 3134x     54x 3134x 38x 38x 16x 16x 3134x     16x 16x 16x 16x 16x 16x 16x 3134x 3134x 6x 6x 6x 16x 16x 16x 16x 16x 16x 16x 16x 15888x 15888x 15888x 15888x 8x 8x 8x 8x   8x     8x 8x 8x 1x 1x 7x 7x 8x 1x 1x 6x 6x 15888x 15888x 15888x 506x 132x 132x 374x 374x 506x 506x 506x 506x 506x 506x 506x 506x 301x 301x 73x 73x 73x 90x 90x 54x 90x 36x 36x 73x 73x 73x 73x 73x 73x 73x 73x 73x 506x 132x 132x 82x 82x 10x 10x 8x 8x 1x 1x 7x 7x 7x 8x 8x 8x 8x 8x 2x 10x 10x 10x 10x 82x 72x 72x 82x 132x 63x 506x 61x 49x 18x 18x 49x 61x 63x 506x 53x 53x 10x 506x 2x 2x 2x 1x 1x 1x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 9x 9x 9x 15888x 15888x 15888x 515x 132x 515x 378x 378x 5x 515x 515x 515x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 15888x 15888x 516x 132x 516x 335x 335x 49x 49x 516x 47x 47x 516x 516x 1x 1x 1x 516x     516x 516x 516x 516x 516x 516x 516x 516x 516x 516x 516x 15888x 15888x 532x 532x 132x 532x 330x 330x 70x 70x 70x 532x 10x 10x 60x 60x 532x 6x 6x 54x 54x 54x 15888x 15888x 293x 293x 102x 293x 182x 182x 9x 9x 293x     9x 9x 9x 9x 9x 9x 9x 293x 4x 4x 1x 1x 4x 9x 9x 9x 9x 9x 9x 15888x 15888x 70x 70x     70x 70x 70x 35x 35x 35x 35x 70x 25x 25x 10x 10x 70x     10x 70x 70x     10x 10x 10x 70x     70x     10x 10x 70x 70x 5x 5x 2x 5x 1x 3x 2x 1x 1x           1x 1x 2x 2x 2x 1x 1x 1x 10x 10x 10x 10x 10x 10x 10x 10x 15888x 15888x 60x 60x     60x 60x 60x 26x 26x 34x 34x 34x 60x 28x 28x 6x 6x 60x     6x 60x 60x     6x 6x 60x 10x 10x     10x 10x 10x 6x 6x 60x     6x 6x 60x 12x 12x     12x 5x 5x 5x 5x 12x 12x 12x 12x 12x 6x 6x 60x 60x 60x 60x 60x 60x 60x 1x 1x 1x 6x 6x 6x 6x 6x 6x 15888x 15888x 15888x 21x     21x 21x 21x 16x 16x 5x 5x 5x 5x 5x 5x 5x 5x 5x 15888x 15888x 40x 37x 37x 3x 40x     3x 3x 40x 5x   5x 1x 5x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x       15888x 15888x 52x 50x 50x 2x 2x 2x 2x 2x 2x     2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x       15888x 15888x 37x 34x 34x 3x 3x 37x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 15888x 15888x 41x 37x 37x 4x 4x 41x 41x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 15888x 15888x 50x 41x 41x 9x 9x 9x 9x 9x 9x     9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x       15888x 15888x 75x 14x 14x 61x 61x 61x 61x 38x 38x 23x 23x 61x       23x 23x 23x 61x 48x 23x 48x 23x 23x 25x 25x 61x     23x 23x 23x 23x 61x 8x 8x     8x 8x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 61x 5x 5x 5x 5x 5x 5x 23x 23x 23x 23x 23x 23x 23x 61x 2x 2x 21x 21x 21x 38x 38x 38x 15888x 15888x 15888x 15888x 15888x 15888x 15888x 15888x 15888x 15888x 10x     10x 10x 10x 10x 30x 10x 10x   10x 3x 3x 3x 10x 30x     20x 30x 10x 10x 10x 10x 10x 10x 30x 2x 2x     2x 2x 10x 10x 30x     10x 10x     10x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 9x 9x     15888x 15888x 31x 31x 31x 124x 62x 62x 13x 12x 13x 1x 1x 62x 18x 49x 1x 31x 1x 1x 1x 60x 60x 31x 31x 15888x 15888x 15888x 15888x 15888x 15888x 15888x 15888x 15888x 15888x 15888x 15888x 15888x 15888x 575x 575x 132x 132x 443x 575x 70x 70x 314x 49x 49x 314x 265x 265x 216x 216x 49x 49x 314x 47x 47x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 68x 441x 441x 441x 15888x 15888x 15888x 2657x 2657x 2610x 2657x 1x 47x     46x 46x 46x 46x 2657x 2657x 2657x 43x 43x 3x 3x 2657x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 15888x 15888x 15888x 15888x 15888x 3202x 3185x 3202x 1x 1x 16x 16x 3202x 1x 1x 15x 15x 15x 15x 3202x 3202x 3202x 3202x 3202x 3202x 3202x 3202x 1x 1x 14x 14x 3202x     14x 14x 3202x 3202x 3202x 3202x 3202x 3202x 3202x 10x 10x 3202x 8x 8x     8x 4x 4x 4x 4x 4x 3202x 3202x 3202x 3202x 3202x 3202x 3202x 3202x 3202x 3202x 3202x 3202x 3202x 3202x 3202x 15888x 15888x 15888x 15888x 52x 52x 52x 220x 220x 214x 214x 6x 220x 2x 2x 220x 220x 46x 46x 46x 15888x 15888x 232x 232x 232x 8x 8x 224x 232x 223x 223x 1x 1x 232x     1x 1x 232x     1x 1x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 15888x 15888x 15888x 15888x 7x 7x 3x 3x 4x 4x 15888x 15888x 231x 224x 224x 7x 7x 231x     7x 7x 231x     7x 231x 231x 231x 231x 231x 231x 231x 231x 231x 231x 231x 15888x 15888x 224x 106x 106x 118x 224x 3x 3x 115x 115x 224x 40x 40x 75x 75x 75x 224x   224x 6x 75x 34x 69x 1x 35x 1x 34x 3x 3x 3x 3x 3x 1x 3x 2x 2x 33x 30x 30x 30x 30x 2x 2x 30x 28x 28x 28x 29x 224x 224x 224x 224x 224x 224x 224x 224x 224x 224x 15888x 15888x 614x 8x 8x 606x 614x 1x 1x     1x 1x     1x 1x 1x 605x 605x 605x 15888x 15888x 613x 613x 613x 613x 613x 613x 613x 613x 613x 613x 613x 613x 613x 613x 613x 613x 613x 613x 613x 613x 613x 613x 606x 606x 7x 7x 7x 7x 7x 613x 2x 2x 2x 2x     2x 2x 1x 1x 613x 5x 5x 2x 2x 3x 5x 2x 5x 1x 1x 3x 5x 2x 5x 1x 1x 3x 3x 3x 5x 613x 613x 613x 613x 613x 613x 613x 613x 613x 613x 613x 613x 2x 2x 2x 2x 2x 5x 5x 5x 613x 2x 2x 5x 613x 6x 6x 6x 5x 5x 5x 5x 5x 5x 15888x 15888x 608x 132x 132x 476x 608x 4x 4x     4x 4x 4x     4x 4x     4x 4x 4x 4x 472x 608x 3x 3x 3x 23x 3x 3x 3x 23x   469x 469x 469x 15888x 15888x 542x 540x 540x 2x 2x 542x 3x 3x 3x 3x 1x 1x 3x 2x 2x 3x 542x     2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 15888x 15888x 560x 560x 560x 551x 551x 9x 9x 560x     9x 560x 560x 2x 2x 2x 2x 2x 2x 2x 560x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 5x 5x 5x 15888x 15888x 567x 567x 567x 560x 560x 7x 7x 567x     567x 567x 567x     7x 7x 567x 2x 2x 2x 2x 2x 2x 567x 5x 5x 5x 5x 5x 4x 4x 4x 4x 4x 1x 1x 1x 4x 4x 5x 5x 7x 7x 7x 7x 7x 7x 7x 15888x 15888x 553x 493x 493x 60x 553x 49x 49x 553x 553x 553x 553x 553x 553x 553x 553x 553x 553x 553x 553x 553x 11x 11x 11x 10x 10x 11x 11x 11x 11x 11x 11x 553x 10x 10x 10x 2x 2x 10x 1x 1x 8x 7x 1x 1x 7x 7x 7x 7x 10x 10x 11x 11x 553x 5x 5x 5x 5x 5x 5x 5x 11x 11x 11x 11x 11x 11x 11x 11x 553x 553x 1x 1x 11x 11x 553x 2x 2x 553x 553x 553x 553x 10x 10x 10x 1x 10x 2x 9x 7x 7x 10x 553x 5x 5x 553x 553x 553x 553x 553x 553x 553x 553x 553x 11x 11x     11x 15x 4x 4x     4x 4x 4x 4x 4x 15x 11x 11x 11x 11x 15888x 15888x 555x 132x 132x 423x 423x 555x 1025x 1025x 2x 2x 1025x 555x 421x 421x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 15888x 15888x 573x 132x 132x 441x 573x 432x 573x     9x 573x 573x 573x 573x 573x 4x 4x 5x 5x 573x 2x 2x     2x 573x 3x 3x 3x 3x 3x 5x 5x 573x 12x 5x 5x 7x 7x 5x 5x 573x 573x 573x 573x 573x 573x 15888x 15888x 568x 132x 132x 436x 568x 432x 432x 4x 4x 568x 3x 3x 1x 1x 568x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 15888x 15888x 589x 132x 132x 457x 457x 589x 256x 256x 201x 201x 589x     201x 589x     201x 589x 41x 41x 160x 589x 102x 102x 58x 589x 7x 7x 51x 51x 589x 34x 589x 3x 3x 14x 14x 14x 589x 16x 16x 14x 14x 14x 14x 14x 14x 14x 14x 15888x 15888x 15888x 616x 616x 614x 614x 616x 616x     616x     2x 616x 616x 616x 616x 616x 616x 616x 616x 4x 4x 4x 2x 2x 4x 4x 2x 2x 2x 2x 2x 2x 2x 2x 2x 15888x 15888x 540x 132x 132x 408x 408x 540x 175x 540x 233x 233x 233x 29x 29x 29x 29x 29x 540x 227x 227x 181x 540x 173x 173x 8x 540x     8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 540x 540x     8x 8x 8x 8x 8x 8x 8x 15888x 15888x 595x 132x 595x 256x 256x 207x 207x 595x     207x 207x 207x 207x 595x 1x 1x 595x 1x 1x 595x 1x 1x 595x 1x 1x 595x 2x 2x 595x 201x 595x 6x 595x 595x     6x 595x 595x     6x 6x 6x 6x 6x 15888x 15888x 601x 132x 132x 469x 601x 27x 27x 27x 21x 21x 6x 6x 6x 27x 2x 2x 27x 4x 4x 27x   27x 6x 6x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 463x 463x 463x 463x 15888x 15888x 442x 132x 442x 292x 310x 17x 17x 1x 1x 442x 442x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 15888x 15888x 441x 441x 393x 393x 48x 441x 1x 1x 47x 441x 441x     441x 441x     47x 47x 47x 47x 47x 47x 47x 47x 441x 4x 4x 43x 43x 43x 441x 441x 30x 30x 30x 9x 9x 9x 30x 30x 30x 30x 30x 13x 441x 441x 13x 13x 13x 13x 2x 2x 13x 13x 13x 13x 13x 13x       15888x 15888x 44x 44x 44x 44x 44x 44x 44x 44x 44x 5x 5x 5x 44x 3x 3x 3x 44x 44x 25x 25x 25x 25x 2x 2x 25x 25x 42x 44x 44x 1x 1x 42x 42x 44x 44x 44x 44x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 1x 16x 15x 15x 16x 16x 44x 23x 23x 23x 23x 23x 23x 23x 3x 1x 1x 3x 3x 23x 2x 2x 23x 23x 3x 3x 23x 3x 3x 23x     23x 23x 23x 5x 5x 1x 5x 4x 4x 5x 23x 23x 23x 1x 1x 23x 23x 23x 1x 1x 23x 23x 23x 1x 1x 23x 26x 3x 3x 3x 3x 1x 1x 3x 3x 42x 42x 44x 1x 1x 42x 42x 42x 15888x 15888x 280x 102x 102x 178x 280x 487x 487x 485x 485x 2x 2x 487x     2x 487x 487x     2x 2x 487x   487x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 176x 176x 176x 15888x 15888x 284x 102x 102x 182x 284x 495x 495x 490x 490x 5x 5x 495x 3x 3x 3x 2x 2x 3x 1x 1x 495x 2x 2x 4x 4x 4x 4x 4x 495x     4x 495x       4x 4x 4x 4x 495x 36x 4x 4x 36x 7x 7x 32x 7x 7x 25x   18x 2x 2x 18x 7x 16x 9x 9x 36x 4x 4x 4x 4x 4x 4x 4x 4x 178x 178x 178x 15888x 15888x 324x 102x 102x 222x 324x 552x 552x 526x 526x 26x 26x 552x 1x 1x 25x 25x 25x 25x 25x 552x     25x 25x 552x 1x 1x 25x 25x 552x 29x 29x 25x 25x 29x 29x 29x 1x 1x 28x 29x 29x 29x 27x 2x 27x 25x 25x 29x 1x 1x 29x 24x 24x 552x 25x 25x 25x 25x 23x 23x 552x     552x 104x 104x 23x 104x 27x 81x 27x 27x 27x 27x 104x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 197x 197x 197x 15888x 15888x 299x 102x 102x 197x 197x 299x 521x 521x 513x 513x 8x 8x 8x 521x 1x 1x 7x 7x 7x 7x 7x 521x             521x 7x 7x 7x 521x 521x 5x 5x 5x 1x 1x 4x 4x 4x 5x 1x 1x 5x 3x 3x 3x 4x 4x 3x 5x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 191x 191x 191x 15888x 15888x 391x 102x 102x 289x 289x 391x 707x 707x 632x 632x 75x 75x 75x 75x 707x 29x 28x 28x 29x 1x 1x 707x 46x 46x 74x 74x 74x 74x 707x 707x 9x 9x 74x 74x 74x 74x 74x 74x 74x 707x 46x 46x 46x 46x 74x 74x 74x 707x 707x 707x 707x 124x 18x 3x 3x 3x 3x 18x 12x 12x 12x 15x 124x 19x 19x 19x 19x 106x 4x 4x 1x 1x 87x 6x 6x 124x 65x 65x 20x 10x 10x 10x 20x 20x 4x 4x 20x 65x 222x 68x 12x 12x 12x 68x 222x 23x 23x 23x 154x 1x 1x 131x 65x 3x 3x 3x 65x 41x 41x 65x 222x 222x 65x 124x 72x 707x 3x 3x 3x 3x 3x 3x 3x 8x 3x 8x 3x 5x 2x 2x 8x 3x 3x 3x 1x 3x 2x 2x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 3x 72x 707x 16x 16x 16x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 215x 215x 215x 15888x 15888x 15888x 86x 86x 86x 15888x 15888x 15888x 15888x 15888x 62x 62x 62x 124x 18x 1x 1x 124x 106x 106x 41x 41x 41x 41x 41x 41x 9x 9x 32x 32x 124x 52x 52x 15888x 15888x 12x 12x 14x 14x     14x 14x 14x 14x     14x 14x 2x 2x 12x 12x 14x             14x 14x 14x 14x 14x 14x 12x 12x 14x 10x 10x 15888x 15888x 5x 5x 5x 5x 5x 15888x 15888x 15888x 5x 5x     5x 5x     5x 5x     5x 5x 26x 26x 26x 5x 5x 26x     5x           15888x 15888x 164x 164x     164x 164x 164x 164x 74x 74x 90x 90x 164x     90x 90x 164x 435x 435x 435x 435x 435x 53x 53x 53x 435x 164x 37x 37x 53x 164x 2x 164x 51x 51x 164x 15888x 15888x 139x 139x 18x 18x 121x 139x 12x 12x     12x 12x 12x 12x 1x 12x 11x 11x     11x 11x   11x     11x 11x 11x 12x 12x 12x 12x 12x 12x 12x 12x 12x 109x 109x 109x 15888x 15888x 15888x 195x 173x 173x 22x 195x 1x 1x 21x 21x 21x 195x 195x 10x 10x 11x 195x 195x     11x 11x 11x 195x 195x 195x 195x   195x 11x 6x 6x 5x 5x 5x 195x 1x 1x 1x 5x 5x 5x 5x 5x 5x 15888x 15888x 190x 190x 190x 8x 8x 182x 190x 62x 62x     62x 62x 62x 62x     62x 62x 62x   62x 10x 62x 1x 1x 51x 51x 62x 62x 62x 2x 2x 62x     51x 51x 51x 51x 51x 51x 51x 51x 51x 131x 131x 131x 15888x 15888x 250x 102x 102x 148x 250x 317x 298x 298x 19x 19x 317x     19x 19x 19x 317x 3x 3x 3x 2x 2x 3x 1x 1x 317x 16x 16x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 130x 130x 130x 15888x 15888x 18x 18x 18x 18x 18x 102x 49x 49x 18x 17x 17x 18x 1x 1x 18x 49x 18x 18x 49x 13x 13x 13x 49x   49x 102x 18x 53x 4x 35x 29x 31x 2x 2x     102x 18x 4x 4x 4x 4x 17x 17x 17x 17x 17x 17x 15888x 15888x 275x 102x 102x 173x 275x 425x 400x 400x 25x 425x     25x 425x 425x     25x 25x 25x 25x 25x 25x 425x 425x 1x 1x 24x 425x 425x 425x 425x 425x 425x 425x 425x 425x 425x 425x 425x 148x 148x 148x 15888x 15888x 15888x 15888x 2707x 2707x 2678x 2707x 2x 29x     27x 27x 2707x 2707x 2707x 2707x 2707x 2707x 2707x 2707x 2707x 2707x 23x 23x 4x 2707x 2707x 1x 1x 3x 3x 2707x 2707x     3x 3x 2707x 7x 7x 3x 3x 3x 3x 3x 3x 7x 2707x     3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 15888x 15888x 15888x 15888x 25x 25x 21x 25x     25x 25x 15888x 15888x 15888x 278x 102x 102x 176x 278x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 173x 173x 173x 15888x 15888x 15888x 15888x 15888x 457x 457x 457x 457x         457x 457x 457x 2x 2x 2x 2x 457x 457x 509x 509x 509x 509x 457x 457x 509x 457x 15888x 15888x 15888x 666x 666x 47x 47x 619x 666x 162x 6x 6x 162x 613x 613x 613x 15888x 15888x 15888x 15888x 618x 615x 618x       3x 3x 3x 618x 14x 14x 14x 14x 2x 2x 2x 2x 2x 14x 1x 1x 1x 15888x 15888x 78x 4x 4x 74x 74x 74x 78x 157x 157x 27x 27x 27x 27x 10x 8x 8x 8x 10x 27x 27x 19x 19x 8x 8x 8x 8x 8x 8x 157x 66x 66x 66x 15888x 15888x 20x 20x 20x 20x 20x     15888x 15888x 77x 14x 14x 63x 77x 42x 42x 40x 40x 2x 2x 42x       2x 2x 2x 42x 3x 3x 1x 1x 1x 3x 2x 2x 2x 42x 1x 1x 1x 1x 2x 2x 61x 61x 61x 15888x 15888x 78x 78x 78x   78x 78x     78x 78x 78x                     15888x 15888x 78x 78x 78x 78x 78x 44x 44x 4x 4x 44x 78x 74x 74x 4x 78x 8x 4x 4x 4x 8x 1x 1x 1x 1x     1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 8x 3x 3x 3x 15888x 15888x 97x 8x 8x 89x 89x 89x 97x 418x 383x 383x 35x 418x 19x 19x 19x 19x     19x 19x 19x 102x 38x 102x 18x 64x 1x 1x 64x 64x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 4x 4x 4x     4x 19x 19x 19x 19x 19x 19x 38x 5x 5x 38x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 418x 70x 70x 70x 15888x 15888x 15888x 15888x 104x 104x 14x 104x 90x 90x 52x 52x 52x 38x 104x 54x 54x 54x 47x 47x 7x 7x 7x 7x 7x 54x 1x 1x 1x     1x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 54x 54x 54x 54x 31x 31x 31x 15888x 15888x 15888x 15888x 19x 19x 19x 19x 19x 19x 57x 15x 13x 13x 15x 57x 19x 19x 19x 19x 76x 2x 2x 2x 2x 76x 19x 19x 19x 125x 48x 48x 77x 125x 271x 5x 5x 5x 5x 5x 271x 77x 19x 19x 15888x 15888x 5x 5x 5x 6x 6x 5x 5x 6x 1x       15888x 15888x 127x 14x 14x 113x 113x 113x 113x 113x 113x 127x 19x 19x 19x 19x 19x 19x 19x 17x 17x 17x 17x 17x 17x 19x 113x 127x 96x 96x 90x 90x 6x 6x 96x     6x 6x 6x 6x 6x 6x 6x 6x 96x 1x 1x 96x 5x 5x 5x 5x 96x 23x 23x 23x 127x     127x 15888x 15888x 15888x 15888x 17x 17x 17x 17x 17x 1x 1x 16x 16x 16x 17x 17x 17x 17x 12x 12x 12x 12x 12x 17x 4x 4x 17x 10x 10x 6x 6x 17x 17x 3x 3x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 15888x 15888x 17x 17x 17x 17x 1x 17x 16x 16x 4x 4x 4x 4x 4x 17x 17x 17x 5x 5x 17x 4x 3x 3x 3x 3x 1x 1x 1x 3x     3x 4x 4x     4x 4x 4x 4x             4x 16x 17x 17x 17x 17x 17x 15888x 15888x 4x 4x 5x 5x 4x 4x 1x 1x 1x 5x     5x 4x 15888x 15888x  
/* eslint-disable max-len */
import * as crypto from "crypto";
import {IRegistry} from "../_iregistry";
import {At, ParenLeftW, WAt, WParenLeftW, WParenRight, WParenRightW} from "../abap/1_lexer/tokens";
import {AbstractToken} from "../abap/1_lexer/tokens/abstract_token";
import * as Expressions from "../abap/2_statements/expressions";
import * as Statements from "../abap/2_statements/statements";
import {ElseIf} from "../abap/2_statements/statements";
import {Unknown} from "../abap/2_statements/statements/_statement";
import * as Structures from "../abap/3_structures/structures";
import {BuiltIn} from "../abap/5_syntax/_builtin";
import {ReferenceType} from "../abap/5_syntax/_reference";
import {ScopeType} from "../abap/5_syntax/_scope_type";
import {ISpaghettiScopeNode, ISyntaxResult} from "../abap/5_syntax/_spaghetti_scope";
import {SyntaxLogic} from "../abap/5_syntax/syntax";
import {ABAPFile} from "../abap/abap_file";
import {ExpressionNode, StatementNode, StructureNode, TokenNode} from "../abap/nodes";
import {IClassDefinition} from "../abap/types/_class_definition";
import {IMethodDefinition} from "../abap/types/_method_definition";
import {TypedIdentifier} from "../abap/types/_typed_identifier";
import {AbstractType} from "../abap/types/basic/_abstract_type";
import {AnyType, DataReference, ObjectReferenceType, StructureType, TableAccessType, TableType, VoidType} from "../abap/types/basic";
import {Config} from "../config";
import {EditHelper, IEdit} from "../edit_helper";
import {Issue} from "../issue";
import {Class, Program} from "../objects";
import {ABAPObject} from "../objects/_abap_object";
import {IObject} from "../objects/_iobject";
import {Position} from "../position";
import {Registry} from "../registry";
import {IncludeGraph} from "../utils/include_graph";
import {Release} from "../version";
import {VirtualPosition} from "../virtual_position";
import {BasicRuleConfig} from "./_basic_rule_config";
import {IRule, IRuleMetadata, RuleTag} from "./_irule";
 
// todo: refactor each sub-rule to new classes?
// todo: add configuration
 
 
export class DownportConf extends BasicRuleConfig {
}
 
class SkipToNextFile extends Error {
  public issue: Issue;
  public constructor(issue: Issue) {
    super();
    this.issue = issue;
  }
}
 
class SpagHelper {
  private readonly spag: ISpaghettiScopeNode;
 
  public constructor(spag: ISpaghettiScopeNode) {
    this.spag = spag;
  }
 
  public renameVariable(oldName: string, pos: Position, lowFile: ABAPFile, newName: string) {
    let fix: IEdit | undefined = undefined;
 
    const references = this.findReferences(oldName, pos);
    references.sort((a, b) => {
      if (a.start.equals(b.start)) {
        return 0;
      }
      return a.start.isAfter(b.start) ? 1 : -1;
    });
 
    for (const r of references) {
      const replace = EditHelper.replaceRange(lowFile, r.start, r.end, newName);
      if (fix === undefined) {
        fix = replace;
      } else {
        fix = EditHelper.merge(replace, fix);
      }
    }
 
    return fix;
  }
 
  private findReferences(name: string, pos: Position): {start: Position, end: Position}[] {
    const positions: {start: Position, end: Position}[] = [];
 
    function has(element: {start: Position, end: Position}): boolean {
      return positions.some(a => a.start.equals(element.start));
    }
 
    for (const r of this.spag.getData().references) {
      if (r.resolved?.getName() === name && r.resolved?.getStart().equals(pos)) {
        const sub = {
          start: r.position.getStart(),
          end: r.position.getEnd(),
        };
        if (has(sub) === false) {
          positions.push(sub);
        }
      }
    }
    for (const child of this.spag.getChildren()) {
      const subPositions = new SpagHelper(child).findReferences(name, pos);
      for (const sub of subPositions) {
        if (has(sub) === false) {
          positions.push(sub);
        }
      }
    }
    return positions;
  }
 
  public findRecursiveDuplicate(name: string, skip: Position): TypedIdentifier | undefined {
    const found = this.spag.findVariable(name);
    if (found?.getStart().equals(skip) === false) {
      return found;
    }
 
    for (const child of this.spag?.getChildren() || []) {
      const sub = new SpagHelper(child).findRecursiveDuplicate(name, skip);
      if (sub) {
        return sub;
      }
    }
 
    return undefined;
  }
 
  public isDuplicateName(name: string, pos: Position) {
    let parent = this.spag.getParent();
    while (parent?.getIdentifier().stype === ScopeType.Let
        || parent?.getIdentifier().stype === ScopeType.For) {
      parent = parent.getParent();
    }
 
    if (parent === undefined) {
      return undefined;
    }
    return new SpagHelper(parent).findRecursiveDuplicate(name, pos) !== undefined;
  }
 
}
 
export class Downport implements IRule {
  private lowReg: IRegistry;
  private highReg: IRegistry;
  private conf = new DownportConf();
  private counter: number;
  private graph: IncludeGraph | undefined;
 
  public getMetadata(): IRuleMetadata {
    return {
      key: "downport",
      title: "Downport statement",
      shortDescription: `Downport functionality`,
      extendedInformation: `Much like the 'commented_code' rule this rule loops through unknown statements and tries parsing with
a higher level language version. If successful, various rules are applied to downport the statement.
Target downport version is always v702, thus rule is only enabled if target version is v702.
 
Current rules:
* NEW transformed to CREATE OBJECT, opposite of https://rules.abaplint.org/use_new/
* DATA() definitions are outlined, opposite of https://rules.abaplint.org/prefer_inline/
* FIELD-SYMBOL() definitions are outlined
* CONV is outlined
* COND is outlined
* REDUCE is outlined
* SWITCH is outlined
* FILTER is outlined
* APPEND expression is outlined
* INSERT expression is outlined
* EMPTY KEY is changed to DEFAULT KEY, opposite of DEFAULT KEY in https://rules.abaplint.org/avoid_use/
* CAST changed to ?=
* LOOP AT method_call( ) is outlined
* VALUE # with structure fields
* VALUE # with internal table lines
* Table Expressions are outlined
* SELECT INTO @DATA definitions are outlined
* Some occurrences of string template formatting option ALPHA changed to function module call
* SELECT/INSERT/MODIFY/DELETE/UPDATE "," in field list removed, "@" in source/targets removed
* OPEN CURSOR/FETCH NEXT CURSOR/CLOSE CURSOR "@" in source/targets removed
* PARTIALLY IMPLEMENTED removed, it can be quick fixed via rule implement_methods
* RAISE EXCEPTION ... MESSAGE
* Moving with +=, -=, /=, *=, &&= is expanded
* line_exists and line_index is downported to READ TABLE
* ENUMs, but does not nessesarily give the correct type and value
* MESSAGE with non simple source
 
Only one transformation is applied to a statement at a time, so multiple steps might be required to do the full downport.
 
Make sure to test the downported code, it might not always be completely correct.`,
      tags: [RuleTag.Downport, RuleTag.Quickfix],
    };
  }
 
  public getConfig() {
    return this.conf;
  }
 
  public setConfig(conf: DownportConf): void {
    this.conf = conf;
  }
 
  public initialize(reg: IRegistry) {
    this.lowReg = reg;
    const config = this.lowReg.getConfig();
    if (config.getRelease() === Release.v702 || config.isOpenABAP()) {
      this.initHighReg();
    }
    return this;
  }
 
  private listMainForInclude(filename: string | undefined) {
    if (filename === undefined) {
      return [];
    }
    // only initialize this.graph if needed
    if (this.graph === undefined) {
      this.graph = new IncludeGraph(this.lowReg);
    }
    return this.graph.listMainForInclude(filename);
  }
 
  private containsError(highObj: ABAPObject): boolean {
    for (const file of highObj.getABAPFiles()) {
      for (const statement of file.getStatements()) {
        if (statement.get() instanceof Unknown) {
          return true; // contains parser errors
        }
      }
      if (file.getStructure() === undefined) {
        return true;
      }
    }
 
    return false;
  }
 
  public run(lowObj: IObject): Issue[] {
    const ret: Issue[] = [];
    this.counter = 1;
 
    const config = this.lowReg.getConfig();
    if (config.getRelease() !== Release.v702 && !config.isOpenABAP()) {
      return ret;
    } else if (!(lowObj instanceof ABAPObject)) {
      return ret;
    }
 
    const highObj = this.highReg.getObject(lowObj.getType(), lowObj.getName());
    if (highObj === undefined || !(highObj instanceof ABAPObject)) {
      return ret;
    }
 
    let highSyntaxObj = highObj;
 
    if (this.containsError(highObj)) {
      return ret;
    }
 
    // for includes do the syntax check via a main program
    if (lowObj instanceof Program && lowObj.isInclude()) {
      const mains = this.listMainForInclude(lowObj.getMainABAPFile()?.getFilename());
      if (mains.length <= 0) {
        return [];
      }
      const f = this.highReg.getFileByName(mains[0]);
      if (f === undefined) {
        return [];
      }
      highSyntaxObj = this.highReg.findObjectForFile(f) as ABAPObject;
    }
 
    for (const lowFile of lowObj.getABAPFiles()) {
      let highSyntax: ISyntaxResult | undefined = undefined;
 
      const highFile = highObj.getABAPFileByName(lowFile.getFilename());
      if (highFile === undefined) {
        continue;
      }
 
      const lowStatements = lowFile.getStatements();
      const highStatements = highFile.getStatements();
      if (lowStatements.length !== highStatements.length) {
        // after applying a fix, there might be more statements in lowFile
        // should highReg be initialized again?
        /*
        const message = "Internal Error: Statement lengths does not match";
        ret.push(Issue.atStatement(lowFile, lowStatements[0], message, this.getMetadata().key));
        */
        // hmm, add some way to disable lazyUnknown() in statement_parser.ts
        // alternatively explicit enable it in vscode, its only relevant when a user is
        // actively editing the files
        continue;
      }
 
      if (highSyntax === undefined) {
        highSyntax = new SyntaxLogic(this.highReg, highSyntaxObj).run();
      }
 
      let containsUnknown = false;
      const notDownported: Issue[] = [];
      for (let i = 0; i < lowStatements.length; i++) {
        const low = lowStatements[i];
        const high = highStatements[i];
        if ((low.get() instanceof Unknown && !(high.get() instanceof Unknown))
            || high.findFirstExpression(Expressions.InlineData)) {
          containsUnknown = true;
 
          try {
            const issue = this.checkStatement(low, high, lowFile, highSyntax, highFile);
            if (issue) {
              ret.push(issue);
            } else {
              const nope = this.notDownported(low, high, lowFile, highSyntax);
              if (nope) {
                notDownported.push(nope);
              }
            }
 
          } catch (e) {
            if (e instanceof SkipToNextFile) {
              ret.push(e.issue);
              break;
            } else {
              throw e;
            }
          }
        }
      }
 
      if (ret.length === 0 && containsUnknown) {
// this is a hack in order not to change too many unit tests
        for (let i = 0; i < lowStatements.length; i++) {
          const high = highStatements[i];
          if (high.get() instanceof Statements.Data) {
            const issue = this.anonymousTableType(high, lowFile, highSyntax);
            if (issue) {
              ret.push(issue);
            }
          }
        }
      }
 
      if (ret.length === 0 && lowFile.getRaw().includes(" xsdbool(")) {
        for (let i = 0; i < lowStatements.length; i++) {
          const high = highStatements[i];
          const issue = this.replaceXsdBool(high, lowFile, highSyntax);
          if (issue) {
            ret.push(issue);
          }
        }
      }
 
      // a chained call with EXPORTING/IMPORTING/CHANGING/RECEIVING/EXCEPTIONS parses in the low
      // version, but 702 reads the last call of a chain as a functional call,
      // "Unexpected word CHANGING in functional method call"
      if (ret.length === 0) {
        for (let i = 0; i < lowStatements.length; i++) {
          const issue = this.outlineChainedCallParameters(lowStatements[i], highStatements[i], lowFile, highSyntax);
          if (issue) {
            ret.push(issue);
            break;
          }
        }
      }
 
      // INSERT with a 702 built-in function as the operand parses in the low version, but 702
      // reads the function as a method call, "Method SUBSTRING does not exist"
      if (ret.length === 0) {
        for (let i = 0; i < lowStatements.length; i++) {
          const issue = this.outlineInsertBuiltin(lowStatements[i], highStatements[i], lowFile, highSyntax);
          if (issue) {
            ret.push(issue);
            break;
          }
        }
      }
 
      // MOVE-CORRESPONDING between tables parses in the low version, but is only allowed from
      // v740sp05, "MOVE-CORRESPONDING with tables possible from v740sp05"
      if (ret.length === 0) {
        for (let i = 0; i < lowStatements.length; i++) {
          if (lowStatements[i].getFirstToken().getStart() instanceof VirtualPosition) {
            continue;
          }
          const issue = this.downportMoveCorrespondingTables(highStatements[i], lowFile, highSyntax);
          if (issue) {
            ret.push(issue);
            break;
          }
        }
      }
 
      // INTO after WHERE parses as a valid SELECT in the low version, but is only allowed in
      // strict SQL syntax, so move it also when the statement is no longer Unknown
      if (ret.length === 0) {
        for (let i = 0; i < lowStatements.length; i++) {
          const low = lowStatements[i];
          const high = highStatements[i];
          const issue = this.downportSQLMoveInto(low, high, lowFile, highSyntax);
          if (issue) {
            ret.push(issue);
          }
        }
      }
 
      // nothing could be rewritten, name the statements which stay invalid in the low version
      if (ret.length === 0) {
        ret.push(...notDownported);
      }
 
    }
 
    return ret;
  }
 
////////////////////
 
  /** for a statement no downport applies to, an issue without fix if it stays invalid in the low version */
  private notDownported(low: StatementNode, high: StatementNode, lowFile: ABAPFile, highSyntax: ISyntaxResult): Issue | undefined {
    if (this.lowReg.getConfig().isOpenABAP()) {
      return undefined;
    }
 
    // a constructor expression with #, where the type cannot be inferred as it is void
    if (low.get() instanceof Unknown) {
      for (const infer of high.findAllExpressionsRecursive(Expressions.TypeNameOrInfer)) {
        if (infer.concatTokens() !== "#") {
          continue;
        }
        const token = infer.getFirstToken();
        const spag = highSyntax.spaghetti.lookupPosition(token.getStart(), lowFile.getFilename());
        const voided = spag?.getData().references.some(r => r.referenceType === ReferenceType.InferredType
          && r.position.getStart().equals(token.getStart())
          && r.resolved instanceof TypedIdentifier
          && r.resolved.getType() instanceof VoidType
          && r.resolved.getType().getQualifiedName() === undefined);
        if (voided === true) {
          return Issue.atToken(lowFile, token, "Cannot downport, inferred type is void",
                               this.getMetadata().key, this.conf.severity);
        }
      }
      return undefined;
    }
 
    // the statement might still parse in the low version, eg. DATA(name) as offset/length access
    for (const i of high.findAllExpressionsRecursive(Expressions.InlineData)) {
      const nameToken = i.findDirectExpression(Expressions.TargetField)?.getFirstToken();
      if (nameToken === undefined) {
        continue;
      }
      const name = nameToken.getStr();
      const found = highSyntax.spaghetti.lookupPosition(nameToken.getStart(), lowFile.getFilename())?.findVariable(name);
      if (found?.getType() instanceof VoidType && found.getType().getQualifiedName() === undefined) {
        return Issue.atToken(lowFile, i.getFirstToken(), `Cannot downport, type of ${name} is void`,
                             this.getMetadata().key, this.conf.severity);
      }
    }
 
    return undefined;
  }
 
  /** clones the orginal repository into highReg, and parses it with higher language version */
  private initHighReg() {
    // use default configuration, ie. default target version
    const highConfig = Config.getDefault().get();
    const lowConfig = this.lowReg.getConfig().get();
    highConfig.syntax.errorNamespace = lowConfig.syntax.errorNamespace;
    highConfig.syntax.globalConstants = lowConfig.syntax.globalConstants;
    highConfig.syntax.ambigiousVoids = lowConfig.syntax.ambigiousVoids;
    highConfig.syntax.globalMacros = lowConfig.syntax.globalMacros;
    this.highReg = new Registry();
 
    for (const o of this.lowReg.getObjects()) {
      for (const f of o.getFiles()) {
        if (this.lowReg.isDependency(o) === true) {
          this.highReg.addDependency(f);
        } else {
          this.highReg.addFile(f);
        }
      }
    }
 
    this.highReg.parse();
  }
 
  /** applies one rule at a time, multiple iterations are required to transform complex statements */
  private checkStatement(low: StatementNode, high: StatementNode, lowFile: ABAPFile,
                         highSyntax: ISyntaxResult, highFile: ABAPFile): Issue | undefined {
    if (low.getFirstToken().getStart() instanceof VirtualPosition) {
      return undefined;
    }
 
    // downport XSDBOOL() early, as it is valid 702 syntax
    /*
    let found = this.replaceXsdBool(high, lowFile, highSyntax);
    if (found) {
      return found;
    }
    */
 
    let found = this.stripCallTransactionAuthorityCheck(high, lowFile);
    if (found) {
      return found;
    }
 
    found = this.downportEnum(low, high, lowFile, highSyntax, highFile);
    if (found) {
      return found;
    }
 
    found = this.partiallyImplemented(high, lowFile);
    if (found) {
      return found;
    }
 
    found = this.raiseException(high, lowFile, highSyntax);
    if (found) {
      return found;
    }
 
    found = this.emptyKey(low, high, lowFile);
    if (found) {
      return found;
    }
 
    found = this.stringTemplateAlpha(low, high, lowFile, highSyntax);
    if (found) {
      return found;
    }
 
    found = this.moveWithOperator(low, high, lowFile);
    if (found) {
      return found;
    }
 
    found = this.moveWithSimpleValue(low, high, lowFile);
    if (found) {
      return found;
    }
 
    found = this.outlineTableExpressionKeyBuiltin(low, high, lowFile, highSyntax);
    if (found) {
      return found;
    }
 
    found = this.assignWithTable(low, high, lowFile);
    if (found) {
      return found;
    }
 
    found = this.assignComponent(low, high, lowFile, highSyntax);
    if (found) {
      return found;
    }
 
    found = this.downportRefSimple(high, lowFile, highSyntax);
    if (found) {
      return found;
    }
 
    found = this.downportCorrespondingSimple(high, lowFile);
    if (found) {
      return found;
    }
 
    found = this.downportMoveCorrespondingTables(high, lowFile, highSyntax);
    if (found) {
      return found;
    }
 
    found = this.downportRef(low, high, lowFile, highSyntax);
    if (found) {
      return found;
    }
 
    found = this.downportLoopGroup(high, lowFile, highSyntax, highFile);
    if (found) {
      return found;
    }
 
    found = this.callFunctionParameterSimple(high, lowFile, highSyntax);
    if (found) {
      return found;
    }
 
    found = this.moveWithTableTarget(low, high, lowFile, highSyntax);
    if (found) {
      return found;
    }
 
    found = this.downportSelectInline(low, high, lowFile, highSyntax);
    if (found) {
      return found;
    }
 
    found = this.downportSelectExistence(low, high, lowFile, highSyntax);
    if (found) {
      return found;
    }
 
    found = this.downportOpenCursorInline(low, high, lowFile);
    if (found) {
      return found;
    }
 
    found = this.downportSQLMoveInto(low, high, lowFile, highSyntax);
    if (found) {
      return found;
    }
 
    found = this.downportSQLExtras(low, high, lowFile, highSyntax);
    if (found) {
      return found;
    }
 
    found = this.outlineLoopInput(low, high, lowFile, highSyntax);
    if (found) {
      return found;
    }
 
    found = this.outlineLoopTarget(high, lowFile, highSyntax);
    if (found) {
      return found;
    }
 
    let skipValue = false;
    let skipReduce = false;
    const valueBody = high.findFirstExpression(Expressions.ValueBody);
    const reduceBody = high.findFirstExpression(Expressions.ReduceBody);
    if (valueBody && reduceBody) {
      const valueToken = valueBody.getFirstToken();
      const reduceToken = reduceBody.getFirstToken();
      if (valueToken.getStart().isBefore(reduceToken.getStart())) {
        skipReduce = true;
      } else {
        skipValue = true;
      }
    }
 
    if (skipValue !== true) {
      found = this.outlineValue(low, high, lowFile, highSyntax);
      if (found) {
        return found;
      }
    }
 
    if (skipReduce !== true) {
      found = this.outlineReduce(low, high, lowFile, highSyntax);
      if (found) {
        return found;
      }
    }
 
    found = this.outlineCorresponding(low, high, lowFile, highSyntax);
    if (found) {
      return found;
    }
 
    found = this.downportSelectFields(low, high, lowFile, highSyntax);
    if (found) {
      return found;
    }
 
    found = this.outlineSwitch(low, high, lowFile, highSyntax);
    if (found) {
      return found;
    }
 
    found = this.outlineFilter(low, high, lowFile, highSyntax);
    if (found) {
      return found;
    }
 
    found = this.outlineCast(low, high, lowFile, highSyntax);
    if (found) {
      return found;
    }
 
    found = this.outlineConv(low, high, lowFile, highSyntax);
    if (found) {
      return found;
    }
 
    found = this.outlineCond(low, high, lowFile, highSyntax);
    if (found) {
      return found;
    }
 
    found = this.outlineCatchSimple(high, lowFile);
    if (found) {
      return found;
    }
 
    found = this.outlineGetReferenceSimple(high, lowFile, highSyntax);
    if (found) {
      return found;
    }
 
    found = this.outlineDataSimple(high, lowFile, highSyntax);
    if (found) {
      return found;
    }
 
    found = this.outlineReadTableVoidTarget(high, lowFile, highSyntax);
    if (found) {
      return found;
    }
 
    found = this.outlineData(high, lowFile, highSyntax);
    if (found) {
      return found;
    }
 
    found = this.outlineFS(low, high, lowFile, highSyntax);
    if (found) {
      return found;
    }
 
    found = this.newToCreateObject(low, high, lowFile, highSyntax);
    if (found) {
      return found;
    }
 
    found = this.replaceInstanceOf(low, high, lowFile, highSyntax, highFile);
    if (found) {
      return found;
    }
 
    found = this.replaceLineFunctions(high, lowFile, highSyntax, highFile);
    if (found) {
      return found;
    }
 
    found = this.getReference(high, lowFile, highSyntax);
    if (found) {
      return found;
    }
 
    found = this.replaceContains(high, lowFile, highSyntax);
    if (found) {
      return found;
    }
 
    found = this.replaceMethodConditional(low, high, lowFile, highSyntax);
    if (found) {
      return found;
    }
 
    found = this.replaceTableExpression(low, high, lowFile, highSyntax);
    if (found) {
      return found;
    }
 
    found = this.replaceAppendExpression(high, lowFile, highSyntax);
    if (found) {
      return found;
    }
 
    found = this.replaceInsertExpression(high, lowFile, highSyntax);
    if (found) {
      return found;
    }
 
    found = this.downportMessageSource(high, lowFile, highSyntax);
    if (found) {
      return found;
    }
 
    found = this.downportMessage(high, lowFile, highSyntax);
    if (found) {
      return found;
    }
 
    found = this.downportReadTable(high, lowFile, highSyntax);
    if (found) {
      return found;
    }
 
    return undefined;
  }
 
//////////////////////////////////////////
 
  /** move INTO from after WHERE to after FROM,
   * note that INTO after WHERE is only valid in strict SQL syntax, so it must be moved when
   * downporting; this can happen both while the statement is still Unknown(from the main loop)
   * and after the @ and FIELDS have been removed, leaving a SELECT that parses in the low version */
  private downportSQLMoveInto(low: StatementNode, high: StatementNode, lowFile: ABAPFile, _highSyntax: ISyntaxResult): Issue | undefined {
    if (!(high.get() instanceof Statements.Select)
        && !(high.get() instanceof Statements.SelectLoop)) {
      return undefined;
    }
 
    // note: SQLCond is also used in JOIN(FROM) conditions
    const where = high.findFirstExpression(Expressions.Select)?.findDirectExpression(Expressions.SQLCond);
    if (where === undefined) {
      return undefined;
    }
 
    // the FIELDS list sits between FROM and WHERE, wait for it to be removed first
    if (high.findFirstExpression(Expressions.SQLFields) !== undefined) {
      return undefined;
    }
 
    let into = high.findFirstExpression(Expressions.SQLIntoList);
    if (into === undefined) {
      into = high.findFirstExpression(Expressions.SQLIntoStructure);
    }
    if (into === undefined) {
      into = high.findFirstExpression(Expressions.SQLIntoTable);
    }
    if (into === undefined) {
      return undefined;
    }
 
    if (where.getLastToken().getEnd().isBefore(into.getFirstToken().getStart()) === false) {
      return undefined;
    }
 
    const from = high.findFirstExpression(Expressions.SQLFrom);
    if (from === undefined) {
      return undefined;
    }
 
    // UP TO after INTO is only valid behind WHERE when it follows an ORDER BY, else move it along in front of INTO
    let move = into.concatTokens();
    const fixes: IEdit[] = [];
    const upTo = high.findFirstExpression(Expressions.SQLUpTo);
    const orderBy = high.findFirstExpression(Expressions.SQLOrderBy);
    if (upTo !== undefined
        && into.getLastToken().getEnd().isBefore(upTo.getFirstToken().getStart())
        && (orderBy === undefined || upTo.getFirstToken().getStart().isBefore(orderBy.getFirstToken().getStart()))) {
      move = upTo.concatTokens() + ` ` + move;
      fixes.push(EditHelper.deleteRange(lowFile, upTo.getFirstToken().getStart(), upTo.getLastToken().getEnd()));
    }
 
    // edits are applied in sequence, so work from the end of the statement towards the start
    fixes.push(EditHelper.deleteRange(lowFile, into.getFirstToken().getStart(), into.getLastToken().getEnd()));
    fixes.push(EditHelper.insertAt(lowFile, from.getLastToken().getEnd(), ` ` + move));
    const fix = EditHelper.mergeList(fixes);
 
    return Issue.atToken(lowFile, low.getFirstToken(), "SQL, move INTO", this.getMetadata().key, this.conf.severity, fix);
  }
 
  /** the work area of INSERT/MODIFY/UPDATE/DELETE dbtab FROM @( ... ) takes its type from the
   * database table, a "#" constructor cannot be outlined with DATA( ) as there is nothing to infer from */
  private sqlWorkAreaType(high: StatementNode, sqlSource: ExpressionNode): string | undefined {
    if (!(high.get() instanceof Statements.InsertDatabase)
        && !(high.get() instanceof Statements.ModifyDatabase)
        && !(high.get() instanceof Statements.UpdateDatabase)
        && !(high.get() instanceof Statements.DeleteDatabase)) {
      return undefined;
    } else if (high.getChildren().includes(sqlSource) === false) {
      return undefined;
    }
 
    const table = high.findDirectExpression(Expressions.DatabaseTable);
    if (table === undefined || table.findDirectExpression(Expressions.Dynamic) !== undefined) {
      return undefined;
    }
 
    const name = table.concatTokens();
    if (high.findDirectTokenByText("TABLE") !== undefined) {
      return `STANDARD TABLE OF ${name} WITH DEFAULT KEY`;
    }
    return name;
  }
 
  /** removes @'s and commas */
  private downportSQLExtras(low: StatementNode, high: StatementNode, lowFile: ABAPFile, highSyntax: ISyntaxResult): Issue | undefined {
    if (!(low.get() instanceof Unknown)) {
      return undefined;
    }
 
    if (!(high.get() instanceof Statements.Select)
        && !(high.get() instanceof Statements.SelectLoop)
        && !(high.get() instanceof Statements.UpdateDatabase)
        && !(high.get() instanceof Statements.ModifyDatabase)
        && !(high.get() instanceof Statements.DeleteDatabase)
        && !(high.get() instanceof Statements.InsertDatabase)
        && !(high.get() instanceof Statements.OpenCursor)
        && !(high.get() instanceof Statements.FetchNextCursor)
        && !(high.get() instanceof Statements.CloseCursor)) {
      return undefined;
    }
 
    let fix: IEdit | undefined = undefined;
    const addFix = (token: AbstractToken) => {
      const add = EditHelper.deleteToken(lowFile, token);
      if (fix === undefined) {
        fix = add;
      } else {
        fix = EditHelper.merge(fix, add);
      }
    };
 
    const candidates = [high.findAllExpressionsRecursive(Expressions.SQLTarget),
      high.findAllExpressionsRecursive(Expressions.SQLSource),
      high.findAllExpressionsRecursive(Expressions.SQLSourceNoSpace),
      high.findAllExpressionsRecursive(Expressions.SQLSourceSimple)].flat();
    // the deletions are applied one after the other, so handle the candidates from the end of the statement,
    // in FETCH NEXT CURSOR and OPEN CURSOR a source or target comes before the others
    candidates.sort((a, b) => a.getFirstToken().getStart().isAfter(b.getFirstToken().getStart()) ? -1 : 1);
    for (const c of candidates) {
      if (c.getFirstToken() instanceof WAt
          || c.getFirstToken() instanceof At) {
        const tokens = c.getAllTokens();
        if (tokens[1] instanceof ParenLeftW && tokens[tokens.length - 1] instanceof WParenRightW) {
          const source = c.findDirectExpression(Expressions.Source);
          if (source?.findDirectExpression(Expressions.TypeNameOrInfer)?.concatTokens() === "#") {
            const workAreaType = this.sqlWorkAreaType(high, c);
            if (workAreaType === undefined) {
              return Issue.atToken(lowFile, low.getFirstToken(), "SQL, outline complex @, type of # not known", this.getMetadata().key, this.conf.severity);
            }
            const uniqueName = this.uniqueName(high.getFirstToken().getStart(), lowFile.getFilename(), highSyntax);
            const indentation = " ".repeat(high.getFirstToken().getStart().getCol() - 1);
            const fix1 = EditHelper.insertAt(lowFile, high.getFirstToken().getStart(), `DATA ${uniqueName} TYPE ${workAreaType}.
${indentation}${uniqueName} = ${source?.concatTokens()}.\n${indentation}`);
            const fix2 = EditHelper.replaceRange(lowFile, c.getFirstToken().getStart(), c.getLastToken().getEnd(), "@" + uniqueName);
            const fix = EditHelper.merge(fix2, fix1);
            return Issue.atToken(lowFile, low.getFirstToken(), "SQL, outline complex @", this.getMetadata().key, this.conf.severity, fix);
          }
          const uniqueName = this.uniqueName(high.getFirstToken().getStart(), lowFile.getFilename(), highSyntax);
          const fix1 = EditHelper.insertAt(lowFile, high.getStart(), `DATA(${uniqueName}) = ${source?.concatTokens()}.\n`);
          const fix2 = EditHelper.replaceRange(lowFile, c.getFirstToken().getStart(), c.getLastToken().getEnd(), "@" + uniqueName);
          const fix = EditHelper.merge(fix2, fix1);
          return Issue.atToken(lowFile, low.getFirstToken(), "SQL, outline complex @", this.getMetadata().key, this.conf.severity, fix);
        } else {
          addFix(c.getFirstToken());
        }
      }
    }
 
    for (const fieldList of high.findAllExpressionsMulti([Expressions.SQLFieldList, Expressions.SQLFieldListLoop, Expressions.SQLOrderBy], true)) {
      for (const token of fieldList.getDirectTokens()) {
        if (token.getStr() === ",") {
          addFix(token);
        }
      }
    }
 
    if (fix !== undefined) {
      return Issue.atToken(lowFile, low.getFirstToken(), "SQL, remove @ and ,", this.getMetadata().key, this.conf.severity, fix);
    }
 
    for (const c of high.findAllExpressionsRecursive(Expressions.SQLIn)) {
      const children = c.getChildren();
      const first = children[1];
      if (!(first.get() instanceof WParenLeftW)) {
        continue;
      }
      const last = children[children.length - 1];
      if (last.get() instanceof WParenRightW || last.get() instanceof WParenRight) {
        const firstEnd = first.getFirstToken().getEnd();
        const endDelete = new Position(firstEnd.getRow(), firstEnd.getCol() + 1);
        const fix1 = EditHelper.deleteRange(lowFile, firstEnd, endDelete);
 
        const lastStart = last.getFirstToken().getStart();
        const startDelete = new Position(lastStart.getRow(), lastStart.getCol() - 1);
        const fix2 = EditHelper.deleteRange(lowFile, startDelete, lastStart);
        fix = EditHelper.merge(fix2, fix1);
        return Issue.atToken(lowFile, low.getFirstToken(), "SQL, remove spaces", this.getMetadata().key, this.conf.severity, fix);
      }
    }
 
    return undefined;
  }
 
  /** OPEN CURSOR @DATA(name), the cursor is always of type cursor */
  private downportOpenCursorInline(low: StatementNode, high: StatementNode, lowFile: ABAPFile): Issue | undefined {
    if (!(low.get() instanceof Unknown)) {
      return undefined;
    } else if (!(high.get() instanceof Statements.OpenCursor)) {
      return undefined;
    }
 
    const inlineData = high.findDirectExpression(Expressions.SQLTarget)?.findDirectExpression(Expressions.Target)?.findDirectExpression(Expressions.InlineData);
    const name = inlineData?.findFirstExpression(Expressions.TargetField)?.concatTokens();
    if (inlineData === undefined || name === undefined) {
      return undefined;
    }
 
    const indentation = " ".repeat(high.getFirstToken().getStart().getCol() - 1);
    const fix1 = EditHelper.insertAt(lowFile, high.getStart(), `DATA ${name} TYPE cursor.\n${indentation}`);
    const fix2 = EditHelper.replaceRange(lowFile, inlineData.getFirstToken().getStart(), inlineData.getLastToken().getEnd(), name);
    const fix = EditHelper.merge(fix2, fix1);
 
    return Issue.atToken(lowFile, inlineData.getFirstToken(), "Outline OPEN CURSOR @DATA", this.getMetadata().key, this.conf.severity, fix);
  }
 
  private downportSelectExistence(low: StatementNode, high: StatementNode, lowFile: ABAPFile, highSyntax: ISyntaxResult): Issue | undefined {
    if (!(low.get() instanceof Unknown)) {
      return undefined;
    } else if (!(high.get() instanceof Statements.Select)) {
      return undefined;
    }
 
    const fieldList = high.findFirstExpression(Expressions.SQLFieldList);
    if (fieldList?.concatTokens().toUpperCase() !== "@ABAP_TRUE") {
      return undefined;
    }
    const fieldName = high.findFirstExpression(Expressions.SQLCond)?.findFirstExpression(Expressions.SQLFieldName)?.concatTokens();
    if (fieldName === undefined) {
      return undefined;
    }
    const into = high.findFirstExpression(Expressions.SQLIntoStructure);
    if (into === undefined) {
      return undefined;
    }
    const intoName = into.findFirstExpression(Expressions.SQLTarget)?.findFirstExpression(Expressions.Target)?.concatTokens();
 
    const uniqueName = this.uniqueName(high.getFirstToken().getStart(), lowFile.getFilename(), highSyntax);
    const fix1 = EditHelper.replaceRange(lowFile, fieldList.getFirstToken().getStart(), fieldList.getLastToken().getEnd(), fieldName);
    const fix2 = EditHelper.replaceRange(lowFile, into?.getFirstToken().getStart(), into?.getLastToken().getEnd(), `INTO @DATA(${uniqueName})`);
    let fix = EditHelper.merge(fix2, fix1);
    const fix3 = EditHelper.insertAt(lowFile, high.getLastToken().getEnd(), `\nCLEAR ${intoName}.\nIF sy-subrc = 0.\n  ${intoName} = abap_true.\nENDIF.`);
    fix = EditHelper.merge(fix, fix3);
 
    return Issue.atToken(lowFile, low.getFirstToken(), "SQL, refactor existence check", this.getMetadata().key, this.conf.severity, fix);
  }
 
  private downportSelectInline(low: StatementNode, high: StatementNode, lowFile: ABAPFile, highSyntax: ISyntaxResult): Issue | undefined {
 
    if (!(low.get() instanceof Unknown)) {
      return undefined;
    } else if (!(high.get() instanceof Statements.Select) && !(high.get() instanceof Statements.SelectLoop)) {
      return undefined;
    }
 
// as first step outline the @DATA, note that void types are okay, as long the field names are specified
    let found = this.downportSelectSingleInline(low, high, lowFile, highSyntax);
    if (found) {
      return found;
    }
 
    found = this.downportSelectTableInline(low, high, lowFile, highSyntax);
    if (found) {
      return found;
    }
 
    return undefined;
  }
 
  private downportSelectFields(low: StatementNode, high: StatementNode, lowFile: ABAPFile, _highSyntax: ISyntaxResult): Issue | undefined {
 
    if (!(low.get() instanceof Unknown)) {
      return undefined;
    } else if (!(high.get() instanceof Statements.Select)) {
      return undefined;
    }
 
    const fields = high.findFirstExpression(Expressions.SQLFields);
    if (fields === undefined) {
      return undefined;
    }
 
    // everything behind the FIELDS keyword, including DISTINCT
    const code = fields.concatTokens().replace(/^FIELDS\s+/i, "");
 
    // the field list goes behind SELECT, or behind SINGLE [FOR UPDATE], which must stay in front of it
    const tokens = high.getTokens();
    let insertAfter = tokens[0];
    if (tokens[1]?.getStr().toUpperCase() === "SINGLE") {
      insertAfter = tokens[1];
      if (tokens[2]?.getStr().toUpperCase() === "FOR" && tokens[3]?.getStr().toUpperCase() === "UPDATE") {
        insertAfter = tokens[3];
      }
    }
 
    const fix1 = EditHelper.deleteRange(lowFile, fields.getFirstToken().getStart(), fields.getLastToken().getEnd());
    const fix2 = EditHelper.insertAt(lowFile, insertAfter.getEnd(), " " + code);
    const fix = EditHelper.merge(fix1, fix2);
    return Issue.atToken(lowFile, fields.getFirstToken(), "Replace FIELDS", this.getMetadata().key, this.conf.severity, fix);
  }
 
  private downportSelectSingleInline(low: StatementNode, high: StatementNode,
                                     lowFile: ABAPFile, _highSyntax: ISyntaxResult): Issue | undefined {
    if (!(low.get() instanceof Unknown)) {
      return undefined;
    }
 
    const targets = high.findFirstExpression(Expressions.SQLIntoStructure)?.findDirectExpressions(Expressions.SQLTarget) || [];
    if (targets.length !== 1) {
      return undefined;
    }
 
    const inlineData = targets[0].findFirstExpression(Expressions.InlineData);
    if (inlineData === undefined) {
      return undefined;
    }
 
    const sqlFrom = high.findAllExpressions(Expressions.SQLFromSource);
    if (sqlFrom.length !== 1) {
      return undefined;
    }
 
    const tableName = sqlFrom[0].findDirectExpression(Expressions.DatabaseTable)?.concatTokens();
    if (tableName === undefined) {
      return undefined;
    }
 
    const indentation = " ".repeat(high.getFirstToken().getStart().getCol() - 1);
    let fieldList = high.findFirstExpression(Expressions.SQLFieldList);
    if (fieldList === undefined) {
      fieldList = high.findFirstExpression(Expressions.SQLFieldListLoop);
    }
    if (fieldList === undefined) {
      return undefined;
    }
    let fieldDefinition = "";
    const fields = fieldList.findAllExpressions(Expressions.SQLFieldName);
    const name = inlineData.findFirstExpression(Expressions.TargetField)?.concatTokens() || "error";
    if (fields.length === 1) {
      fieldDefinition = `DATA ${name} TYPE ${tableName}-${fields[0].concatTokens()}.`;
    } else if (fieldList.concatTokens() === "*") {
      fieldDefinition = `DATA ${name} TYPE ${tableName}.`;
    } else if (fieldList.concatTokens().toUpperCase() === "COUNT( * )") {
      fieldDefinition = `DATA ${name} TYPE i.`;
    } else if (fieldList.concatTokens().toUpperCase() === "@ABAP_TRUE"
        || fieldList.concatTokens().toUpperCase() === "@ABAP_FALSE") {
      fieldDefinition = `DATA ${name} TYPE abap_bool.`;
    } else if (fieldList.getChildren().length === 1 && fieldList.getChildren()[0].get() instanceof Expressions.SQLAggregation) {
      const c = fieldList.getChildren()[0];
      if (c instanceof ExpressionNode) {
        const concat = c.findFirstExpression(Expressions.SQLArithmetics)?.concatTokens();
        fieldDefinition = `DATA ${name} TYPE ${tableName}-${concat}.`;
      }
    } else {
      for (const f of fields) {
        const fieldName = f.concatTokens();
        fieldDefinition += indentation + "        " + fieldName + " TYPE " + tableName + "-" + fieldName + ",\n";
      }
      fieldDefinition = `DATA: BEGIN OF ${name},
${fieldDefinition}${indentation}      END OF ${name}.`;
    }
 
    const fix1 = EditHelper.insertAt(lowFile, high.getStart(), `${fieldDefinition}
${indentation}`);
    const fix2 = EditHelper.replaceRange(lowFile, inlineData.getFirstToken().getStart(), inlineData.getLastToken().getEnd(), name);
    const fix = EditHelper.merge(fix2, fix1);
 
    return Issue.atToken(lowFile, inlineData.getFirstToken(), "Outline SELECT @DATA", this.getMetadata().key, this.conf.severity, fix);
  }
 
  private downportSelectTableInline(low: StatementNode, high: StatementNode,
                                    lowFile: ABAPFile, highSyntax: ISyntaxResult): Issue | undefined {
    if (!(low.get() instanceof Unknown)) {
      return undefined;
    }
 
    const targets = high.findFirstExpression(Expressions.SQLIntoTable)?.findDirectExpressions(Expressions.SQLTarget) || [];
    if (targets.length !== 1) {
      return undefined;
    }
    const indentation = " ".repeat(high.getFirstToken().getStart().getCol() - 1);
 
    const inlineData = targets[0].findFirstExpression(Expressions.InlineData);
    if (inlineData === undefined) {
      return undefined;
    }
 
    const sqlFrom = high.findAllExpressions(Expressions.SQLFromSource);
    if (sqlFrom.length === 0) {
      return Issue.atToken(lowFile, high.getFirstToken(), "Error outlining, sqlFrom not found", this.getMetadata().key, this.conf.severity);
    }
 
    let tableName = sqlFrom[0].findDirectExpression(Expressions.DatabaseTable)?.concatTokens();
    if (tableName === undefined) {
      return undefined;
    }
 
    const tableMap: {[key: string]: string} = {};
    for (const from of sqlFrom) {
      const dbName = from.findDirectExpression(Expressions.DatabaseTable)?.concatTokens().toUpperCase();
      if (dbName === undefined) {
        continue;
      }
      const asName = from.findDirectExpression(Expressions.SQLAsName)?.concatTokens().toUpperCase() || dbName;
      tableMap[asName] = dbName;
    }
 
    const fieldList = high.findFirstExpression(Expressions.SQLFieldList);
    if (fieldList === undefined) {
      return undefined;
    }
 
    let fieldDefinitions = "";
    for (const f of fieldList.findAllExpressions(Expressions.SQLField)) {
      let fieldName = f.findFirstExpression(Expressions.SQLFieldName)?.concatTokens();
      if (fieldName === undefined) {
        continue;
      }
      if (fieldName.includes("~")) {
        const split = fieldName.split("~");
        tableName = split[0];
        fieldName = split[1];
      }
      const translated = tableMap[tableName.toUpperCase()];
      const typeName = translated + "-" + fieldName;
      fieldName = f.findFirstExpression(Expressions.SQLAsName)?.concatTokens() || fieldName;
      fieldDefinitions += indentation + "        " + fieldName + " TYPE " + typeName.toLowerCase() + ",\n";
    }
 
    const uniqueName = this.uniqueName(high.getFirstToken().getStart(), lowFile.getFilename(), highSyntax);
    const name = inlineData.findFirstExpression(Expressions.TargetField)?.concatTokens() || "error";
 
    let fix1 = EditHelper.insertAt(lowFile, high.getStart(), `TYPES: BEGIN OF ${uniqueName},
${fieldDefinitions}${indentation}      END OF ${uniqueName}.
${indentation}DATA ${name} TYPE STANDARD TABLE OF ${uniqueName} WITH DEFAULT KEY.
${indentation}`);
    if (fieldDefinitions === "") {
      fix1 = EditHelper.insertAt(lowFile, high.getStart(), `DATA ${name} TYPE STANDARD TABLE OF ${tableName} WITH DEFAULT KEY.
${indentation}`);
    }
 
    const fix2 = EditHelper.replaceRange(lowFile, inlineData.getFirstToken().getStart(), inlineData.getLastToken().getEnd(), name);
    const fix = EditHelper.merge(fix2, fix1);
 
    return Issue.atToken(lowFile, inlineData.getFirstToken(), "Outline SELECT @DATA", this.getMetadata().key, this.conf.severity, fix);
  }
 
  // the anonymous type might be used in inferred type statements, define it so it can be referred
  private anonymousTableType(high: StatementNode, lowFile: ABAPFile, highSyntax: ISyntaxResult): Issue | undefined {
    if (!(high.get() instanceof Statements.Data)) {
      return undefined;
    }
 
    const tt = high.findFirstExpression(Expressions.TypeTable);
    if (tt === undefined) {
      return undefined;
    }
 
    const uniqueName = this.uniqueName(high.getFirstToken().getStart(), lowFile.getFilename(), highSyntax);
    const code = `TYPES ${uniqueName} ${tt.concatTokens()}.\n`;
 
    const fix1 = EditHelper.insertAt(lowFile, high.getStart(), code);
    const fix2 = EditHelper.replaceRange(lowFile, tt.getFirstToken().getStart(), tt.getLastToken().getEnd(), "TYPE " + uniqueName);
    const fix = EditHelper.merge(fix2, fix1);
    return Issue.atToken(lowFile, high.getFirstToken(), "Add type for table definition", this.getMetadata().key, this.conf.severity, fix);
  }
 
  private downportMessage(high: StatementNode, lowFile: ABAPFile, highSyntax: ISyntaxResult): Issue | undefined {
    if (!(high.get() instanceof Statements.Message)) {
      return undefined;
    }
    const foundWith = high.findExpressionAfterToken("WITH");
    if (foundWith === undefined) {
      return undefined;
    }
    const likeSource = high.findExpressionAfterToken("LIKE");
 
    for (const s of high.findAllExpressions(Expressions.Source)) {
      if (s === likeSource) {
        continue;
      } else if (s.getChildren().length === 1 && s.getFirstChild()?.get() instanceof Expressions.Constant) {
        continue;
      } else if (s.getChildren().length === 1 && s.getFirstChild()?.get() instanceof Expressions.FieldChain) {
        continue;
      }
      const uniqueName = this.uniqueName(high.getFirstToken().getStart(), lowFile.getFilename(), highSyntax);
      const indentation = " ".repeat(high.getFirstToken().getStart().getCol() - 1);
      const firstToken = high.getFirstToken();
      const code = `DATA(${uniqueName}) = ${s.concatTokens()}.\n${indentation}`;
      const fix1 = EditHelper.insertAt(lowFile, firstToken.getStart(), code);
      const fix2 = EditHelper.replaceRange(lowFile, s.getFirstToken().getStart(), s.getLastToken().getEnd(), uniqueName);
      const fix = EditHelper.merge(fix2, fix1);
      return Issue.atToken(lowFile, high.getFirstToken(), "Refactor MESSAGE WITH source", this.getMetadata().key, this.conf.severity, fix);
    }

    return undefined;
  }
 
  private replaceAppendExpression(high: StatementNode, lowFile: ABAPFile, highSyntax: ISyntaxResult): Issue | undefined {
    if (!(high.get() instanceof Statements.Append)) {
      return undefined;
    }
 
    const children = high.getChildren();
    if (children[1].get() instanceof Expressions.Source) {
      const source = children[1];
      const target = high.findDirectExpression(Expressions.Target);
      if (target === undefined) {
        return undefined;
      }
 
      const uniqueName = this.uniqueName(high.getFirstToken().getStart(), lowFile.getFilename(), highSyntax);
      const indentation = " ".repeat(high.getFirstToken().getStart().getCol() - 1);
      const firstToken = high.getFirstToken();
      const fix1 = EditHelper.insertAt(lowFile, firstToken.getStart(), `DATA ${uniqueName} LIKE LINE OF ${target?.concatTokens()}.
${indentation}${uniqueName} = ${source.concatTokens()}.\n${indentation}`);
      const fix2 = EditHelper.replaceRange(lowFile, source.getFirstToken().getStart(), source.getLastToken().getEnd(), uniqueName);
      const fix = EditHelper.merge(fix2, fix1);
 
      return Issue.atToken(lowFile, high.getFirstToken(), "Outline APPEND source expression", this.getMetadata().key, this.conf.severity, fix);
    }

    return undefined;
  }
 
  private downportReadTable(high: StatementNode, lowFile: ABAPFile, highSyntax: ISyntaxResult): Issue | undefined {
    if (!(high.get() instanceof Statements.ReadTable)) {
      return undefined;
    }
 
    const source = high.findExpressionAfterToken("TABLE");
    if (source?.get() instanceof Expressions.Source) {
      const uniqueName = this.uniqueName(high.getFirstToken().getStart(), lowFile.getFilename(), highSyntax);
      const indentation = " ".repeat(high.getFirstToken().getStart().getCol() - 1);
      const firstToken = high.getFirstToken();
      const fix1 = EditHelper.insertAt(lowFile, firstToken.getStart(), `DATA(${uniqueName}) = ${source.concatTokens()}.\n` + indentation);
      const fix2 = EditHelper.replaceRange(lowFile, source.getFirstToken().getStart(), source.getLastToken().getEnd(), uniqueName);
      const fix = EditHelper.merge(fix2, fix1);
      return Issue.atToken(lowFile, high.getFirstToken(), "Outline table source", this.getMetadata().key, this.conf.severity, fix);
    }
 
    return undefined;
  }
 
  private downportMessageSource(high: StatementNode, lowFile: ABAPFile, highSyntax: ISyntaxResult): Issue | undefined {
    if (!(high.get() instanceof Statements.Message)) {
      return undefined;
    }
 
    const source = high.findExpressionAfterToken("MESSAGE");
    if (source?.get() instanceof Expressions.MessageSourceSource
        && source.getFirstChild()?.get() instanceof Expressions.Source) {
      const uniqueName = this.uniqueName(high.getFirstToken().getStart(), lowFile.getFilename(), highSyntax);
      const indentation = " ".repeat(high.getFirstToken().getStart().getCol() - 1);
      const firstToken = high.getFirstToken();
      const fix1 = EditHelper.insertAt(lowFile, firstToken.getStart(), `DATA(${uniqueName}) = ${source.concatTokens()}.\n` + indentation);
      const fix2 = EditHelper.replaceRange(lowFile, source.getFirstToken().getStart(), source.getLastToken().getEnd(), uniqueName);
      const fix = EditHelper.merge(fix2, fix1);
      return Issue.atToken(lowFile, high.getFirstToken(), "Outline message source", this.getMetadata().key, this.conf.severity, fix);
    }
 
    return undefined;
  }
 
  private replaceInsertExpression(high: StatementNode, lowFile: ABAPFile, highSyntax: ISyntaxResult): Issue | undefined {
    if (!(high.get() instanceof Statements.InsertInternal)) {
      return undefined;
    }
 
    const children = high.getChildren();
    if (children[1].get() instanceof Expressions.Source) {
      const source = children[1];
      const target = high.findDirectExpression(Expressions.Target);
      if (target === undefined) {
        return undefined;
      }
 
      const uniqueName = this.uniqueName(high.getFirstToken().getStart(), lowFile.getFilename(), highSyntax);
      const indentation = " ".repeat(high.getFirstToken().getStart().getCol() - 1);
      const firstToken = high.getFirstToken();
      const fix1 = EditHelper.insertAt(lowFile, firstToken.getStart(), `DATA ${uniqueName} LIKE LINE OF ${target?.concatTokens()}.
${indentation}${uniqueName} = ${source.concatTokens()}.\n${indentation}`);
      const fix2 = EditHelper.replaceRange(lowFile, source.getFirstToken().getStart(), source.getLastToken().getEnd(), uniqueName);
      const fix = EditHelper.merge(fix2, fix1);
 
      return Issue.atToken(lowFile, high.getFirstToken(), "Outline INSERT source expression", this.getMetadata().key, this.conf.severity, fix);
    }

    return undefined;
  }
 
  private replaceTableExpression(low: StatementNode, high: StatementNode, lowFile: ABAPFile, highSyntax: ISyntaxResult): Issue | undefined {
    if (!(low.get() instanceof Unknown)) {
      return undefined;
    }
 
    for (const fieldChain of high.findAllExpressionsRecursive(Expressions.FieldChain)) {
      const tableExpression = fieldChain.findDirectExpression(Expressions.TableExpression);
      if (tableExpression === undefined) {
        continue;
      }
 
      const concat = high.concatTokens().toUpperCase();
      if (concat.includes(" LINE_EXISTS( ") || concat.includes(" LINE_INDEX( ")) {
        // note: line_exists() must be replaced before handling table expressions
        continue;
      }
 
      let pre = "";
      let startToken: AbstractToken | undefined = undefined;
      for (const child of fieldChain.getChildren()) {
        if (startToken === undefined) {
          startToken = child.getFirstToken();
        } else if (child === tableExpression) {
          break;
        }
        pre += child.concatTokens();
      }
      if (startToken === undefined) {
        continue;
      }
 
      const condition = this.tableCondition(tableExpression);
 
      let guard: string[] = [];
      if (high.get() instanceof Statements.If) {
        const found = this.shortCircuitGuard(high.findDirectExpression(Expressions.Cond), fieldChain);
        if (found === "later") {
          continue;
        }
        guard = found;
      }
 
      // ASSIGNING, not INTO: from v740 a table expression in a read position addresses the
      // row rather than copying it, so "REF #( tab[ i ]-comp )" and "ASSIGN tab[ i ]-comp"
      // hand back an address INTO a work area would not preserve. The write path
      // (moveWithTableTarget) already lowers to ASSIGNING for the same reason.
      const uniqueName = this.uniqueName(high.getFirstToken().getStart(), lowFile.getFilename(), highSyntax, true);
      const tabixBackup = this.uniqueName(high.getFirstToken().getStart(), lowFile.getFilename(), highSyntax);
      const indentation = " ".repeat(high.getFirstToken().getStart().getCol() - 1);
      const firstToken = high.getFirstToken();
      // note that the tabix restore should be done before throwing the exception
      let read = `${tabixBackup} = sy-tabix.
READ TABLE ${pre} ${condition}ASSIGNING ${uniqueName}.
sy-tabix = ${tabixBackup}.
IF sy-subrc <> 0.
  RAISE EXCEPTION TYPE cx_sy_itab_line_not_found.
ENDIF.`;
      if (guard.length > 0) {
        // the operands in front of the table expression are evaluated first and can stop the
        // evaluation, so the row is only read when they let the evaluation reach it
        read = `IF ${guard.join(" AND ")}.
${read.replace(/^/gm, "  ")}
ENDIF.`;
      }
      const fix1 = EditHelper.insertAt(lowFile, firstToken.getStart(), `FIELD-SYMBOLS ${uniqueName} LIKE LINE OF ${pre}.
${indentation}DATA ${tabixBackup} LIKE sy-tabix.
${read.replace(/\n/g, "\n" + indentation).replace(/^/, indentation)}
${indentation}`);
      const fix2 = EditHelper.replaceRange(lowFile, startToken.getStart(), tableExpression.getLastToken().getEnd(), uniqueName);
      const fix = EditHelper.merge(fix2, fix1);
 
      if (high.get() instanceof Statements.ElseIf) {
        throw "downport, unable to downport table expression in ELSEIF";
      }
 
      return Issue.atToken(lowFile, high.getFirstToken(), "Outline table expression", this.getMetadata().key, this.conf.severity, fix);
    }
 
    return undefined;
  }
 
  /** ABAP evaluates the operands of AND and OR left to right and stops as soon as the result
   * is known, so in "IF lv_last > 0 AND tab[ lv_last ] = x." the table expression is only read
   * when lv_last > 0. Outlined in front of the IF, the read and its CX_SY_ITAB_LINE_NOT_FOUND
   * raise would run unconditionally. Returns the operands that must hold for the evaluation to
   * reach the target, empty when it is always reached (or the shape is not handled, which keeps
   * the unconditional outline), and "later" when an operand in front of it holds a table
   * expression itself, which must be outlined first. Operands with method calls or NEW are not
   * repeated in a guard, as that would evaluate them twice. */
  private shortCircuitGuard(cond: ExpressionNode | undefined, target: ExpressionNode): string[] | "later" {
    if (cond === undefined) {
      return [];
    }
    const guard: ExpressionNode[] = [];
    const negated: ExpressionNode[][] = [];
    let term: ExpressionNode[] = [];
    for (const child of cond.getChildren()) {
      if (child instanceof TokenNode) {
        const operator = child.getFirstToken().getStr().toUpperCase();
        if (operator === "EQUIV") {
          return [];
        } else if (operator === "OR") {
          negated.push(term);
          term = [];
        }
        continue;
      } else if (!(child instanceof ExpressionNode)) {
        return [];
      }
 
      if (child.findAllExpressionsRecursive(Expressions.FieldChain).includes(target) === false) {
        term.push(child);
        continue;
      }
 
      guard.push(...term);
      let inner: string[] = [];
      if (child.get() instanceof Expressions.CondSub) {
        const found = this.shortCircuitGuard(child.findDirectExpression(Expressions.Cond), target);
        if (found === "later") {
          return found;
        }
        inner = found;
      }
 
      const operands = [...negated.flat(), ...guard];
      if (operands.some(o => o.findFirstExpression(Expressions.TableExpression) !== undefined)) {
        return "later";
      }
      for (const o of operands) {
        if (o.findFirstExpression(Expressions.NewObject) !== undefined) {
          return [];
        }
        for (const m of o.findAllExpressionsRecursive(Expressions.MethodCall)) {
          const name = m.findDirectExpression(Expressions.MethodName)?.concatTokens().toUpperCase();
          if (BuiltIn.searchBuiltin(name) === undefined) {
            return [];
          }
        }
      }
 
      return [
        ...negated.map(t => "NOT ( " + t.map(o => o.concatTokens()).join(" AND ") + " )"),
        ...guard.map(o => o.concatTokens()),
        ...inner];
    }
    return [];
  }
 
  private tableCondition(tableExpression: ExpressionNode) {
    let condition = "";
    let keyName = "";
    for (const c of tableExpression.getChildren() || []) {
      if (c.getFirstToken().getStr() === "[" || c.getFirstToken().getStr() === "]") {
        continue;
      } else if (c.get() instanceof Expressions.ComponentChainSimple && condition === "") {
        if (keyName === "") {
          condition = "WITH KEY ";
        } else {
          condition = "WITH TABLE KEY " + keyName + " COMPONENTS ";
        }
      } else if (c.get() instanceof Expressions.Source && condition === "") {
        condition = "INDEX ";
      } else if (c instanceof TokenNode && c.getFirstToken().getStr().toUpperCase() === "KEY") {
        continue;
      } else if (c.get() instanceof Expressions.SimpleName) {
        keyName = c.concatTokens();
        continue;
      }
      condition += c.concatTokens() + " ";
    }
    return condition;
  }
 
  /** A built-in function is only recognized as one in an operand position that admits an
   * expression, and "WITH KEY comp = ..." does not become such a position until v740. The
   * table expression rewrites carry the key operand over verbatim, so
   * "tab[ comp = to_upper( x ) ]" downports to a READ TABLE that a 702 or 731 compiler can
   * only read as a functional method call - "method TO_UPPER is unknown", reported as a
   * SYNTAX_ERROR of the whole class pool. Hoist the call into a variable first, an
   * assignment IS an expression position at 702.
   *
   * Built-ins that predate 702 (lines, strlen, numofchar, ...) carry no release in
   * BuiltIn.methods; they are accepted in the operand as they are and stay untouched. So do
   * functional method calls, which are exactly the reading that makes the built-in fail, and
   * the INDEX operand of "tab[ 1 ]", which is not a key operand. */
  private outlineTableExpressionKeyBuiltin(low: StatementNode, high: StatementNode, lowFile: ABAPFile,
                                           highSyntax: ISyntaxResult): Issue | undefined {
    if (!(low.get() instanceof Unknown)) {
      return undefined;
    }
 
    for (const tableExpression of high.findAllExpressionsRecursive(Expressions.TableExpression)) {
      let afterComponent = false;
      for (const child of tableExpression.getChildren()) {
        if (child.get() instanceof Expressions.ComponentChainSimple) {
          afterComponent = true;
          continue;
        } else if (afterComponent === false
            || !(child.get() instanceof Expressions.Source)
            || !(child instanceof ExpressionNode)) {
          continue;
        }
 
        const type = this.builtinReturnType(child, lowFile, highSyntax);
        if (type === undefined) {
          continue;
        }
 
        const uniqueName = this.uniqueName(high.getFirstToken().getStart(), lowFile.getFilename(), highSyntax);
        const indentation = " ".repeat(high.getFirstToken().getStart().getCol() - 1);
        const code = `DATA ${uniqueName} TYPE ${type}.\n` +
          indentation + `${uniqueName} = ${child.concatTokens()}.\n` +
          indentation;
 
        const fix1 = EditHelper.insertAt(lowFile, high.getFirstToken().getStart(), code);
        const fix2 = EditHelper.replaceRange(lowFile, child.getFirstToken().getStart(), child.getLastToken().getEnd(), uniqueName);
        const fix = EditHelper.merge(fix2, fix1);
 
        return Issue.atToken(lowFile, child.getFirstToken(), "Outline built-in function in table expression key",
                             this.getMetadata().key, this.conf.severity, fix);
      }
    }
 
    return undefined;
  }
 
  /** INSERT substring( ... ) INTO TABLE tab, the operand is outlined into a variable */
  private outlineInsertBuiltin(low: StatementNode, high: StatementNode, lowFile: ABAPFile,
                               highSyntax: ISyntaxResult): Issue | undefined {
    if (!(high.get() instanceof Statements.InsertInternal)) {
      return undefined;
    } else if (this.lowReg.getConfig().isOpenABAP()) {
      return undefined;
    } else if (low.getFirstToken().getStart() instanceof VirtualPosition) {
      return undefined;
    }
 
    // the whole operand is the call, a longer expression is outlined by replaceInsertExpression
    const source = high.getChildren()[1];
    if (!(source instanceof ExpressionNode)
        || !(source.get() instanceof Expressions.SimpleSource4 || source.get() instanceof Expressions.Source)
        || source.getChildren().length !== 1
        || !(source.getFirstChild()?.get() instanceof Expressions.MethodCallChain)) {
      return undefined;
    }
 
    const type = this.builtinReturnType(source, lowFile, highSyntax);
    if (type === undefined) {
      return undefined;
    }
 
    const uniqueName = this.uniqueName(high.getFirstToken().getStart(), lowFile.getFilename(), highSyntax);
    const indentation = " ".repeat(high.getFirstToken().getStart().getCol() - 1);
    const code = `DATA ${uniqueName} TYPE ${type}.\n` +
      indentation + `${uniqueName} = ${source.concatTokens()}.\n` +
      indentation;
 
    const fix1 = EditHelper.insertAt(lowFile, high.getFirstToken().getStart(), code);
    const fix2 = EditHelper.replaceRange(lowFile, source.getFirstToken().getStart(), source.getLastToken().getEnd(), uniqueName);
    const fix = EditHelper.merge(fix2, fix1);
 
    return Issue.atToken(lowFile, source.getFirstToken(), "Outline built-in function in INSERT",
                         this.getMetadata().key, this.conf.severity, fix);
  }
 
  /** MOVE-CORRESPONDING between internal tables is possible from v740sp05, in 702 move row by row;
   * a typed target must be a standard table, as a row is added before its fields are filled, and a
   * fully generic target carries no table kind, so its row is added with INSERT INTO TABLE */
  private downportMoveCorrespondingTables(high: StatementNode, lowFile: ABAPFile, highSyntax: ISyntaxResult): Issue | undefined {
    if (!(high.get() instanceof Statements.MoveCorresponding)) {
      return undefined;
    } else if (this.lowReg.getConfig().isOpenABAP()) {
      return undefined;
    }
 
    const concat = high.concatTokens().toUpperCase();
    if (concat.includes(" EXPANDING NESTED TABLES") || concat.startsWith("MOVE-CORRESPONDING EXACT ")) {
      return undefined;
    }
    const keeping = concat.includes(" KEEPING TARGET LINES");
 
    // only plain variables and field symbols, their types are known from the scope
    const source = high.findDirectExpression(Expressions.Source);
    const sourceField = source?.getFirstChild();
    const target = high.findDirectExpression(Expressions.SimpleTarget);
    if (source === undefined
        || target === undefined
        || source.getChildren().length !== 1
        || !(sourceField?.get() instanceof Expressions.FieldChain)
        || sourceField.getChildren().length !== 1
        || target.getChildren().length !== 1) {
      return undefined;
    }
    const sourceName = source.concatTokens();
    const targetName = target.concatTokens();
    if (sourceName.toUpperCase() === targetName.toUpperCase()) {
      return undefined;
    }
 
    const spag = highSyntax.spaghetti.lookupPosition(high.getFirstToken().getStart(), lowFile.getFilename());
    const sourceType = spag?.findVariable(sourceName)?.getType();
    const targetType = spag?.findVariable(targetName)?.getType();
    if (!(sourceType instanceof TableType)
        || !(targetType instanceof TableType)
        || sourceType.isWithHeader() === true
        || targetType.isWithHeader() === true
        || (targetType.getAccessType() !== TableAccessType.standard && targetType.getAccessType() !== undefined)) {
      return undefined;
    }
    for (const t of [sourceType, targetType]) {
      const row = t.getRowType();
      if (!(row instanceof StructureType || row instanceof AnyType || row instanceof VoidType)) {
        return undefined;
      }
    }
 
    const fsType = (name: string, type: TableType) => type.isGeneric() ? "TYPE any" : "LIKE LINE OF " + name;
    const sourceFS = this.uniqueName(high.getFirstToken().getStart(), lowFile.getFilename(), highSyntax, true);
    const targetFS = this.uniqueName(high.getFirstToken().getStart(), lowFile.getFilename(), highSyntax, true);
    const addRow = targetType.getAccessType() === undefined
      ? `INSERT INITIAL LINE INTO TABLE ${targetName}`
      : `APPEND INITIAL LINE TO ${targetName}`;
    const indentation = " ".repeat(high.getFirstToken().getStart().getCol() - 1);
    const code = `FIELD-SYMBOLS ${sourceFS} ${fsType(sourceName, sourceType)}.\n` +
      indentation + `FIELD-SYMBOLS ${targetFS} ${fsType(targetName, targetType)}.\n` +
      (keeping ? "" : indentation + `CLEAR ${targetName}.\n`) +
      indentation + `LOOP AT ${sourceName} ASSIGNING ${sourceFS}.\n` +
      indentation + `  ${addRow} ASSIGNING ${targetFS}.\n` +
      indentation + `  MOVE-CORRESPONDING ${sourceFS} TO ${targetFS}.\n` +
      indentation + `ENDLOOP.`;
 
    const fix = EditHelper.replaceRange(lowFile, high.getFirstToken().getStart(), high.getLastToken().getEnd(), code);
    return Issue.atToken(lowFile, high.getFirstToken(), "Downport MOVE-CORRESPONDING with tables",
                         this.getMetadata().key, this.conf.severity, fix);
  }
 
  /** the ABAP type returned by the built-in function this Source starts with, or undefined
   * if it does not start with one, or with one that predates 702 */
  private builtinReturnType(source: ExpressionNode, lowFile: ABAPFile, highSyntax: ISyntaxResult): string | undefined {
    const spag = highSyntax.spaghetti.lookupPosition(source.getFirstToken().getStart(), lowFile.getFilename());
 
    for (const r of spag?.getData().references || []) {
      if (r.referenceType !== ReferenceType.BuiltinMethodReference
          || r.position.getStart().equals(source.getFirstToken().getStart()) === false) {
        continue;
      }
      const name = r.position.getName().toUpperCase();
      if (BuiltIn.methods[name]?.release === undefined) {
        return undefined;
      }
      return BuiltIn.searchBuiltin(name)?.getParameters().getReturning()?.getType().toABAP();
    }
 
    return undefined;
  }
 
  private outlineCatchSimple(node: StatementNode, lowFile: ABAPFile): Issue | undefined {
    // outlines "CATCH cx_bcs INTO DATA(lx_bcs_excep).", note that this does not need to look at types
 
    if (this.lowReg.getConfig().isOpenABAP()) {
      return undefined;
    }
 
    if (!(node.get() instanceof Statements.Catch)) {
      return undefined;
    }
 
    const target = node.findFirstExpression(Expressions.Target);
    if (!(target?.getFirstChild()?.get() instanceof Expressions.InlineData)) {
      return undefined;
    }
 
    const classNames = node.findDirectExpressions(Expressions.ClassName);
    if (classNames.length !== 1) {
      return undefined;
    }
    const className = classNames[0].concatTokens();
 
    const targetName = target.findFirstExpression(Expressions.TargetField)?.concatTokens();
    const indentation = " ".repeat(node.getFirstToken().getStart().getCol() - 1);
 
    const code = `  DATA ${targetName} TYPE REF TO ${className}.
${indentation}CATCH ${className} INTO ${targetName}.`;
 
    const fix = EditHelper.replaceRange(lowFile, node.getStart(), node.getEnd(), code);
 
    return Issue.atToken(lowFile, node.getFirstToken(), "Outline DATA", this.getMetadata().key, this.conf.severity, fix);
  }
 
  /** the type of a reference to the source: LIKE REF TO it, or REF TO data when its type is generic,
   *  as LIKE REF TO a generically typed field symbol or parameter does not activate */
  private refTypeOf(sourceName: string, node: StatementNode, lowFile: ABAPFile, highSyntax: ISyntaxResult): string {
    const spag = highSyntax.spaghetti.lookupPosition(node.getFirstToken().getStart(), lowFile.getFilename());
    if (spag?.findVariable(sourceName)?.getType().isGeneric() === true) {
      return "TYPE REF TO data";
    }
    return "LIKE REF TO " + sourceName;
  }
 
  private outlineGetReferenceSimple(node: StatementNode, lowFile: ABAPFile, highSyntax: ISyntaxResult): Issue | undefined {
    if (!(node.get() instanceof Statements.GetReference)) {
      return undefined;
    }
 
    const target = node.findFirstExpression(Expressions.Target);
    if (!(target?.getFirstChild()?.get() instanceof Expressions.InlineData)) {
      return undefined;
    }
 
    const source = node.findFirstExpression(Expressions.Source);
    if (!(source?.getFirstChild()?.get() instanceof Expressions.FieldChain)) {
      return undefined;
    }
 
    const targetName = target.findFirstExpression(Expressions.TargetField)?.concatTokens() || "errorError";
    const indentation = " ".repeat(node.getFirstToken().getStart().getCol() - 1);
    const firstToken = target.getFirstToken();
    const lastToken = target.getLastToken();
    const refType = this.refTypeOf(source.concatTokens(), node, lowFile, highSyntax);
    const fix1 = EditHelper.insertAt(lowFile, node.getStart(), `DATA ${targetName} ${refType}.\n${indentation}`);
    const fix2 = EditHelper.replaceRange(lowFile, firstToken.getStart(), lastToken.getEnd(), targetName);
    const fix = EditHelper.merge(fix2, fix1);
 
    return Issue.atToken(lowFile, node.getFirstToken(), "Outline DATA", this.getMetadata().key, this.conf.severity, fix);
  }
 
  private outlineDataSimple(node: StatementNode, lowFile: ABAPFile, highSyntax: ISyntaxResult): Issue | undefined {
    if (!(node.get() instanceof Statements.Move)) {
      return undefined;
    }
 
    if (this.lowReg.getConfig().isOpenABAP()) {
      return undefined;
    }
 
    const target = node.findFirstExpression(Expressions.Target);
    if (!(target?.getFirstChild()?.get() instanceof Expressions.InlineData)) {
      return undefined;
    }
 
    let type: string;
    const source = node.findFirstExpression(Expressions.Source);
    if (source === undefined) {
      return undefined;
    } else if (source.getChildren().length !== 1) {
      return undefined;
    } else if (!(source.getFirstChild()?.get() instanceof Expressions.FieldChain)) {
      return undefined;
    } else if (source.findFirstExpression(Expressions.FieldOffset)) {
      return undefined;
    } else if (source.findFirstExpression(Expressions.FieldLength)) {
      return undefined;
    } else if (source.findFirstExpression(Expressions.TableExpression)) {
      const chain = source.findDirectExpression(Expressions.FieldChain);
      if (chain !== undefined
          && chain.getChildren().length === 2
          && chain.getChildren()[0].get() instanceof Expressions.SourceField
          && chain.getChildren()[1].get() instanceof Expressions.TableExpression) {
        type = "LINE OF " + chain.getChildren()[0].concatTokens();
      } else {
        return undefined;
      }
    } else {
      const spag = highSyntax.spaghetti.lookupPosition(source.getFirstToken().getStart(), lowFile.getFilename());
      if (spag) {
        const found = spag.findVariable(source.concatTokens());
        if (found && found.getType().isGeneric() === true) {
          return undefined;
        }
      }
 
      type = source.concatTokens();
    }
 
    const targetName = target.findFirstExpression(Expressions.TargetField)?.concatTokens();
    const indentation = " ".repeat(node.getFirstToken().getStart().getCol() - 1);
    const firstToken = node.getFirstToken();
    const lastToken = node.getLastToken();
    const fix1 = EditHelper.insertAt(lowFile, firstToken.getStart(), `DATA ${targetName} LIKE ${type}.\n${indentation}`);
    const fix2 = EditHelper.replaceRange(lowFile, firstToken.getStart(), lastToken.getEnd(), `${targetName} = ${source.concatTokens()}.`);
    const fix = EditHelper.merge(fix2, fix1);
 
    return Issue.atToken(lowFile, node.getFirstToken(), "Outline DATA", this.getMetadata().key, this.conf.severity, fix);
  }
 
  private partiallyImplemented(node: StatementNode, lowFile: ABAPFile): Issue | undefined {
    if (this.lowReg.getConfig().isOpenABAP()) {
      return undefined;
    }
 
    if (node.get() instanceof Statements.InterfaceDef) {
      const partially = node.findDirectTokenByText("PARTIALLY");
      if (partially === undefined) {
        return undefined;
      }
      const implemented = node.findDirectTokenByText("IMPLEMENTED");
      if (implemented === undefined) {
        return undefined;
      }
      const fix = EditHelper.deleteRange(lowFile, partially.getStart(), implemented.getEnd());
      return Issue.atToken(lowFile, partially, "Downport PARTIALLY IMPLEMENTED", this.getMetadata().key, this.conf.severity, fix);
    }
 
    return undefined;
  }
 
  private raiseException(node: StatementNode, lowFile: ABAPFile, highSyntax: ISyntaxResult): Issue | undefined {
 
    /*
    Note: IF_T100_DYN_MSG does not exist in 702, so this rule is mostly relevant for the transpiler
 
    DATA foo LIKE if_t100_message=>t100key.
    foo-msgid = 'ZHVAM'.
    foo-msgno = '001'.
    foo-attr1 = 'IF_T100_DYN_MSG~MSGV1'.
    foo-attr2 = 'IF_T100_DYN_MSG~MSGV2'.
    foo-attr3 = 'IF_T100_DYN_MSG~MSGV3'.
    foo-attr4 = 'IF_T100_DYN_MSG~MSGV4'.
    DATA bar TYPE REF TO zcl_hvam_exception.
    CREATE OBJECT bar EXPORTING textid = foo.
    bar->if_t100_dyn_msg~msgty = 'E'.
    bar->if_t100_dyn_msg~msgv1 = 'abc'.
    bar->if_t100_dyn_msg~msgv2 = 'abc'.
    bar->if_t100_dyn_msg~msgv3 = 'abc'.
    bar->if_t100_dyn_msg~msgv4 = 'abc'.
    RAISE EXCEPTION bar.
    */
 
    if (!(node.get() instanceof Statements.Raise)) {
      return undefined;
    }
 
    let id: string | undefined;
    let number: string | undefined;
 
    let startToken = node.findDirectTokenByText("ID");
    if (startToken) {
      const sources = node.findDirectExpressions(Expressions.Source);
      id = sources[0].concatTokens();
      const numberExpression = node.findExpressionAfterToken("NUMBER");
      if (numberExpression === undefined) {
        throw "downport raiseException, could not find number";
      }
      number = numberExpression.concatTokens();
      if (numberExpression.get() instanceof Expressions.MessageNumber) {
        number = "'" + number + "'";
      }
    } else {
      const s = node.findDirectExpression(Expressions.MessageSource);
      if (s === undefined) {
        return undefined;
      }
 
      if (s.findDirectExpression(Expressions.MessageClass)) {
        id = "'" + s.findDirectExpression(Expressions.MessageClass)?.concatTokens()?.toUpperCase() + "'";
      } else {
        id = s.findExpressionAfterToken("ID")?.concatTokens();
      }
 
      if (s.findDirectExpression(Expressions.MessageTypeAndNumber)) {
        number = "'" + s.findDirectExpression(Expressions.MessageTypeAndNumber)?.concatTokens().substring(1) + "'";
      } else {
        number = s.findExpressionAfterToken("NUMBER")?.concatTokens();
      }
 
      startToken = node.getFirstToken();
    }
 
    const withs = node.findDirectExpression(Expressions.RaiseWith)?.findDirectExpressionsMulti([Expressions.SimpleSource1, Expressions.Source]) || [];
 
    const className = node.findDirectExpression(Expressions.ClassName)?.concatTokens() || "ERROR";
 
    const uniqueName1 = this.uniqueName(node.getFirstToken().getStart(), lowFile.getFilename(), highSyntax);
    const uniqueName2 = this.uniqueName(node.getFirstToken().getStart(), lowFile.getFilename(), highSyntax);
    const indentation = " ".repeat(node.getFirstToken().getStart().getCol() - 1);
 
    let abap = `DATA ${uniqueName1} LIKE if_t100_message=>t100key.
${indentation}${uniqueName1}-msgid = ${id}.
${indentation}${uniqueName1}-msgno = ${number}.\n`;
    if (withs.length > 0) {
      abap += `${indentation}${uniqueName1}-attr1 = 'IF_T100_DYN_MSG~MSGV1'.
${indentation}${uniqueName1}-attr2 = 'IF_T100_DYN_MSG~MSGV2'.
${indentation}${uniqueName1}-attr3 = 'IF_T100_DYN_MSG~MSGV3'.
${indentation}${uniqueName1}-attr4 = 'IF_T100_DYN_MSG~MSGV4'.\n`;
    }
    abap += `${indentation}DATA ${uniqueName2} TYPE REF TO ${className}.
${indentation}CREATE OBJECT ${uniqueName2}.
${indentation}${uniqueName2}->if_t100_message~t100key = ${uniqueName1}.\n`;
    if (withs.length > 0) {
      abap += `${indentation}${uniqueName2}->if_t100_dyn_msg~msgty = 'E'.\n`;
    }
    let count = 1;
    for (const w of withs) {
      abap += `${indentation}${uniqueName2}->if_t100_dyn_msg~msgv${count} = ${w.concatTokens()}.\n`;
      count++;
    }
 
    abap += `${indentation}RAISE EXCEPTION ${uniqueName2}.`;
 
    const fix = EditHelper.replaceRange(lowFile, node.getStart(), node.getEnd(), abap);
    return Issue.atToken(lowFile, startToken, "Downport RAISE EXCEPTION MESSAGE", this.getMetadata().key, this.conf.severity, fix);
  }
 
  private emptyKey(low: StatementNode, node: StatementNode, lowFile: ABAPFile): Issue | undefined {
    if (!(low.get() instanceof Unknown)) {
      return undefined;
    }
 
    for (let i of node.findAllExpressions(Expressions.TypeTable)) {
      const key = i.findDirectExpression(Expressions.TypeTableKey);
      if (key === undefined) {
        continue;
      }
      i = key;
      const concat = i.concatTokens();
      if (concat.toUpperCase().includes("WITH EMPTY KEY") === false) {
        continue;
      }
      const token = i.findDirectTokenByText("EMPTY");
      if (token === undefined) {
        continue;
      }
 
      const fix = EditHelper.replaceToken(lowFile, token, "DEFAULT");
      return Issue.atToken(lowFile, i.getFirstToken(), "Downport EMPTY KEY", this.getMetadata().key, this.conf.severity, fix);
    }
 
    if (node.get() instanceof Statements.CreateData) {
      // the key of CREATE DATA is not a TypeTableKey expression, its keywords are direct tokens
      const tokens = node.getChildren().filter(c => c instanceof TokenNode).map(c => c.getFirstToken());
      for (let j = 0; j < tokens.length - 1; j++) {
        if (tokens[j].getStr().toUpperCase() === "EMPTY" && tokens[j + 1].getStr().toUpperCase() === "KEY") {
          const fix = EditHelper.replaceToken(lowFile, tokens[j], "DEFAULT");
          return Issue.atToken(lowFile, tokens[j], "Downport EMPTY KEY", this.getMetadata().key, this.conf.severity, fix);
        }
      }
    }
 
    return undefined;
  }
 
  private callFunctionParameterSimple(high: StatementNode, lowFile: ABAPFile, highSyntax: ISyntaxResult): Issue | undefined {
    if (!(high.get() instanceof Statements.CallFunction)) {
      return undefined;
    }
 
    let found: ExpressionNode | undefined = undefined;
    for (const p of high.findAllExpressions(Expressions.FunctionExportingParameter)) {
      found = p.findDirectExpression(Expressions.Source);
      if (found && (found.findDirectExpression(Expressions.FieldChain)
          || found.findDirectExpression(Expressions.Constant)
          || found.findDirectExpression(Expressions.TextElement))) {
// its actually simple, ok
        found = undefined;
      } else if (found !== undefined) {
        break;
      }
    }
    if (found === undefined) {
      return undefined;
    }
 
    const uniqueName = this.uniqueName(high.getFirstToken().getStart(), lowFile.getFilename(), highSyntax);
 
    const code = `DATA(${uniqueName}) = ${found.concatTokens()}.\n`;
 
    const fix1 = EditHelper.insertAt(lowFile, high.getFirstToken().getStart(), code);
    const fix2 = EditHelper.replaceRange(lowFile, found.getFirstToken().getStart(), found.getLastToken().getEnd(), uniqueName);
    const fix = EditHelper.merge(fix2, fix1);
 
    return Issue.atToken(lowFile, high.getFirstToken(), "Downport, call function parameter", this.getMetadata().key, this.conf.severity, fix);
  }
 
  private downportCorrespondingSimple(high: StatementNode, lowFile: ABAPFile): Issue | undefined {
    if (!(high.get() instanceof Statements.Move)
        || high.getChildren().length !== 4
        || high.getChildren()[2].getFirstToken().getStr().toUpperCase() !== "CORRESPONDING") {
      return undefined;
    }
 
    const target = high.findDirectExpression(Expressions.Target);
    if (target === undefined) {
      return undefined;
    }
 
    const sourceRef = high.findFirstExpression(Expressions.Source)?.findFirstExpression(Expressions.CorrespondingBody);
    if (sourceRef?.getChildren().length === 1 && target.concatTokens().toUpperCase().startsWith("DATA(") === false) {
      const code = `MOVE-CORRESPONDING ${sourceRef.concatTokens()} TO ${target.concatTokens()}`;
 
      const start = high.getFirstToken().getStart();
      const end = high.getLastToken().getStart();
      const fix = EditHelper.replaceRange(lowFile, start, end, code);
 
      return Issue.atToken(lowFile, high.getFirstToken(), "Downport, simple CORRESPONDING move", this.getMetadata().key, this.conf.severity, fix);
    } else if (sourceRef?.getChildren().length === 2 && sourceRef.findDirectExpression(Expressions.CorrespondingBodyBase) !== undefined) {
      const base = sourceRef.findDirectExpression(Expressions.CorrespondingBodyBase)!;
      let code = `${target.concatTokens()} = ${base.getChildren()[2].concatTokens()}.\n`;
      code += `MOVE-CORRESPONDING ${sourceRef.getChildren()[1].concatTokens()} TO ${target.concatTokens()}`;
 
      const start = high.getFirstToken().getStart();
      const end = high.getLastToken().getStart();
      const fix = EditHelper.replaceRange(lowFile, start, end, code);
 
      return Issue.atToken(lowFile, high.getFirstToken(), "Downport, CORRESPONDING BASE move", this.getMetadata().key, this.conf.severity, fix);
    }
 
    return undefined;
  }
 
  private downportRefSimple(high: StatementNode, lowFile: ABAPFile, highSyntax: ISyntaxResult): Issue | undefined {
    if (!(high.get() instanceof Statements.Move)
        || high.getChildren().length !== 4
        || high.getChildren()[2].getFirstToken().getStr().toUpperCase() !== "REF") {
      return undefined;
    }
 
    const target = high.findDirectExpression(Expressions.Target);
    if (target === undefined) {
      return undefined;
    }
    const sourceRef = high.findFirstExpression(Expressions.Source)?.findDirectExpression(Expressions.Source);
    if (sourceRef === undefined
        || sourceRef.getChildren().length !== 1) {
      return undefined;
    }
 
    let code: string;
    if (sourceRef.findFirstExpression(Expressions.TableExpression)) {
      const uniqueName = this.uniqueName(high.getFirstToken().getStart(), lowFile.getFilename(), highSyntax);
      code = `ASSIGN ${sourceRef.concatTokens()} TO FIELD-SYMBOL(<${uniqueName}>).
IF sy-subrc <> 0.
  RAISE EXCEPTION TYPE cx_sy_itab_line_not_found.
ENDIF.
GET REFERENCE OF <${uniqueName}> INTO ${target.concatTokens()}`;
    } else {
      const concat = target.concatTokens();
      code = `GET REFERENCE OF ${sourceRef.concatTokens()} INTO ${concat}`;
 
      // workaround for handling generic ANY type,
      if (concat.toUpperCase().startsWith("DATA(")) {
        const spag = highSyntax.spaghetti.lookupPosition(high.getFirstToken().getStart(), lowFile.getFilename());
        if (spag !== undefined) {
          const found = spag.findVariable(sourceRef.concatTokens());
          const tt = found?.getType();
          if (tt instanceof AnyType) {
            const tname = target.findFirstExpression(Expressions.TargetField)?.concatTokens();
            code = `DATA ${tname} TYPE REF TO data.\nGET REFERENCE OF ${sourceRef.concatTokens()} INTO ${tname}`;
          }
        }
      }
 
    }
 
    const start = high.getFirstToken().getStart();
    const end = high.getLastToken().getStart();
    const fix = EditHelper.replaceRange(lowFile, start, end, code);
 
    return Issue.atToken(lowFile, high.getFirstToken(), "Downport, simple REF move", this.getMetadata().key, this.conf.severity, fix);
  }
 
  private downportLoopGroup(high: StatementNode, lowFile: ABAPFile, highSyntax: ISyntaxResult, highFile: ABAPFile): Issue | undefined {
    if (!(high.get() instanceof Statements.Loop)) {
      return undefined;
    }
    const group = high.findDirectExpression(Expressions.LoopGroupBy);
    if (group === undefined) {
      return undefined;
    }
    const groupTargetName = group.findFirstExpression(Expressions.TargetField)?.concatTokens()
      || group.findFirstExpression(Expressions.TargetFieldSymbol)?.concatTokens().replace("<", "_").replace(">", "_")
      || "nameNotFound";
    const loopSourceName = high.findFirstExpression(Expressions.SimpleSource2)?.concatTokens() || "nameNotFound";
    const loopTargetName = high.findFirstExpression(Expressions.TargetField)?.concatTokens()
      || high.findFirstExpression(Expressions.TargetFieldSymbol)?.concatTokens()
      || "nameNotFound";
    const groupTarget = group.findDirectExpression(Expressions.LoopGroupByTarget)?.concatTokens() || "";
    const isReference = high.findFirstExpression(Expressions.LoopTarget)?.concatTokens().toUpperCase().startsWith("REFERENCE INTO ");
 
    let loopSourceRowType = "typeNotFound";
    const spag = highSyntax.spaghetti.lookupPosition(high.getFirstToken().getStart(), lowFile.getFilename());
    if (spag !== undefined) {
      const found = spag.findVariable(loopSourceName);
      const tt = found?.getType();
      if (tt instanceof TableType) {
        loopSourceRowType = tt.getRowType().getQualifiedName() || "typeNotFound";
      }
    }
 
    let code = `TYPES: BEGIN OF ${groupTargetName}type,\n`;
    let condition = "";
    let groupCountName: string | undefined = undefined;
    let groupIndexName: string | undefined = undefined;
    for (const c of group.findAllExpressions(Expressions.LoopGroupByComponent)) {
      const name = c.findFirstExpression(Expressions.ComponentName);
      let type = c.findFirstExpression(Expressions.Source)?.concatTokens() || "todo";
      if (c.concatTokens()?.toUpperCase().endsWith(" = GROUP SIZE")) {
        type = "i";
        groupCountName = name?.concatTokens();
      } else if (c.concatTokens()?.toUpperCase().endsWith(" = GROUP INDEX")) {
        type = "i";
        groupIndexName = name?.concatTokens();
      } else {
        if (condition !== "") {
          condition += " ";
        }
        condition += c.concatTokens();
        type = type.replace(loopTargetName, loopSourceRowType);
        type = type.replace("->", "-");
      }
      code += `         ${name?.concatTokens()} TYPE ${type},\n`;
    }
    const s = group.findDirectExpression(Expressions.Source);
    let singleName = "";
    if (s) {
      let type = s.concatTokens();
      type = type.replace(loopTargetName, loopSourceRowType);
      type = type.replace("->", "-");
      singleName = s.concatTokens().split("-")[1];
      code += `         ${singleName} TYPE ${type},\n`;
      condition = singleName + " = " + s.concatTokens();
    }
 
    const uniqueName = this.uniqueName(high.getFirstToken().getStart(), lowFile.getFilename(), highSyntax);
    const uniqueFS = this.uniqueName(high.getFirstToken().getStart(), lowFile.getFilename(), highSyntax);
    const uniqueNameIndex = this.uniqueName(high.getFirstToken().getStart(), lowFile.getFilename(), highSyntax);
    code += `         items LIKE ${loopSourceName},
       END OF ${groupTargetName}type.
DATA ${groupTargetName}tab TYPE STANDARD TABLE OF ${groupTargetName}type WITH DEFAULT KEY.
DATA ${uniqueName} LIKE LINE OF ${groupTargetName}tab.
LOOP AT ${loopSourceName} ${high.findFirstExpression(Expressions.LoopTarget)?.concatTokens()}.\n`;
    if (groupIndexName !== undefined) {
      code += `DATA(${uniqueNameIndex}) = sy-tabix.\n`;
    }
    code += `READ TABLE ${groupTargetName}tab ASSIGNING FIELD-SYMBOL(<${uniqueFS}>) WITH KEY ${condition}.
IF sy-subrc = 0.\n`;
    if (groupCountName !== undefined) {
      code += `  <${uniqueFS}>-${groupCountName} = <${uniqueFS}>-${groupCountName} + 1.\n`;
    }
    code += `  INSERT ${loopTargetName}${isReference ? "->*" : ""} INTO TABLE <${uniqueFS}>-items.
ELSE.\n`;
    code += `  CLEAR ${uniqueName}.\n`;
    for (const c of group.findAllExpressions(Expressions.LoopGroupByComponent)) {
      const concat = c.concatTokens();
//      console.dir(concat);
      if (concat.endsWith(" GROUP INDEX")) {
        code += `  ${uniqueName}-${groupIndexName} = ${uniqueNameIndex}.\n`;
      } else if (concat.endsWith(" GROUP SIZE")) {
        code += `  ${uniqueName}-${groupCountName} = 1.\n`;
      } else {
        code += `  ${uniqueName}-${concat}.\n`;
      }
    }
    if (singleName !== "") {
      code += `  ${uniqueName}-${singleName} = ${loopTargetName}-${singleName}.\n`;
    }
    code += `  INSERT ${loopTargetName}${isReference ? "->*" : ""} INTO TABLE ${uniqueName}-items.\n`;
    code += `  INSERT ${uniqueName} INTO TABLE ${groupTargetName}tab.\n`;
    code += `ENDIF.
ENDLOOP.
LOOP AT ${groupTargetName}tab ${groupTarget}.`;
 
    let fix = EditHelper.replaceRange(lowFile, high.getFirstToken().getStart(), high.getLastToken().getEnd(), code);
 
    for (const l of highFile.getStructure()?.findAllStructures(Structures.Loop) || []) {
// make sure to find the correct/current loop statement
      if (l.findDirectStatement(Statements.Loop) !== high) {
        continue;
      }
      for (const loop of l.findAllStatements(Statements.Loop)) {
        if (loop.concatTokens()?.toUpperCase().startsWith("LOOP AT GROUP ")) {
          const subLoopSource = loop.findFirstExpression(Expressions.SimpleSource2);
          if (subLoopSource === undefined) {
            continue;
          }
          const subLoopSourceName = subLoopSource?.concatTokens() || "nameNotFound";
          const subCode = `LOOP AT ${subLoopSourceName}${isReference ? "->" : "-"}items`;
          const subFix = EditHelper.replaceRange(lowFile, loop.getFirstToken().getStart(), subLoopSource.getLastToken().getEnd(), subCode);
          fix = EditHelper.merge(subFix, fix);
        }
      }
    }
 
    return Issue.atToken(lowFile, high.getFirstToken(), "Downport, LOOP GROUP", this.getMetadata().key, this.conf.severity, fix);
  }
 
  private downportRef(low: StatementNode, high: StatementNode, lowFile: ABAPFile, highSyntax: ISyntaxResult): Issue | undefined {
    if (!(low.get() instanceof Unknown)) {
      return undefined;
    }
 
    let found: ExpressionNode | undefined = undefined;
    for (const s of high.findAllExpressionsRecursive(Expressions.Source)) {
      if (s.getFirstToken().getStr().toUpperCase() === "REF"
          && s.findDirectExpression(Expressions.TypeNameOrInfer)) {
        found = s;
      }
    }
    if (found === undefined) {
      return undefined;
    }
 
    const uniqueName = this.uniqueName(high.getFirstToken().getStart(), lowFile.getFilename(), highSyntax);
 
    const code = `DATA(${uniqueName}) = ${found.concatTokens()}.\n`;
 
    const fix1 = EditHelper.insertAt(lowFile, high.getFirstToken().getStart(), code);
    const fix2 = EditHelper.replaceRange(lowFile, found.getFirstToken().getStart(), found.getLastToken().getEnd(), uniqueName);
    const fix = EditHelper.merge(fix2, fix1);
 
    return Issue.atToken(lowFile, high.getFirstToken(), "Downport, REF", this.getMetadata().key, this.conf.severity, fix);
  }
 
  private assignWithTable(low: StatementNode, high: StatementNode, lowFile: ABAPFile): Issue | undefined {
    if (!(low.get() instanceof Unknown)) {
      return undefined;
    }
 
    if (!(high.get() instanceof Statements.Assign)) {
      return undefined;
    } else if (high.getChildren().length !== 5) {
      return undefined;
    }
 
    const fieldChain = high.findDirectExpression(Expressions.AssignSource)?.findDirectExpression(Expressions.Source)?.findDirectExpression(Expressions.FieldChain);
    const tableExpression = fieldChain?.getLastChild();
    if (tableExpression === undefined
        || !(tableExpression.get() instanceof Expressions.TableExpression)
        || !(tableExpression instanceof ExpressionNode)) {
      return undefined;
    }
 
    let condition: string;
    if (tableExpression.getChildren().length === 3) {
      const index = tableExpression.findDirectExpression(Expressions.Source);
      if (index === undefined) {
        return undefined;
      }
      condition = `INDEX ${index.concatTokens()}`;
    } else {
      let concat = tableExpression.concatTokens();
      concat = concat.substring(2);
      concat = concat.substring(0, concat.length - 2);
      condition = `WITH KEY ${concat}`;
    }
 
    let pre = "";
    for (const c of fieldChain!.getChildren()) {
      if (c === tableExpression) {
        break;
      }
      pre += c.concatTokens();
    }
 
    const fsTarget = high.findDirectExpression(Expressions.FSTarget);
    const code = `READ TABLE ${pre} ${condition} ASSIGNING ${fsTarget?.concatTokens()}.`;
 
    const fix = EditHelper.replaceRange(lowFile, high.getFirstToken().getStart(), high.getLastToken().getEnd(), code);
 
    return Issue.atToken(lowFile, high.getFirstToken(), "Downport, ASSIGN table expr", this.getMetadata().key, this.conf.severity, fix);
  }
 
  private assignComponent(low: StatementNode, high: StatementNode, lowFile: ABAPFile, highSyntax: ISyntaxResult): Issue | undefined {
    if (!(low.get() instanceof Unknown)) {
      return undefined;
    }
 
    if (!(high.get() instanceof Statements.Assign)) {
      return undefined;
    }
 
    const assignSource = high.findDirectExpression(Expressions.AssignSource);
    if (assignSource === undefined || assignSource.getFirstToken().getStr().toUpperCase() !== "COMPONENT") {
      return undefined;
    }
 
    const componentSource = assignSource.findExpressionAfterToken("COMPONENT");
    if (componentSource === undefined || componentSource.get() instanceof Expressions.SimpleSource3) {
      return undefined;
    }
 
    const uniqueName = this.uniqueName(assignSource.getFirstToken().getStart(), lowFile.getFilename(), highSyntax);
 
    const code = `DATA(${uniqueName}) = ${componentSource.concatTokens()}.\n`;
    const fix1 = EditHelper.insertAt(lowFile, high.getFirstToken().getStart(), code);
    const fix2 = EditHelper.replaceRange(lowFile, componentSource.getFirstToken().getStart(), componentSource.getLastToken().getEnd(), uniqueName);
    const fix = EditHelper.merge(fix2, fix1);
 
    return Issue.atToken(lowFile, high.getFirstToken(), "Downport, ASSIGN COMPONENT source", this.getMetadata().key, this.conf.severity, fix);
  }
 
  private moveWithSimpleValue(low: StatementNode, high: StatementNode, lowFile: ABAPFile): Issue | undefined {
    if (!(low.get() instanceof Unknown)) {
      return undefined;
    }
 
    if (!(high.get() instanceof Statements.Move)
        || high.getChildren().length !== 4) {
      return undefined;
    }
 
    const target = high.findDirectExpression(Expressions.Target);
    if (target === undefined) {
      return undefined;
    }
    const source = high.findDirectExpression(Expressions.Source);
    if (source === undefined) {
      return undefined;
    }
    const field = target.findDirectExpression(Expressions.TargetField);
    if (field === undefined) {
      return;
    }
    const valueBody = source.findDirectExpression(Expressions.ValueBody);
    if (valueBody === undefined) {
      return;
    }
    const type = source.findDirectExpression(Expressions.TypeNameOrInfer);
    if (type === undefined || type?.concatTokens() !== "#") {
      return;
    }
 
    const fieldAssignments = valueBody.findDirectExpressions(Expressions.FieldAssignment);
    if (fieldAssignments.length === 0) {
      return;
    } else if (fieldAssignments.length !== valueBody.getChildren().length) {
      return;
    }
 
    const indentation = " ".repeat(high.getFirstToken().getStart().getCol() - 1);
    let code = `CLEAR ${target.concatTokens()}.\n`;
    for (const fieldAssignment of fieldAssignments) {
      code += indentation + target.concatTokens() + "-" + fieldAssignment.concatTokensWithLinebreaks() + `.\n`;
    }
    code = code.trimEnd();
 
    const start = high.getFirstToken().getStart();
    const end = high.getLastToken().getEnd();
    const fix = EditHelper.replaceRange(lowFile, start, end, code);
 
    return Issue.atToken(lowFile, high.getFirstToken(), "Downport, simple move", this.getMetadata().key, this.conf.severity, fix);
  }
 
  // note, downporting ENUM does not give the correct types, but it will work in most cases?
  private downportEnum(_low: StatementNode, high: StatementNode, lowFile: ABAPFile,
                       _highSyntax: ISyntaxResult, highFile: ABAPFile): Issue | undefined {
    if (!(high.get() instanceof Statements.TypeEnumBegin)) {
      return undefined;
    }
    const enumStructure = highFile.getStructure()?.findFirstStructure(Structures.TypeEnum);
    if (enumStructure === undefined) {
      return undefined;
    }
    if (enumStructure.getFirstStatement() !== high) {
      return undefined;
    }
 
    const enumName = high.findExpressionAfterToken("ENUM")?.concatTokens();
    const structureName = high.findExpressionAfterToken("STRUCTURE")?.concatTokens();
 
// all ENUMS are char like?
    let code = `TYPES ${enumName} TYPE string.
CONSTANTS: BEGIN OF ${structureName},\n`;
    let count = 1;
    for (const e of enumStructure.findDirectStatements(Statements.TypeEnum).concat(enumStructure.findDirectStatements(Statements.Type))) {
      const name = e.findFirstExpression(Expressions.NamespaceSimpleName)?.concatTokens();
      let value = e.findFirstExpression(Expressions.Value)?.concatTokens();
      if (value === undefined) {
        value = "VALUE '" + count++ + "'";
      }
      code += `             ${name} TYPE ${enumName} ${value},\n`;
    }
    code += `           END OF ${structureName}.`;
 
    const start = enumStructure.getFirstToken().getStart();
    const end = enumStructure.getLastToken().getEnd();
    const fix = EditHelper.replaceRange(lowFile, start, end, code);
 
    return Issue.atToken(lowFile, high.getFirstToken(), "Downport ENUM", this.getMetadata().key, this.conf.severity, fix);
 
  }
 
  private moveWithTableTarget(low: StatementNode, high: StatementNode, lowFile: ABAPFile, highSyntax: ISyntaxResult): Issue | undefined {
    if (!(low.get() instanceof Unknown)) {
      return undefined;
    }
 
    let target: ExpressionNode | undefined = undefined;
    if (high.get() instanceof Statements.Move) {
      target = high.findDirectExpression(Expressions.Target);
    } else if (high.get() instanceof Statements.Clear
        || high.get() instanceof Statements.Free
        || high.get() instanceof Statements.Append
        || high.get() instanceof Statements.InsertInternal) {
      // the writable operand, eg. "CLEAR tab[ 1 ]-comp" or "APPEND 1 TO tab[ 1 ]-sub", is a Target
      // just like the left-hand side of an assignment, so it is lowered the same way
      target = high.findDirectExpressions(Expressions.Target).find(
        t => t.findDirectExpression(Expressions.TableExpression) !== undefined);
    }
    if (target === undefined) {
      return undefined;
    }
    const tableExpression = target.findDirectExpression(Expressions.TableExpression);
    if (tableExpression === undefined) {
      return undefined;
    }
    const index = tableExpression.findDirectExpression(Expressions.Source);
    if (index === undefined) {
      return undefined;
    }
 
    const uniqueName = this.uniqueName(high.getFirstToken().getStart(), lowFile.getFilename(), highSyntax, true);
 
    const tName = target.concatTokens().split("[")[0];
    const condition = this.tableCondition(tableExpression);
 
    const tabixBackup = this.uniqueName(high.getFirstToken().getStart(), lowFile.getFilename(), highSyntax);
    const indentation = " ".repeat(high.getFirstToken().getStart().getCol() - 1);
    // restore tabix before exeption
    const code = `FIELD-SYMBOLS ${uniqueName} LIKE LINE OF ${tName}.
${indentation}DATA ${tabixBackup} LIKE sy-tabix.
${indentation}${tabixBackup} = sy-tabix.
${indentation}READ TABLE ${tName} ${condition}ASSIGNING ${uniqueName}.
${indentation}sy-tabix = ${tabixBackup}.
${indentation}IF sy-subrc <> 0.
${indentation}  RAISE EXCEPTION TYPE cx_sy_itab_line_not_found.
${indentation}ENDIF.
${indentation}`;
 
    const start = target.getFirstToken().getStart();
    const end = tableExpression.findDirectTokenByText("]")?.getEnd();
    if (end === undefined) {
      return undefined;
    }
    // the READ TABLE goes in front of the statement, the target need not be its first operand
    const fix1 = EditHelper.insertAt(lowFile, high.getFirstToken().getStart(), code);
    const fix2 = EditHelper.replaceRange(lowFile, start, end, uniqueName);
    const fix = EditHelper.merge(fix2, fix1);
 
    return Issue.atToken(lowFile, high.getFirstToken(), "Downport, move with table target", this.getMetadata().key, this.conf.severity, fix);
  }
 
  private moveWithOperator(low: StatementNode, high: StatementNode, lowFile: ABAPFile): Issue | undefined {
    if (!(low.get() instanceof Unknown)) {
      return undefined;
    } else if (!(high.get() instanceof Statements.Move)) {
      return undefined;
    }
    const children = high.getChildren();
    const secondChild = children[1];
    if (secondChild === undefined) {
      return undefined;
    }
 
    const op = secondChild.getFirstToken();
    let operator: string;
    switch (op.getStr()) {
      case "+":
        operator = " + ";
        break;
      case "-":
        operator = " - ";
        break;
      case "/=":
        operator = " / ";
        break;
      case "*=":
        operator = " * ";
        break;
      case "&&=":
        operator = " && ";
        break;
      default:
        return undefined;
    }
 
    const target = high.findDirectExpression(Expressions.Target)?.concatTokens();
    if (target === undefined) {
      return;
    }
 
    const sourceStart = high.findDirectExpression(Expressions.Source)?.getFirstChild()?.getFirstToken().getStart();
    if (sourceStart === undefined) {
      return;
    }
 
    const fix = EditHelper.replaceRange(lowFile, op.getStart(), sourceStart, "= " + target + operator);
 
    return Issue.atToken(lowFile, high.getFirstToken(), "Expand operator", this.getMetadata().key, this.conf.severity, fix);
  }
 
  private stringTemplateAlpha(low: StatementNode, high: StatementNode, lowFile: ABAPFile, highSyntax: ISyntaxResult): Issue | undefined {
    if (!(low.get() instanceof Unknown)) {
      return undefined;
    }
 
    for (const child of high.findAllExpressionsRecursive(Expressions.StringTemplateSource)) {
      const formatting = child.findDirectExpression(Expressions.StringTemplateFormatting)?.concatTokens().toUpperCase();
      if (formatting === undefined
          || formatting?.startsWith("ALPHA = ") === false) {
        continue;
      }
 
      let functionName: string;
      switch (formatting) {
        case "ALPHA = IN":
          functionName = "CONVERSION_EXIT_ALPHA_INPUT";
          break;
        case "ALPHA = OUT":
          functionName = "CONVERSION_EXIT_ALPHA_OUTPUT";
          break;
        default:
          return undefined;
      }
 
      const indentation = " ".repeat(high.getFirstToken().getStart().getCol() - 1);
      const source = child.findDirectExpression(Expressions.Source)?.concatTokens();
      const uniqueName = this.uniqueName(high.getFirstToken().getStart(), lowFile.getFilename(), highSyntax);
 
      const code = `DATA ${uniqueName} TYPE string.
${indentation}CALL FUNCTION '${functionName}'
${indentation}  EXPORTING
${indentation}    input  = ${source}
${indentation}  IMPORTING
${indentation}    output = ${uniqueName}.\n`;
      const fix1 = EditHelper.insertAt(lowFile, high.getFirstToken().getStart(), code);
      const fix2 = EditHelper.replaceRange(lowFile, child.getFirstToken().getStart(), child.getLastToken().getEnd(), uniqueName);
      const fix = EditHelper.merge(fix2, fix1);
      return Issue.atToken(lowFile, high.getFirstToken(), "Downport ALPHA", this.getMetadata().key, this.conf.severity, fix);
    }
 
    return undefined;
 
  }
 
  private outlineLoopInput(low: StatementNode, high: StatementNode, lowFile: ABAPFile, highSyntax: ISyntaxResult): Issue | undefined {
    if (!(low.get() instanceof Unknown)) {
      return undefined;
    } else if (!(high.get() instanceof Statements.Loop)) {
      return undefined;
    } else if (high.findDirectExpression(Expressions.LoopSource)?.findDirectExpression(Expressions.SimpleSource2)) {
      return undefined;
    }
 
    // the first Source must be outlined
    const s = high.findDirectExpression(Expressions.LoopSource)?.findDirectExpression(Expressions.Source);
    if (s === undefined) {
      return undefined;
    }
 
    const uniqueName = this.uniqueName(high.getFirstToken().getStart(), lowFile.getFilename(), highSyntax);
 
    const code = `DATA(${uniqueName}) = ${s.concatTokens()}.\n` +
      " ".repeat(high.getFirstToken().getStart().getCol() - 1);
    const fix1 = EditHelper.insertAt(lowFile, high.getFirstToken().getStart(), code);
    const fix2 = EditHelper.replaceRange(lowFile, s.getFirstToken().getStart(), s.getLastToken().getEnd(), uniqueName);
    const fix = EditHelper.merge(fix2, fix1);
 
    return Issue.atToken(lowFile, high.getFirstToken(), "Outline LOOP input", this.getMetadata().key, this.conf.severity, fix);
  }
 
  private outlineLoopTarget(node: StatementNode, lowFile: ABAPFile, highSyntax: ISyntaxResult): Issue | undefined {
// also allows outlining of voided types
    if (!(node.get() instanceof Statements.Loop)) {
      return undefined;
    }
 
    if (this.lowReg.getConfig().isOpenABAP()) {
      return undefined;
    }
 
    const source = node.findDirectExpression(Expressions.LoopSource)?.findDirectExpression(Expressions.SimpleSource2);
    if (source === undefined) {
      return undefined;
    }
    const sourceName = source?.concatTokens();
    if (sourceName === undefined) {
      return undefined;
    }
 
    let foundType: TypedIdentifier | undefined = undefined;
    const spag = highSyntax.spaghetti.lookupPosition(source.getFirstToken().getStart(), lowFile.getFilename());
    if (spag) {
      foundType = spag.findVariable(source.concatTokens());
    }
 
    const concat = node.concatTokens().toUpperCase();
    if (concat.includes(" GROUP BY ") || concat.startsWith("LOOP AT GROUP ")) {
      return undefined;
    }
    const isReference = concat.includes(" REFERENCE INTO ");
    const indentation = " ".repeat(node.getFirstToken().getStart().getCol() - 1);
 
    const dataTarget = node.findDirectExpression(Expressions.LoopTarget)?.findDirectExpression(Expressions.Target)?.findDirectExpression(Expressions.InlineData);
    if (dataTarget) {
      const targetName = dataTarget.findDirectExpression(Expressions.TargetField)?.concatTokens() || "DOWNPORT_ERROR";
      let code = `DATA ${targetName} LIKE LINE OF ${sourceName}.\n${indentation}`;
      if (isReference) {
        const likeName = this.uniqueName(node.getFirstToken().getStart(), lowFile.getFilename(), highSyntax);
        code = `DATA ${likeName} LIKE LINE OF ${sourceName}.\n${indentation}DATA ${targetName} LIKE REF TO ${likeName}.\n${indentation}`;
      }
      const fix1 = EditHelper.insertAt(lowFile, node.getFirstToken().getStart(), code);
      const fix2 = EditHelper.replaceRange(lowFile, dataTarget.getFirstToken().getStart(), dataTarget.getLastToken().getEnd(), targetName);
      const fix = EditHelper.merge(fix2, fix1);
      return Issue.atToken(lowFile, node.getFirstToken(), "Outline LOOP data target", this.getMetadata().key, this.conf.severity, fix);
    }
 
    const fsTarget = node.findDirectExpression(Expressions.LoopTarget)?.findDirectExpression(Expressions.FSTarget)?.findDirectExpression(Expressions.InlineFS);
    if (fsTarget) {
      const targetName = fsTarget.findDirectExpression(Expressions.TargetFieldSymbol)?.concatTokens() || "DOWNPORT_ERROR";
      let type = `LIKE LINE OF ${sourceName}`;
      const f = foundType?.getType();
      if (f instanceof TableType && f.getRowType() instanceof AnyType) {
        type = "TYPE ANY";
      }
      const code = `FIELD-SYMBOLS ${targetName} ${type}.\n${indentation}`;
      const fix1 = EditHelper.insertAt(lowFile, node.getFirstToken().getStart(), code);
      const fix2 = EditHelper.replaceRange(lowFile, fsTarget.getFirstToken().getStart(), fsTarget.getLastToken().getEnd(), targetName);
      const fix = EditHelper.merge(fix2, fix1);
      return Issue.atToken(lowFile, node.getFirstToken(), "Outline LOOP fs target", this.getMetadata().key, this.conf.severity, fix);
    }

    return undefined;
  }
 
  private outlineFor(forLoop: ExpressionNode, indentation: string, lowFile: ABAPFile, highSyntax: ISyntaxResult):
  {body: string, end: string} {
    let body = "";
    let end = "";
    const loopSource = forLoop.findFirstExpression(Expressions.Source)?.concatTokens();
 
    let loopTargetFieldExpression = forLoop.findFirstExpression(Expressions.TargetField);
    let loopTargetFieldName = loopTargetFieldExpression?.concatTokens();
    const of = forLoop.findExpressionAfterToken("OF");
    if (of !== undefined) {
      loopTargetFieldExpression = of;
      loopTargetFieldName = of?.concatTokens();
    }
    if (forLoop.findDirectExpression(Expressions.InlineLoopDefinition)?.getFirstChild()?.get() instanceof Expressions.TargetFieldSymbol) {
      loopTargetFieldExpression = undefined;
      loopTargetFieldName = undefined;
    }
 
    if (loopTargetFieldExpression) {
      const start = loopTargetFieldExpression.getFirstToken().getStart();
      const spag = highSyntax.spaghetti.lookupPosition(start, lowFile.getFilename());
      if (loopTargetFieldName && spag) {
        if (new SpagHelper(spag).isDuplicateName(loopTargetFieldName, start)) {
          this.renameVariable(spag, loopTargetFieldName, start, lowFile, highSyntax);
        }
      }
    }
 
    let cond = forLoop.findDirectExpression(Expressions.ComponentCond)?.concatTokens() || "";
    if (cond !== "") {
      cond = " WHERE " + cond;
    }
 
    const loop = forLoop.findDirectExpression(Expressions.InlineLoopDefinition);
    const indexInto = loop?.findExpressionAfterToken("INTO")?.concatTokens();
 
    if (forLoop.findDirectTokenByText("UNTIL")
        || forLoop.findDirectTokenByText("WHILE")) {
      const fieldDef = forLoop.findDirectExpression(Expressions.InlineFieldDefinition);
      const field = fieldDef?.findFirstExpression(Expressions.Field)?.concatTokens();
      const indexBackup = this.uniqueName(forLoop.getFirstToken().getStart(), lowFile.getFilename(), highSyntax);
      body += indentation + "DATA " + field + " TYPE i.\n";
      const second = fieldDef?.getChildren()[2];
      if (second?.get() instanceof Expressions.Source) {
        body += indentation + field + " = " + second.concatTokens() + ".\n";
      }
 
      const not = forLoop.findDirectTokenByText("UNTIL") ? " NOT" : "";
      const cond = forLoop.findFirstExpression(Expressions.Cond);
      body += indentation + `DATA ${indexBackup} LIKE sy-index.\n`;
      body += indentation + `${indexBackup} = sy-index.\n`;
      body += indentation + `WHILE${not} ${cond?.concatTokens()}.\n`;
      body += indentation + `  sy-index = ${indexBackup}.\n`;
 
      const then = forLoop.findExpressionAfterToken("THEN");
      if (then) {
        end += `  ${field} = ${then.concatTokens()}.\n`;
      } else {
        end += `  ${field} = ${field} + 1.\n`;
      }
 
      end += indentation + "ENDWHILE";
    } else if (loopTargetFieldName !== undefined) {
      let from = forLoop.findExpressionAfterToken("FROM")?.concatTokens();
      from = from ? " FROM " + from : "";
      let to = forLoop.findExpressionAfterToken("TO")?.concatTokens();
      to = to ? " TO " + to : "";
 
      let gby = "";
      for (const lg of forLoop.findDirectExpressions(Expressions.LoopGroupByComponent)) {
        if (gby !== "") {
          gby += " ";
        }
        gby += lg.concatTokens();
      }
      if (gby !== "") {
        gby = " GROUP BY ( " + gby + " )";
      }
      const fc = forLoop.findDirectExpression(Expressions.FieldChain);
      if (fc) {
        gby = " GROUP BY " + fc.concatTokens();
      }
      if (forLoop.findDirectTokenByText("ASCENDING")) {
        gby += " ASCENDING";
      }
      if (forLoop.findDirectTokenByText("DESCENDING")) {
        gby += " DESCENDING";
      }
 
      const groups = forLoop.findExpressionAfterToken("GROUPS");
      if (groups) {
        const concat = groups.concatTokens();
        if (concat.startsWith("<")) {
          gby += " ASSIGNING FIELD-SYMBOL(" + concat + ")";
        } else {
          gby += " INTO DATA(" + concat + ")";
        }
      }
 
      let inGroup = "";
      if (forLoop.concatTokens().toUpperCase().includes(" IN GROUP ")) {
        inGroup = "-items";
      }
 
      let into = "INTO DATA";
      if (loopTargetFieldName.startsWith("<")) {
        into = "ASSIGNING FIELD-SYMBOL";
      }
      // todo, also backup sy-index / sy-tabix here?
      body += indentation + `LOOP AT ${loopSource}${inGroup} ${into}(${loopTargetFieldName})${from}${to}${cond}${gby}.\n`;
      if (indexInto) {
        body += indentation + "  DATA(" + indexInto + ") = sy-tabix.\n";
      }
      end = "ENDLOOP";
    } else if (loopTargetFieldName === undefined) {
      // todo, also backup sy-index / sy-tabix here?
      const loopTargetFieldSymbol = forLoop.findFirstExpression(Expressions.TargetFieldSymbol)?.concatTokens();
      body += indentation + `LOOP AT ${loopSource} ASSIGNING FIELD-SYMBOL(${loopTargetFieldSymbol})${cond}.\n`;
      if (indexInto) {
        body += indentation + "  DATA(" + indexInto + ") = sy-tabix.\n";
      }
      end = "ENDLOOP";
    }
 
    const l = forLoop.findDirectExpression(Expressions.Let);
    if (l) {
      body += this.outlineLet(l, indentation, highSyntax, lowFile);
    }
 
    return {body, end};
  }
 
  private outlineFilter(low: StatementNode, high: StatementNode, lowFile: ABAPFile, highSyntax: ISyntaxResult): Issue | undefined {
    if (!(low.get() instanceof Unknown)) {
      return undefined;
    }
 
    for (const i of high.findAllExpressionsRecursive(Expressions.Source)) {
      const firstToken = i.getFirstToken();
      if (firstToken.getStr().toUpperCase() !== "FILTER") {
        continue;
      }
 
      const filterBody = i.findDirectExpression(Expressions.FilterBody);
      if (filterBody === undefined) {
        continue;
      }
 
      const sourceName = filterBody.findDirectExpression(Expressions.Source)?.concatTokens();
      if (sourceName === undefined) {
        continue;
      }
 
      let type = this.findType(i, lowFile, highSyntax);
      if (type === undefined) {
        type = "LIKE " + sourceName;
      } else {
        type = "TYPE " + type;
      }
 
      const uniqueName = this.uniqueName(firstToken.getStart(), lowFile.getFilename(), highSyntax);
      const loopName = this.uniqueName(firstToken.getStart(), lowFile.getFilename(), highSyntax);
      const indentation = " ".repeat(high.getFirstToken().getStart().getCol() - 1);
      let body = "";
 
      body += `DATA ${uniqueName} ${type}.\n`;
      body += `${indentation}LOOP AT ${sourceName} INTO DATA(${loopName}) ${filterBody.concatTokens().substring(sourceName.length + 1)}.\n`;
      body += `${indentation}  INSERT ${loopName} INTO TABLE ${uniqueName}.\n`;
      body += `${indentation}ENDLOOP.\n${indentation}`;
 
      const fix1 = EditHelper.insertAt(lowFile, high.getFirstToken().getStart(), body);
      const fix2 = EditHelper.replaceRange(lowFile, firstToken.getStart(), i.getLastToken().getEnd(), uniqueName);
      const fix = EditHelper.merge(fix2, fix1);
 
      return Issue.atToken(lowFile, firstToken, "Downport FILTER", this.getMetadata().key, this.conf.severity, fix);
    }
 
    return undefined;
  }
 
  private outlineSwitch(low: StatementNode, high: StatementNode, lowFile: ABAPFile, highSyntax: ISyntaxResult): Issue | undefined {
    if (!(low.get() instanceof Unknown)) {
      return undefined;
    }
 
    for (const i of high.findAllExpressionsRecursive(Expressions.Source)) {
      const firstToken = i.getFirstToken();
      if (firstToken.getStr().toUpperCase() !== "SWITCH") {
        continue;
      }
 
      let type = this.findType(i, lowFile, highSyntax);
      if (type === undefined) {
        if (high.get() instanceof Statements.Move
            && high.findDirectExpression(Expressions.Source) === i
            && high.findDirectExpression(Expressions.Target)?.findDirectExpression(Expressions.TargetField) !== undefined) {
          type = "LIKE " + high.findDirectExpression(Expressions.Target)?.concatTokens();
        }
        if (type === undefined) {
          continue;
        }
      } else {
        type = "TYPE " + type;
      }
 
      const uniqueName = this.uniqueName(firstToken.getStart(), lowFile.getFilename(), highSyntax);
      const indentation = " ".repeat(high.getFirstToken().getStart().getCol() - 1);
      let body = "";
      const switchBody = i.findDirectExpression(Expressions.SwitchBody);
      if (switchBody === undefined) {
        continue;
      }
 
      for (const l of switchBody?.findDirectExpression(Expressions.Let)?.findDirectExpressions(Expressions.InlineFieldDefinition) || []) {
        const name = l.getFirstToken().getStr();
        body += indentation + `DATA(${name}) = ${switchBody.findFirstExpression(Expressions.Source)?.concatTokens()}.\n`;
      }
 
      body += `DATA ${uniqueName} ${type}.\n`;
      let firstSource = false;
      let inWhen = false;
      for (const c of switchBody.getChildren()) {
        if (c.get() instanceof Expressions.Source && firstSource === false) {
          body += indentation + `CASE ${c.concatTokens()}.`;
          firstSource = true;
        } else if (c instanceof TokenNode && c.concatTokens().toUpperCase() === "THEN") {
          inWhen = true;
          body += ".\n";
        } else if (c instanceof TokenNode && c.concatTokens().toUpperCase() === "WHEN") {
          inWhen = false;
          body += `\n${indentation}  WHEN `;
        } else if (c instanceof TokenNode && c.concatTokens().toUpperCase() === "OR") {
          body += ` OR `;
        } else if (c instanceof TokenNode && c.concatTokens().toUpperCase() === "ELSE") {
          inWhen = true;
          body += `\n${indentation}  WHEN OTHERS.\n`;
        } else if (inWhen === false) {
          body += c.concatTokens();
        } else {
          body += indentation + "    " + uniqueName + " = " + c.concatTokens() + ".";
        }
      }
      body += "\n" + indentation + "ENDCASE.\n" + indentation;
 
      const fix1 = EditHelper.insertAt(lowFile, high.getFirstToken().getStart(), body);
      const fix2 = EditHelper.replaceRange(lowFile, firstToken.getStart(), i.getLastToken().getEnd(), uniqueName);
      const fix = EditHelper.merge(fix2, fix1);
 
      return Issue.atToken(lowFile, firstToken, "Downport SWITCH", this.getMetadata().key, this.conf.severity, fix);
    }
 
    return undefined;
  }
 
  private outlineReduce(low: StatementNode, high: StatementNode, lowFile: ABAPFile, highSyntax: ISyntaxResult): Issue | undefined {
    if (!(low.get() instanceof Unknown)) {
      return undefined;
    }
 
    for (const i of high.findAllExpressionsRecursive(Expressions.Source)) {
      const firstToken = i.getFirstToken();
      if (firstToken.getStr().toUpperCase() !== "REDUCE") {
        continue;
      }
 
      const type = this.findType(i, lowFile, highSyntax);
      if (type === undefined) {
        continue;
      }
 
      const uniqueName = this.uniqueName(firstToken.getStart(), lowFile.getFilename(), highSyntax);
      const indentation = " ".repeat(high.getFirstToken().getStart().getCol() - 1);
      let body = "";
      const reduceBody = i.findDirectExpression(Expressions.ReduceBody);
      if (reduceBody === undefined) {
        continue;
      }
 
      const letNode = reduceBody.findDirectExpression(Expressions.Let);
      if (letNode) {
        body += this.outlineLet(letNode, indentation, highSyntax, lowFile);
      }
 
      let firstName = "";
      for (const init of reduceBody.findDirectExpressions(Expressions.InlineFieldDefinition)) {
        const name = init.getFirstToken().getStr();
        if (firstName === "") {
          firstName = name;
        }
 
        const spag = highSyntax.spaghetti.lookupPosition(init.getFirstToken().getStart(), lowFile.getFilename());
        if (spag && new SpagHelper(spag).isDuplicateName(name, init.getFirstToken().getStart())) {
          this.renameVariable(spag, name, init.getFirstToken().getStart(), lowFile, highSyntax);
        }
 
        const s = init.findFirstExpression(Expressions.Source)?.concatTokens();
        const t = init.findFirstExpression(Expressions.TypeName)?.concatTokens();
        if (s) {
          if (s.toUpperCase().startsWith("VALUE #")) {
            body += indentation + `DATA(${name}) = ${s.replace("#", type)}.\n`;
          } else {
            body += indentation + `DATA(${name}) = ${s}.\n`;
          }
        } else {
          body += indentation + `DATA ${name} TYPE ${t}.\n`;
        }
      }
 
      let end = "";
      for (const forLoop of reduceBody?.findDirectExpressions(Expressions.For) || []) {
        const outlineFor = this.outlineFor(forLoop, indentation, lowFile, highSyntax);
        body += outlineFor.body;
        end = outlineFor.end + `.\n` + end;
      }
 
      const next = reduceBody.findDirectExpression(Expressions.ReduceNext);
      if (next === undefined) {
        continue;
      }
      for (const n of next.getChildren()) {
        const concat = n.concatTokens();
        if (concat.toUpperCase() === "NEXT") {
          continue;
        } else if (n.get() instanceof Expressions.SimpleTarget) {
          body += indentation + "  " + concat + " ";
        } else if (n.get() instanceof Expressions.Source) {
          body += " " + concat + ".\n";
        } else {
          body += concat;
        }
      }
 
      body += indentation + end;
      body += indentation + `${uniqueName} = ${firstName}.\n`;
 
      const abap = `DATA ${uniqueName} TYPE ${type}.\n` +
        body +
        indentation;
      const reduceEnd = i.findDirectTokenByText(")");
      const fix1 = EditHelper.insertAt(lowFile, high.getFirstToken().getStart(), abap);
      const fix2 = EditHelper.replaceRange(lowFile, firstToken.getStart(), reduceEnd!.getEnd(), uniqueName);
      const fix = EditHelper.merge(fix2, fix1);
 
      return Issue.atToken(lowFile, firstToken, "Downport REDUCE", this.getMetadata().key, this.conf.severity, fix);
    }
 
    return undefined;
  }
 
  private outlineCorresponding(low: StatementNode, high: StatementNode, lowFile: ABAPFile, highSyntax: ISyntaxResult): Issue | undefined {
    if (!(low.get() instanceof Unknown)) {
      return undefined;
    }
 
    const allSources = high.findAllExpressionsRecursive(Expressions.Source);
    for (const s of allSources) {
      const firstToken = s.getFirstToken();
      if (firstToken.getStr().toUpperCase() !== "CORRESPONDING") {
        continue;
      }
 
      const correspondingBody = s.findDirectExpression(Expressions.CorrespondingBody);
 
      if (correspondingBody?.getFirstToken().getStr().toUpperCase() === "BASE") {
        continue;
      }
 
      const uniqueName = this.uniqueName(firstToken.getStart(), lowFile.getFilename(), highSyntax);
      const indentation = " ".repeat(high.getFirstToken().getStart().getCol() - 1);
 
      let type = this.findType(s, lowFile, highSyntax);
      if (type === undefined) {
        if (high.get() instanceof Statements.Move && high.findDirectExpression(Expressions.Source) === s) {
          type = "LIKE " + high.findDirectExpression(Expressions.Target)?.concatTokens();
        }
        if (type === undefined) {
          continue;
        }
      } else {
        type = "TYPE " + type;
      }
 
      let move = indentation + `MOVE-CORRESPONDING ${correspondingBody?.concatTokens()} TO ${uniqueName}.\n`;
      if (correspondingBody?.findDirectTokenByText("EXCEPT") !== undefined) {
        // MOVE-CORRESPONDING has no EXCEPT, move everything and clear the excepted components afterwards
        if (correspondingBody.findDirectExpression(Expressions.CorrespondingBodyMapping) !== undefined
            || !(this.findCorrespondingType(s, high, lowFile, highSyntax) instanceof StructureType)) {
          continue;
        }
        const children = correspondingBody.getChildren();
        const exceptIndex = children.findIndex(c => c instanceof TokenNode && c.getFirstToken().getStr().toUpperCase() === "EXCEPT");
        const fields = correspondingBody.findDirectExpressions(Expressions.Field);
        if (fields.length === 0) {
          // EXCEPT *, without MAPPING nothing is moved
          move = "";
        } else {
          const body = children.slice(0, exceptIndex).map(c => c.concatTokens()).join(" ");
          move = indentation + `MOVE-CORRESPONDING ${body} TO ${uniqueName}.\n`;
          for (const f of fields) {
            move += indentation + `CLEAR ${uniqueName}-${f.concatTokens()}.\n`;
          }
        }
      }
 
      const abap = `DATA ${uniqueName} ${type}.\n` +
        indentation + `CLEAR ${uniqueName}.\n` + // might be called inside a loop
        move +
        indentation;
      const fix1 = EditHelper.insertAt(lowFile, high.getFirstToken().getStart(), abap);
      const fix2 = EditHelper.replaceRange(lowFile, firstToken.getStart(), s.getLastToken().getEnd(), uniqueName);
      const fix = EditHelper.merge(fix2, fix1);
 
      return Issue.atToken(lowFile, firstToken, "Downport CORRESPONDING", this.getMetadata().key, this.conf.severity, fix);
    }
 
    return undefined;
  }
 
  private outlineValue(low: StatementNode, high: StatementNode, lowFile: ABAPFile, highSyntax: ISyntaxResult): Issue | undefined {
    if (!(low.get() instanceof Unknown)) {
      return undefined;
    }
 
    const allSources = high.findAllExpressionsRecursive(Expressions.Source);
    for (const s of allSources) {
      const firstToken = s.getFirstToken();
      if (firstToken.getStr().toUpperCase() !== "VALUE") {
        continue;
      }
 
      const valueBody = s.findDirectExpression(Expressions.ValueBody);
 
      let type = this.findType(s, lowFile, highSyntax);
      if (type === undefined) {
        if (high.get() instanceof Statements.Move && high.findDirectExpression(Expressions.Source) === s) {
          type = "LIKE " + high.findDirectExpression(Expressions.Target)?.concatTokens();
        }
        if (type === undefined) {
          continue;
        }
      } else {
        type = "TYPE " + type;
      }
 
      const uniqueName = this.uniqueName(firstToken.getStart(), lowFile.getFilename(), highSyntax);
      let indentation = " ".repeat(high.getFirstToken().getStart().getCol() - 1);
      let body = "";
      const base = valueBody?.findDirectExpression(Expressions.ValueBase)?.findExpressionAfterToken("BASE");
      if (base) {
        body += indentation + uniqueName + " = " + base.concatTokens() + ".\n";
      }
      let end = "";
 
      let structureName = uniqueName;
      let added = false;
      let data = "";
      let previous: ExpressionNode | TokenNode | undefined = undefined;
 
      if (valueBody?.findDirectExpression(Expressions.ValueBodyLine) !== undefined) {
        structureName = this.uniqueName(firstToken.getStart(), lowFile.getFilename(), highSyntax);
        const extra = valueBody?.findDirectExpression(Expressions.For) ? "  " : "";
        data = indentation + extra + `DATA ${structureName} LIKE LINE OF ${uniqueName}.\n`;
      }
 
      // all rows are built in the same work area, a component a row leaves out must be initial,
      // not what an earlier row (or an earlier pass of a surrounding loop) put there
      const clearRows = valueBody !== undefined && this.valueRowsNeedClear(valueBody);
      const prefix: string[] = [];
 
      for (const a of valueBody?.getChildren() || []) {
        if (a.get() instanceof Expressions.FieldAssignment) {
          if (clearRows === true) {
            // the shared prefix applies to every following row, re-applied after each CLEAR
            prefix.push(a.concatTokens());
            continue;
          }
          if (added === false) {
            body += data;
            added = true;
          }
          body += indentation + structureName + "-" + a.concatTokens() + ".\n";
        } else if (a instanceof ExpressionNode && a.get() instanceof Expressions.For) {
          const outlineFor = this.outlineFor(a, indentation, lowFile, highSyntax);
          body += outlineFor.body;
          end = outlineFor.end + `.\n` + end;
          indentation += "  ";
        } else if (a instanceof ExpressionNode && a.get() instanceof Expressions.Source) {
          // special handling for superflous value expression
          if (valueBody?.getChildren().length === 1) {
            body += indentation + uniqueName + " = " + a.concatTokens() + `.\n`;
          }
        } else if (a instanceof ExpressionNode && a.get() instanceof Expressions.Let) {
          body += this.outlineLet(a, indentation, highSyntax, lowFile);
        }
        if (a instanceof ExpressionNode && a.get() instanceof Expressions.ValueBodyLine) {
          let skip = false;
          if (clearRows === true && this.isStructuredValueRow(a)) {
            if (added === false) {
              body += data;
              added = true;
            }
            body += indentation + `CLEAR ${structureName}.\n`;
            for (const p of prefix) {
              body += indentation + structureName + "-" + p + ".\n";
            }
          }
          for (const b of a?.getChildren() || []) {
            if (b.get() instanceof Expressions.FieldAssignment) {
              if (added === false) {
                body += data;
                added = true;
              }
              body += indentation + structureName + "-" + (b as ExpressionNode).concatTokensWithLinebreaks() + ".\n";
            } else if (b.get() instanceof Expressions.Source) {
// note: it wont work with APPEND for Hashed/Sorted Tables, so use INSERT,
              body += indentation + "INSERT " + b.concatTokens() + ` INTO TABLE ${uniqueName}.\n`;
              skip = true;
            } else if (b.get() instanceof Expressions.ValueBodyLines) {
              body += indentation + "INSERT " + b.concatTokens() + ` INTO TABLE ${uniqueName}.\n`;
              skip = true;
            } else if (b.concatTokens() === ")") {
              if (added === false && previous?.concatTokens() === "(") {
                body += data;
                added = true;
              }
              if (skip === false) {
                body += indentation + `INSERT ${structureName} INTO TABLE ${uniqueName}.\n`;
              }
            }
            previous = b;
          }
        }
      }
 
      if (body === "" && valueBody?.getLastChild()?.getFirstToken().getStr().toUpperCase() === "OPTIONAL") {
        const fieldChain = valueBody.findFirstExpression(Expressions.FieldChain);
        const rowName = this.uniqueName(firstToken.getStart(), lowFile.getFilename(), highSyntax);
 
        let tableExpression: ExpressionNode | undefined = undefined;
        let tabName = "";
        let after = "";
        for (const c of fieldChain?.getChildren() || []) {
          if (c.get() instanceof Expressions.TableExpression && c instanceof ExpressionNode) {
            tableExpression = c;
          } else if (tableExpression === undefined) {
            tabName += c.concatTokens();
          } else {
            after += c.concatTokens();
          }
        }
 
        let condition: string;
        if (tableExpression?.getChildren().length === 3) {
          condition = "INDEX " + tableExpression?.findDirectExpression(Expressions.Source)?.concatTokens();
        } else {
          condition = "WITH KEY " + tableExpression?.concatTokens().replace("[ ", "").replace(" ]", "");
        }
 
        body +=
          indentation + `READ TABLE ${tabName} INTO DATA(${rowName}) ${condition}.\n` +
          indentation + `IF sy-subrc = 0.\n` +
          indentation + `  ${uniqueName} = ${rowName}${after}.\n` +
          indentation + `ENDIF.\n`;
 
        if (type.includes("LIKE DATA(")) {
          type = `LIKE LINE OF ${tabName}`;
        }
      }
 
      if (end !== "") {
        indentation = indentation.substring(2);
        body += indentation + end;
      }
 
      const abap = `DATA ${uniqueName} ${type}.\n` +
        indentation + `CLEAR ${uniqueName}.\n` + // might be called inside a loop
        body +
        indentation;
      const fix1 = EditHelper.insertAt(lowFile, high.getFirstToken().getStart(), abap);
      const fix2 = EditHelper.replaceRange(lowFile, firstToken.getStart(), s.getLastToken().getEnd(), uniqueName);
      const fix = EditHelper.merge(fix2, fix1);
 
      return Issue.atToken(lowFile, firstToken, "Downport VALUE", this.getMetadata().key, this.conf.severity, fix);
    }
 
    return undefined;
  }
 
  /** a row that is built in the work area, ie. not "( source )" or "( LINES OF source )" */
  private isStructuredValueRow(row: ExpressionNode): boolean {
    return row.findDirectExpression(Expressions.Source) === undefined
      && row.findDirectExpression(Expressions.ValueBodyLines) === undefined;
  }
 
  /** true if a row can observe a component that an earlier row, or an earlier pass of a surrounding loop,
   * left in the shared work area. Not the case if all rows assign the same components, and the shared
   * prefix is not changed between rows, eg. FOR rows or "( a = 1 b = 2 ) ( a = 3 b = 4 )" */
  private valueRowsNeedClear(valueBody: ExpressionNode): boolean {
    let shape: string | undefined = undefined;
    let rowSeen = false;
    for (const c of valueBody.getChildren()) {
      if (c.get() instanceof Expressions.FieldAssignment) {
        if (rowSeen === true) {
          return true;
        }
      } else if (c instanceof ExpressionNode
          && c.get() instanceof Expressions.ValueBodyLine
          && this.isStructuredValueRow(c)) {
        rowSeen = true;
        const current = c.findDirectExpressions(Expressions.FieldAssignment)
          .map(f => f.findDirectExpression(Expressions.FieldSub)?.concatTokens().toUpperCase().replace(/\s/g, ""))
          .sort()
          .join(",");
        if (shape !== undefined && shape !== current) {
          return true;
        }
        shape = current;
      }
    }
    return false;
  }
 
  private outlineLet(node: ExpressionNode, indentation: string, highSyntax: ISyntaxResult, lowFile: ABAPFile): string {
    let ret = "";
    for (const f of node.findDirectExpressions(Expressions.InlineFieldDefinition)) {
      const c = f.getFirstChild();
      if (c === undefined) {
        continue;
      }
      const name = c.concatTokens().toLowerCase();
 
      const spag = highSyntax.spaghetti.lookupPosition(c.getFirstToken().getStart(), lowFile.getFilename());
      if (spag === undefined) {
        continue;
      }
 
      if (new SpagHelper(spag).isDuplicateName(name, c.getFirstToken().getStart())) {
        this.renameVariable(spag, name, c.getFirstToken().getStart(), lowFile, highSyntax);
      }
 
      const found = spag.findVariable(name);
      if (found === undefined) {
        const source = f.findFirstExpression(Expressions.Source);
        if (source) {
          ret += indentation + "DATA(" + name + `) = ${source.concatTokens()}.\n`;
        }
        continue;
      }
      const type = found.getType().getQualifiedName() ? found.getType().getQualifiedName()?.toLowerCase() : found.getType().toABAP();
 
      ret += indentation + "DATA " + name + ` TYPE ${type}.\n`;
 
      const source = f.findFirstExpression(Expressions.Source);
      if (source) {
        ret += indentation + name + ` = ${source.concatTokens()}.\n`;
      }
    }
    return ret;
  }
 
  private renameVariable(spag: ISpaghettiScopeNode, name: string, pos: Position, lowFile: ABAPFile, highSyntax: ISyntaxResult) {
    const newName = this.uniqueName(pos, lowFile.getFilename(), highSyntax);
    const fix = new SpagHelper(spag).renameVariable(name, pos, lowFile, newName);
    const issue = Issue.atPosition(lowFile, pos, "Rename before outline", this.getMetadata().key, this.conf.severity, fix);
    throw new SkipToNextFile(issue);
  }
 
  /** the type of the value a CORRESPONDING operator returns, if it can be determined */
  private findCorrespondingType(s: ExpressionNode, high: StatementNode, lowFile: ABAPFile, highSyntax: ISyntaxResult): AbstractType | undefined {
    const expr = s.findDirectExpression(Expressions.TypeNameOrInfer);
    if (expr === undefined) {
      return undefined;
    }
    const spag = highSyntax.spaghetti.lookupPosition(expr.getFirstToken().getStart(), lowFile.getFilename());
    if (spag === undefined) {
      return undefined;
    }
 
    if (expr.concatTokens() !== "#") {
      return spag.findType(expr.concatTokens())?.getType();
    }
 
    for (const r of spag.getData().references) {
      if (r.referenceType === ReferenceType.InferredType
          && r.resolved instanceof TypedIdentifier
          && r.position.getStart().equals(expr.getFirstToken().getStart())) {
        return r.resolved.getType();
      }
    }

    const target = high.findDirectExpression(Expressions.Target);
    if (high.get() instanceof Statements.Move && high.findDirectExpression(Expressions.Source) === s && target !== undefined) {
      return spag.findVariable(target.concatTokens())?.getType();
    }

    return undefined;
  }
 
  private findType(i: ExpressionNode, lowFile: ABAPFile, highSyntax: ISyntaxResult, ref = false): string | undefined {
    const expr = i.findDirectExpression(Expressions.TypeNameOrInfer);
    if (expr === undefined) {
      return undefined;
    }
    const firstToken = expr.getFirstToken();
 
    const concat = expr.concatTokens().toLowerCase();
    if (concat !== "#") {
      return ref ? "REF TO " + concat : concat;
    }
 
    const spag = highSyntax.spaghetti.lookupPosition(firstToken.getStart(), lowFile.getFilename());
    if (spag === undefined) {
      return undefined;
    }
 
    let inferred: TypedIdentifier | undefined = undefined;
    for (const r of spag?.getData().references || []) {
      if (r.referenceType === ReferenceType.InferredType
          && r.resolved
          && r.position.getStart().equals(firstToken.getStart())
          && r.resolved instanceof TypedIdentifier
          && r.extra?.foundQualified === true) {
        inferred = r.resolved;
        break;
      }
    }
    if (inferred === undefined) {
      return undefined;
    }
 
    if (inferred.getType() instanceof ObjectReferenceType) {
      return inferred.getType().toABAP();
    } else {
      return inferred.getType().getQualifiedName()?.toLowerCase();
    }
  }
 
  private outlineFS(low: StatementNode, high: StatementNode, lowFile: ABAPFile, highSyntax: ISyntaxResult): Issue | undefined {
    if (!(low.get() instanceof Unknown)
        || (high.get() instanceof Statements.Loop)) {
      return undefined;
    }
 
    for (const i of high.findAllExpressionsRecursive(Expressions.InlineFS)) {
      const nameToken = i.findDirectExpression(Expressions.TargetFieldSymbol)?.getFirstToken();
      if (nameToken === undefined) {
        continue;
      }
      const name = nameToken.getStr();
 
      let type: string;
      if (high.concatTokens().toUpperCase().startsWith("APPEND INITIAL LINE TO ")) {
        type = "LIKE LINE OF " + high.findFirstExpression(Expressions.Target)?.concatTokens();
      } else {
        const spag = highSyntax.spaghetti.lookupPosition(nameToken.getStart(), lowFile.getFilename());
        if (spag === undefined) {
          continue;
        }
        const found = spag.findVariable(name);
        if (found === undefined) {
          continue;
        } else if (found.getType() instanceof VoidType) {
          return Issue.atToken(lowFile, i.getFirstToken(), "Error outlining voided type", this.getMetadata().key, this.conf.severity);
        }
        type = "TYPE ";
        type += found.getType().getQualifiedName() ? found.getType().getQualifiedName()!.toLowerCase() : found.getType().toABAP();
      }
 
      const code = `FIELD-SYMBOLS ${name} ${type}.\n` +
        " ".repeat(high.getFirstToken().getStart().getCol() - 1);
      const fix1 = EditHelper.insertAt(lowFile, high.getFirstToken().getStart(), code);
      const fix2 = EditHelper.replaceRange(lowFile, i.getFirstToken().getStart(), i.getLastToken().getEnd(), name);
      const fix = EditHelper.merge(fix2, fix1);
 
      return Issue.atToken(lowFile, i.getFirstToken(), "Outline FIELD-SYMBOL", this.getMetadata().key, this.conf.severity, fix);
    }
 
    return undefined;
  }
 
  /** READ TABLE [REFERENCE] INTO DATA( ) where the row type is void, no TYPE can be written, use LIKE LINE OF like LOOP does */
  private outlineReadTableVoidTarget(node: StatementNode, lowFile: ABAPFile, highSyntax: ISyntaxResult): Issue | undefined {
    if (!(node.get() instanceof Statements.ReadTable)) {
      return undefined;
    }
 
    if (this.lowReg.getConfig().isOpenABAP()) {
      return undefined;
    }
 
    const source = node.findDirectExpression(Expressions.SimpleSource2);
    const target = node.findDirectExpression(Expressions.ReadTableTarget);
    const inline = target?.findDirectExpression(Expressions.Target)?.findDirectExpression(Expressions.InlineData);
    if (source === undefined || target === undefined || inline === undefined) {
      return undefined;
    }
 
    const nameToken = inline.findDirectExpression(Expressions.TargetField)?.getFirstToken();
    if (nameToken === undefined) {
      return undefined;
    }
    const name = nameToken.getStr();
 
    const spag = highSyntax.spaghetti.lookupPosition(nameToken.getStart(), lowFile.getFilename());
    const found = spag?.findVariable(name);
    const table = spag?.findVariable(source.concatTokens());
    const isReference = target.findDirectTokenByText("REFERENCE") !== undefined;
    if (isReference === true && !(table?.getType() instanceof VoidType)) {
      return undefined;
    } else if (isReference === false
        && (!(found?.getType() instanceof VoidType) || found.getType().getQualifiedName() !== undefined)) {
      return undefined;
    }
 
    const indentation = " ".repeat(node.getFirstToken().getStart().getCol() - 1);
    let code = `DATA ${name} LIKE LINE OF ${source.concatTokens()}.\n${indentation}`;
    if (isReference === true) {
      const likeName = this.uniqueName(node.getFirstToken().getStart(), lowFile.getFilename(), highSyntax);
      code = `DATA ${likeName} LIKE LINE OF ${source.concatTokens()}.\n${indentation}DATA ${name} LIKE REF TO ${likeName}.\n${indentation}`;
    }
    const fix1 = EditHelper.insertAt(lowFile, node.getFirstToken().getStart(), code);
    const fix2 = EditHelper.replaceRange(lowFile, inline.getFirstToken().getStart(), inline.getLastToken().getEnd(), name);
    const fix = EditHelper.merge(fix2, fix1);
 
    return Issue.atToken(lowFile, inline.getFirstToken(), "Outline DATA", this.getMetadata().key, this.conf.severity, fix);
  }
 
  private outlineData(node: StatementNode, lowFile: ABAPFile, highSyntax: ISyntaxResult): Issue | undefined {
    // hmm, no guard here, as DATA(SDF) is valid in 702
 
    if (this.lowReg.getConfig().isOpenABAP()) {
      return undefined;
    }
 
    for (const i of node.findAllExpressionsRecursive(Expressions.InlineData)) {
      const nameToken = i.findDirectExpression(Expressions.TargetField)?.getFirstToken();
      if (nameToken === undefined) {
        continue;
      }
      const name = nameToken.getStr();
 
      const spag = highSyntax.spaghetti.lookupPosition(nameToken.getStart(), lowFile.getFilename());
      if (spag === undefined) {
        continue;
      }
 
      const found = spag.findVariable(name);
      if (found === undefined) {
        continue;
      } else if (found.getType() instanceof VoidType && found.getType().getQualifiedName() === undefined) {
        continue;
      } else if (found.getType() instanceof StructureType && found.getType().getQualifiedName() === undefined) {
        continue;
      }
 
      let type = found.getType().getQualifiedName()
        ? found.getType().getQualifiedName()?.toLowerCase()
        : found.getType().toABAP();
      if (found.getType() instanceof ObjectReferenceType) {
        type = found.getType().toABAP();
      }
      if (type === "") {
        continue;
      }
 
      const code = `DATA ${name} TYPE ${type}.\n` +
        " ".repeat(node.getFirstToken().getStart().getCol() - 1);
      const fix1 = EditHelper.insertAt(lowFile, node.getFirstToken().getStart(), code);
      const fix2 = EditHelper.replaceRange(lowFile, i.getFirstToken().getStart(), i.getLastToken().getEnd(), name);
      const fix = EditHelper.merge(fix2, fix1);
 
      return Issue.atToken(lowFile, i.getFirstToken(), "Outline DATA", this.getMetadata().key, this.conf.severity, fix);
    }
 
    return undefined;
  }
 
  private outlineCond(low: StatementNode, high: StatementNode, lowFile: ABAPFile, highSyntax: ISyntaxResult): Issue | undefined {
    if (!(low.get() instanceof Unknown)) {
      return undefined;
    }
 
    for (const i of high.findAllExpressionsRecursive(Expressions.Source)) {
      if (i.getFirstToken().getStr().toUpperCase() !== "COND") {
        continue;
      }
 
      const body = i.findDirectExpression(Expressions.CondBody);
      if (body === undefined) {
        continue;
      }
 
      const uniqueName = this.uniqueName(i.getFirstToken().getStart(), lowFile.getFilename(), highSyntax);
      let type = this.findType(i, lowFile, highSyntax);
      if (type === undefined) {
        if (high.get() instanceof Statements.Move
            && high.findDirectExpression(Expressions.Source) === i
            && high.findDirectExpression(Expressions.Target)?.findDirectExpression(Expressions.TargetField) !== undefined) {
          type = "LIKE " + high.findDirectExpression(Expressions.Target)?.concatTokens();
        }
        if (type === undefined) {
          continue;
        }
      } else {
        type = "TYPE " + type;
      }
 
      const indent = " ".repeat(high.getFirstToken().getStart().getCol() - 1);
      const bodyCode = this.buildCondBody(body, uniqueName, indent, lowFile, highSyntax);
 
      const last = i.findDirectTokenByText(")")!;
 
      const abap = `DATA ${uniqueName} ${type}.\n` + bodyCode;
      const fix1 = EditHelper.insertAt(lowFile, high.getFirstToken().getStart(), abap);
      const fix2 = EditHelper.replaceRange(lowFile, i.getFirstToken().getStart(), last.getEnd(), uniqueName);
      const fix = EditHelper.merge(fix2, fix1);
      return Issue.atToken(lowFile, i.getFirstToken(), "Downport COND", this.getMetadata().key, this.conf.severity, fix);
    }
 
    return undefined;
  }
 
  private buildCondBody(body: ExpressionNode, uniqueName: string, indent: string, lowFile: ABAPFile, highSyntax: ISyntaxResult) {
    let code = "";
 
    let first = true;
    let addElse = true;
    for (const c of body.getChildren()) {
      if (c instanceof TokenNode) {
        switch (c.getFirstToken().getStr().toUpperCase()) {
          case "WHEN":
            if (first === true) {
              code += indent + "IF ";
              first = false;
            } else {
              code += indent + "ELSEIF ";
            }
            break;
          case "THEN":
            code += ".\n";
            break;
          case "ELSE":
            code += indent + "ELSE.\n";
            addElse = false;
            break;
          default:
            throw "buildCondBody, unexpected token";
        }
      } else if (c.get() instanceof Expressions.Cond) {
        code += c.concatTokens();
      } else if (c.get() instanceof Expressions.Let) {
        code += this.outlineLet(c, indent, highSyntax, lowFile);
      } else if (c.get() instanceof Expressions.Source) {
        code += indent + "  " + uniqueName + " = " + c.concatTokens() + ".\n";
      } else if (c.get() instanceof Expressions.Throw) {
        code += indent + "  " + c.concatTokens().replace(/THROW /i, "RAISE EXCEPTION NEW ") + ".\n";
      } else {
        throw "buildCondBody, unexpected expression, " + c.get().constructor.name;
      }
    }
    if (addElse) {
      // COND might be called inside a loop
      code += indent + "ELSE.\n";
      code += indent + `  CLEAR ${uniqueName}.\n`;
    }
 
    code += indent + "ENDIF.\n";
 
    code += indent;
    return code;
  }
 
  private outlineConv(low: StatementNode, high: StatementNode, lowFile: ABAPFile, highSyntax: ISyntaxResult): Issue | undefined {
    if (!(low.get() instanceof Unknown)) {
      return undefined;
    }
 
    for (const i of high.findAllExpressionsRecursive(Expressions.Source)) {
      if (i.getFirstToken().getStr().toUpperCase() !== "CONV") {
        continue;
      }
      const end = i.findDirectTokenByText(")");
      if (end === undefined) {
        continue;
      }
 
      const body = i.findDirectExpression(Expressions.ConvBody)?.concatTokens();
      if (body === undefined) {
        continue;
      }
 
      const uniqueName = this.uniqueName(i.getFirstToken().getStart(), lowFile.getFilename(), highSyntax);
      const indent = " ".repeat(high.getFirstToken().getStart().getCol() - 1);
 
      // the CONV type might just be a component of the row type, so prefer the row type
      const rowOf = this.findRowTypeOf(high, i);
      const type = rowOf === undefined ? this.findType(i, lowFile, highSyntax) : undefined;
      if (rowOf === undefined && type === undefined) {
        return Issue.atToken(lowFile, i.getFirstToken(), "Downport CONV, type of # not known", this.getMetadata().key, this.conf.severity);
      }
      const declaration = rowOf === undefined
        ? `DATA ${uniqueName} TYPE ${type}.`
        : `DATA ${uniqueName} LIKE LINE OF ${rowOf}.`;
 
      const abap = declaration + "\n" +
        indent + `${uniqueName} = ${body}.\n` +
        indent;
      const fix1 = EditHelper.insertAt(lowFile, high.getFirstToken().getStart(), abap);
      const fix2 = EditHelper.replaceRange(lowFile, i.getFirstToken().getStart(), end.getEnd(), uniqueName);
      const fix = EditHelper.merge(fix2, fix1);
 
      return Issue.atToken(lowFile, i.getFirstToken(), "Downport CONV", this.getMetadata().key, this.conf.severity, fix);
    }
 
    return undefined;
  }
 
  /** a( )->b( CHANGING c = d ), the object the last method is called on is outlined into a
   * variable typed via the RETURNING parameter of the method before it */
  private outlineChainedCallParameters(low: StatementNode, high: StatementNode, lowFile: ABAPFile,
                                       highSyntax: ISyntaxResult): Issue | undefined {
    if (!(high.get() instanceof Statements.Call)) {
      return undefined;
    } else if (this.lowReg.getConfig().isOpenABAP()) {
      return undefined;
    } else if (low.getFirstToken().getStart() instanceof VirtualPosition) {
      return undefined;
    }
 
    const chain = high.findDirectExpression(Expressions.MethodCallChain);
    const children = chain?.getChildren() || [];
    const last = children[children.length - 1];
    const arrow = children[children.length - 2];
    const previous = children[children.length - 3];
    if (chain === undefined
        || !(last instanceof ExpressionNode)
        || !(last.get() instanceof Expressions.MethodCall)
        || arrow?.getFirstToken().getStr() !== "->"
        || !(previous instanceof ExpressionNode)
        || !(previous.get() instanceof Expressions.MethodCall)) {
      return undefined;
    }
 
    const parameters = last.findDirectExpression(Expressions.MethodCallParam)?.findDirectExpression(Expressions.MethodParameters);
    if (parameters === undefined) {
      return undefined;
    }
 
    // the type of the object, from the method that returns it
    const methodToken = previous.findDirectExpression(Expressions.MethodName)?.getFirstToken();
    if (methodToken === undefined) {
      return undefined;
    }
    const spag = highSyntax.spaghetti.lookupPosition(methodToken.getStart(), lowFile.getFilename());
    let type: string | undefined = undefined;
    for (const r of spag?.getData().references || []) {
      if (r.referenceType === ReferenceType.MethodReference
          && r.position.getStart().equals(methodToken.getStart())) {
        const returning = (r.resolved as IMethodDefinition | undefined)?.getParameters().getReturning()?.getType();
        if (returning instanceof ObjectReferenceType) {
          type = returning.toABAP();
        }
        break;
      }
    }
    if (type === undefined) {
      return undefined;
    }
 
    const object = children.slice(0, children.length - 2).map(c => c.concatTokens()).join("");
    const uniqueName = this.uniqueName(high.getFirstToken().getStart(), lowFile.getFilename(), highSyntax);
    const indentation = " ".repeat(high.getFirstToken().getStart().getCol() - 1);
    const code = `DATA ${uniqueName} TYPE ${type}.\n` +
      indentation + `${uniqueName} = ${object}.\n` +
      indentation;
 
    const fix1 = EditHelper.insertAt(lowFile, high.getFirstToken().getStart(), code);
    const fix2 = EditHelper.replaceRange(lowFile, chain.getFirstToken().getStart(), previous.getLastToken().getEnd(), uniqueName);
    const fix = EditHelper.merge(fix2, fix1);
 
    return Issue.atToken(lowFile, chain.getFirstToken(), "Outline object of chained call with parameter keywords",
                         this.getMetadata().key, this.conf.severity, fix);
  }
 
  /** if the source expression is the complete source of an INSERT or APPEND statement, then the
   * outlined variable must be typed via the row type of the table, returns the table name */
  private findRowTypeOf(high: StatementNode, source: ExpressionNode): string | undefined {
    if (!(high.get() instanceof Statements.InsertInternal)
        && !(high.get() instanceof Statements.Append)) {
      return undefined;
    } else if (high.getChildren()[1] !== source) {
      return undefined;
    }
    return high.findDirectExpression(Expressions.Target)?.concatTokens();
  }
 
  // "CAST" to "?="
  private outlineCast(low: StatementNode, high: StatementNode, lowFile: ABAPFile, highSyntax: ISyntaxResult): Issue | undefined {
    if (!(low.get() instanceof Unknown)) {
      return undefined;
    }
 
    for (const i of high.findAllExpressionsRecursive(Expressions.Cast)) {
      const uniqueName = this.uniqueName(i.getFirstToken().getStart(), lowFile.getFilename(), highSyntax);
      const type = this.findType(i, lowFile, highSyntax, true);
      const body = i.findDirectExpression(Expressions.Source)?.concatTokens();
 
      const abap = `DATA ${uniqueName} TYPE ${type}.\n` +
        " ".repeat(high.getFirstToken().getStart().getCol() - 1) +
        `${uniqueName} ?= ${body}.\n` +
        " ".repeat(high.getFirstToken().getStart().getCol() - 1);
      const fix1 = EditHelper.insertAt(lowFile, high.getFirstToken().getStart(), abap);
      const fix2 = EditHelper.replaceRange(lowFile, i.getFirstToken().getStart(), i.getLastToken().getEnd(), uniqueName);
      const fix = EditHelper.merge(fix2, fix1);
 
      return Issue.atToken(lowFile, i.getFirstToken(), "Downport CAST", this.getMetadata().key, this.conf.severity, fix);
    }
 
    return undefined;
  }
 
  /** a FIELD-SYMBOLS declaration is known to the scope under its bracketed spelling, so
   * the collision check has to use that spelling too - otherwise a second outline in the
   * same method is handed a name that is already taken and the result does not compile */
  private uniqueName(position: Position, filename: string, highSyntax: ISyntaxResult, fieldSymbol = false): string {
    const decorate = (name: string) => fieldSymbol === true ? `<${name}>` : name;
 
    const spag = highSyntax.spaghetti.lookupPosition(position, filename);
    if (spag === undefined) {
      const name = "temprr" + this.counter;
      this.counter++;
      return decorate(name);
    }
 
    let postfix = "";
    if (spag.getIdentifier().stype === ScopeType.ClassDefinition) {
// try making sure this name is not used in subclasses
      const hash = crypto.createHash("sha1").update(spag.getIdentifier().sname).digest("hex");
      postfix = "_" + hash.substring(0, 10);
    }
 
    while (true) {
      const name = decorate("temp" + this.counter + postfix);
      const exists = this.existsRecursive(spag, name);
      this.counter++;
      if (exists === false) {
        return name;
      }
    }
  }
 
  // todo, optimize, the findVariable() and findType() does a lot of redundant checks
  private existsRecursive(spag: ISpaghettiScopeNode, name: string): boolean {
    const existsDirect = spag.findVariable(name) || spag.findType(name);
    if (existsDirect) {
      return true;
    }
 
    for (const child of spag.getChildren()) {
      if (child.findVariable(name) || child.findType(name) || this.existsRecursive(child, name)) {
        return true;
      }
    }
 
    return false;
  }
 
  /** WITH/WITHOUT AUTHORITY-CHECK on CALL TRANSACTION requires v740sp02, so the statement is
   * Unknown in the low version, note that only WITHOUT is handled here */
  private stripCallTransactionAuthorityCheck(high: StatementNode, lowFile: ABAPFile): Issue | undefined {
    if (!(high.get() instanceof Statements.CallTransaction)) {
      return undefined;
    } else if (this.lowReg.getConfig().isOpenABAP()) {
      // open-abap supports the addition
      return undefined;
    }
 
    const tokens = high.getTokens();
    // the lexer splits "AUTHORITY-CHECK" into three tokens: AUTHORITY, -, CHECK
    for (let i = 1; i < tokens.length - 3; i++) {
      if (tokens[i].getStr().toUpperCase() === "WITHOUT"
          && tokens[i + 1].getStr().toUpperCase() === "AUTHORITY"
          && tokens[i + 2].getStr() === "-"
          && tokens[i + 3].getStr().toUpperCase() === "CHECK") {
        // also remove the preceding space so no double space is left behind
        const fix = EditHelper.deleteRange(lowFile, tokens[i - 1].getEnd(), tokens[i + 3].getEnd());
        const message = "Remove WITHOUT AUTHORITY-CHECK from CALL TRANSACTION";
        return Issue.atToken(lowFile, tokens[i], message, this.getMetadata().key, this.conf.severity, fix);
      }
    }
 
    return undefined;
  }
 
  private replaceXsdBool(node: StatementNode, lowFile: ABAPFile, highSyntax: ISyntaxResult): Issue | undefined {
    if (this.lowReg.getConfig().isOpenABAP()) {
      return undefined;
    }
 
    const spag = highSyntax.spaghetti.lookupPosition(node.getFirstToken().getStart(), lowFile.getFilename());
 
    for (const r of spag?.getData().references || []) {
      if (r.referenceType === ReferenceType.BuiltinMethodReference
          && r.position.getName().toUpperCase() === "XSDBOOL") {
        const token = r.position.getToken();
 
        let source: ExpressionNode | undefined = undefined;
        for (const s of node.findAllExpressionsRecursive(Expressions.Source)) {
          if (s.getFirstToken().getStart().equals(token.getStart())) {
            source = s;
            break;
          }
        }
        const children = source?.getChildren();
        if (source === undefined || children?.length !== 4) {
          continue;
        }
 
        // make sure to convert to the correct type, RTTI might be used on the result of XSDBOOL
        const code = "CONV xsdboolean( boolc( " + children[2].concatTokens() + " ) )";
        const fix = EditHelper.replaceRange(lowFile, source.getFirstToken().getStart(), source.getLastToken().getEnd(), code);
        return Issue.atToken(lowFile, token, "Use BOOLC", this.getMetadata().key, this.conf.severity, fix);
      }
    }
 
    return undefined;
  }
 
  private findMethodCallExpression(node: StatementNode, token: AbstractToken) {
    for (const m of node.findAllExpressions(Expressions.MethodCall)) {
      if (m.findDirectExpression(Expressions.MethodName)?.getFirstToken().getStart().equals(token.getStart())) {
        return m;
      }
    }
    return undefined;
  }
 
  private replaceMethodConditional(low: StatementNode, high: StatementNode, lowFile: ABAPFile, highSyntax: ISyntaxResult): Issue | undefined {
    if (!(low.get() instanceof Unknown)) {
      return undefined;
    }
 
    for (const c of high.findAllExpressionsRecursive(Expressions.Compare)) {
      const chain = c.findDirectExpression(Expressions.MethodCallChain);
      if (chain === undefined) {
        continue;
      }
 
      const concat = chain.concatTokens().toUpperCase();
      if (concat.startsWith("LINE_EXISTS( ") || concat.startsWith("LINE_INDEX( ")) {
        // these are handled separately
        continue;
      }
 
      let predicate = false;
      const spag = highSyntax.spaghetti.lookupPosition(high.getFirstToken().getStart(), lowFile.getFilename());
      for (const r of spag?.getData().references || []) {
        if (r.referenceType === ReferenceType.BuiltinMethodReference &&
              BuiltIn.isPredicate(chain.getFirstToken().getStr().toUpperCase())) {
          predicate = true;
          break;
        }
      }
 
      const end = chain.getLastToken().getEnd();
      let fix = EditHelper.insertAt(lowFile, end, " IS NOT INITIAL");
      if (predicate === true) {
        fix = EditHelper.insertAt(lowFile, end, " ) = abap_true");
        const fix1 = EditHelper.insertAt(lowFile, chain.getFirstToken().getStart(), "boolc( ");
        fix = EditHelper.merge(fix, fix1);
      }
      return Issue.atToken(lowFile, chain.getFirstToken(), "Downport method conditional", this.getMetadata().key, this.conf.severity, fix);
    }
 
    return undefined;
  }
 
  private getReference(node: StatementNode, lowFile: ABAPFile, highSyntax: ISyntaxResult): Issue | undefined {
    if (!(node.get() instanceof Statements.GetReference)) {
      return undefined;
    }

    const inline = node.findDirectExpression(Expressions.Target)?.findDirectExpression(Expressions.InlineData);
    if (inline === undefined) {
      return undefined;
    }
    const targetName = inline.findDirectExpression(Expressions.TargetField)?.concatTokens();
    const sourceName = node.findDirectExpression(Expressions.Source)?.concatTokens();
    if (targetName === undefined || sourceName === undefined) {
      return undefined;
    }

    const code = `DATA ${targetName} ${this.refTypeOf(sourceName, node, lowFile, highSyntax)}.\n`;
    const fix1 = EditHelper.insertAt(lowFile, node.getFirstToken().getStart(), code);
    const fix2 = EditHelper.replaceRange(lowFile, inline.getFirstToken().getStart(), inline.getLastToken().getEnd(), targetName);
    const fix = EditHelper.merge(fix2, fix1);
    return Issue.atToken(lowFile, inline.getFirstToken(), "Downport, outline DATA ref", this.getMetadata().key, this.conf.severity, fix);

  }
 
  private replaceContains(node: StatementNode, lowFile: ABAPFile, highSyntax: ISyntaxResult): Issue | undefined {
    const spag = highSyntax.spaghetti.lookupPosition(node.getFirstToken().getStart(), lowFile.getFilename());
 
    // only downport if its an single method call condition
    let found = false;
    for (const c of node.findAllExpressionsRecursive(Expressions.Compare)) {
      found = c.findDirectExpression(Expressions.MethodCallChain) !== undefined;
      if (found === true) {
        break;
      }
    }
    if (found === false) {
      return undefined;
    }
 
    for (const r of spag?.getData().references || []) {
      if (r.referenceType !== ReferenceType.BuiltinMethodReference) {
        continue;
      }
      const func = r.position.getName().toUpperCase();
      if (func === "CONTAINS") {
        const token = r.position.getToken();
 
        const expression = this.findMethodCallExpression(node, token);
        if (expression === undefined) {
          continue;
        }
 
        const sList = expression.findAllExpressions(Expressions.Source).map(e => e.concatTokens());
        if (sList.length !== 2) {
          continue;
        }
 
        const code = sList[0] + " CS " + sList[1];
        const start = expression.getFirstToken().getStart();
        const end = expression.getLastToken().getEnd();
        const fix = EditHelper.replaceRange(lowFile, start, end, code);
 
        return Issue.atToken(lowFile, token, "Downport contains()", this.getMetadata().key, this.conf.severity, fix);
      }
    }
 
    return undefined;
  }
 
  private replaceLineFunctions(node: StatementNode, lowFile: ABAPFile, highSyntax: ISyntaxResult, highFile: ABAPFile): Issue | undefined {
    if (this.lowReg.getConfig().isOpenABAP()) {
      return undefined;
    }
 
    const spag = highSyntax.spaghetti.lookupPosition(node.getFirstToken().getStart(), lowFile.getFilename());
 
    for (const r of spag?.getData().references || []) {
      if (r.referenceType !== ReferenceType.BuiltinMethodReference) {
        continue;
      }
      const func = r.position.getName().toUpperCase();
      if (func === "LINE_EXISTS" || func === "LINE_INDEX") {
        const token = r.position.getToken();
 
        const expression = this.findMethodCallExpression(node, token);
        if (expression === undefined) {
          continue;
        }
 
        let condition = "";
        for (const c of expression?.findFirstExpression(Expressions.TableExpression)?.getChildren() || []) {
          if (c.getFirstToken().getStr() === "[" || c.getFirstToken().getStr() === "]") {
            continue;
          } else if (c.get() instanceof Expressions.ComponentChainSimple && condition === "") {
            condition = "WITH KEY ";
          } else if (c.get() instanceof Expressions.Source && condition === "") {
            condition = "INDEX ";
          }
          condition += c.concatTokens() + " ";
        }
 
        const tableName = expression.findFirstExpression(Expressions.Source)?.concatTokens().split("[")[0];
 
        const uniqueName = this.uniqueName(node.getFirstToken().getStart(), lowFile.getFilename(), highSyntax);
        const indentation = " ".repeat(node.getFirstToken().getStart().getCol() - 1);
 
        const sy = func === "LINE_EXISTS" ? "sy-subrc" : "sy-tabix";
 
        let insertAt: Position | undefined = node.getFirstToken().getStart();
        if (node.get() instanceof ElseIf) {
          // assumption: no side effects in IF conditions, except the READ itself, see below
          insertAt = this.findStartOfIf(node, highFile);
          if (insertAt === undefined) {
            continue;
          }
        }
 
        // the READ sets sy-subrc and sy-tabix, which the built-in function does not,
        // keep the values for the code that reads them after the inserted READ
        const keep: {field: string, name: string}[] = [];
        const reads = this.readSyFields(insertAt, highFile);
        for (const field of ["sy-subrc", "sy-tabix"]) {
          if (reads.has(field)) {
            keep.push({field, name: this.uniqueName(node.getFirstToken().getStart(), lowFile.getFilename(), highSyntax)});
          }
        }
 
        const code = `DATA ${uniqueName} LIKE sy-subrc.\n` +
          keep.map(k => indentation + `DATA ${k.name} LIKE ${k.field}.\n`).join("") +
          keep.map(k => indentation + `${k.name} = ${k.field}.\n`).join("") +
          indentation + `READ TABLE ${tableName} ${condition}TRANSPORTING NO FIELDS.\n` +
          indentation + uniqueName + ` = ${sy}.\n` +
          keep.map(k => indentation + `${k.field} = ${k.name}.\n`).join("") +
          indentation ;
        const fix1 = EditHelper.insertAt(lowFile, insertAt, code);
        const start = expression.getFirstToken().getStart();
        const end = expression.getLastToken().getEnd();
        const fix2 = EditHelper.replaceRange(lowFile, start, end, uniqueName + (func === "LINE_EXISTS" ? " = 0" : ""));
        const fix = EditHelper.merge(fix2, fix1);
 
        return Issue.atToken(lowFile, token, "Replace line function", this.getMetadata().key, this.conf.severity, fix);
      }
    }
 
    return undefined;
  }
 
  /** IS [NOT] INSTANCE OF is 750, outline it as a cast in a TRY before the statement,
   *  the cast of an initial reference succeeds, while IS INSTANCE OF is false, hence the IS BOUND */
  private replaceInstanceOf(low: StatementNode, high: StatementNode, lowFile: ABAPFile,
                            highSyntax: ISyntaxResult, highFile: ABAPFile): Issue | undefined {
    if (!(low.get() instanceof Unknown)) {
      return undefined;
    } else if (!(high.get() instanceof Statements.If)
        && !(high.get() instanceof Statements.ElseIf)
        && !(high.get() instanceof Statements.Check)) {
      // the condition of eg. WHILE is evaluated more than once
      return undefined;
    }
 
    for (const c of high.findAllExpressionsRecursive(Expressions.Compare)) {
      const className = c.findDirectExpression(Expressions.ClassName);
      const source = c.findDirectExpression(Expressions.Source);
      if (className === undefined || source === undefined) {
        continue;
      }
      const children = c.getChildren();
      const operator = children.slice(children.indexOf(source) + 1).map(n => n.concatTokens().toUpperCase()).join(" ");
      const negated = operator.startsWith("IS NOT INSTANCE OF");
 
      let insertAt: Position | undefined = high.getFirstToken().getStart();
      if (high.get() instanceof Statements.ElseIf) {
        // assumption: no side effects in IF conditions
        insertAt = this.findStartOfIf(high, highFile);
        if (insertAt === undefined) {
          return undefined;
        }
      }
 
      const castName = this.uniqueName(high.getFirstToken().getStart(), lowFile.getFilename(), highSyntax);
      const boolName = this.uniqueName(high.getFirstToken().getStart(), lowFile.getFilename(), highSyntax);
      const indentation = " ".repeat(insertAt.getCol() - 1);
 
      const code = `DATA ${castName} TYPE REF TO ${className.concatTokens()}.
${indentation}DATA ${boolName} TYPE abap_bool.
${indentation}TRY.
${indentation}    ${castName} ?= ${source.concatTokens()}.
${indentation}    ${boolName} = boolc( ${castName} IS BOUND ).
${indentation}  CATCH cx_sy_move_cast_error.
${indentation}    ${boolName} = abap_false.
${indentation}ENDTRY.
${indentation}`;
      const fix1 = EditHelper.insertAt(lowFile, insertAt, code);
      const fix2 = EditHelper.replaceRange(lowFile, source.getFirstToken().getStart(), className.getLastToken().getEnd(),
                                           boolName + (negated ? " = abap_false" : " = abap_true"));
      const fix = EditHelper.merge(fix2, fix1);
      return Issue.atToken(lowFile, source.getFirstToken(), "Downport IS INSTANCE OF", this.getMetadata().key, this.conf.severity, fix);
    }
 
    return undefined;
  }
 
  /** sy-subrc and sy-tabix, when read from the position on, in the procedure around it or the file outside of one;
   *  inside a loop from the start of the outermost loop, as the next pass reads what this one left */
  private readSyFields(position: Position, highFile: ABAPFile): Set<string> {
    const structure = highFile.getStructure();
    const contains = (s: StructureNode) => !position.isBefore(s.getFirstToken().getStart())
      && !position.isAfter(s.getLastToken().getStart());
 
    let scope: StructureNode | undefined = undefined;
    for (const s of [Structures.Method, Structures.Form, Structures.FunctionModule]) {
      for (const p of structure?.findAllStructuresRecursive(s) || []) {
        if (contains(p)) {
          scope = p;
        }
      }
    }
    scope = scope || structure;
 
    let from = position;
    for (const s of [Structures.Loop, Structures.Do, Structures.While, Structures.Select]) {
      for (const l of scope?.findAllStructuresRecursive(s) || []) {
        if (contains(l) && l.getFirstToken().getStart().isBefore(from)) {
          from = l.getFirstToken().getStart();
        }
      }
    }
 
    const ret = new Set<string>();
    for (const s of scope?.findAllStatementNodes() || []) {
      if (s.getLastToken().getStart().isBefore(from)) {
        continue;
      }
      const tokens = s.getTokens();
      for (let i = 0; i < tokens.length - 2; i++) {
        if (tokens[i].getStr().toUpperCase() === "SY" && tokens[i + 1].getStr() === "-") {
          const field = "sy-" + tokens[i + 2].getStr().toLowerCase();
          if (field === "sy-subrc" || field === "sy-tabix") {
            ret.add(field);
          }
        }
      }
    }
    return ret;
  }
 
  private findStartOfIf(node: StatementNode, highFile: ABAPFile): Position | undefined {
    const structure = highFile.getStructure();
 
    for (const c of structure?.findAllStructuresRecursive(Structures.If) || []) {
      for (const ei of c.findDirectStructures(Structures.ElseIf)) {
        if (ei.getFirstStatement() === node) {
          return c.getFirstToken().getStart();
        }
      }
    }

    return undefined;
  }
 
  private newToCreateObject(low: StatementNode, high: StatementNode, lowFile: ABAPFile, highSyntax: ISyntaxResult): Issue | undefined {
    if (!(low.get() instanceof Unknown)) {
      return undefined;
    }
 
    const source = high.findDirectExpression(Expressions.Source);
 
    let fix: IEdit | undefined = undefined;
    if (high.get() instanceof Statements.Move
        && source
        && source.getFirstToken().getStr().toUpperCase() === "NEW") {
      const target = high.findDirectExpression(Expressions.Target);
      const found = source?.findFirstExpression(Expressions.NewObject);
      // must be at top level of the source for quickfix to work(todo: handle more scenarios)
      if (target
          && found
          && source.concatTokens() === found.concatTokens()
          && target.findDirectExpression(Expressions.InlineData) === undefined) {
        const abap = this.newDataReference(high, target, found, lowFile, highSyntax)
          ?? this.newParameters(found, target.concatTokens(), highSyntax, lowFile);
        if (abap !== undefined) {
          fix = EditHelper.replaceRange(lowFile, high.getFirstToken().getStart(), high.getLastToken().getEnd(), abap);
        }
      }
    }
 
    if (fix === undefined) {
      const found = high.findFirstExpression(Expressions.NewObject);
      if (found === undefined) {
        return undefined;
      }
      const name = this.uniqueName(found.getFirstToken().getStart(), lowFile.getFilename(), highSyntax);
      const abap = this.newParameters(found, name, highSyntax, lowFile);
      if (abap === undefined) {
        return undefined;
      }
 
      const type = this.findType(found, lowFile, highSyntax);
      const indentation = " ".repeat(high.getFirstToken().getStart().getCol() - 1);
 
      const data = `DATA ${name} TYPE REF TO ${type}.\n` +
        indentation + abap + "\n" +
        indentation;
      if (found.getFirstToken().getStart().equals(high.getFirstToken().getStart())
          && found.getLastToken().getEnd().equals(high.getLastToken().getStart())) {
// full statement = standalone NEW expression
        fix = EditHelper.replaceRange(lowFile, high.getFirstToken().getStart(), high.getLastToken().getEnd(), abap);
      } else {
        const fix1 = EditHelper.insertAt(lowFile, high.getFirstToken().getStart(), data);
        const fix2 = EditHelper.replaceRange(lowFile, found.getFirstToken().getStart(), found.getLastToken().getEnd(), name);
        fix = EditHelper.merge(fix2, fix1);
      }
    }
 
    if (fix) {
      return Issue.atToken(lowFile, high.getFirstToken(), "Use CREATE OBJECT instead of NEW", this.getMetadata().key, this.conf.severity, fix);
    } else {
      return undefined;
    }
  }
 
  /** NEW into a data reference creates data, CREATE OBJECT cannot: "target = NEW #|type( [value] )"
   *  with a target typed REF TO a data type becomes CREATE DATA plus the assignment of the value */
  private newDataReference(high: StatementNode, target: ExpressionNode, found: ExpressionNode,
                           lowFile: ABAPFile, highSyntax: ISyntaxResult): string | undefined {
    const children = found.getChildren();
    const value = found.findDirectExpression(Expressions.Source);
    // NEW, the type, "(", optionally one value, ")"
    if (children.length !== 4 + (value ? 1 : 0)) {
      return undefined;
    }
 
    const name = target.concatTokens();
    const typeExpr = found.findDirectExpression(Expressions.TypeNameOrInfer);
    const typeName = typeExpr?.concatTokens();
    const spag = highSyntax.spaghetti.lookupPosition(high.getFirstToken().getStart(), lowFile.getFilename());
    let type: AbstractType | undefined = undefined;
    if (typeName === "#") {
      // the type of the target, as inferred by the syntax check
      const typeToken = typeExpr!.getFirstToken();
      const resolved = spag?.getData().references.find(r => r.referenceType === ReferenceType.InferredType
        && r.position.getStart().equals(typeToken.getStart()))?.resolved;
      type = resolved instanceof TypedIdentifier ? resolved.getType() : undefined;
    } else if (target.getChildren().length === 1 && target.getFirstChild()?.get() instanceof Expressions.TargetField) {
      type = spag?.findVariable(name)?.getType();
    }
    if (!(type instanceof DataReference)) {
      return undefined;
    }
 
    const indentation = " ".repeat(high.getFirstToken().getStart().getCol() - 1);
    let abap = `CREATE DATA ${name}` + (typeName === "#" ? "" : ` TYPE ${typeName}`) + ".";
    if (value === undefined) {
      return abap;
    } else if (type.getType().isGeneric() === false) {
      return abap + `\n${indentation}${name}->* = ${value.concatTokens()}.`;
    }
    // a generic reference cannot be dereferenced as a target below v756
    const fs = this.uniqueName(high.getFirstToken().getStart(), lowFile.getFilename(), highSyntax, true);
    abap = `FIELD-SYMBOLS ${fs} TYPE any.\n` +
      indentation + abap + "\n" +
      indentation + `ASSIGN ${name}->* TO ${fs}.\n` +
      indentation + `${fs} = ${value.concatTokens()}.`;
    return abap;
  }
 
  private newParameters(found: ExpressionNode, name: string, highSyntax: ISyntaxResult, lowFile: ABAPFile): string | undefined {
    const typeToken = found.findDirectExpression(Expressions.TypeNameOrInfer)?.getFirstToken();
    let extra = typeToken?.getStr() === "#" ? "" : " TYPE " + typeToken?.getStr();
    const parameters = found.findFirstExpression(Expressions.ParameterListS);
    if (parameters) {
      extra = parameters ? extra + " EXPORTING " + parameters.concatTokens() : extra;
    } else if (typeToken) {
      const source = found.findDirectExpression(Expressions.Source)?.concatTokens();
      if (source) {
        // find the default parameter name for the constructor
        const spag = highSyntax.spaghetti.lookupPosition(typeToken?.getStart(), lowFile.getFilename());
 
        let cdef: IClassDefinition | TypedIdentifier | undefined = undefined;
        for (const r of spag?.getData().references || []) {
          if ((r.referenceType === ReferenceType.InferredType
              || r.referenceType === ReferenceType.ObjectOrientedReference)
              && r.resolved && r.position.getStart().equals(typeToken.getStart())) {
            cdef = r.resolved as IClassDefinition | TypedIdentifier;
          }
        }
        if (cdef instanceof TypedIdentifier) {
          const foo = cdef.getType();
          if (foo instanceof ObjectReferenceType) {
            cdef = spag?.findClassDefinition(foo.getQualifiedName()!);
            if (cdef === undefined) {
              const cglobal = this.highReg.getObject("CLAS", foo.getQualifiedName()!) as Class | undefined;
              cdef = cglobal?.getDefinition();
            }
          } else {
            return undefined; // not an object, CREATE OBJECT does not apply
          }
        }
 
        if (cdef && cdef.getMethodDefinitions === undefined) {
          return undefined; // something wrong
        }
        const importing = this.findConstructor(cdef, spag)?.getParameters().getDefaultImporting();
        if (importing) {
          extra += " EXPORTING " + importing + " = " + source;
        } else if (spag === undefined) {
          extra += " SpagUndefined ERROR";
        } else if (cdef === undefined) {
          extra += " ClassDefinitionNotFound ERROR";
        } else {
          extra += " SomeError ERROR";
        }
      }
    }
 
    const abap = `CREATE OBJECT ${name}${extra}.`;
 
    return abap;
  }
 
  private findConstructor(cdef: IClassDefinition | undefined, spag: ISpaghettiScopeNode | undefined): any {
    let def = cdef;
    while (def !== undefined) {
      const method = def?.getMethodDefinitions().getByName("CONSTRUCTOR");
      if (method) {
        return method;
      }
      const name = def.getSuperClass();
      if (name) {
        def = spag?.findClassDefinition(name);
      } else {
        return undefined;
      }
    }
  }
 
}