All files / src/rules downport.ts

92.13% Statements 3035/3294
79.4% Branches 1103/1389
100% Functions 78/78
92.13% Lines 3035/3294

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 32951x 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 289x 289x 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 215x 215x 5x 5x 210x 215x 147x 147x 6x 6x 147x 204x 204x 204x 1x 1x 68x 68x 68x 16x 16x 68x 68x     68x 68x 1x 1x 1x 10588x 10588x 10588x 10588x 10588x 10588x 10588x 10588x 31228x 31228x 31228x 31228x 31228x 31228x 31228x 31228x 31228x 31228x 31228x 31228x 31228x 31228x 31228x 31228x 31228x 31228x 31228x 31228x 31228x 31228x 31228x 31228x 31228x 31228x 31228x 31228x 31228x 31228x 31228x 31228x 31228x 31228x 31228x 31228x 31228x 31228x 31228x 31228x 31228x 10588x 10588x 9814x 9814x 10588x 10588x 241x 241x 10588x 10588x 751x 751x 751x 510x 510x 751x 751x 10588x 10588x 1x     1x 1x 1x 1x 1x 1x 10588x 10588x 510x 510x 3475x 1x 1x 3475x 510x     510x 509x 509x 509x 10588x 10588x 817x 817x 817x 817x 817x 307x 817x     510x 510x 817x     510x 510x 510x 817x 1x 1x 509x 509x 817x 1x 1x     1x 1x     1x 1x 509x 509x 509x 509x 509x 509x     509x 509x 509x 509x                       509x 509x 509x 509x 509x 509x 509x 3466x 3466x 3466x 3466x 432x 432x 432x 432x 432x 403x 403x 432x 432x 7x 5x 5x 7x 2x 2x 7x 432x 3466x 507x 509x 11x 11x 115x 115x 12x 12x 3x 3x 12x 115x 11x 507x 509x 8x 74x 74x 74x 8x 8x 74x 8x 509x 509x 507x 507x 507x 10588x 10588x 10588x 10588x 10588x 510x 510x 510x 510x 510x 510x 510x 510x 510x 521x 522x   522x 522x 522x 522x 521x 510x 510x 510x 10588x 10588x 10588x 432x 432x     432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 2x 2x 430x 430x 432x 1x 1x 429x 429x 432x 5x 5x 424x 424x 432x 4x 4x 420x 420x 432x 5x 5x 415x 415x 432x 6x 6x 409x 409x 432x 8x 8x 401x 401x 432x 5x 5x 396x 396x 432x 1x 1x 395x 395x 432x 5x 5x 390x 390x 432x 4x 4x 386x 386x 432x 1x 1x 385x 385x 432x 11x 11x 374x 374x 432x 2x 2x 372x 372x 432x 2x 2x 370x 370x 432x 12x 12x 358x 358x 432x 1x 1x 357x 357x 432x 21x 21x 336x 336x 432x 1x 1x 335x 335x 432x 41x 41x 294x 294x 294x 294x 294x 432x 7x 7x 7x   7x 7x 7x 7x 294x 432x 287x 287x 57x 57x 287x 235x 235x 235x 235x 23x 23x 235x 210x 210x 432x 2x 2x 208x 208x 432x 1x 1x 207x 207x 432x 4x 4x 203x 203x 432x 2x 2x 201x 201x 432x 3x 3x 198x 198x 432x 14x 14x 184x 184x 432x 17x 17x 166x 166x 432x 1x 1x 165x 165x 432x 3x 3x 162x 162x 432x 27x 27x 135x 135x 432x 51x 51x 84x 84x 432x 11x 11x 73x 73x 432x 15x 15x 58x 58x 432x 10x 10x 48x 48x 432x     48x 48x 432x 1x 1x 47x 47x 432x 2x 2x 45x 45x 432x 7x 7x 36x 36x 432x 2x 2x 34x 34x 432x 8x 8x 26x 26x 432x 3x 3x 23x 23x 432x 1x 1x 22x 22x 22x 10588x 10588x 10588x 10588x 10588x 357x 111x 111x 246x 246x 357x 357x 357x 357x 357x 224x 224x 22x 22x 22x 30x 30x 19x 30x 11x 11x 22x 22x 22x 22x 22x 22x 357x 42x 42x 24x 24x 1x 1x 1x 1x 1x 1x 24x 23x 23x 24x 42x 21x 357x 26x 15x 7x 7x 15x 26x 21x 357x 19x 19x 2x 357x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 10588x 10588x 358x 111x 358x 228x 228x 19x 19x 358x 17x 17x 358x 358x 1x 1x 1x 358x     358x 358x 358x 358x 358x 358x 358x 358x 358x 358x 358x 10588x 10588x 370x 370x 111x 370x 225x 225x 34x 34x 34x 370x 8x 8x 26x 26x 370x 4x 4x 22x 22x 22x 10588x 10588x 208x 208x 82x 208x 125x 125x 1x 1x 208x     1x 208x 208x     1x 1x 1x 1x 1x 1x 10588x 10588x 34x 34x     34x 34x 34x 12x 12x 22x 22x 34x 14x 14x 8x 8x 34x     8x 34x 34x     8x 8x 8x 34x 1x 1x 34x     8x 8x 34x 34x 3x 34x 2x 5x 1x 3x 2x 1x 1x           1x 1x 2x 2x 2x 1x 1x 1x 8x 8x 8x 8x 8x 8x 8x 8x 10588x 10588x 26x 26x     26x 26x 26x 15x 15x 11x 11x 11x 26x 7x 7x 4x 4x 26x     4x 26x 26x     4x 4x 26x     4x 26x 6x 6x 3x 3x 3x 3x 6x 6x 4x 4x 26x 26x 26x 26x 26x 26x 26x 1x 1x 1x 4x 4x 4x 4x 4x 4x 10588x 10588x 10588x 12x     12x 12x 12x 9x 9x 3x 3x 3x 3x 3x 3x 3x 3x 3x 10588x 10588x 26x 23x 23x 3x 26x     3x 3x 26x 5x   5x 1x 5x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x       10588x 10588x 36x 34x 34x 2x 2x 2x 2x 2x 2x     2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x       10588x 10588x 23x 20x 20x 3x 3x 23x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 10588x 10588x 34x 26x 26x 8x 8x 8x 8x 8x 8x     8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x       10588x 10588x 45x 5x 5x 40x 45x 30x 30x 21x 21x 9x 9x 30x       9x 9x 9x 30x 20x 9x 20x 9x 9x 11x 11x 30x     9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 30x 2x 2x 7x 7x 7x 31x 31x 31x 10588x 10588x 11x 11x 11x 54x 22x 54x 8x 7x 8x 1x 1x 32x 3x 24x 1x 21x 1x 1x 1x 30x 30x 11x 11x 10588x 10588x 166x 166x 166x 165x 165x 1x 1x 166x     1x 1x 166x     1x 1x 166x 166x 166x 166x 166x 166x 166x 166x 166x 166x 10588x 10588x 165x 162x 162x 3x 3x 165x     3x 3x 165x     3x 165x 165x 165x 165x 165x 165x 165x 165x 165x 165x 10588x 10588x 162x 65x 65x 97x 97x 162x 25x 25x 72x 72x 72x 162x   162x 6x 72x 33x 33x 1x 33x 1x 32x 3x 3x 3x 3x 3x 1x 3x 2x 2x 31x 28x 28x 28x 28x 2x 2x 28x 26x 26x 26x 27x 162x 162x 162x 162x 162x 162x 162x 162x 162x 162x 10588x 10588x 430x 430x 1x 1x     1x 1x     1x 1x 1x 429x 429x 429x 10588x 10588x 429x 429x 429x 429x 429x 429x 429x 429x 429x 429x 429x 429x 429x 429x 429x 429x 429x 429x 429x 429x 429x 429x 422x 422x 7x 7x 7x 7x 7x 429x 2x 2x 2x 2x     2x 2x 1x 1x 429x 5x 5x 2x 2x 3x 5x 2x 5x 1x 1x 3x 5x 2x 5x 1x 1x 3x 3x 3x 5x 429x 429x 429x 429x 429x 429x 429x 429x 429x 429x 429x 429x 2x 2x 2x 2x 2x 5x 5x 429x 2x 2x 5x 429x 6x 6x 6x 5x 5x 5x 5x 5x 5x 10588x 10588x 424x 111x 111x 313x 424x 4x 4x     4x 4x 4x     4x 4x     4x 4x 4x 4x 309x 309x 309x 10588x 10588x 374x 372x 372x 2x 2x 374x 3x 3x 3x 3x 1x 1x 3x 2x 2x 3x 374x     2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 10588x 10588x 390x 390x 390x 385x 385x 5x 5x 390x     5x 390x 390x 1x 1x 1x 1x 1x 1x 1x 390x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 10588x 10588x 395x 395x 395x 390x 390x 5x 5x 395x     395x 395x 395x     5x 5x 395x 1x 1x 1x 1x 1x 1x 395x 4x 4x 4x 4x 4x 3x 3x 3x 3x 3x 1x 1x 1x 3x 3x 4x 4x 5x 5x 5x 5x 5x 5x 5x 10588x 10588x 385x 328x 328x 57x 385x 46x 46x 385x 385x 385x 385x 385x 385x 385x 385x 385x 385x 385x 385x 385x 11x 11x 11x 10x 10x 11x 11x 11x 11x 11x 11x 385x 10x 10x 10x 2x 2x 10x 1x 1x 8x 7x 1x 1x 7x 7x 7x 7x 10x 10x 11x 11x 385x 5x 5x 5x 5x 5x 5x 5x 11x 11x 11x 11x 11x 11x 11x 11x 385x 385x 1x 1x 11x 11x 385x 2x 2x 385x 385x 385x 385x 10x 10x 10x 1x 10x 2x 9x 7x 7x 10x 385x 5x 5x 385x 385x 385x 385x 385x 385x 385x 385x 385x 11x 11x     11x 15x 4x 4x     4x 4x 4x 4x 4x 15x 11x 11x 11x 11x 10588x 10588x 386x 111x 111x 275x 275x 386x 768x 768x 1x 1x 768x 386x 274x 274x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 10588x 10588x 401x 111x 111x 290x 401x 283x 401x     7x 401x 401x 401x 401x 401x 2x 2x 5x 5x 401x 2x 2x     2x 401x 3x 3x 3x 3x 3x 5x 5x 401x 12x 5x 5x 7x 7x 5x 5x 401x 401x 401x 401x 401x 401x 10588x 10588x 396x 111x 111x 285x 396x 283x 283x 2x 2x 396x 1x 1x 1x 1x 396x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 10588x 10588x 409x 111x 111x 298x 298x 409x 140x 140x 158x 158x 409x     158x 409x     158x 409x 39x 39x 119x 409x 79x 79x 40x 409x 7x 7x 33x 33x 409x 24x 409x 1x 1x 8x 8x 8x 409x 9x 9x 8x 8x 8x 8x 8x 8x 8x 8x 10588x 10588x 10588x 432x 432x 430x 430x 432x 432x     432x     2x 432x 432x 432x 432x 432x 432x 432x 432x 4x 4x 4x 2x 2x 4x 4x 2x 2x 2x 2x 2x 2x 2x 2x 2x 10588x 10588x 372x 111x 111x 261x 372x 120x 120x 141x 141x 372x     141x 372x 139x 139x 2x 372x     2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 372x 372x     2x 2x 2x 2x 10588x 10588x 415x 111x 415x 140x 140x 164x 164x 415x     164x 164x 164x 164x 415x 1x 1x 415x 1x 1x 415x 1x 1x 415x 1x 1x 415x 2x 2x 415x 158x 415x 6x 415x 415x     6x 415x 415x     6x 6x 6x 6x 6x 10588x 10588x 10588x 420x 111x 111x 309x 420x 51x 51x 51x 51x 40x 40x 11x 11x 51x 51x 51x 51x 1x 1x 51x 4x 4x 51x 6x 51x 5x 5x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 298x 298x 298x 298x 10588x 10588x 336x 111x 336x 208x 225x 16x 16x 1x 1x 1x 336x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 10588x 10588x 335x 335x 290x 290x 45x 335x 335x     45x 45x 335x 4x 4x 41x 41x 41x 335x 335x 29x 29x 29x 9x 9x 9x 29x 29x 29x 29x 29x 12x 335x 335x 12x 12x 12x 12x 12x 12x 12x       10588x 10588x 43x 43x 43x 43x 43x 43x 43x 43x 43x 5x 5x 5x 43x 3x 3x 3x 43x 43x 25x 25x 25x 25x 2x 2x 25x 25x 41x 43x 43x 1x 1x 41x 41x 43x 43x 43x 43x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 1x 15x 14x 14x 15x 15x 43x 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 41x 41x 43x 1x 1x 41x 41x 41x 10588x 10588x 203x 82x 82x 121x 203x 338x 338x 336x 336x 2x 2x 338x     2x 338x 338x     2x 2x 338x   338x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 119x 119x 119x 10588x 10588x 207x 82x 82x 125x 207x 346x 346x 341x 341x 5x 5x 346x 3x 3x 3x 2x 2x 3x 1x 1x 346x 2x 2x 4x 4x 4x 4x 4x 4x 4x 346x     4x 346x       4x 4x 4x 4x 346x 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 121x 121x 121x 10588x 10588x 235x 82x 82x 153x 235x 395x 395x 369x 369x 26x 26x 395x 1x 1x 25x 25x 25x 25x 25x 25x 25x 395x     25x 25x 395x 1x 1x 25x 25x 395x 29x 29x 25x 25x 29x 29x 29x 1x 1x 28x 29x 29x 29x 27x 2x 27x 25x 25x 29x 1x 1x 29x 24x 24x 395x 25x 25x 25x 25x 23x 23x 395x     395x 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 128x 128x 128x 10588x 10588x 210x 82x 82x 128x 128x 210x 368x 368x 365x 365x 3x 3x 3x 368x 1x 1x 2x 2x 2x 2x 2x 368x             368x 2x 2x 2x 2x 2x 368x 368x 368x 368x 368x 368x 368x 368x 126x 126x 126x 10588x 10588x 287x 82x 82x 205x 205x 287x 534x 534x 474x 474x 60x 60x 60x 60x 534x 17x 16x 16x 17x 1x 1x 534x 43x 43x 59x 59x 59x 59x 534x 534x 8x 8x 59x 59x 59x 59x 59x 59x 59x 534x 33x 33x 33x 33x 59x 534x 100x 13x 10x 10x 10x 13x 100x 18x 18x 18x 18x 87x 12x 12x 1x 1x 69x 6x 6x 100x 40x 40x 128x 26x 10x 10x 10x 26x 128x 21x 21x 21x 102x 1x 1x 81x 40x 3x 3x 3x 40x 18x 18x 40x 128x 128x 40x 100x 57x 534x 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 57x 534x 15x 15x 15x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 146x 146x 146x 10588x 10588x 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 10588x 10588x 5x 5x 5x 5x 5x 10588x 10588x 137x 137x     137x 137x 137x 137x 71x 71x 66x 66x 137x     66x 66x 137x 278x 278x 278x 278x 47x 47x 47x 278x 137x 19x 19x 47x 137x 2x 137x 45x 45x 137x 10588x 10588x 84x 84x 9x 9x 75x 84x 11x 11x     11x 11x 11x 11x 1x 11x 10x 10x     10x 10x   10x     10x 10x 10x 11x 11x 11x 11x 11x 11x 11x 11x 11x 64x 64x 64x 10588x 10588x 135x 135x 135x 61x 61x     61x 61x 61x 61x     61x 61x 61x 4x 61x 5x 57x 1x 1x 51x 51x 61x 61x 61x 3x 3x 61x     51x 51x 51x 51x 51x 51x 51x 51x 51x 84x 84x 84x 10588x 10588x 184x 82x 82x 102x 184x 195x 176x 176x 19x 19x 195x     19x 19x 19x 195x 3x 3x 3x 2x 2x 3x 1x 1x 195x 16x 16x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 84x 84x 84x 10588x 10588x 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 10588x 10588x 198x 82x 82x 116x 198x 288x 274x 274x 14x 288x     14x 288x 288x     14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 102x 102x 102x 10588x 10588x 10588x 201x 82x 82x 119x 201x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 116x 116x 116x 10588x 10588x 310x 310x         310x 310x 310x 2x 2x 2x 2x 310x 310x 350x 350x 350x 350x 310x 310x 350x 310x 10588x 10588x 10588x 490x 490x 35x 35x 455x 490x 145x 6x 6x 145x 449x 449x 449x 10588x 10588x 74x 74x 74x 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 10588x 10588x 11x 11x 11x 11x 11x     10588x 10588x 47x 5x 5x 42x 47x 21x 21x 19x 19x 2x 2x 21x       2x 2x 2x 21x 3x 3x 1x 1x 1x 3x 2x 2x 2x 21x 1x 1x 1x 1x 2x 2x 40x 40x 40x 10588x 10588x 48x 48x 48x   48x 48x     48x 48x 48x                     10588x 10588x 48x 48x 48x 48x 48x 22x 22x 3x 3x 22x 48x 45x 45x 3x 48x 4x 2x 2x 2x 4x 1x 1x 1x 1x     1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 4x 2x 2x 2x 10588x 10588x 58x 58x 58x 277x 257x 257x 20x 277x 10x 10x 10x 10x     10x 10x 10x 57x 20x 57x 9x 37x 1x 1x 37x 37x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 3x 3x 3x     3x 10x 10x 10x 10x 10x 10x 10x 10x 277x 48x 48x 48x 10588x 10588x 3x 3x 3x 4x 4x 3x 3x 4x 1x       10588x 10588x 73x 5x 5x 68x 68x 68x 68x 68x 68x 73x 11x 11x 11x 11x 11x 11x 11x 9x 9x 9x 9x 9x 11x 68x 73x 59x 59x 53x 53x 6x 6x 59x     6x 6x 6x 6x 6x 6x 6x 6x 59x 1x 1x 59x 5x 5x 5x 5x 59x 15x 15x 15x 73x     73x 10588x 10588x 15x 15x 15x 15x 15x 1x 15x 14x 14x 3x 3x 3x 3x 3x 9x 9x 9x 3x 3x 9x 3x 3x     3x 3x 3x 3x             3x 14x 15x 15x 15x 15x 15x 10588x 10588x 3x 3x 4x 4x 3x 3x 1x 1x 1x 4x     4x 3x 10588x 10588x  
/* eslint-disable max-len */
import * as Statements from "../abap/2_statements/statements";
import * as Expressions from "../abap/2_statements/expressions";
import * as Structures from "../abap/3_structures/structures";
import {BasicRuleConfig} from "./_basic_rule_config";
import {Issue} from "../issue";
import {IRule, IRuleMetadata, RuleTag} from "./_irule";
import {Unknown} from "../abap/2_statements/statements/_statement";
import {ExpressionNode, StatementNode, TokenNode} from "../abap/nodes";
import {IEdit, EditHelper} from "../edit_helper";
import {Position} from "../position";
import {VirtualPosition} from "../virtual_position";
import {ABAPFile} from "../abap/abap_file";
import {IRegistry} from "../_iregistry";
import {IObject} from "../objects/_iobject";
import {ABAPObject} from "../objects/_abap_object";
import {Version} from "../version";
import {Registry} from "../registry";
import {SyntaxLogic} from "../abap/5_syntax/syntax";
import {ISpaghettiScopeNode, ISyntaxResult} from "../abap/5_syntax/_spaghetti_scope";
import {ReferenceType} from "../abap/5_syntax/_reference";
import {IClassDefinition} from "../abap/types/_class_definition";
import {TypedIdentifier} from "../abap/types/_typed_identifier";
import {AnyType, ObjectReferenceType, StructureType, TableType, VoidType} from "../abap/types/basic";
import {Config} from "../config";
import {AbstractToken} from "../abap/1_lexer/tokens/abstract_token";
import {At, ParenLeftW, WAt, WParenLeftW, WParenRight, WParenRightW} from "../abap/1_lexer/tokens";
import {IncludeGraph} from "../utils/include_graph";
import {Program} from "../objects";
import {BuiltIn} from "../abap/5_syntax/_builtin";
import {ScopeType} from "../abap/5_syntax/_scope_type";
import {ElseIf} from "../abap/2_statements/statements";
import * as crypto from "crypto";
 
// 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
* 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 version = this.lowReg.getConfig().getVersion();
    if (version === Version.v702 || version === Version.OpenABAP) {
      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 version = this.lowReg.getConfig().getVersion();
    if (version !== Version.v702 && version !== Version.OpenABAP) {
      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;
      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);
            }
 
          } 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);
          }
        }
      }
 
    }
 
    return ret;
  }
 
////////////////////
 
  /** 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.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.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.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.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.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);
    if (found) {
      return found;
    }
 
    found = this.outlineDataSimple(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.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.downportMessage(high, lowFile, highSyntax);
    if (found) {
      return found;
    }
 
    found = this.downportReadTable(high, lowFile, highSyntax);
    if (found) {
      return found;
    }
 
    return undefined;
  }
 
//////////////////////////////////////////
 
  /** removes @'s */
  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)) {
      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();
    for (const c of candidates.reverse()) {
      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);
          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], 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;
  }
 
  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;
    }
 
    const code = fields.getLastChild()?.concatTokens();
    if (code === undefined) {
      return undefined;
    }
 
    const fix1 = EditHelper.deleteRange(lowFile, fields.getFirstToken().getStart(), fields.getLastToken().getEnd());
    const fix2 = EditHelper.insertAt(lowFile, high.getFirstToken().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 fieldList = high.findFirstExpression(Expressions.SQLFieldList);
    if (fieldList === undefined) {
      return undefined;
    }
    let fieldDefinitions = "";
    for (const f of fieldList.findAllExpressions(Expressions.SQLFieldName)) {
      let fieldName = f.concatTokens();
      if (fieldName.includes("~")) {
        const split = fieldName.split("~");
        tableName = split[0];
        fieldName = split[1];
      }
      fieldDefinitions += indentation + "        " + fieldName + " TYPE " + tableName + "-" + fieldName + ",\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 minght 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 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);
 
      const uniqueName = this.uniqueName(high.getFirstToken().getStart(), lowFile.getFilename(), highSyntax);
      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
      const fix1 = EditHelper.insertAt(lowFile, firstToken.getStart(), `DATA ${uniqueName} LIKE LINE OF ${pre}.
${indentation}DATA ${tabixBackup} LIKE sy-tabix.
${indentation}${tabixBackup} = sy-tabix.
${indentation}READ TABLE ${pre} ${condition}INTO ${uniqueName}.
${indentation}sy-tabix = ${tabixBackup}.
${indentation}IF sy-subrc <> 0.
${indentation}  RAISE EXCEPTION TYPE cx_sy_itab_line_not_found.
${indentation}ENDIF.
${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;
  }
 
  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;
  }
 
  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 (!(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);
  }
 
  private outlineGetReferenceSimple(node: StatementNode, lowFile: ABAPFile): 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 fix1 = EditHelper.insertAt(lowFile, node.getStart(), `DATA ${targetName} LIKE REF TO ${source.concatTokens()}.\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;
    }
 
    const target = node.findFirstExpression(Expressions.Target);
    if (!(target?.getFirstChild()?.get() instanceof Expressions.InlineData)) {
      return undefined;
    }
 
    let type = "";
    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 (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 = undefined;
    let number: string | undefined = 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)?.findDirectExpressions(Expressions.SimpleSource1) || [];
 
    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} EXPORTING textid = ${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 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);
    }
 
    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 === 5 && sourceRef.getFirstChild()?.concatTokens().toUpperCase() === "BASE") {
      let code = `${target.concatTokens()} = ${sourceRef.getChildren()[2].concatTokens()}.\n`;
      code += `MOVE-CORRESPONDING ${sourceRef.getChildren()[4].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 = "";
    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 = "";
    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;
    }
 
    if (!(high.get() instanceof Statements.Move)) {
      return undefined;
    }
 
    const target = high.findDirectExpression(Expressions.Target);
    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;
    }
 
    let uniqueName = this.uniqueName(high.getFirstToken().getStart(), lowFile.getFilename(), highSyntax);
    uniqueName = `<${uniqueName}>`;
 
    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}${uniqueName}`;
 
    const start = target.getFirstToken().getStart();
    const end = tableExpression.findDirectTokenByText("]")?.getEnd();
    if (end === undefined) {
      return undefined;
    }
    const fix = EditHelper.replaceRange(lowFile, start, end, code);
 
    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 = "";
    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);
  }
 
  // must be very simple string templates, like "|{ ls_line-no ALPHA = IN }|"
  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.StringTemplate)) {
      const templateTokens = child.getChildren();
      if (templateTokens.length !== 3
          || templateTokens[0].getFirstToken().getStr() !== "|{"
          || templateTokens[2].getFirstToken().getStr() !== "}|") {
        continue;
      }
 
      const templateSource = child.findDirectExpression(Expressions.StringTemplateSource);
      const formatting = templateSource?.findDirectExpression(Expressions.StringTemplateFormatting)?.concatTokens();
      let functionName = "";
      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 = templateSource?.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.SimpleSource2)) {
      return undefined;
    }
 
    // the first Source must be outlined
    const s = high.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;
    }
 
    const sourceName = node.findDirectExpression(Expressions.SimpleSource2)?.concatTokens();
    if (sourceName === undefined) {
      return undefined;
    }
 
    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";
      const code = `FIELD-SYMBOLS ${targetName} LIKE LINE OF ${sourceName}.\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 = "";
      let name = "";
 
      const switchBody = i.findDirectExpression(Expressions.SwitchBody);
      if (switchBody === undefined) {
        continue;
      }
 
      for (const l of switchBody?.findDirectExpression(Expressions.Let)?.findDirectExpressions(Expressions.InlineFieldDefinition) || []) {
        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 = "";
      let name = "";
 
      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)) {
        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;
      }
 
      const abap = `DATA ${uniqueName} ${type}.\n` +
        indentation + `CLEAR ${uniqueName}.\n` + // might be called inside a loop
        indentation + `MOVE-CORRESPONDING ${correspondingBody?.concatTokens()} TO ${uniqueName}.\n` +
        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?.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`;
      }
 
      for (const a of valueBody?.getChildren() || []) {
        if (a.get() instanceof Expressions.FieldAssignment) {
          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;
          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 = "";
        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;
  }
 
  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);
  }
 
  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) {
        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 = "";
      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;
  }
 
  private outlineData(node: StatementNode, lowFile: ABAPFile, highSyntax: ISyntaxResult): Issue | undefined {
    // hmm, no guard here, as DATA(SDF) is valid in 702
 
    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 type = this.findType(i, lowFile, highSyntax);
      const indent = " ".repeat(high.getFirstToken().getStart().getCol() - 1);
 
      const abap = `DATA ${uniqueName} TYPE ${type}.\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;
  }
 
  // "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;
  }
 
  private uniqueName(position: Position, filename: string, highSyntax: ISyntaxResult): string {
    const spag = highSyntax.spaghetti.lookupPosition(position, filename);
    if (spag === undefined) {
      const name = "temprr" + this.counter;
      this.counter++;
      return 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 = "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;
  }
 
  private replaceXsdBool(node: StatementNode, lowFile: ABAPFile, highSyntax: ISyntaxResult): Issue | 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 &&
              new 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} LIKE REF TO ${sourceName}.\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 {
    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";
 
        const code = `DATA ${uniqueName} LIKE sy-subrc.\n` +
          indentation + `READ TABLE ${tableName} ${condition}TRANSPORTING NO FIELDS.\n` +
          indentation + uniqueName + ` = ${sy}.\n` +
          indentation ;
        let insertAt: Position | undefined = node.getFirstToken().getStart();
        if (node.get() instanceof ElseIf) {
          // assumption: no side effects in IF conditions
          insertAt = this.findStartOfIf(node, highFile);
          if (insertAt === undefined) {
            continue;
          }
        }
        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;
  }
 
  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.newParameters(found, target.concatTokens(), highSyntax, lowFile);
        if (abap !== undefined) {
          fix = EditHelper.replaceRange(lowFile, high.getFirstToken().getStart(), high.getLastToken().getEnd(), abap);
        }
      }
    }
 
    if (fix === undefined && high.findAllExpressions(Expressions.NewObject)) {
      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;
    }
  }
 
  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 | 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;
          }
        }
 
        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;
      }
    }
  }
 
}