1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475
|
#!/usr/bin/tclsh
# Part of MCU 8051 IDE ( http://https://sourceforge.net/projects/mcu8051ide/ )
############################################################################
# Copyright (C) 2007, 2008, 2009, 2010, 2011, 2012 by Martin Ošmera #
# martin.osmera@gmail.com #
# #
# Copyright (C) 2014 by Moravia Microsystems, s.r.o. #
# martin.osmera@gmail.com #
# #
# This program is free software; you can redistribute it and#or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation; either version 2 of the License, or #
# (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program; if not, write to the #
# Free Software Foundation, Inc., #
# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #
############################################################################
# >>> File inclusion guard
if { ! [ info exists _PREPROCESSOR_TCL ] } {
set _PREPROCESSOR_TCL _
# <<< File inclusion guard
# --------------------------------------------------------------------------
# DESCRIPTION
# 8051 Assembly language compiler preprocessor. This code is part of Compiler
# (see compiler.tcl). This NS generates precompiled code for assembler
# (see assembler.tcl).
#
# Requires:
# - CompilerConsts (compilerconsts.tcl)
# - CodeListing (codelisting.tcl)
# - NumSystem (Math.tcl)
#
# Basic principle of operation:
# 1) Remove comments and include files
# 2) Process control sequences ($SOMETHING)
# 3) Define as much constants/variables as possible (with cross references)
# 4) Conditional compilation and directive USING
# 5) Define macro instructions
# 6) Recomposite code according to ORG directives
# 7) Expand macro instructions (recursive with cross references)
# 8) Final stage
#
# Summary:
# As you can see it is not just antother two pass assembler. This one
# is much more sophisticated an much much slower than almost any other
# 8051 assembler. This assembler should be backward compatible with
# MetaLink® ASM51 and ASEM-51 by W.W. Heinz.
# --------------------------------------------------------------------------
namespace eval PreProcessor {
## General
variable asm {} ;# Resulting pre-compiled code
variable tmp_asm {} ;# Temporary auxiliary pre-compiled code
variable lineNum 0 ;# Number of the current line
variable fileNum 0 ;# Number of the current file
variable program_memory ;# String of booleans: Map of program memory usage
variable idx 0 ;# Current position in asm list
variable optims 0 ;# Number of performed optimizations
variable macros_first 1 ;# Bool: Define and expand macro instruction before conditional
;#+ assembly and constants expansions
## Errors and warnings
variable ErrorAtLine 0 ;# Bool: Error occurred on the current line
variable Error 0 ;# Bool: An error occurred during precompilation
variable error_count 0 ;# Number of errors occurred
variable warning_count 0 ;# Number of warnings occurred
## Conditional compilation
variable Enable 1 ;# Bool: Compilation enabled (conditional compilation)
variable IfElse_map ;# Array: Conditional compilation map ($IfElse_map($level) == $bool)
variable IfElse_pcam ;# Array: Conditional compilation -- Positive condition already met ($IfElse_pcam($level) == $bool)
variable IfElse_level 0 ;# Current level of conditional compilation evaluation
## Memory reservation
variable selected_segment ;# Current memory segment (one of {cseg bseg dseg iseg xseg})
variable memory_reservation_map ;# Array: memory reservation map (see code)
variable segment_pointer ;# Current memory segment pointer
## Contants/Variables definitions
variable const_BIT ;# Array: Bit values -- ($const_BIT($bit_name) == $value)
variable const_CODE ;# Array: Constants defined by directive 'CODE'
variable const_DATA ;# Array: Constants defined by directive 'DATA'
variable const_IDATA ;# Array: Constants defined by directive 'IDATA'
variable const_XDATA ;# Array: Constants defined by directive 'XDATA'
variable const_SET ;# Array: Constants defined by directive 'CODE'
variable const_EQU ;# Array: Constants defined by directive 'EQU'
variable const_SET_SPEC ;# Array: Special constants defined by directive 'CODE'
variable const_EQU_SPEC ;# Array: Special constants defined by directive 'EQU'
variable labels ;# Array: Values of defined labels ($labels($label) == $address)
variable defined_BIT {} ;# List of defined bits (directove 'BIT')
variable defined_CODE {} ;# List of constants defined by 'CODE'
variable defined_DATA {} ;# List of constants defined by 'DATA'
variable defined_IDATA {} ;# List of constants defined by 'IDATA'
variable defined_XDATA {} ;# List of constants defined by 'XDATA'
variable defined_SET {} ;# List of variables defined by 'SET'
variable defined_EQU {} ;# List of constants defined by 'EQU'
variable defined_SET_SPEC {} ;# List of special variables defined by 'SET'
variable defined_EQU_SPEC {} ;# List of special constants defined by 'EQU'
variable defined_LABEL {} ;# List of defined labels
# List of lists containing names of defined constants
variable const_definitions {
defined_BIT defined_CODE
defined_DATA defined_IDATA
defined_XDATA defined_SET
defined_EQU defined_SET_SPEC
defined_EQU_SPEC
}
## Macro expansion
variable macro ;# Array: Code of defined macro instructions
variable defined_MACRO {} ;# List of defined macro instructions
variable local_M_labels ;# Array of lists: Local labels in macros $local_M_labels($macro_name) == {integer label0 ... labelN}
variable macro_name_to_append ;# Name of currently defined macro instruction
## Special variables
variable original_expression ;# Auxiliary variable (see proc. 'ComputeExpr')
variable tmp ;# General purpose tempotary variable
variable DB_asm {} ;# Temporary asm code for creating code memory tables
variable included_files {} ;# List: Unique unsorted list of included files
variable working_dir {} ;# String: Current working directory
variable origin_d_addr {} ;# List: Addresses of static program blocks
## Configuration variables
variable max_include_level 8 ;# Maximum inclusion level
variable max_macro_level 8 ;# Maximum macro expansion level
variable check_sfr_usage 0 ;# Bool: Check for legal usage of SFR and SFB
variable available_SFR {} ;# List: Available SFR and SFB on the target MCU
# ----------------------------------------------------------------
# GENERAL PURPOSE PROCEDURES
# ----------------------------------------------------------------
## Initialize preprocessor
# @parm String current_dir - Directory containing source file
# @parm String filename - Name of file containing source code
# @parm String data - Source code to compile
# @return List - precompiled source code
proc compile {current_dir filename data} {
variable macros_first 1 ;# Bool: Define and expand macro instruction before conditional
;#+ assembly and constants expansions
variable memory_reservation_map ;# Array: memory reservation map (see code)
variable working_dir ;# String: Current working directory
variable asm ;# Resulting pre-compiled code
variable segment_pointer ;# Current memory segment pointer
variable error_count ;# Number of errors occurred
variable warning_count ;# Number of warnings occurred
variable max_include_level ;# Maximum inclusion level
variable max_macro_level ;# Maximum macro expansion level
variable optims ;# Number of performed optimizations
variable included_files ;# List: Unique unsorted list of included files
variable selected_segment ;# Current memory segment (one of {cseg bseg dseg iseg xseg})
variable const_EQU ;# Array: Constants defined by directive 'EQU'
variable defined_EQU ;# List of constants defined by 'EQU'
# Reset memory segment pointers
set segment_pointer(bseg) 0
set segment_pointer(dseg) 0
set segment_pointer(iseg) 0
set segment_pointer(xseg) 0
set selected_segment cseg
# Reset maps of memory reservation
set memory_reservation_map(bseg) [ string repeat 0 256 ]
set memory_reservation_map(iseg) [ string repeat 0 256 ]
set memory_reservation_map(dseg) [ string repeat 0 256 ]
set memory_reservation_map(xseg) [ string repeat 0 65536]
# Set constants "??MCU_8051_IDE" and "??VERSION"
lappend defined_EQU {??mcu_8051_ide} {??version}
set const_EQU(??mcu_8051_ide) 32849 ;# 8051h
scan $::VERSION "%d.%d.%d" i j k
set i [expr {($i << 8) + ($j << 4) + $k}]
set const_EQU(??version) $i
# Reset counters of errors and warnings
set error_count 0
set warning_count 0
# Incialize list of included files
set working_dir $current_dir
set included_files [list [file normalize [file join $current_dir $filename]]]
set asm $data
if {${::Compiler::Settings::ABORT_VARIABLE}} {
${::Compiler::Settings::TEXT_OUPUT_COMMAND} [mc "Aborted"]
free_resources
return
}
## Convert code to this format:
# {
# {{lineNumber} {fileNumber} {line of code}}
# ...
# }
line_numbers
if {${::Compiler::Settings::ABORT_VARIABLE}} {
${::Compiler::Settings::TEXT_OUPUT_COMMAND} [mc "Aborted"]
free_resources
return
}
# Import code pieces (INCLUDE file.asm // $INCLUDE('file.inc'))
set counter 0
while {1} {
if {![include_directive $current_dir]} {break}
incr counter
if {$counter > $max_include_level} {
CompilationError "unknown" {} [mc "Inclusion nesting exceeded maximum allowed level"]
break
}
}
# Remove code after END directive
end_of_code
if {${::Compiler::Settings::ABORT_VARIABLE}} {
${::Compiler::Settings::TEXT_OUPUT_COMMAND} [mc "Aborted"]
free_resources
return
}
# Remove comments and redutant white space
trim_code
if {${::Compiler::Settings::ABORT_VARIABLE}} {
${::Compiler::Settings::TEXT_OUPUT_COMMAND} [mc "Aborted"]
free_resources
return
}
## Parse controls like $TITLE('bla...bla') or $DATE(36/13/1907)
parse_controls
if {${::Compiler::Settings::ABORT_VARIABLE}} {
${::Compiler::Settings::TEXT_OUPUT_COMMAND} [mc "Aborted"]
free_resources
return
}
# Discard code listing if listing os not required
if {!${::Compiler::Settings::PRINT}} {
CodeListing::free_resources
}
# Define basic symbolc names (eg. P0)
if {!${::Compiler::Settings::NOMOD}} {
define_basic_symbolic_names
}
if {$macros_first} {
# Define macro instructions
define_macro_instructions
if {${::Compiler::Settings::ABORT_VARIABLE}} {
${::Compiler::Settings::TEXT_OUPUT_COMMAND} [mc "Aborted"]
free_resources
return
}
# Expand macro instructions
set counter 0
while {1} {
if {![expand_macro_instructions]} {break}
incr counter
if {$counter > $max_macro_level} {
CompilationError "unknown" {} [mc "Macro nesting exceeded maximum allowed level"]
break
}
}
if {${::Compiler::Settings::ABORT_VARIABLE}} {
${::Compiler::Settings::TEXT_OUPUT_COMMAND} [mc "Aborted"]
free_resources
return
}
}
## Parse these directives:
# - Donditional compilation (IF, ELSE, ENDIF) (group 0)
# - Code listing enable/disable (LIST, NOLIST) (group 1)
# - Active bank selection (USING) (group 2)
# - Data memory segment selection (BSEG, DSEG, ISEG, XSEG) (group 3)
# - Constant definitions (SET, EQU, BIT, DATA, IDATA, XDATA) (group 4)
# - Date memory reservation (DS, DBIT) (group 5)
while {1} {
if {![parse_Consts_and_ConditionalCompilation {0 0 1 1 1 1} 1]} {
break
}
}
parse_Consts_and_ConditionalCompilation {1 1 1 1 1 1} 1
if {${::Compiler::Settings::ABORT_VARIABLE}} {
${::Compiler::Settings::TEXT_OUPUT_COMMAND} [mc "Aborted"]
free_resources
return
}
# Process code memory related directives (CSEG DB DW)
code_segment 1
if {${::Compiler::Settings::ABORT_VARIABLE}} {
${::Compiler::Settings::TEXT_OUPUT_COMMAND} [mc "Aborted"]
free_resources
return
}
if {!$macros_first} {
# Define macro instructions
define_macro_instructions
if {${::Compiler::Settings::ABORT_VARIABLE}} {
${::Compiler::Settings::TEXT_OUPUT_COMMAND} [mc "Aborted"]
free_resources
return
}
}
# Reassemble code according to ORG directives
origin_directive
if {${::Compiler::Settings::ABORT_VARIABLE}} {
${::Compiler::Settings::TEXT_OUPUT_COMMAND} [mc "Aborted"]
free_resources
return
}
if {!$macros_first} {
# Expand macro instructions
set counter 0
while {1} {
if {![expand_macro_instructions]} {break}
incr counter
if {$counter > $max_macro_level} {
CompilationError "unknown" {} [mc "Macro nesting exceeded maximum allowed level"]
break
}
}
if {${::Compiler::Settings::ABORT_VARIABLE}} {
${::Compiler::Settings::TEXT_OUPUT_COMMAND} [mc "Aborted"]
free_resources
return
}
}
## Do three things:
# * Convert code to this format:
# {
# {
# {lineNumber} {fileNumber} {instructionAddress} {instructionLength} {instruction}
# {oprerand0 operand1 ...} {operand0_type ...}
# } ...
# }
# * Parse labels definition
# * Create map of program memory usage (bitmap)
parse_instructions
# Perform code optimizations
set optims 0
if {${::Compiler::Settings::optim_ena}} {
optimization
}
# Final constants expansion
while {1} {
if {![parse_Consts_and_ConditionalCompilation {0 0 1 1 1 1} 0]} {
break
}
}
# Import table of symbols to current code listing
CodeListing::import_symbolic_names
if {${::Compiler::Settings::ABORT_VARIABLE}} {
${::Compiler::Settings::TEXT_OUPUT_COMMAND} [mc "Aborted"]
free_resources
return
}
## Final stage -- finaly encapsulate code to the resulting form:
# {
# {
# {lineNumber} {fileNumber} {instructionAddress} {instruction}
# {oprerand0 operand1 ...} {operand0_type ...}
# } ...
# }
final_stage
# Free reserved resources
free_resources
# Return precompiled code
return $asm
}
## Free reserved resources
# @return void
proc free_resources {} {
variable memory_reservation_map ;# Array: memory reservation map (see code)
variable segment_pointer ;# Current memory segment pointer
variable const_BIT ;# Array: Bit values -- ($const_BIT($bit_name) == $value)
variable const_CODE ;# Array: Constants defined by directive 'CODE'
variable const_DATA ;# Array: Constants defined by directive 'DATA'
variable const_IDATA ;# Array: Constants defined by directive 'IDATA'
variable const_XDATA ;# Array: Constants defined by directive 'XDATA'
variable const_SET ;# Array: Constants defined by directive 'CODE'
variable const_EQU ;# Array: Constants defined by directive 'EQU'
variable macro ;# Array: Code of defined macro instructions
variable local_M_labels ;# Array of lists: Local labels in macros $local_M_labels($macro_name) == {integer label0 ... labelN}
variable program_memory ;# String of booleans: Map of program memory usage
variable labels ;# Array: Values of defined labels ($labels($label) == $address)
variable defined_BIT {} ;# List of defined bits (directove 'BIT')
variable defined_CODE {} ;# List of constants defined by 'CODE'
variable defined_DATA {} ;# List of constants defined by 'DATA'
variable defined_IDATA {} ;# List of constants defined by 'IDATA'
variable defined_XDATA {} ;# List of constants defined by 'XDATA'
variable defined_SET {} ;# List of variables defined by 'SET'
variable defined_EQU {} ;# List of constants defined by 'EQU'
variable defined_SET_SPEC {} ;# List of variables defined by 'SET'
variable defined_EQU_SPEC {} ;# List of constants defined by 'EQU'
variable defined_LABEL {} ;# List of defined labels
variable defined_MACRO {} ;# List of defined macro instructions
catch {unset macro}
catch {unset local_M_labels}
catch {unset memory_reservation_map}
catch {unset segment_pointer}
catch {unset const_BIT}
catch {unset const_CODE}
catch {unset const_DATA}
catch {unset const_IDATA}
catch {unset const_XDATA}
catch {unset const_SET}
catch {unset const_EQU}
catch {unset const_SET_SPEC}
catch {unset const_EQU_SPEC}
catch {unset program_memory}
catch {unset labels}
}
# ----------------------------------------------------------------
# INTERNAL AUXILIARY PROCEDURES
# ----------------------------------------------------------------
## Define basic symbolic names according to MapOfSFRArea, MapOfSFRBitArea and progVectors
# @return void
proc define_basic_symbolic_names {} {
variable const_BIT ;# Array: Bit values -- ($const_BIT($bit_name) == $value)
variable const_DATA ;# Array: Constants defined by directive 'DATA'
variable const_CODE ;# Array: Constants defined by directive 'CODE'
variable defined_BIT ;# List of defined bits (directove 'BIT')
variable defined_DATA ;# List of constants defined by 'DATA'
variable defined_CODE ;# List of constants defined by 'CODE'
# Define bits
foreach def ${::CompilerConsts::MapOfSFRBitArea} {
set var [lindex $def 0] ;# Name
set val [lindex $def 1] ;# Address
# Adjust name
set var [string tolower $var]
# Define
lappend defined_BIT $var
set const_BIT($var) [expr "0x$val"]
}
# Define registers
foreach def ${::CompilerConsts::MapOfSFRArea} {
set var [lindex $def 0] ;# Name
set val [lindex $def 1] ;# Address
# Adjust name
set var [string tolower $var]
# Define
lappend defined_DATA $var
set const_DATA($var) [expr "0x$val"]
}
# Define Program vectors
foreach def ${::CompilerConsts::progVectors} {
set var [lindex $def 0] ;# Name
set val [lindex $def 1] ;# Address
# Adjust name
set var [string tolower $var]
# Define
lappend defined_CODE $var
set const_CODE($var) [expr "0x$val"]
}
}
## Split the given cotrol sequence into its name and argument (without parentheses and quotes)
# @parm String data - line of source code to evaluate
# @return List - {control argument}
proc evaluateControl {data} {
variable lineNum ;# Number of the current line
variable fileNum ;# Number of the current file
# Make backup for input data
set original_data $data
# Determinate control name
set data [string range $data 1 end]
if {[regexp {^\w+} $data control]} {
regsub {^\w+} $data {} data
set control [string tolower $control]
} else {
set control {}
}
# Control without argument
if {$data == {}} {
return [list $control {}]
}
# Determinate argument
if {[regexp {^\(.*\)} $data argument]} {
# Remove parentheses
regsub {^\(.*\)} $data {} data
set argument [string trimleft $argument {(}]
set argument [string trimright $argument {)}]
# Remove quotes
if {[string index $argument 0] == {'}} {
if {[string index $argument end] != {'}} {
SyntaxError $lineNum $fileNum [mc "Invalid argument: %s" $argument]
} else {
set argument [string trimleft $argument {'}]
set argument [string trimright $argument {'}]
}
}
} else {
set argument {}
}
# Line cannot contain anything except CS
if {$data != {}} {
SyntaxError $lineNum $fileNum [mc "Extra characters after control sequence: %s" $original_data]
}
# Return result
return [list $control $argument]
}
## Adjust compiler settings to the specified control sequence
# @parm String condition - Condition variable (if 1 then dismiss)
# @parm String setting - Target configuration variable
# @parm String value - New configuration value
# @return Bool - One if setting was accepted, zero if setting was dismissed
proc AssemblerContol {condition setting value} {
variable lineNum ;# Number of the current line
variable fileNum ;# Number of the current file
# Determinate condition value
set condition [subst -nocommands "\${::Compiler::Settings::$condition}"]
# Accept
if {$condition == 0} {
set Compiler::Settings::$setting $value
return 1
# Dismiss
} else {
Notice $lineNum $fileNum [mc "Control %s has been overridden (by compiler settings)" $setting]
return 0
}
}
## Invoke error message if the given control sequence has no argument
# @parm String control - Control sequence (name only)
# @parm String argument - Argument (without parantesis and quotes)
# @return Bool - result (1 == success; 0 == error message)
proc AssemblerContol_expect_one_argument {control argument} {
variable lineNum ;# Number of the current line
variable fileNum ;# Number of the current file
if {$argument == {}} {
SyntaxError $lineNum $fileNum \
[mc "Control `%s' expect exactly one argument, but no argument given" "\$[string toupper $control]"]
return 0
}
return 1
}
## Invoke error message if the given control sequence has an argument
# @parm String control - Control sequence (name only)
# @parm String argument - Argument (without parantesis and quotes)
# @return Bool - result (1 == success; 0 == error message)
proc AssemblerContol_expect_no_argument {control argument} {
variable lineNum ;# Number of the current line
variable fileNum ;# Number of the current file
if {$argument != {}} {
SyntaxError $lineNum $fileNum [mc "Control `%s' takes no arguments." "\$[string toupper $control]"]
return 0
}
return 1
}
## Evaluate and remove control sequences
# @return void
proc parse_controls {} {
variable asm ;# Resulting pre-compiled code
variable tmp_asm ;# Temporary auxiliary pre-compiled code
variable lineNum ;# Number of the current line
variable fileNum ;# Number of the current file
variable idx ;# Current position in asm list
variable macros_first 1 ;# Bool: Define and expand macro instruction before conditional
;#+ assembly and constants expansions
# Reset NS variables
set tmp_asm {}
set idx -1
# Iterate over the code
foreach line $asm {
incr idx
# Update after each 25 iterations
if {[expr {$idx % 25}] == 0} {
${::Compiler::Settings::UPDATE_COMMAND}
}
if {${::Compiler::Settings::ABORT_VARIABLE}} {
${::Compiler::Settings::TEXT_OUPUT_COMMAND} [mc "Aborted"]
free_resources
return
}
# Determinate line number and line content
set lineNum [lindex $line 0]
set fileNum [lindex $line 1]
set line [lindex $line 2]
# Skip lines without a control sequence
if {[string index $line 0] != "\$"} {
lappend tmp_asm [list $lineNum $fileNum $line]
continue
}
# Remove this line from sync. map in code listing
CodeListing::delete_line $idx
incr idx -1
# Get and anylize control sequence
set ctrl [evaluateControl $line]
set control [lindex $ctrl 0] ;# Name
set argument [lindex $ctrl 1] ;# Argument
# Adjust compiler settings according to the control sequence
switch -- $control {
{nomacrosfirst} {
if {[AssemblerContol_expect_no_argument $control $argument]} {
set macros_first 0
}
}
{eject} {
if {[AssemblerContol_expect_no_argument $control $argument]} {
CodeListing::directive_eject $idx
}
}
{ej} {
if {[AssemblerContol_expect_no_argument $control $argument]} {
CodeListing::directive_eject $idx
}
}
{nolist} {
if {[AssemblerContol_expect_no_argument $control $argument]} {
CodeListing::directive_nolist $idx
}
}
{noli} {
if {[AssemblerContol_expect_no_argument $control $argument]} {
CodeListing::directive_nolist $idx
}
}
{list} {
if {[AssemblerContol_expect_no_argument $control $argument]} {
CodeListing::directive_list $idx
}
}
{li} {
if {[AssemblerContol_expect_no_argument $control $argument]} {
CodeListing::directive_list $idx
}
}
{nomod} {
if {[AssemblerContol_expect_no_argument $control $argument]} {
AssemblerContol _nomod NOMOD 1
}
}
{nomod51} {
if {[AssemblerContol_expect_no_argument $control $argument]} {
AssemblerContol _nomod NOMOD 1
}
}
{nomo} {
if {[AssemblerContol_expect_no_argument $control $argument]} {
AssemblerContol _nomod NOMOD 1
}
}
{paging} {
if {[AssemblerContol_expect_no_argument $control $argument]} {
AssemblerContol _paging PAGING 1
}
}
{pi} {
if {[AssemblerContol_expect_no_argument $control $argument]} {
AssemblerContol _paging PAGING 1
}
}
{nopaging} {
if {[AssemblerContol_expect_no_argument $control $argument]} {
AssemblerContol _paging PAGING 0
}
}
{nopi} {
if {[AssemblerContol_expect_no_argument $control $argument]} {
AssemblerContol _paging PAGING 0
}
}
{pagewidth} {
if {[AssemblerContol_expect_one_argument $control $argument]} {
if {[regexp {^\d+$} $argument]} {
AssemblerContol _pagewidth PAGEWIDTH $argument
} else {
SyntaxError $lineNum $fileNum \
[mc "Invalid argument (must be integer): %s" $argument]
}
}
}
{pw} {
if {[AssemblerContol_expect_one_argument $control $argument]} {
if {[regexp {^\d+$} $argument]} {
AssemblerContol _pagewidth PAGEWIDTH $argument
} else {
SyntaxError $lineNum $fileNum \
[mc "Invalid argument (must be integer): %s" $argument]
}
}
}
{pagelength} {
if {[AssemblerContol_expect_one_argument $control $argument]} {
if {[regexp {^\d+$} $argument]} {
AssemblerContol _pagelength PAGELENGTH $argument
} else {
SyntaxError $lineNum $fileNum \
[mc "Invalid argument (must be integer): %s" $argument]
}
}
}
{pl} {
if {[AssemblerContol_expect_one_argument $control $argument]} {
if {[regexp {^\d+$} $argument]} {
AssemblerContol _pagelength PAGELENGTH $argument
} else {
SyntaxError $lineNum $fileNum \
[mc "Invalid argument (must be integer): %s" $argument]
}
}
}
{title} {
if {[AssemblerContol_expect_one_argument $control $argument]} {
AssemblerContol _title TITLE $argument
}
}
{tt} {
if {[AssemblerContol_expect_one_argument $control $argument]} {
AssemblerContol _title TITLE $argument
}
}
{date} {
if {[AssemblerContol_expect_one_argument $control $argument]} {
AssemblerContol _date DATE $argument
}
}
{da} {
if {[AssemblerContol_expect_one_argument $control $argument]} {
AssemblerContol _date DATE $argument
}
}
{object} {
if {[AssemblerContol_expect_one_argument $control $argument]} {
AssemblerContol _object OBJECT_FILE $argument
AssemblerContol _object OBJECT 1
}
}
{noobject} {
if {[AssemblerContol_expect_no_argument $control $argument]} {
AssemblerContol _object OBJECT 0
}
}
{nosb} {
if {[AssemblerContol_expect_no_argument $control $argument]} {
AssemblerContol _symbols SYMBOLS 0
}
}
{nosymbols} {
if {[AssemblerContol_expect_no_argument $control $argument]} {
AssemblerContol _symbols SYMBOLS 0
}
}
{noprint} {
if {[AssemblerContol_expect_no_argument $control $argument]} {
AssemblerContol _print PRINT 0
}
}
{symbols} {
if {[AssemblerContol_expect_no_argument $control $argument]} {
AssemblerContol _symbols SYMBOLS 1
}
}
{sb} {
if {[AssemblerContol_expect_no_argument $control $argument]} {
AssemblerContol _symbols SYMBOLS 1
}
}
{print} {
if {[AssemblerContol_expect_one_argument $control $argument]} {
AssemblerContol _print PRINT_FILE $argument
AssemblerContol _print PRINT 1
}
}
default {
Warning $lineNum $fileNum [mc "Unsupported control sequence: %s -- control sequence ignored" $line]
}
}
}
# Replace old code with the new one
set asm $tmp_asm
}
## Evaluate and code memory reservation directives (CSEG DB DW)
# @parm Bool ignore_undefined - Ignore undefined symbolic names
# @return void
proc code_segment {ignore_undefined} {
variable asm ;# Resulting pre-compiled code
variable tmp_asm ;# Temporary auxiliary pre-compiled code
variable lineNum ;# Number of the current line
variable fileNum ;# Number of the current file
variable selected_segment ;# Current memory segment (one of {cseg bseg dseg iseg xseg})
variable segment_pointer ;# Current memory segment pointer
variable idx ;# Current position in asm list
# Reset NS variables
set tmp_asm {}
set segment_pointer(cseg) {}
set value {}
set idx -1
# Iterate over the code
foreach line $asm {
incr idx
# Update after each 25 iterations
if {[expr {$idx % 25}] == 0} {
${::Compiler::Settings::UPDATE_COMMAND}
}
if {${::Compiler::Settings::ABORT_VARIABLE}} {
${::Compiler::Settings::TEXT_OUPUT_COMMAND} [mc "Aborted"]
free_resources
return
}
# Anylize line
set lineNum [lindex $line 0] ;# Line number
set fileNum [lindex $line 1] ;# File number
set line [lindex $line 2] ;# Line code
set cmd [split_line $line] ;# label, command and argumet(s)
set directive [regsub {^\.} [lindex $cmd 1] {}] ;# Directive
# Directive 'DB' (byte reservation) or 'DW' (word reservation)
if {$directive == {db} || $directive == {dw} || $directive == {byte}} {
# Handle directive "BYTE", which has exactly the same meaning as the "DB"
#+ "BYTE" is borrowed from AS31 assembler
if {$directive == {byte}} {
Warning $lineNum $fileNum [mc "You are using unusual directive 'BYTE', consider usage of 'DB' instead"]
set directive {db}
}
set result [reserve_code_memory $cmd $directive $idx $ignore_undefined]
if {$result != {}} {
incr idx $result
}
# Directive 'CSEG' - code segment selection
} elseif {$directive == {cseg}} {
set discontinue 0
# Check if there is a label
if {[lindex $cmd 0] != {}} {
SyntaxError $lineNum $fileNum [mc "CSEG cannot take any label: %s" [lindex $cmd 0]]
set discontinue 1
}
if {!$discontinue} {
# Set the code segment
set selected_segment {cseg}
# Check for presence of an address expression
set expr [lindex $cmd 2]
if {$expr == {}} {
set segment_pointer(cseg) {}
set discontinue 1
}
if {!$discontinue} {
# Check for presence of 'AT' operator (CSEG AT addr)
if {[string tolower [lindex $expr 0]] != {at}} {
SyntaxError $lineNum $fileNum [mc "Missing `AT' operator"]
set discontinue 1
}
set expr [lreplace $expr 0 0]
}
}
# Remove this line from the code listing
if {$discontinue} {
CodeListing::delete_line $idx
incr idx -1
continue
}
# Determinate, set and validate segment pointer
set value [ComputeExpr $expr]
if {$value != {}} {
# Validate address
if {$value > 65535} {
SyntaxError $lineNum $fileNum [mc "Argument value out of range: %s (%s)" $expr $value]
continue
}
# Set pointer
set segment_pointer(cseg) $value
# Adjust code
lappend tmp_asm [list $lineNum $fileNum [list {ORG} $value]]
} else {
SyntaxError $lineNum $fileNum [mc "Invalid expression `%s'" $expr]
CodeListing::delete_line $idx
incr idx -1
}
# Line does not contain any of {CSEG DB DW}
} else {
lappend tmp_asm [list $lineNum $fileNum $line]
}
}
# Finalize code adjustment
append tmp_asm { }
set asm $tmp_asm
}
## Reserve code memory (byte or word) -- directives 'DB' 'DW'
# -- auxiliary procedure for proc. 'code_segment'
# This procedure writes result to NS variable 'tmp_asm'
# @parm String cmd - Line of source code adjusted by proc. 'split_line'
# @parm String directive - Directive name (one of {DB DW})
# @parm String idx - Source index (precompiled code list)
# @parm Bool ignore_undefined - Ignore undefined symbolic names
# @return Int - Byte length of occupied program memory
proc reserve_code_memory {cmd directive idx ignore_undefined} {
variable lineNum ;# Number of the current line
variable fileNum ;# Number of the current file
variable selected_segment ;# Current memory segment (one of {cseg bseg dseg iseg xseg})
variable segment_pointer ;# Current memory segment pointer
variable tmp_asm ;# Temporary auxiliary pre-compiled code
# Determinate maximum value
if {$directive == {db}} {
set directive_db 1
set max 255
} elseif {$directive == {dw}} {
set directive_db 0
set max 65535
} else {
CompilationError $lineNum $fileNum "Unknown error 7"
return
}
# Check if the currently selected memory segment is 'CSEG'
if {$selected_segment != {cseg}} {
Warning $lineNum $fileNum [mc "Using `%s', but active segment is `%s' (should be CSEG)" [string toupper $directive] [string toupper $selected_segment]]
}
# Validate directive operands
set operands [lindex $cmd 2]
if {$operands == {}} {
SyntaxError $lineNum $fileNum [mc "Missing value"]
return
}
set operands [getOperands $operands 1]
if {[llength $operands] == 0} {
SyntaxError $lineNum $fileNum [mc "Invalid value"]
return
}
# Check for allowed number of arguments
if {!$directive_db && [llength $operands] > 1} {
SyntaxError $lineNum $fileNum [mc "Directive DW can take only one argument"]
return
}
# Determinate label
set label [lindex $cmd 0]
if {$label != {}} {
append label { }
}
# Iterate over directive operands
set first_time 1
set undefined 0
set total_len 0
foreach opr $operands {
set undefined 0
set len -1
# Operand is a string
if {![isExpression $opr] && ([string index $opr 0] == {'}) && ([string index $opr end] == {'})} {
# Adjust operand
set opr [string trimleft $opr {'}]
set opr [string trimright $opr {'}]
regsub -all {''} $opr {'} opr
set opr [subst -nocommands -novariables $opr]
set opr_length [string length $opr]
# Initialize list of decimal operand values (per bytes)
set values {}
# Convert each character separately (to decimal)
set escaped 0
for {set char_idx 0} {$char_idx < $opr_length} {incr char_idx} {
set char [string index $opr $char_idx]
# Convert character
set value [character2number $char]
# Invalid value
if {$value == {}} {
CompilationError $lineNum $fileNum [mc "Unable to recognize character: `%s'" $char]
continue
# Valid value
} else {
if {$first_time} {
set line [list [list $lineNum $fileNum "${label}DB $value"]]
} else {
set line [list [list $lineNum $fileNum [list DB $value]]]
}
set first_time 0
lappend values $value
}
incr len
# Adjust precompiled code
append tmp_asm { }
append tmp_asm $line
}
# Adjust code listing
CodeListing::db $idx $values
CodeListing::insert_empty_lines $idx $len
# Operand is a direct numerical value, expression, constant, label or variable
} else {
# Evaluate operand value
set value [ComputeExpr $opr $ignore_undefined]
# Unable to compute value
if {$value == {}} {
# Value could not be determinated in this pass
if {$ignore_undefined} {
set undefined 1
set value $opr
# Invalid value
} else {
CompilationError $lineNum $fileNum [mc "Invalid expression `%s'" $opr]
continue
}
}
## Valid value
# Check for valid range
if {!$undefined && (($value > $max) || ($value < 0))} {
SyntaxError $lineNum $fileNum [mc "Argument value out of range: %s" $opr]
continue
}
# Round value
if {!$undefined} {
set value [expr {int($value)}]
}
# One byte (directive DB)
if {$directive_db} {
if {$first_time} {
set line [list [list $lineNum $fileNum "${label}DB $value"]]
} else {
set line [list [list $lineNum $fileNum [list DB $value]]]
}
incr len
set first_time 0
# Adjust code listing
CodeListing::db $idx $value
# Two bytes (directive DW)
} else {
# Spilt value into high- and low-order bytes
if {$undefined} {
set H_value "(($value) / 256)"
set L_value "(($value) % 256)"
} else {
set H_value [expr {$value / 256}]
set L_value [expr {$value % 256}]
}
if {$first_time} {
set line [list \
[list $lineNum $fileNum "${label}DB {$H_value}"]\
[list $lineNum $fileNum [list {DB} $L_value]] \
]
} else {
set line [list \
[list $lineNum $fileNum [list {DB} $H_value]] \
[list $lineNum $fileNum [list {DB} $L_value]] \
]
}
incr len 2
set first_time 0
# Adjust code listing
CodeListing::db $idx [list $H_value $L_value]
CodeListing::insert_empty_lines $idx 1
}
# Adjust precompiled code
append tmp_asm { }
append tmp_asm $line
}
incr len
incr total_len $len
}
CodeListing::insert_empty_lines $idx [expr {[llength $operands] - 1}]
incr total_len -1
return $total_len
}
## Split the given line of code into label, command and argumet(s)
# @parm String line - Line of source code
# @return List - {label command argument} or {label}
proc split_line {line} {
# Determinate label
if {[regexp {^\w+:} $line label]} {
regsub {^\w+:\s*} $line {} line
} else {
set label {}
}
# If line contains only label -> return only label
if {$line == {}} {
return $label
}
# Determinate command and argumet(s)
if {![regexp {^\s*\.?\w+} $line command]} {
set command {}
} else {
set command [string tolower [string trim $command]]
}
set argument [regsub {^[^\s]+\s*} $line {}]
# Return result
return [list $label $command $argument]
}
## Convert given list op operands to their final values (expand constants, labels and expressions)
# @parm Int address - Instruction address
# @parm Int instr_lenght - Instruction length in bytes
# @parm List operands - List of operands
# @parm List operand_types - List of operand types
# @parm String instruction - Instruction name
# @parm Bool ignore_undefined - Ignore undefined symbolic names
# @return List - resulting list of operands
proc operands_to_absolute_values {address instr_lenght operands operand_types instruction ignore_undefined} {
variable lineNum ;# Number of the current line
variable fileNum ;# Number of the current file
# Initialize list of operands
if {$instruction == {db}} {
set new_operands $operands
set operands {}
} else {
set new_operands {}
}
# Replace symbolic names with absolute values
foreach opr $operands type $operand_types {
# Fixed value (eg. 'A')
if {[isFixed $opr]} {
set char {}
set opr_val $opr
# Regular value
} else {
# Adjust value (remove 1st char is it's one of {# @ /})
set char [string index $opr 0]
if {$char == {#} || $char == {@} || $char == {/}} {
set opr [string replace $opr 0 0]
} else {
set char {}
}
set opr_val {}
# Value is an expression
if {[isExpression $opr]} {
append opr_val [ComputeExpr $opr $ignore_undefined $address]
# Value is bit addres represented by dot notation
} elseif {[regexp {^\w+\.\w+$} $opr]} {
if {$type != {bit} && $type != {/bit}} {
if {!$ignore_undefined} {
SyntaxError $lineNum $fileNum [mc "Expected bit address: %s" $opr]
}
} else {
set bitAddr [getBitAddr $opr $ignore_undefined]
if {$bitAddr == {}} {set bitAddr 0}
append opr_val $bitAddr
}
# Value is regular symbolic name
} elseif {[isSymbolicName $opr]} {
# Determinate list of substitution priorities
switch -- $type {
{code8} {set priorities {labels code equset xdata} }
{code11} {set priorities {labels code equset xdata} }
{code16} {set priorities {labels code equset xdata} }
{imm8} {set priorities {equset data idata xdata bit code labels}}
{imm16} {set priorities {equset data idata xdata bit code labels}}
{data} {set priorities {data idata equset} }
{bit} {set priorities {bit equset} }
{/bit} {set priorities {bit equset} }
default {
CompilationError $lineNum $fileNum "Unknown error 0"
}
}
# Perform substitution
append opr_val [getValueOfSymbolicName \
$opr $priorities $address \
$ignore_undefined \
]
# Direct value (some number)
} else {
append opr_val [COprToDec $opr]
}
# Adjust relative offset
if {[string is digit -strict $opr_val]} {
if {$type == {code8}} {
incr opr_val -$address
incr opr_val -$instr_lenght
if {($opr_val > 127) || ($opr_val < -128)} {
incr opr_val -0x10000
if {($opr_val > 127) || ($opr_val < -128)} {
if {!$ignore_undefined} {
SyntaxError $lineNum $fileNum \
[mc "Label is too far for 8-bit relative addressing.\nTry to disable peephole optimizations if they are on."]
}
set opr_val 0
}
}
if {$opr_val < 0} {
incr opr_val 0x100
}
} elseif {$type == {code11}} {
if {($opr_val & 0x0f800) != (($address + $instr_lenght) & 0x0f800)} {
if {!$ignore_undefined} {
SyntaxError $lineNum $fileNum [mc "Operand value out of range: `%s' (`%s')" $opr $opr_val]
}
set opr_val 0
} else {
set opr_val [expr {$opr_val & 0x007ff}]
}
}
}
}
# Adjust list of operands
lappend new_operands "${char}${opr_val}"
# Check for valid value range
if {$opr_val != {} && ![checkRange $opr_val $type]} {
if {!$ignore_undefined && [string is digit -strict $opr_val]} {
SyntaxError $lineNum $fileNum [mc "Operand value out of range: `%s' (`%s')" $opr $opr_val]
} else {
return {}
}
}
}
# Return result
return $new_operands
}
## Finaly precompiled encapsulate code to the resulting form
# @return void
proc final_stage {} {
variable asm ;# Resulting pre-compiled code
variable tmp_asm ;# Temporary auxiliary pre-compiled code
variable lineNum ;# Number of the current line
variable fileNum ;# Number of the current file
variable idx ;# Current position in asm list
# Reset NS variables
set idx -1
set tmp_asm {}
set new_operands {}
# Expand constants, variables and labels
foreach line $asm {
incr idx
# Update after each 25 iterations
if {[expr {$idx % 25}] == 0} {
${::Compiler::Settings::UPDATE_COMMAND}
}
if {${::Compiler::Settings::ABORT_VARIABLE}} {
${::Compiler::Settings::TEXT_OUPUT_COMMAND} [mc "Aborted"]
free_resources
return
}
# Split line into separate fields
set i 0
foreach var {lineNum fileNum address instr_lenght instruction operands operand_types} {
set $var [lindex $line $i]
incr i
}
# Directive DB
if {$instruction == {db}} {
# Undefined value -> try to define
set operands [lindex $operands 0]
if {![string is digit -strict $operands]} {
set value [ComputeExpr $operands 0 $address]
if {$value == {}} {
SyntaxError $lineNum $fileNum [mc "Invalid expression: `%s'" $operands]
} elseif {$value < 0 || $value > 255} {
SyntaxError $lineNum $fileNum [mc "Value out of range: `%s' (%s)" $operands $value]
}
set operands $value
}
# Check for instruction validity
} elseif {[lsearch -exact -ascii ${::CompilerConsts::AllInstructions} $instruction] == -1} {
if {[string index $address end] == {:}} {
SyntaxError $lineNum $fileNum [mc "Invalid label declaration: `%s'\n\tLabels can contain alphanumeric characters only and must not begin with a digit" $address]
} else {
SyntaxError $lineNum $fileNum [mc "Unknown keyword: `%s'\n\t`%s' is neither macro nor instruction nor directive" [lindex $address 0] [lindex $address 0]]
}
continue
}
# Append adjusted line to the code
lappend tmp_asm [list \
$lineNum $fileNum $address \
$instruction \
[operands_to_absolute_values \
$address $instr_lenght \
$operands $operand_types \
$instruction 0 \
] \
$operand_types \
]
}
# Resolve: "DW <label>", and "DB ..., <label>, ..."
if {${::Compiler::Settings::PRINT}} {
set new_lst {}
foreach lst_line $CodeListing::lst {
set op_code [lindex $lst_line 1]
if {[llength $op_code] > 1} {
set take_next 0
set new_op_code {}
foreach op $op_code {
if {{} == $op} {
set take_next 1
continue
} elseif {$take_next} {
set take_next 0
append new_op_code [format %02X [ComputeExpr $op 0]]
} else {
append new_op_code $op
}
}
lset lst_line 1 $new_op_code
}
lappend new_lst $lst_line
}
set CodeListing::lst $new_lst
}
# Replace old code with the new one
set asm $tmp_asm
}
## Convert bit addres represented by dot notation to decimal string
# @parm String expression - bit address (eg. 'PSW.4')
# @parm Bool ignore_undefined - Ignore undefined symbolic names
# @return Int - Bit address
proc getBitAddr {expression ignore_undefined} {
variable lineNum ;# Number of the current line
variable fileNum ;# Number of the current file
# Split bit address into two parts
set opr1 [split $expression {.}]
set opr0 [lindex $opr1 0] ;# Register
set opr1 [lindex $opr1 1] ;# Bit
# Register is 'A'
if {$opr0 == {A} || $opr0 == {a}} {
set regAddr 224
# Register is a symbolic name
} elseif {[isSymbolicName $opr0]} {
set regAddr [getValueOfSymbolicName \
$opr0 {data idata equset} {} \
$ignore_undefined \
]
# Register is regular number
} else {
set regAddr [COprToDec $opr0]
}
# Bit is a symbolic name
if {[isSymbolicName $opr1]} {
set bitNum [getValueOfSymbolicName \
$opr1 {equset} {} \
$ignore_undefined \
]
# Bit is regular number
} else {
set bitNum [COprToDec $opr1]
}
# Check for valid bit number value
if {$bitNum < 0 || $bitNum > 7} {
SyntaxError $lineNum $fileNum [mc "Invalid bit designator: %s" $expression]
return {}
}
# Register is in high bit addressable area
if {$regAddr > 31 && $regAddr < 48} {
return [expr {($regAddr - 32) * 8 + $bitNum}]
# Register bit addressable SFR
} elseif {[lsearch -exact -ascii {128 136 144 152 160 168 176 184 208 224 240} $regAddr] != -1} {
return [expr {$regAddr + $bitNum}]
# Register is not bit addressable
} else {
SyntaxError $lineNum $fileNum [mc "Given register does not belong to the bit addressable area: %s" $expression]
return {}
}
}
## Convert operand value to decimal string (operand must not be an expression)
# @parm String operand - operand string (eg. '#0F5h')
# @return String - converted operand
proc COprToDec {operand} {
variable lineNum ;# Number of the current line
variable fileNum ;# Number of the current file
# If the given operand is fixed string -> return it unchanged
if {[lsearch -exact -ascii ${::CompilerConsts::FixedOperands} [string tolower $operand]] != -1} {
return $operand
}
# Adjust operand string
set char [string index $operand 0]
if {$char == {#} || $char == {@} || $char == {/}} {
set operand [string replace $operand 0 0]
} else {
set char {}
}
# Handle prefix notation for hexadecimal numbers, like 0xfa
if {
[string index $operand 0] == {0}
&&
([string index $operand 1] == {x} || [string index $operand 1] == {X})
} then {
set operand [string replace $operand 0 1]
if {![string is digit [string index $operand 0]]} {
set operand "0${operand}"
}
append operand {h}
}
# Determinate numeric base and adjust operand string
set base [string index $operand end]
set operand [string range $operand 0 {end-1}]
# No base specified -- decimal number
if {[regexp {[0-9]} $base]} {
append operand $base
# Convert and return
if {[NumSystem::isdec $operand]} {
return "$char$operand"
} else {
SyntaxError $lineNum $fileNum [mc "Invalid value: `%s'" "${char}${operand}"]
}
# Value is a charater
} elseif {$base == {'}} {
# Remove leading quote
if {[string index $operand 0] != {'}} {
SyntaxError $lineNum $fileNum [mc "Invalid value: `%s'" "${char}${operand}"]
return {}
} else {
set operand [string range $operand 1 end]
}
}
# Conevert operand value to decimal string
set base [string tolower $base]
switch -- $base {
{h} { ;# From hexadecimal
if {[NumSystem::ishex $operand]} {
set operand [expr "0x$operand"]
return "$char$operand"
} else {
SyntaxError $lineNum $fileNum [mc "Invalid value: `%s'" "${operand}${base}"]
return {}
}
}
{b} { ;# From binary
if {[NumSystem::isbin $operand]} {
set operand [NumSystem::bin2dec $operand]
return "$char$operand"
} else {
SyntaxError $lineNum $fileNum [mc "Invalid value: `%s'" "${operand}${base}"]
return {}
}
}
{o} { ;# From octal
if {[NumSystem::isoct $operand]} {
set operand [NumSystem::oct2dec $operand]
return "$char$operand"
} else {
SyntaxError $lineNum $fileNum [mc "Invalid value: `%s'" "${operand}${base}"]
return {}
}
}
{q} { ;# From octal
if {[NumSystem::isoct $operand]} {
set operand [NumSystem::oct2dec $operand]
return "$char$operand"
} else {
SyntaxError $lineNum $fileNum [mc "Invalid value: `%s'" "${operand}${base}"]
return {}
}
}
{'} { ;# From character
if {[string length $operand] != 0} {
set operand $char[character2number [subst -nocommands -novariables $operand]]
} else {
SyntaxError $lineNum $fileNum [mc "Invalid value: `%s'" $operand]
return {}
}
}
{d} { ;# From decimal (no conversion)
if {[NumSystem::isdec $operand]} {
return "$char$operand"
} else {
SyntaxError $lineNum $fileNum [mc "Invalid value: `%s'" "${operand}${base}"]
return {}
}
}
default { ;# Error -- invalid base
SyntaxError $lineNum $fileNum [mc "Invalid numeric base `%s'\n\tPossible options are: __H (hex), __D (dec) __B (bin), __Q __O (oct) and 'char'" $base]
return {}
}
}
}
## Check for valid operand range
# @parm String operand - Operand string
# @parm String type - Operand type (one of {code8 code11 code16 imm8 imm16 data bit /bit})
# @return Bool - result (1 == valid; 0 == invalid)
proc checkRange {operand type} {
variable lineNum ;# Number of the current line
variable fileNum ;# Number of the current file
# Both strings to lowercase
set type [string tolower $type]
set operand [string tolower $operand]
# Fixed operand
if {[lsearch -exact -ascii ${::CompilerConsts::FixedOperands} $operand] != -1} {
if {$operand == $type} {
return 1
} else {
return 0
}
}
# Adjust operand
set char [string index $operand 0]
if {$char == {#} || $char == {@} || $char == {/}} {
set operand [string trimleft $operand {#@/}]
} else {
set char {}
}
# Determinate maximum value
switch -- $type {
{code8} {set max 255}
{code11} {set max 2047}
{code16} {set max 65535}
{imm8} {set max 255}
{imm16} {set max 65535}
{data} {set max 255}
{bit} {set max 255}
{/bit} {set max 255}
default {
CompilationError $lineNum $fileNum "Unknown error 1"
return 0
}
}
# Check for allowed range
if {$operand > $max || $operand < 0} {
return 0
} else {
return 1
}
}
## Determinate whether the given string is an expression
# @parm String expression - expression
# @return Bool - result (1 == is an expression; 0 == is not an expression)
proc isExpression {expression} {
# Remove strings and quoted characters
regsub -all {'[^']*'} $expression {} expression
# Remove redutant white space
set expression [string trimleft $expression "\t "]
set expression [string trimright $expression "\t "]
if {[regexp {[ \?\+\-\=<>\(\)\*/%]} $expression]} {
return 1
} else {
return 0
}
}
## Determinate whether the given string is fixed value (for instance 'A' or 'AB')
# @parm String operand - operand string to evaluate
# @return Bool - result (1 == is fixed; 0 == is not fixed)
proc isFixed {operand} {
set operand [string tolower $operand]
if {[lsearch -exact -ascii ${::CompilerConsts::FixedOperands} $operand] != -1} {
return 1
} else {
return 0
}
}
## Determinate whether the given string is a symbolic name
# @parm String symbolic_name - operand string to evaluate
# @return Bool - result (1 == is symbolic name; 0 == is not symbolic name)
proc isSymbolicName {symbolic_name} {
# Adjust operand
set char [string index $symbolic_name 0]
if {$char == {#} || $char == {@} || $char == {/}} {
set symbolic_name [string trimleft $symbolic_name {#@/}]
}
# Check if the string starts with a digit or quote
if {[regexp {^(\d|')} $symbolic_name]} {
return 0
} else {
return 1
}
}
## Determinate value of the given symbolic name
# @parm String symbolic_name - Symbolic name to evaluate
# @parm List list_of_priorities - Substitution priorities
# @parm Int address - Instruction address
# @parm Bool ignore_undefined - Ignore undefined symbolic names
# @return Int - decimal string
proc getValueOfSymbolicName {symbolic_name list_of_priorities address ignore_undefined} {
variable lineNum ;# Number of the current line
variable fileNum ;# Number of the current file
variable check_sfr_usage;# Bool: Check for legal usage of SFR and SFB
variable available_SFR ;# List: Available SFR and SFB on the target MCU
variable const_BIT ;# Array: Bit values -- ($const_BIT($bit_name) == $value)
variable const_CODE ;# Array: Constants defined by directive 'CODE'
variable const_DATA ;# Array: Constants defined by directive 'DATA'
variable const_IDATA ;# Array: Constants defined by directive 'IDATA'
variable const_XDATA ;# Array: Constants defined by directive 'XDATA'
variable const_SET ;# Array: Constants defined by directive 'CODE'
variable const_EQU ;# Array: Constants defined by directive 'EQU'
variable defined_BIT ;# List of defined bits (directove 'BIT')
variable defined_CODE ;# List of constants defined by 'CODE'
variable defined_DATA ;# List of constants defined by 'DATA'
variable defined_IDATA ;# List of constants defined by 'IDATA'
variable defined_XDATA ;# List of constants defined by 'XDATA'
variable defined_SET ;# List of variables defined by 'SET'
variable defined_EQU ;# List of constants defined by 'EQU'
variable labels ;# Array: Values of defined labels ($labels($label) == $address)
variable defined_LABEL ;# List of defined labels
# Convert symbolic name to tower case
set symbolic_name [string tolower $symbolic_name]
# Search definition list
foreach type $list_of_priorities {
switch -- $type {
{labels} {
if {
([lsearch -exact -ascii $defined_LABEL $symbolic_name] == -1) &&
($symbolic_name != "\$")
} then {
continue
}
if {$symbolic_name == "\$"} {
set value $address
} else {
set value $labels($symbolic_name)
}
CodeListing::symbol_used $symbolic_name {label}
return $value
}
{code} {
if {[lsearch -exact -ascii $defined_CODE $symbolic_name] != -1} {
CodeListing::symbol_used $symbolic_name {code}
return $const_CODE($symbolic_name)
}
}
{xdata} {
if {[lsearch -exact -ascii $defined_XDATA $symbolic_name] != -1} {
CodeListing::symbol_used $symbolic_name {xdata}
return $const_XDATA($symbolic_name)
}
}
{idata} {
if {[lsearch -exact -ascii $defined_IDATA $symbolic_name] != -1} {
CodeListing::symbol_used $symbolic_name {idata}
return $const_IDATA($symbolic_name)
}
}
{data} {
if {[lsearch -exact -ascii $defined_DATA $symbolic_name] != -1} {
CodeListing::symbol_used $symbolic_name {data}
if {$check_sfr_usage} {
if {
[lsearch -ascii -exact $::CompilerConsts::defined_SFR $symbolic_name] != -1
&&
[lsearch -ascii -exact $available_SFR $symbolic_name] == -1
} then {
Warning $lineNum $fileNum [mc "Special function register \"%s\" is not available on the target MCU" [string toupper $symbolic_name]]
}
}
return $const_DATA($symbolic_name)
}
}
{bit} {
if {[lsearch -exact -ascii $defined_BIT $symbolic_name] != -1} {
CodeListing::symbol_used $symbolic_name {bit}
if {$check_sfr_usage} {
if {
[lsearch -ascii -exact $::CompilerConsts::defined_SFRBitArea $symbolic_name] != -1
&&
[lsearch -ascii -exact $available_SFR $symbolic_name] == -1
} then {
Warning $lineNum $fileNum [mc "Special function bit \"%s\" is not available on the target MCU" [string toupper $symbolic_name]]
}
}
return $const_BIT($symbolic_name)
}
}
{equset} {
if {![const_exists $symbolic_name]} {
continue
}
set val [const_value $symbolic_name $lineNum]
if {$val == {}} {
break
} else {
CodeListing::symbol_used $symbolic_name {equset}
return $val
}
}
default {
CompilationError $lineNum $fileNum "Unknown error 2"
}
}
}
# Symbolic name not found
if {!$ignore_undefined} {
SyntaxError $lineNum $fileNum [mc "Symbol not defined: %s" $symbolic_name]
}
return {}
}
## Perform peerhole optimization
# This function must be called between "parse_instructions" and "final_stage"
# @return void
proc optimization {} {
variable asm ;# Resulting pre-compiled code
variable tmp_asm ;# Temporary auxiliary pre-compiled code
variable lineNum ;# Number of the current line
variable fileNum ;# Number of the current file
variable idx ;# Current position in asm list
variable labels ;# Array: Values of defined labels ($labels($label) == $address)
variable defined_LABEL ;# List of defined labels
variable program_memory ;# String of booleans: Map of program memory usage
variable optims ;# Number of performed optimizations
variable origin_d_addr ;# List: Addresses of static program blocks
# Iterate over the code
set tmp_asm {}
set asm_len [llength $asm]
for {set idx 0} {$idx < $asm_len} {incr idx} {
# Update after each 25 iterations
if {[expr {$idx % 25}] == 0} {
${::Compiler::Settings::UPDATE_COMMAND}
}
if {${::Compiler::Settings::ABORT_VARIABLE}} {
${::Compiler::Settings::TEXT_OUPUT_COMMAND} [mc "Aborted"]
free_resources
return
}
# Split line into separate fields
set i 0
foreach var {lineNum fileNum address instr_lenght instruction operands operand_types} {
set $var [lindex $asm [list $idx $i]]
incr i
}
# Convert instruction operands to absolute values
set operands_abs [operands_to_absolute_values \
$address $instr_lenght \
$operands $operand_types \
$instruction 1 \
]
# Do not try to optimalize unresolved lines
if {$operands_abs == {} || [string first {$} $operands] != -1} {
lappend tmp_asm [list \
$lineNum $fileNum $address \
$instr_lenght $instruction $operands \
$operand_types \
]
continue
}
# Optimalize code on this line
set bytes_saved 0
switch -- $instruction {
{setb} { ;# SETB 215 --> SETB C
if {[lindex $operands_abs 0] == {215}} {
lset operands 0 C
lset operand_types 0 c
set bytes_saved 1
}
}
{clr} { ;# CLR 215 --> CLR C
if {[lindex $operands_abs 0] == {215}} {
lset operands 0 C
lset operand_types 0 c
set bytes_saved 1
}
}
{jmp} { ;# A) JMP code11 --> AJMP code11
;# B) JMP code8 --> SJMP code8
## A)
if {[string is digit -strict [lindex $operands_abs 0]]} {
set diff [expr {$address - [lindex $operands_abs 0]}]
} else {
set diff 200 ;# Some value out of range [-126; 129]
}
if {[lindex $operand_types 0] != {code8} && $diff >= -126 && $diff <= 129} {
set instruction {sjmp}
set operand_types {code8}
set bytes_saved 1
## B)
} elseif {
[lindex $operand_types 0] != {code8} &&
[lindex $operand_types 0] != {code11} &&
($address & 0x0f800) == ([lindex $operands_abs 0] & 0x0f800)
} then {
set instruction {ajmp}
set operand_types {code11}
set bytes_saved 1
}
}
{ljmp} { ;# A) LJMP code11 --> AJMP code11
;# B) LJMP code8 --> SJMP code8
## A)
if {[string is digit -strict [lindex $operands_abs 0]]} {
set diff [expr {$address - [lindex $operands_abs 0]}]
} else {
set diff 200 ;# Some value out of range [-126; 129]
}
if {$diff >= -126 && $diff <= 129} {
set instruction {sjmp}
set operand_types {code8}
set bytes_saved 1
## B)
} elseif {[lindex $operands_abs 0] < 2048} {
set instruction {ajmp}
set operand_types {code11}
set bytes_saved 1
}
}
{ajmp} { ;# AJMP code8 --> SJMP code8
if {[string is digit -strict [lindex $operands_abs 0]]} {
set diff [expr {$address - [lindex $operands_abs 0]}]
} else {
set diff 200 ;# Some value out of range [-126; 129]
}
if {$diff >= -126 && $diff <= 129} {
set instruction {sjmp}
set operand_types {code8}
}
}
{call} { ;# CALL code11 --> ACALL code11
if {
[lindex $operand_types 0] != {code11}
&&
($address & 0x0f800) == ([lindex $operands_abs 0] & 0x0f800)
} then {
set instruction {acall}
set operand_types {code11}
set bytes_saved 1
}
}
{lcall} { ;# LCALL code11 --> ACALL code11
if {[lindex $operands_abs 0] < 2048} {
set instruction {acall}
set operand_types {code11}
set bytes_saved 1
}
}
{mov} { ;# A) MOV 224, ... --> MOV A, ...
;# B) MOV ..., 224 --> MOV ..., A
## A)
if {
[lindex $operands_abs 0] == 224
&&
[lindex $operand_types 0] == {data}
} then {
if {[lindex $operands_abs 1] != {A}} {
lset operands 0 A
lset operand_types 0 a
set bytes_saved 1
}
## B)
} elseif {
[lindex $operands_abs 1] == 224
&&
[lindex $operand_types 1] == {data}
} then {
lset operands 1 A
lset operand_types 1 a
set bytes_saved 1
}
}
}
if {$bytes_saved} {
# Increment number of performed optimizations
incr optims
# Shift code
set max_addr $address
set last_len $instr_lenght
for {set i [expr {$idx + 1}]} {$i < $asm_len} {incr i} {
set addr [lindex $asm [list $i 2]]
if {$addr != ($max_addr + $last_len) || [lsearch $origin_d_addr $addr] != -1} {
break
}
set max_addr $addr
set last_len [lindex $asm [list $i 3]]
lset asm [list $i 2] [expr {$addr - $bytes_saved}]
}
# Shift labels
foreach lbl $defined_LABEL {
if {$labels($lbl) > $address && $labels($lbl) <= $max_addr} {
incr labels($lbl) -$bytes_saved
}
}
# Adjust instruction length
incr instr_lenght -$bytes_saved
}
lappend tmp_asm [list \
$lineNum $fileNum $address \
$instr_lenght $instruction $operands \
$operand_types \
]
}
set asm $tmp_asm
}
## Evaluate and remove instructions
# @return void
proc parse_instructions {} {
variable asm ;# Resulting pre-compiled code
variable tmp_asm ;# Temporary auxiliary pre-compiled code
variable lineNum ;# Number of the current line
variable fileNum ;# Number of the current file
variable idx ;# Current position in asm list
variable labels ;# Array: Values of defined labels ($labels($label) == $address)
variable defined_LABEL ;# List of defined labels
variable program_memory ;# String of booleans: Map of program memory usage
variable const_SET_SPEC ;# Array: Special constants defined by directive 'CODE'
variable const_EQU_SPEC ;# Array: Special constants defined by directive 'EQU'
variable defined_SET_SPEC ;# List of special variables defined by 'SET'
variable defined_EQU_SPEC ;# List of special constants defined by 'EQU'
# Reset NS variables
set lineNum {}
set instruction_len {}
set instruction {}
set operands {}
set operand_types {}
set local_labels {}
set tmp_asm {}
set program_memory [string repeat 0 65536]
set program_pointer 0
set new_program_pointer 0
set idx -1
# Iterate over the code
foreach line $asm {
incr idx
# Update after each 25 iterations
if {[expr {$idx % 25}] == 0} {
${::Compiler::Settings::UPDATE_COMMAND}
}
if {${::Compiler::Settings::ABORT_VARIABLE}} {
${::Compiler::Settings::TEXT_OUPUT_COMMAND} [mc "Aborted"]
free_resources
return
}
# Determinate line number and line content
set lineNum [lindex $line 0]
set fileNum [lindex $line 1]
set line [lindex $line 2]
## Conditionaly change program pointer
if {![regexp {^\s*\w+} $line first_field]} {
set first_field {}
} else {
set first_field [string trim $first_field]
}
if {$first_field == {ORG}} {
CodeListing::delete_line $idx
incr idx -1
set program_pointer [lindex $line 1]
continue
}
## Determinate label
if {[regexp {^\w+:} $line label]} {
# Check for label validity
set lbl [string trimright $label {:}]
if {[regexp {^\w*:$} $label] && ![regexp {^\d} $label]} {
if {
[lsearch -exact -ascii ${::CompilerConsts::defined_SFR} $lbl] != -1
||
[lsearch -exact -ascii ${::CompilerConsts::defined_progVectors} $lbl] != -1
||
[lsearch -exact -ascii ${::CompilerConsts::defined_SFRBitArea} $lbl] != -1
||
[lsearch -exact -ascii ${::CompilerConsts::FixedOperands} $lbl] != -1
} then {
SyntaxError $lineNum $fileNum [mc "Unable redefine constant: %s" $lbl]
} else {
set label $lbl
if {[isReservedKeyword $label]} {
Warning $lineNum $fileNum [mc "Reserved keyword used as label"]
}
lappend local_labels $label
}
} else {
SyntaxError $lineNum $fileNum [mc "Invalid label: `%s' \n\t(labels can contain only alphanumeric characters and must not begin with a digit)" $label]
}
# Remove label from the line
regsub {^\w+:\s*} $line {} line
}
# If the line contains only label then exit
if {$line == {}} {
CodeListing::delete_line $idx
incr idx -1
continue
}
## Determinate instruction
if {![regexp {^\s*\.?\w+} $line instruction]} {
set instruction {}
} else {
set instruction [string tolower [string trim $instruction]]
}
# Directive 'SKIP'
if {$instruction == {skip} || $instruction == {.skip}} {
set skip [ComputeExpr [regsub {^\s*\.?\w+\s*} $line {}]]
if {$skip == {}} {
set instruction_len 0
SyntaxError $lineNum $fileNum [mc "Invalid expression `%s'" [regsub {^\s*\.?\w+\s*} $line {}]]
} else {
set instruction_len $skip
}
set instruction {} ;# <-- That means delete this line
# Directive 'DB'
} elseif {$instruction == {db}} {
set instruction_len 1
set operand_types {}
set operands [regsub {^\w+\s*} $line {}]
# Regular instruction
} else {
# Check for instruction validity
if {[lsearch -exact -ascii ${::CompilerConsts::AllInstructions} $instruction] == -1} {
lappend tmp_asm [list $lineNum $fileNum {C} $line]
continue
}
# Remove instruction from the line
regsub {^\w+\s*} $line {} line
# Determinate operands
set operands [getOperands $line 1]
# Determinate operand types and instruction length
set instr_info [getInstructionInfo $instruction $operands $program_pointer]
if {$instr_info == {}} {continue}
set instruction_len [lindex $instr_info 0]
set operand_types [lindex $instr_info 1]
set operands [lindex $instr_info 2]
}
# Define found labels
define_labels $local_labels $program_pointer
# Determinate expected program position
set new_program_pointer $program_pointer
incr new_program_pointer $instruction_len
# Check for program pointer validity
for {set i $program_pointer} {$i <= $new_program_pointer} {incr i} {
if {[string index $program_memory $i] != 0} {
CompilationError $lineNum $fileNum [mc "Unable to overwrite already reserved program memory at address 0x%s -- compilation failed" [format %X $i]]
}
}
if {$program_pointer >= ${::Compiler::Settings::code_size}} {
Warning $lineNum $fileNum [mc "This instruction exceeding code memory capacity"]
}
# Adjust map of code memory usage
set program_memory [string replace $program_memory \
$program_pointer [expr {$new_program_pointer - 1}] \
[string repeat 1 $instruction_len] \
]
# Create new code line
if {$instruction != {}} {
lappend tmp_asm [list \
$lineNum $fileNum \
$program_pointer $instruction_len \
$instruction $operands \
$operand_types \
]
}
# Adjust code listing and program pointer
CodeListing::set_addr $idx $program_pointer
set program_pointer $new_program_pointer
# Reset
set lineNum {}
set fileNum {}
set instruction_len {}
set instruction {}
set operands {}
set operand_types {}
set local_labels {}
}
# Chech if reset address engaged
if {![string index $program_memory 0]} {
Warning $lineNum $fileNum [mc "No instruction found at address 0x00. Consider usage of appropriate ORG directive to clarify correct code placement."]
}
# Finalize
define_labels $local_labels $program_pointer
set asm $tmp_asm
}
## Determinate whether the given string is reserved keyword
# @parm String string - String to evaluate
# @parm Bool symbols_too - Consider also special register names
# @return Bool - result (1 == is reserved; 0 == is not reserved)
proc isReservedKeyword {string {symbols_too 0}} {
set string [string tolower $string]
if {
[lsearch -exact -ascii ${::CompilerConsts::AllInstructions} $string] != -1
||
[lsearch -exact -ascii ${::CompilerConsts::AllDirectives} $string] != -1
||
[lsearch -exact -ascii ${::CompilerConsts::FixedOperands} $string] != -1
} then {
return 1
} elseif {$symbols_too && (
[lsearch -exact -ascii ${::CompilerConsts::defined_SFR} $string] != -1
||
[lsearch -exact -ascii ${::CompilerConsts::defined_progVectors} $string] != -1
||
[lsearch -exact -ascii ${::CompilerConsts::defined_SFRBitArea} $string] != -1
)
} then {
return 1
} else {
return 0
}
}
## Assign the given address to the given labels
# @parm List list_of_labels - Labels to define
# @parm Int address - address to assign
# @return void
proc define_labels {list_of_labels address} {
variable defined_LABEL ;# List of defined labels
variable labels ;# Array: Values of defined labels ($labels($label) == $address)
variable lineNum ;# Number of the current line
variable fileNum ;# Number of the current file
# Return if the given list is empty
if {![llength $list_of_labels]} {return}
# Define the given labels
set list_of_labels [string tolower $list_of_labels]
foreach label $list_of_labels {
if {[lsearch -exact -ascii $defined_LABEL $label] != -1} {
SyntaxError $lineNum $fileNum [mc "Label was already defined: `%s'" $label]
} else {
lappend defined_LABEL $label
set labels($label) $address
}
}
}
## Determinate instruction length and list of operand types
# @parm String instruction - instruction name
# @parm List operands - instruction operands
# @parm Inr address - instruction address
# @return List - {instruction_length list_of_operand_types operands}
proc getInstructionInfo {instruction operands address} {
variable lineNum ;# Number of the current line
variable fileNum ;# Number of the current file
variable const_SET_SPEC ;# Array: Special constants defined by directive 'CODE'
variable const_EQU_SPEC ;# Array: Special constants defined by directive 'EQU'
variable defined_SET_SPEC ;# List of special variables defined by 'SET'
variable defined_EQU_SPEC ;# List of special constants defined by 'EQU'
# Convert fixed operands to uppercase
set l [llength $operands]
for {set i 0} {$i < $l} {incr i} {
set o [lindex $operands $i]
if {[lsearch -exact -ascii ${::CompilerConsts::FixedOperands} [string tolower $o]] != -1} {
set operands [lreplace $operands $i $i [string toupper $o]]
}
}
# Initialize variables containing result
set operand_types {}
set instr_len 0
# Expand special constants
set l [llength $operands]
for {set i 0} {$i < $l} {incr i} {
set o [string tolower [lindex $operands $i]]
if {
[lsearch -ascii -exact $defined_EQU_SPEC $o] != -1
||
[lsearch -ascii -exact $defined_SET_SPEC $o] != -1
} then {
set n [const_value $o $lineNum 1]
set operands [lreplace $operands $i $i $n]
Notice $lineNum $fileNum [mc "Overwriting `%s' with `%s' (according to your previous definition!)" [string toupper $o] [string toupper $n]]
}
}
# Determinate basic operand types
set operand_types {}
foreach opr $operands {
lappend operand_types [operandType $opr $instruction $address]
}
# Find instruction set for given instruction
if {[lsearch -exact -ascii ${::CompilerConsts::AllInstructions} $instruction] == -1} {
CompilationError $lineNum $fileNum "Unknown error 3"
return {}
}
set ins_def $::CompilerConsts::InstructionDefinition($instruction)
# Check for valid operands count
set max_oprs [lindex $ins_def 0]
if {[llength $operands] > $max_oprs} {
SyntaxError $lineNum $fileNum [mc "Too many operands, %s can take only %s operand[expr {$max_oprs == 1 ? {} : {s}}]" $instruction $max_oprs]
return {}
} elseif {[llength $operands] < $max_oprs} {
SyntaxError $lineNum $fileNum [mc "Too few operands, %s must take exactly %s operand[expr {$max_oprs == 1 ? {} : {s}}]" $instruction $max_oprs]
return {}
}
# Find matching operand set
set operand_types [string tolower $operand_types]
set operands_org $operands
set operands_changed $operands
set operand_types_org $operand_types
set match 1
for {set i 0} {$i < 3} {incr i} {
foreach opr_set_def [lindex $ins_def 1] {
set opr_list [lindex $opr_set_def 0]
set match 1
foreach given_type $operand_types possible_type $opr_list {
if {[lsearch -exact -ascii $given_type $possible_type] == -1} {
set match 0
break
}
}
if {$match} {
set operand_types $opr_list
set instr_len [lindex $opr_set_def 1]
break
}
}
if {$match} {
if {$i} {
Notice $lineNum $fileNum [mc "`%s' changed by compiler to `%s'" "$instruction [join $operands_org {, }]" "$instruction [join $operands_changed {, }]"]
}
break
}
# Try to change operand set without changing meaning
set operands_i {}
while {$i < 2} {
set operands_i [lindex $operands $i]
if {
$operands_i != {A}
&&
$operands_i != {C}
&&
$operands_i != {/C}
} then {
incr i
continue
}
set operands $operands_org
set operands_changed $operands
set operand_types $operand_types_org
if {$operands_i == {A}} {
lset operands $i {224}
lset operands_changed $i {ACC}
lset operand_types $i {data}
} elseif {$operands_i == {C}} {
lset operands $i {215}
lset operands_changed $i {CY}
lset operand_types $i {bit}
} elseif {$operands_i == {/C}} {
lset operands $i {/215}
lset operands_changed $i {/CY}
lset operand_types $i {/bit}
}
break
}
}
# No matching operand set found -> error
if {!$match} {
SyntaxError $lineNum $fileNum [mc "Invalid set of operands: %s %s" $instruction [join $operands {,}]]
return {}
}
# Return result
return [list $instr_len $operand_types $operands]
}
## Determinate type of the given operand
# @parm String instruction - instruction name
# @parm String operand - operand to evaluate
# @parm Int address - instruction address
# @return List - list of possible types
proc operandType {operand instruction address} {
variable labels ;# Array: Values of defined labels ($labels($label) == $address)
variable const_DATA ;# Array: Constants defined by directive 'DATA'
variable const_IDATA ;# Array: Constants defined by directive 'IDATA'
variable const_XDATA ;# Array: Constants defined by directive 'XDATA'
variable defined_LABEL ;# List of defined labels
variable defined_BIT ;# List of defined bits (directove 'BIT')
variable defined_DATA ;# List of constants defined by 'DATA'
variable defined_IDATA ;# List of constants defined by 'IDATA'
variable defined_XDATA ;# List of constants defined by 'XDATA'
variable lineNum ;# Number of the current line
variable fileNum ;# Number of the current file
# To lowercase
set operand [string tolower $operand]
# Fixed value
if {[lsearch -exact -ascii ${::CompilerConsts::FixedOperands} $operand] != -1} {
return [string toupper $operand]
}
# Immediate or bit address
switch -regexp -- $operand {
{^/.*$} { return {/bit} }
{^#.*$} { return {imm8 imm16} }
}
# determinate whether the instruction can changed content of PC
if {[lsearch {} $instruction] == -1} {
set no_branch 1
} else {
set no_branch 0
}
# Variable length operand (pseudo-instructions: "CALL <code>" and "JMP <code>")
if {$instruction == {jmp} || $instruction == {call}} {
# Value is an expression
if {[isExpression $operand]} {
set operand [ComputeExpr $operand 1 $address]
# Value is regular symbolic name
} elseif {[isSymbolicName $operand]} {
set operand [getValueOfSymbolicName \
$operand {labels code equset} \
$address 1 \
]
# Direct value (some number)
} else {
set operand [COprToDec $operand]
Warning $lineNum $fileNum [mc "Direct value used as operand for %s" $instruction]
}
# Determinate appropriate operand type
if {$operand == {}} {
return {code16}
} elseif {$operand >= 0x800} {
return {code16}
} elseif {(abs($address - $operand) > 126) || $instruction == {call}} {
return {code11}
} else {
return {code8}
}
# Register in SFR area
} elseif {[lsearch ${::CompilerConsts::defined_SFR} $operand] != -1} {
return {data}
# Bit in SFB area
} elseif {[lsearch ${::CompilerConsts::defined_SFRBitArea} $operand] != -1} {
return {bit /bit}
# Address in program memory
} elseif {[lsearch ${::CompilerConsts::defined_progVectors} $operand] != -1} {
return {code16 code11 code8}
# Another type
} else {
return {data code16 code11 code8 bit /bit}
}
}
## Expand macro instructions
# @return Bool - macro expanded
proc expand_macro_instructions {} {
variable asm ;# Resulting pre-compiled code
variable tmp_asm ;# Temporary auxiliary pre-compiled code
variable lineNum ;# Number of the current line
variable fileNum ;# Number of the current file
variable macro ;# Array: Code of defined macro instructions
variable local_M_labels ;# Array of lists: Local labels in macros $local_M_labels($macro_name) == {integer label0 ... labelN}
variable defined_MACRO ;# List of defined macro instructions
variable idx ;# Current position in asm list
# Skip procedure if there are no defined macro instructions
if {![llength $defined_MACRO]} {
return 0
}
set label {}
set operands {}
set instruction {}
set macro_code {}
set tmp_asm {}
set idx -1
set del_line 0
set repeat 0 ;# Bool: Macro expanded
# Iterate over the code
foreach line $asm {
incr idx
# Update after each 25 iterations
if {[expr {$idx % 25}] == 0} {
${::Compiler::Settings::UPDATE_COMMAND}
}
if {${::Compiler::Settings::ABORT_VARIABLE}} {
${::Compiler::Settings::TEXT_OUPUT_COMMAND} [mc "Aborted"]
free_resources
return
}
# Determinate line number and line content
set lineNum [lindex $line 0]
set fileNum [lindex $line 1]
set line [lindex $line 2]
# Make line backup
set original_line $line
# Determinate label, instruction and operands
set label {}
if {[regexp {^\w+:} $line label]} {
regsub {^\w+:\s*} $line {} line
}
if {![regexp {^\s*\.?\w+} $line instruction]} {
set instruction {}
} else {
set instruction [string tolower [string trim $instruction]]
}
regsub {^\.?\w+\s*} $line {} operands
# Check if the instruction is macro
if {[lsearch -exact -ascii $defined_MACRO $instruction] == -1} {
lappend tmp_asm [list $lineNum $fileNum $original_line]
continue
}
set repeat 1
# Get code of the macro
set macro_code [getMacro $instruction [getOperands $operands 1]]
if {$macro_code == {}} {continue}
# Adjust the precompiled code and code listing
if {$label != {}} {
lappend tmp_asm [list $lineNum $fileNum $label]
set del_line 0
} else {
set del_line 1
}
CodeListing::macro $idx $macro_code
if {$del_line} {
CodeListing::delete_line $idx
incr idx -1
}
foreach line $macro_code {
lappend tmp_asm [list $lineNum $fileNum $line]
incr idx
}
}
# Replace old code with the new one and return result
set asm $tmp_asm
return $repeat
}
## Debugging procedure
# Write current content of the precompiled code to stdout
# @return void
proc write_asm {} {
variable asm ;# Resulting pre-compiled code
puts ""
set idx -1
foreach line $asm {
incr idx
puts "$idx:\t$line"
}
}
## Debugging procedure
# Write current content of the tempotary precompiled code to stdout
# @return void
proc write_tmp_asm {} {
variable tmp_asm ;# Temporary auxiliary pre-compiled code
puts ""
set idx -1
foreach line $tmp_asm {
incr idx
puts "$idx:\t$line"
}
}
## Get adjusted code of the given macro instruction
# @parm String macro_name - Macro name
# @parm List args - Expansion arguments (wrapped in '{}')
# @return List - code of the macro
proc getMacro {macro_name args} {
variable macro ;# Array: Code of defined macro instructions
variable local_M_labels ;# Array of lists: Local labels in macros $local_M_labels($macro_name) == {integer label0 ... labelN}
variable lineNum ;# Number of the current line
variable fileNum ;# Number of the current file
# Adjust list of arguments
set args [lindex $args 0]
# Local variables
set new_operands {} ;# Instruction operands
set result {} ;# Resulting list
# Determinate code of the macro and its operands
set macro_code $macro($macro_name)
set m_pars [lindex $macro_code 0]
set macro_code [lindex $macro_code 1]
# Check for valid number of arguments
set arg_len_diff [expr {[llength $args] - [llength $m_pars]}]
if {$arg_len_diff < 0} {
set arg_len_diff [expr {$arg_len_diff * -1}]
SyntaxError $lineNum $fileNum [mc "Too few arguments, %d argument(s) missing for %s ..." $arg_len_diff $macro_name]
return {}
} elseif {$arg_len_diff > 0} {
SyntaxError $lineNum $fileNum [mc "Too many arguments, %d extra argument(s)" $arg_len_diff]
return {}
}
# Increment counter of expansions of this macro
lset local_M_labels($macro_name) 0 [expr {1 + [lindex $local_M_labels($macro_name) 0]}]
# Substitute macro parametrs
foreach line $macro_code {
set new_operands {}
# Determinate label
if {![regexp {^(\?\?)?[A-Za-z_][^\s:]*:\s*} $line label]} {
set label {}
} else {
regsub {^(\?\?)?[A-Za-z_][^\s:]*:\s*} $line {} line
regsub -all {\s+} $label {} label
set label [string trimright $label {:}]
if {[lsearch -ascii -exact [lrange $local_M_labels($macro_name) 1 end] $label] != -1} {
set label "${macro_name}_[lindex $local_M_labels($macro_name) 0]__${label}"
}
}
# Determinate instruction and operands
if {![regexp {^\.?\w+\s*} $line instruction]} {
set instruction {}
} else {
regsub -all {\s+} $instruction {} instruction
}
regsub {^\.?\w+\s*} $line {} operands
if {$operands == {}} {
if {$label != {}} {
lappend result "${label}:\t${instruction}"
} else {
lappend result $instruction
}
continue
}
if {[lsearch -ascii -exact {if ifn ifdef ifndef elseif elseifn elseifdef elseifndef} [string tolower $instruction]] == -1} {
set operands [getOperands $operands 0]
set if_statement 0
} else {
set if_statement 1
}
# Perform substitution
foreach opr $operands {
# Adjust operand
set char [string index $opr 0]
if {
($char == {/}) ||
($char == {#}) ||
($char == {@})
} then {
set opr [string range $opr 1 end]
} else {
set char {}
}
# Find operand in macro parameters
set new_opr [list]
regsub -all {[\(\)]} $opr { & } opr
foreach o $opr {
set idx [lsearch -exact -ascii $m_pars $o]
if {$idx != -1} {
set o [lindex $args $idx]
if {[isReservedKeyword [lindex $m_pars $idx] 1]} {
Warning $lineNum $fileNum [mc "Reserved keyword substituted with macro argument: %s --> %s" [lindex $m_pars $idx] [lindex $args $idx]]
}
} elseif {[lsearch -exact -ascii [lrange $local_M_labels($macro_name) 1 end] $o] != -1} {
set o "${macro_name}_[lindex $local_M_labels($macro_name) 0]__${o}"
}
append new_opr $o { }
}
lappend new_operands "$char$new_opr"
}
# Recomposite line of macro instruction code
if {$if_statement} {
set operands [join $new_operands { }]
} else {
set operands [join $new_operands {, }]
}
append instruction "\t"
append instruction $operands
if {$label != {}} {
set instruction "${label}:\t${instruction}"
}
lappend result $instruction
}
# Return resulting list
return $result
}
## Determinate list of operands
# @parm String operands - Operands (eg. 'A, #55d,main')
# @parm Bool keep_case - Keep letters case
# @return List - list of operands (eg. {A #55d main})
proc getOperands {operands keep_case} {
if {$operands == {}} {return {}}
# Local variables
set simple_operands $operands ;# Original string without strings and chars
set result {} ;# Resulting list
# Convert strings and quoted characters to underscores
while {1} {
if {![regexp {'[^']*'} $simple_operands str]} {break}
set padding [string repeat {_} [string length $str]]
regsub {'[^']*'} $simple_operands $padding simple_operands
}
# Determinate operands
while {1} {
set idx [string first {,} $simple_operands]
if {$idx == -1} {break}
incr idx -1
set operand [string range $operands 0 $idx]
set operand [string trimleft $operand { }]
set operand [string trimright $operand { }]
lappend result $operand
incr idx 2
set operands [string range $operands $idx end]
set simple_operands [string range $simple_operands $idx end]
}
set operands [string trim $operands]
lappend result $operands
if {$keep_case} {
return $result
} else {
return [string tolower $result]
}
}
## Parse and remove definitions of macro instructions
# @return void
proc define_macro_instructions {} {
variable asm ;# Resulting pre-compiled code
variable tmp_asm ;# Temporary auxiliary pre-compiled code
variable lineNum ;# Number of the current line
variable fileNum ;# Number of the current file
variable macro ;# Array: Code of defined macro instructions
variable local_M_labels ;# Array of lists: Local labels in macros $local_M_labels($macro_name) == {integer label0 ... labelN}
variable defined_MACRO ;# List of defined macro instructions
variable idx ;# Current position in asm list
variable macro_name_to_append ;# Name of currently defined macro instruction
# Reset NS variables
set tmp_asm {}
set idx -1
# Local variables
set Macro 0 ;# Bool: definition opened
set NoMacro 0 ;# Definition failed
set del_line 1 ;# Bool: remove this line
set macro_name {} ;# Name of the macro
set macro_params {} ;# List of the macro parameters
set rept_macro 0 ;# Bool: repeat macro starts
# Iterate over the code
foreach line $asm {
incr idx
# Update after each 25 iterations
if {[expr {$idx % 25}] == 0} {
${::Compiler::Settings::UPDATE_COMMAND}
}
if {${::Compiler::Settings::ABORT_VARIABLE}} {
${::Compiler::Settings::TEXT_OUPUT_COMMAND} [mc "Aborted"]
free_resources
return
}
set del_line 1 ;# Flag "remove this line"
# Determinate line number and line content
set lineNum [lindex $line 0]
set fileNum [lindex $line 1]
set line [lindex $line 2]
# Spilt line into first 2 separate fields
if {![regexp {^\s*\.?\w+} $line field0]} {
set field0 {}
} else {
set field0 [string trim $field0]
}
if {![regexp {^\s*\.?\w+:?\s+\.?\w+} $line field1]} {
set field1 {}
} else {
regexp {\.?\w+$} $field1 field1
}
set field0_l [regsub {^\.} [string tolower $field0] {}]
set field1_l [regsub {^\.} [string tolower $field1] {}]
# Repeat macro
if {$field0_l == {rept} || $field0_l == {times}} {
if {$Macro} {
SyntaxError $lineNum $fileNum \
[mc "Cannot define macro inside another one -- macro processing failed"]
} else {
regsub {^\s*\.?\w+\s*} $line {} macro_params
set macro_params [ComputeExpr $macro_params]
if {$macro_params == {}} {
SyntaxError $lineNum $fileNum [mc "Missing number of repeats"]
set NoMacro 1
} elseif {$macro_params < 0} {
Warning $lineNum $fileNum [mc "Number of repeats is lower than zero"]
set NoMacro 1
} elseif {$macro_params == 0} {
Notice $lineNum $fileNum [mc "Zero number of repeats"]
set NoMacro 1
}
set macro_name ${idx}
set macro_name_to_append $macro_name
set macro($macro_name) {}
set Macro 1
set rept_macro 1
}
# Open macro definition
} elseif {$field1_l == {macro}} {
if {$Macro} {
SyntaxError $lineNum $fileNum \
[mc "Cannot define macro inside another one -- macro processing failed"]
} else {
# Determinate name and parameters
regsub {^\w+\s+\.?\w+\s*} $line {} macro_params
set macro_params [getOperands $macro_params 0]
set macro_name $field0_l
foreach parm $macro_params {
if {[isReservedKeyword $parm 1]} {
Warning $lineNum $fileNum [mc "Reserved keyword used as macro parameter: %s in macro %s" $parm $macro_name]
}
}
# Check for validity of the name
if {[isReservedKeyword $macro_name]} {
# Invalid name
SyntaxError $lineNum $fileNum [mc "Macro name is reserved keyword: %s" $macro_name]
set NoMacro 1
} else {
# Check for validity of the name (again, but invoke only warning this time)
if {[isReservedKeyword $macro_name 1]} {
# Invalid name
Warning $lineNum $fileNum [mc "Macro name is reserved keyword: %s" $macro_name]
set NoMacro 1
}
# Valid name
if {[lsearch -exact -ascii $defined_MACRO $macro_name] != -1} {
SyntaxError $lineNum $fileNum [mc "Macro `%s' is already defined" $macro_name]
set NoMacro 1
} else {
set macro_name_to_append $macro_name
set macro($macro_name) [list]
set local_M_labels($macro_name) [list 0]
}
set Macro 1
}
}
# Close macro definition
} elseif {$field0_l == {endm}} {
# No macro was opened
if {!$Macro} {
SyntaxError $lineNum $fileNum [mc "Unable to close macro, no macro is opened"]
# Close macro
} else {
if {$rept_macro} {
set line $macro($macro_name)
set macro($macro_name) [list]
set local_M_labels($macro_name) [list 0]
for {set i 0} {$i < $macro_params} {incr i} {
set macro($macro_name) [concat $macro($macro_name) $line]
}
set macro_params {}
set del_line 0
lappend tmp_asm [list $lineNum $fileNum $macro_name]
}
if {!$NoMacro} {
set macro($macro_name) [list $macro_params $macro($macro_name)]
regsub -all {\s+} $macro($macro_name) { } macro($macro_name)
regsub -all "\\\{ " $macro($macro_name) "\{" macro($macro_name)
lappend defined_MACRO $macro_name_to_append
}
}
# Reset some local variables
set Macro 0
set NoMacro 0
set rept_macro 0
# Directive takes no arguments
if {[string length $field1_l]} {
Warning $lineNum $fileNum [mc "Directive %s takes no arguments" [string toupper $field0_l]]
}
# Regular line
} else {
# Part of macro definition
if {$Macro} {
# Register local label in the macro
if {$field0_l == {local}} {
if {[regexp {^\w+$} $field1_l]} {
lappend local_M_labels($macro_name) $field1_l
} else {
SyntaxError $lineNum $fileNum [mc "Invalid label specification: ``%s''" $field0_l]
}
# Append the line to the currenly opened macro
} else {
if {!$NoMacro} {
lappend macro($macro_name) $line
}
}
# Common line
} else {
if {$field0_l == {macro}} {
SyntaxError $lineNum $fileNum [mc "Missing name of macro"]
} elseif {[regexp {^\s*\w+:} $line] && ($field1_l == {endm})} {
SyntaxError $lineNum $fileNum [mc "Labels are not allowed before directives ENDM"]
} else {
lappend tmp_asm [list $lineNum $fileNum $line]
}
set del_line 0
}
}
# Remove the current line
if {$del_line} {
CodeListing::delete_line $idx
incr idx -1
}
}
# Replace old code with the new one
set asm $tmp_asm
}
## Evaluate and remove inclusion directives
# @parm String dir - path to the current working directory
# @return Bool - code included
proc include_directive {dir} {
variable included_files ;# List: Unique unsorted list of included files
variable asm ;# Resulting pre-compiled code
variable tmp_asm ;# Temporary auxiliary pre-compiled code
variable lineNum ;# Number of the current line
variable fileNum ;# Number of the current file
variable idx ;# Current position in asm list
# Reset NS variables
set tmp_asm {}
# Local variables
set repeat 0 ;# Flag "code included"
# Iterate over the code
set asm_len [llength $asm]
for {set idx 0} {$idx < $asm_len} {incr idx} {
set line [lindex $asm $idx]
set line_org $line
# Update after each 25 iterations
if {[expr {$idx % 25}] == 0} {
${::Compiler::Settings::UPDATE_COMMAND}
}
if {${::Compiler::Settings::ABORT_VARIABLE}} {
${::Compiler::Settings::TEXT_OUPUT_COMMAND} [mc "Aborted"]
free_resources
return
}
set file {} ;# File to include
set lineNum [lindex $line 0] ;# Number of the current line
set fileNum [lindex $line 1] ;# Number of the current file
set line [lindex $line 2] ;# Code of the current line
# Remove comment
regsub {\s*;.*$} $line {} line
# Determinate label
if {[regexp {^\s*\w+:} $line label]} {
regsub {^\s*\w+:\s*} $line {} line
set label [string trimleft $label " \t"]
set label [string trimright $label " \t"]
} else {
set label {}
}
# Determinate directive
if {![regexp {^\s*\.?\w+} $line directive]} {
set directive {}
} else {
set directive [string trim $directive]
}
set directive_l [string tolower $directive]
# Directive 'INCLUDE file'
if {[regsub {^\.} $directive_l {}] == {include}} {
regsub {^\s*\.?\w+} $line {} file_name
regsub {^\s+} $file_name {} file_name
if {![string length $file_name]} {
SyntaxError $lineNum $fileNum [mc "Missing file name"]
}
set asm [lreplace $asm $idx $idx [list $lineNum $fileNum $label]]
# Control sequence '$INCLUDE(file)'
} elseif {[regexp -nocase -- {^[\s ]*\$inc(lude)?[\s ]*\([^\(\)]*\)} $line file_name]} {
set file_name [regsub -nocase -- {^[\s ]*\$include[\s ]*} $file_name {}]
set file_name [string range $file_name 1 end-1]
if {![string length $file_name]} {
SyntaxError $lineNum $fileNum [mc "Missing file name"]
}
set asm [lreplace $asm $idx $idx [list $lineNum $fileNum $label]]
# Nothing interesting
} else {
set file_name {}
}
# Read file if any
if {$file_name != {}} {
# Determinate final file name
set file_name [regsub -all "\\\\\"" [string trim $file_name] "\""]
if {
([string index $file_name 0] == "\"" && [string index $file_name end] == "\"")
||
([string index $file_name 0] == {'} && [string index $file_name end] == {'})
} then {
set file_name [string range $file_name 1 end-1]
}
set file_name [string trim $file_name]
set file_name [file normalize [file join $dir $file_name]]
# Determinate file number
set file_number [lsearch -ascii -exact $included_files $file_name]
if {$file_number == -1} {
set file_number [llength $included_files]
lappend included_files $file_name
}
# Read file and adjust $asm
set file [getFile $dir $file_name $file_number]
}
# File is not empty
if {[string length $file]} {
set repeat 1
CodeListing::include $idx [concat [list $line_org] $file]
set idx_plus_1 [expr {$idx + 1}]
if {$idx_plus_1 >= $asm_len} {
lappend CodeListing::sync_map {}
lappend asm [list $lineNum $fileNum {}]
}
set tmp_asm [lrange $asm $idx_plus_1 end]
set asm [lreplace $asm $idx_plus_1 end]
append asm { }
append asm $file
append asm { }
append asm $tmp_asm
set file_len [llength $file]
incr asm_len $file_len
incr idx $file_len
}
}
# Return flag "code included"
return $repeat
}
## Get content of the specified file
# @parm String dir - Current working directory
# @parm String file - Name of file to include
# @parm Int file_number - Index in $included_files
# @return Bool - content of the file
proc getFile {dir file file_number} {
variable fileNum ;# Number of the current file
variable lineNum ;# Number of the current line
variable tmp_asm ;# Temporary auxiliary pre-compiled code
set tmp_asm {}
# File name enclosed by quotes
if {[string index $file 0] == {'}} {
if {[string index $file end] != {'}} {
SyntaxError $lineNum $fileNum [mc "Invalid expression: `%s'" $file]
} else {
set file [string range $file 1 {end-1}]
}
} elseif {[string index $file 0] == "\""} {
if {[string index $file end] != "\""} {
SyntaxError $lineNum $fileNum [mc "Invalid expression: `%s'" $file]
} else {
set file [string range $file 1 {end-1}]
}
}
# File exists
if {[file exists $file]} {
if {[catch {
set file [open $file r]
set data [read $file]
close $file
}]} then {
CompilationError $lineNum $fileNum [mc "Unable to open file: %s" $file]
return {}
} else {
# Any EOL to LF
regsub -all {\r\n?} $data "\n" data
# Adjust file content
set line_number 1
foreach line [split $data "\n"] {
lappend tmp_asm [list $line_number $file_number $line]
incr line_number
}
return $tmp_asm
}
# File does not exist
} else {
CompilationError $lineNum $fileNum [mc "File not found: %s" $file]
return {}
}
}
## Parse and remove directive(s) 'END'
# @return void
proc end_of_code {} {
variable asm ;# Resulting pre-compiled code
variable lineNum ;# Number of the current line
variable fileNum ;# Number of the current file
variable idx ;# Current position in asm list
# Reset NS variables
set idx -1
# Local variables
set end 0
set last_line {}
# Iterate over the code
foreach line $asm {
incr idx
# Update after each 25 iterations
if {[expr {$idx % 25}] == 0} {
${::Compiler::Settings::UPDATE_COMMAND}
}
if {${::Compiler::Settings::ABORT_VARIABLE}} {
${::Compiler::Settings::TEXT_OUPUT_COMMAND} [mc "Aborted"]
free_resources
return
}
# Determinate line number and line content
set lineNum [lindex $line 0]
set fileNum [lindex $line 1]
set line [lindex $line 2]
# Skip lines without word 'END'
if {![regexp -nocase {end} $line]} {
continue
}
regsub {\s*;.*$} $line {} line
regsub -all {:} $line {: } line
# Determinate 1st and 2nd field of the line
if {![regexp {^\s*[^\s]+} $line field0]} {
set field0 {}
} else {
set field0 [string trim $field0]
}
if {![regexp {^\s*[^\s]+\s+[^\s]+} $line field1]} {
set field1 {}
} else {
regexp {[^\s]+$} $field1 field1
}
set field0 [string tolower [regsub {^\.} $field0 {}]]
set field1 [string tolower [regsub {^\.} $field1 {}]]
# Directive 'end' detected in the 1st field
if {$field0 == {end}} {
set end 1
break
# Directive 'end' and some label
} elseif {
[regexp {^\w+:$} $field0]
&&
($field1 == {end})
} then {
# Determinate content of the last line of the code (that label)
if {![regexp {^\w+:$} $field0 last_line]} {
set last_line {}
}
# Check if the line does not contain anything except the label and 'END'
regsub {^\s*\w+:\s*} $line {} line
set line [string tolower $line]
if {$line != {end}} {
SyntaxError $lineNum $fileNum [mc "Extra symbols after `END' directive"]
}
set end 1
break
}
}
# Directive 'end' detected -> adjust the code
if {$end} {
set asm [lreplace $asm $idx end]
set preserve_current_line 0
if {$last_line != {}} {
lappend asm [list $lineNum $fileNum $last_line]
set preserve_current_line 1
}
CodeListing::end_directive $idx $preserve_current_line
# Directive 'end' not found -> invoke warning
} else {
Warning 0 0 [mc "Missing `END' directive"]
}
}
## Parse and remove directive(s) 'ORG' and reorganize the current code
# @return void
proc origin_directive {} {
variable asm ;# Resulting pre-compiled code
variable tmp_asm ;# Temporary auxiliary pre-compiled code
variable lineNum ;# Number of the current line
variable fileNum ;# Number of the current file
variable idx ;# Current position in asm list
variable defined_LABEL ;# List of defined labels
variable labels ;# Array: Values of defined labels ($labels($label) == $address)
variable ErrorAtLine ;# Bool: Error occurred on the current line
variable origin_d_addr ;# List: Addresses of static program blocks
# Reset NS variables
set tmp_asm {}
set idx -1
set origin_d_addr {}
## Map of program memory organization
# {
# {lineNumber fileNumber address}
# ...
# }
set organization {}
# Create code organization map and remove lines containing directive 'ORG'
set last_value 0
foreach line $asm {
incr idx
set ErrorAtLine 0
# Update after each 25 iterations
if {[expr {$idx % 25}] == 0} {
${::Compiler::Settings::UPDATE_COMMAND}
}
if {${::Compiler::Settings::ABORT_VARIABLE}} {
${::Compiler::Settings::TEXT_OUPUT_COMMAND} [mc "Aborted"]
free_resources
return
}
# Determinate line number and line content
set lineNum [lindex $line 0]
set fileNum [lindex $line 1]
set line [lindex $line 2]
# Skip lines without word 'ORG'
if {![regexp -nocase {\.?org} $line]} {
lappend tmp_asm [list $lineNum $fileNum $line]
continue
}
# Determinate label
if {![regexp {^\w+:} $line label]} {
set label {}
}
# Remove label from the line
regsub {^\w+:} $line {} line
set line [string tolower $line]
# Directive ORG detected
if {![regexp {^\s*\.?\w+} $line field0]} {
set field0 {}
} else {
set field0 [string trim $field0]
}
if {[regsub {^\.} $field0 {}] == {org}} {
# Determinate argument
set line [lreplace $line 0 0]
set value {}
set error 0
if {$line == {}} {
SyntaxError $lineNum $fileNum [mc "Missing address"]
set error 1
} else {
set value [ComputeExpr $line]
}
# Adjust label and check if it is not already defined
if {$label != {}} {
set label [string trimright $label {:}]
if {[regexp {^[a-zA-Z]\w*$} $label]} {
if {[lsearch -exact -ascii $defined_LABEL $label] != -1} {
SyntaxError $lineNum $fileNum [mc "Label already defined: `%s'" $label]
set error 1
}
} else {
SyntaxError $lineNum $fileNum [mc "Invalid label: `%s'" $label]
set error 1
}
}
# Empty argument -> error
if {!$error && $value == {}} {
SyntaxError $lineNum $fileNum [mc "Invalid expression `%s'" $line]
set error 1
}
# Skip lines containing error
if {$error} {continue}
# Define the label
if {$label != {}} {
lappend defined_LABEL $label
set labels($label) $value
}
# Adjust the code and organization map
lappend tmp_asm [list $lineNum $fileNum [list {ORG} $value]]
lappend organization [list $lineNum $fileNum $value]
if {$last_value > $value} {
Warning $lineNum $fileNum [mc "This ORG has lower value than the previous one"]
}
set last_value $value
# Directive ORG wasn't detected
} else {
lappend tmp_asm [list $lineNum $fileNum $line]
}
}
# Replace old code with the new one
set asm $tmp_asm
# Empty organization map -> abort
if {$organization == {}} {return}
## Convert map of program organization to this form:
# {
# {lineNumber_start fileNum_start lineNumber_end fileNum_end address}
# ...
# }
# Sort organization map by start line
set organization [lsort -index 0 -integer $organization]
set last_line {} ;# Last line number
set last_file {} ;# Last file number
set last_addr {} ;# Last address or origin
set new_organization {} ;# New organization map
# Reformat organization map
foreach org $organization {
set line [lindex $org 0] ;# Line number
set file [lindex $org 1] ;# File number
set addr [lindex $org 2] ;# Address or origin
# Adjust new organization map
if {$last_line != {}} {
incr line -1
lappend new_organization [list $last_line $last_file $line $file $last_addr]
incr line
}
set last_line $line ;# Last line number
set last_file $file ;# Last file number
set last_addr $addr ;# Last address or origin
}
lappend new_organization [list $last_line $last_file [lindex $asm {end 0}] [lindex $asm {end 1}] $addr]
# Sort organization map by address
set organization [lsort -index 4 -integer $new_organization]
## Reassemble the code
set tmp_asm {}
set new_organization {}
foreach org $organization {
set start [lineNum2idx [lindex $org 0] [lindex $org 1] 1] ;# Line of the start
set end [lineNum2idx [lindex $org 2] [lindex $org 3] 0] ;# Line of the end
lappend origin_d_addr [lindex $org 4]
lappend new_organization [list $start $end]
append tmp_asm { }
append tmp_asm [lrange $asm $start $end]
set asm [lreplace $asm $start $end]
}
if {$asm != {}} {
append tmp_asm { }
append tmp_asm $asm
}
set asm $tmp_asm
# Adjust code listing
CodeListing::org $new_organization
}
## Convert pair line number and file number to index in the code list
# @parm Int line_number - line number
# @parm Int file_number - file number
# @parm Bool first - match the first
# @return Int - list index
proc lineNum2idx {line_number file_number first} {
variable asm ;# Resulting pre-compiled code
set idx -1
set ln 0
foreach line $asm {
incr idx
if {[lindex $line 1] != $file_number} {
continue
}
set ln [lindex $line 0]
if {($first && ($ln >= $line_number)) || (!$first && ($ln > $line_number))} {
if {$ln > $line_number} {
incr idx -1
}
if {$idx < 0} {
return 0
} else {
return $idx
}
}
}
set len [llength $asm]
incr len -1
return $len
}
## Convert the current code into numbered list (see proc. 'compile')
# @return void
proc line_numbers {} {
variable asm ;# Resulting pre-compiled code
variable tmp_asm ;# Temporary auxiliary pre-compiled code
variable lineNum ;# Number of the current line
variable fileNum ;# Number of the current file
# Reset NS variables
set tmp_asm {}
set lineNum 0
set idx -1
# Adjust some special characters
regsub -all {\r\n?} $asm "\n" asm
regsub -all {\\} $asm "\\\\" asm
regsub -all {\{} $asm "\\\{" asm
regsub -all {\}} $asm "\\\}" asm
regsub -all {\"} $asm "\\\"" asm
# Create new code list
foreach line [split $asm "\n"] {
incr idx
incr lineNum
# Update after each 25 iterations
if {[expr {$idx % 25}] == 0} {
${::Compiler::Settings::UPDATE_COMMAND}
}
if {${::Compiler::Settings::ABORT_VARIABLE}} {
${::Compiler::Settings::TEXT_OUPUT_COMMAND} [mc "Aborted"]
free_resources
return
}
# Append adjusted line to the code
lappend tmp_asm [list $lineNum 0 $line]
}
# Replace old code with the new one
set asm $tmp_asm
# Create code listing
CodeListing::create_listing $asm
}
## Evaluate and remove directives related to:
# - Conditional compilation (IF, ELSE, ENDIF) (group 0)
# - Code listing enable/disable (LIST, NOLIST) (group 1)
# - Active bank selection (USING) (group 2)
# - Data memory segment selection (BSEG, DSEG, ISEG, XSEG) (group 3)
# - Constant definitions (SET, EQU, BIT, DATA, IDATA, XDATA) (group 4)
# - Data memory reservation (DS, DBIT) (group 5)
# @parm List on 6 Bools - Groups to parse
# @parm Bool ignore_undefined - Ignore undefined symbolic names
# @return Bool - Anything expanded
proc parse_Consts_and_ConditionalCompilation {groups ignore_undefined} {
variable asm ;# Resulting pre-compiled code
variable tmp_asm ;# Temporary auxiliary pre-compiled code
variable ErrorAtLine ;# Bool: Error occurred on the current line
variable lineNum ;# Number of the current line
variable fileNum ;# Number of the current file
variable idx ;# Current position in asm list
variable Enable ;# Bool: Compilation enabled (conditional compilation)
variable memory_reservation_map ;# Array: memory reservation map (see code)
variable defined_SET ;# List of variables defined by 'SET'
variable const_SET ;# Array: Constants defined by directive 'CODE'
variable selected_segment ;# Current memory segment (one of {cseg bseg dseg iseg xseg})
variable segment_pointer ;# Current memory segment pointer
# Reset NS variables
set idx -1
set tmp_asm {}
set Enable 1
# Local variables
set deleteLine 1 ;# Remove the current line
set fin_result 0 ;# Anything expanded
set loc_result 0
# Iterate over the code
foreach line $asm {
incr idx
# Final stage -- skip lines without constant definition
if {[llength $line] != 3 && [lindex $line 2] != {C}} {
lappend tmp_asm $line
continue
}
# Update after each 25 iterations
if {[expr {$idx % 25}] == 0} {
${::Compiler::Settings::UPDATE_COMMAND}
}
if {${::Compiler::Settings::ABORT_VARIABLE}} {
${::Compiler::Settings::TEXT_OUPUT_COMMAND} [mc "Aborted"]
free_resources
return $fin_result
}
## Determinate line number and line content
set lineNum [lindex $line 0]
set fileNum [lindex $line 1]
# Firts level pass
if {[llength $line] == 3} {
set line [lindex $line 2]
regsub -nocase -- {if\(} $line {if (} line ;# Make construction "IF(something)" valid
# Final level pass
} else {
set line [lindex $line 3]
}
set ErrorAtLine 0 ;# Reset last error
set deleteLine 1 ;# Remove the current error
# Determinate 1st field of the line
if {![regexp {^\s*\.?\w+:?} $line line_first_field]} {
set line_first_field {}
} else {
set line_first_field [string trim $line_first_field]
}
set directive0 [string tolower $line_first_field]
set directive0 [regsub {^\.} $directive0 {}]
# Determinate 2nd field of the line
if {![regexp {^\s*\.?\w+:?\s*\.?\w+} $line directive1]} {
set directive1 {}
} else {
regsub {^\s*\.?\w+:?\s*} $directive1 {} directive1
set directive1 [string trim $directive1]
}
set directive1 [string tolower $directive1]
set directive1 [regsub {^\.} $directive1 {}]
set label {}
# Constant definition (SET EQU BIT ...) without constant to define (syntax error)
if {
[lindex $groups 4] && $Enable &&
([lsearch -exact -ascii ${::CompilerConsts::ConstDefinitionDirectives} $directive0] != -1)
} then {
if {[regexp {^\s*\.?\w+\s+\w+\s*\,\s*.+$} $line]} {
Warning $lineNum $fileNum [mc "This formulation is deprecated, consider usage of \"<Const> <Directive> <Value>\" instead"]
set line_expr {}
regsub {^\s*\.?\w+\s+\w+\s*\,\s*} $line {} line_expr
set line_aux $directive1
append line_aux { } $directive0 { } $line_expr
set loc_result [define_const $directive0 $line_aux $idx $ignore_undefined]
if {$loc_result == 2} {
lappend tmp_asm [list $lineNum $fileNum $line]
set deleteLine 0
} elseif {$loc_result == 0} {
set fin_result 1
}
} else {
SyntaxError $lineNum $fileNum [mc "Missing name of constant to define"]
}
# Constant definition (SET EQU BIT ...)
} elseif {
[lindex $groups 4] && $Enable &&
([lsearch -exact -ascii ${::CompilerConsts::ConstDefinitionDirectives} $directive1] != -1)
} then {
set loc_result [define_const $directive1 $line $idx $ignore_undefined]
if {$loc_result == 2} {
lappend tmp_asm [list $lineNum $fileNum $line]
set deleteLine 0
} elseif {$loc_result == 0} {
set fin_result 1
}
# Listing control (LIST, NOLIST)
} elseif {
[lindex $groups 1] && (
($directive0 == {list}) ||
($directive0 == {nolist}) ||
($directive1 == {list} && [regexp {^\w+:$} $directive0 label]) ||
($directive1 == {nolist} && [regexp {^\w+:$} $directive0 label])
)
} then {
# Warning messages
if {($directive0 == {list} || $directive0 == {nolist}) && [string length $directive1]} {
Warning $lineNum $fileNum [mc "Directive %s takes no arguments" [string toupper $directive0]]
} elseif {($directive1 == {list} || $directive1 == {nolist}) && [string length [regsub {^\s*\.?\w+:?\s+\.?\w+} $line {}]]} {
Warning $lineNum $fileNum [mc "Directive %s takes no arguments" [string toupper $directive1]]
}
if {($directive0 == {nolist}) || ($directive1 == {nolist})} {
CodeListing::directive_nolist $idx
} else {
CodeListing::directive_list $idx
}
if {($label != {}) && $Enable} {
lappend tmp_asm [list $lineNum $fileNum $label]
set deleteLine 0
}
# Active bank selection directive -- in 1st field (USING)
} elseif {[lindex $groups 2] && $Enable && ($directive0 == {using})} {
set loc_result [define_active_bank \
[regsub {^\.?\w+\s*} $line {}] $ignore_undefined \
]
if {$loc_result == 2} {
lappend tmp_asm [list $lineNum $fileNum $line]
set deleteLine 0
} elseif {$loc_result == 0} {
set fin_result 1
}
# Active bank selection directive -- in 2nd field (USING)
} elseif {
[lindex $groups 2] && ($directive1 == {using}) && $Enable
&&
([regexp {^\w+:$} $directive0 label])
} then {
set loc_result [define_active_bank \
[regsub {^\w+:\s*\.?\w+\s*} $line {}] $ignore_undefined \
]
set deleteLine 0
if {$loc_result == 2} {
lappend tmp_asm [list $lineNum $fileNum $line]
} elseif {$loc_result == 0} {
lappend tmp_asm [list $lineNum $fileNum $label]
set fin_result 1
} else {
lappend tmp_asm [list $lineNum $fileNum $label]
}
# Data segment selection (XSEG DSEG ...)
} elseif {
[lindex $groups 3] && $Enable &&
([lsearch -exact -ascii ${::CompilerConsts::ConstDataSegmentSelectionDirectives} $directive0] != -1)
} then {
set loc_result [data_segment_selection \
$directive0 $directive1 $line $idx $ignore_undefined \
]
if {$loc_result == 2} {
lappend tmp_asm [list $lineNum $fileNum $line]
set deleteLine 0
} elseif {$loc_result == 0} {
set fin_result 1
}
# ORG in other than CODE segment
} elseif {
$directive0 == {org} || $directive1 == {org}
} then {
if {$selected_segment != {cseg}} {
regsub {org} $line "$selected_segment at" line
set address {}
if {$directive0 == {org}} {
set address [ComputeExpr $directive1]
} elseif {$directive1 == {org}} {
set address [ComputeExpr [regsub {^\w+:\s*\.?\w+\s*} $line {}]]
}
if {$address != {}} {
set segment_pointer($selected_segment) $address
}
}
lappend tmp_asm [list $lineNum $fileNum $line]
set deleteLine 0
# Data memory reservation -- without label (DBIT 125)
} elseif {
[lindex $groups 5] && $Enable &&
([lsearch -exact -ascii ${::CompilerConsts::ConstDataMemoryReservationDirectives} $directive0] != -1)
} then {
regsub {^\.?\w+\s*} $line {} value
set loc_result [data_memory_reservation {} $directive0 $value $idx $ignore_undefined]
if {$loc_result == 2} {
lappend tmp_asm [list $lineNum $fileNum $line]
set deleteLine 0
} elseif {$loc_result == 0} {
set fin_result 1
}
# Data memory reservation -- with label (ram: DS 4Fh)
} elseif {
[lindex $groups 5] && [regexp {^\w+:$} $line_first_field] && $Enable
&&
([lsearch -exact -ascii ${::CompilerConsts::ConstDataMemoryReservationDirectives} $directive1] != -1)
} then {
regsub {^\s*\w+:\s*\.?\w+\s*} $line {} value
set loc_result [data_memory_reservation \
$line_first_field $directive1 $value $idx $ignore_undefined \
]
if {$loc_result == 2} {
lappend tmp_asm [list $lineNum $fileNum $line]
set deleteLine 0
} elseif {$loc_result == 0} {
set fin_result 1
}
# Conditional compilation statement -- in 2nd field (IF ELSE ENDIF IFNDEF IFDEF IFN ELSEIF ELSEIFN ELSEIFDEF ELSEIFNDEF)
} elseif {
[lindex $groups 0] && (
[lsearch -ascii -exact {if else endif ifndef ifdef ifn elseif elseifn elseifdef elseifndef} $directive1] != -1
) && (
[regexp {^\w+:$} $line_first_field label]
)
} then {
# Is compilation enabled ?
if {$Enable} {
lappend tmp_asm [list $lineNum $fileNum $label]
set deleteLine 0
}
regsub {^\w+:\s*\.?\w+\s*} $line {} value
If_Else_Endif $directive1 $value
# Directive takes no arguments
if {($directive1 == {else} || $directive1 == {endif}) && [string length $value]} {
Warning $lineNum $fileNum [mc "Directive %s takes no arguments" [string toupper $directive1]]
}
} else {
# Conditional compilation statement -- in 1st field (IF ELSE ENDIF IFNDEF IFDEF IFN ELSEIFN ELSEIFDEF ELSEIFNDEF)
if {
[lindex $groups 0] && (
[lsearch -ascii -exact {if else endif ifndef ifdef ifn elseif elseifn elseifdef elseifndef} $directive0] != -1
)
} then {
regsub {^\.?\w+\s*} $line {} value
# Directive takes no arguments
if {($directive1 == {else} || $directive1 == {endif}) && [string length $value]} {
Warning $lineNum $fileNum [mc "Directive %s takes no arguments" [string toupper $directive0]]
}
If_Else_Endif $directive0 $value
} else {
# Is compilation enabled ?
if {$Enable} {
lappend tmp_asm [list $lineNum $fileNum $line]
set deleteLine 0
if {$directive0 == {cseg} || $directive1 == {cseg}} {
set selected_segment {cseg}
}
}
}
}
if {$deleteLine} {
CodeListing::delete_line $idx
incr idx -1
}
}
# Sort list of SET variables by line numbers
foreach const $defined_SET {
set const_SET($const) [lsort -integer -index 0 $const_SET($const)]
}
# Replace old code with the new one
set asm $tmp_asm
return $fin_result
}
## Set active register bank
# @parm String expr - expression defining bank number
# @parm Bool ignore_undefined - Ignore undefined symbolic names in declaration
# @return Bool - 0 == Resolved; 1 == Unresolved (discard line); 2 == Unresolved (keep line)
proc define_active_bank {expr ignore_undefined} {
variable lineNum ;# Number of the current line
variable fileNum ;# Number of the current file
# Expression must not be empty
if {$expr == {}} {
SyntaxError $lineNum $fileNum [mc "Empty expression"]
return 1
}
# Determinate expression value
set value [ComputeExpr $expr $ignore_undefined]
if {$value == {}} {
if {$ignore_undefined} {
return 2
}
SyntaxError $lineNum $fileNum [mc "Invalid expression: `%s'" $expr]
return 1
}
# Check for value validity
if {($value > 3) || ($value < 0)} {
SyntaxError $lineNum $fileNum [mc "Argument value is out of range ({0 1 2 3}) : `%s'" $value]
return 1
}
# Define variables AR0..7
set value [expr {$value * 8}]
for {set i 0} {$i < 8} {incr i} {
define_variable "ar$i" $value 0
incr value
}
return 0
}
## Reserve space in data memory
# --auxiliary procedure for 'parse_Consts_and_ConditionalCompilation'
# @parm String label - Label
# @parm String directive - Directive
# @parm String expr - Directive argument
# @parm Int idx - Current index in the code list
# @parm Bool ignore_undefined - Ignore undefined symbolic names in declaration
# @return Bool - 0 == Resolved; 1 == Unresolved (discard line); 2 == Unresolved (keep line)
proc data_memory_reservation {label directive expr idx ignore_undefined} {
variable lineNum ;# Number of the current line
variable fileNum ;# Number of the current file
variable selected_segment ;# Current memory segment (one of {cseg bseg dseg iseg xseg})
# Compute expression value
if {![string length $expr]} {
SyntaxError $lineNum $fileNum [mc "Missing size"]
set value 1
} else {
set value [ComputeExpr $expr $ignore_undefined]
}
# Check for value validity
if {$value == {}} {
if {$ignore_undefined} {
return 2
}
SyntaxError $lineNum $fileNum [mc "Invalid expression `%s'" $expr]
return 1
} elseif {$value < 0} {
SyntaxError $lineNum $fileNum [mc "Length of data area cannot be negative number: %s" $value]
return 1
}
# Adjust label
set label [string tolower $label]
# Reserve bit
if {$directive == {dbit}} {
# Check if the active segment is (BSEG)
if {$selected_segment != {bseg}} {
Warning $lineNum $fileNum [mc "Using `DBIT' directive, but active segment is `%s' (should be BSEG)" [string toupper $selected_segment]]
}
# Reserve memory
return [reserve_memory $label bseg $value $idx]
# Reserve byte
} elseif {$directive == {ds}} {
# Check if the active segment is one of {DSEG ISEG XSEG}
if {
($selected_segment != {dseg}) &&
($selected_segment != {iseg}) &&
($selected_segment != {xseg})
} then {
Warning $lineNum $fileNum [mc "Using `%s' directive, but currently active segment is `%s'" [string toupper $directive] [string toupper $selected_segment]]
set seg {dseg}
} else {
set seg $selected_segment
}
# Reserve memory
return [reserve_memory $label $seg $value $idx]
# Unknown request -> compilation error
} else {
CompilationError $lineNum $fileNum "Unknown error 4"
return 1
}
return 0
}
## Reserve bits or bytes of data memory
# --auxiliary procedure for 'data_memory_reservation'
# @parm String label - Symbolic name
# @parm String segment - Target memory segment (one of {dseg iseg xseg bseg})
# @parm Int value - Number of bits/bytes to reserve
# @parm Int idx - Current index in the code list
# @return Bool - 0 == Resolved; 1 == Unresolved
proc reserve_memory {label segment value idx} {
variable lineNum ;# Number of the current line
variable fileNum ;# Number of the current file
variable segment_pointer ;# Current memory segment pointer
variable memory_reservation_map ;# Array: memory reservation map (see code)
variable const_BIT ;# Array: Bit values -- ($const_BIT($bit_name) == $value)
variable const_DATA ;# Array: Constants defined by directive 'DATA'
variable const_IDATA ;# Array: Constants defined by directive 'IDATA'
variable const_XDATA ;# Array: Constants defined by directive 'XDATA'
variable defined_BIT ;# List of defined bits (directove 'BIT')
variable defined_DATA ;# List of constants defined by 'DATA'
variable defined_IDATA ;# List of constants defined by 'IDATA'
variable defined_XDATA ;# List of constants defined by 'XDATA'
## Determinate these things:
# - Type of the defined constant :: const_type
# - Recomended maximum :: recomended_max
# - Name of the target memory segment :: segment_name
# - Maximum value :: max
# - Unit (Bytes or Bits) :: Bytes
switch -- $segment {
{dseg} { ;# General data memory
set const_type {DATA}
set recomended_max 235
set segment_name {general data memory}
set area_name {byte}
set max 255
set unit {Bytes}
}
{iseg} { ;# Internal data memory
set const_type {IDATA}
set recomended_max 235
set segment_name {internal data memory}
set area_name {byte}
set max 255
set unit {Bytes}
}
{xseg} { ;# External data memory
set const_type {XDATA}
set recomended_max 60000
set segment_name {external data memory}
set area_name {byte}
set max 65535
set unit {Bytes}
}
{bseg} { ;# Bit addressable area
set const_type {BIT}
set recomended_max 117
set segment_name {bit}
set area_name {bit addressable}
set max 127
set unit {bites}
}
default { ;# Fatal error
CompilationError $lineNum $fileNum "Unknown error 5"
}
}
# Check if there is enough free space in the segment
set end [expr {$segment_pointer($segment) + $value}]
if {$end > $max} {
Warning $lineNum $fileNum [mc "Exceeding %s segment boundary by %s $unit." $segment_name [expr {$max - $end}]]
} elseif {$end > $recomended_max} {
Notice $lineNum $fileNum [mc "Nearing %s segment boundary" $segment_name]
}
# Check if the requested area if not already reserved
set area [string range $memory_reservation_map($segment) $segment_pointer($segment) $end]
if {[string first 1 $area] != -1} {
set idx 0
set overflow {}
foreach bit [split $area {}] {
if {$bit} {
lappend overwrite [expr {$idx + $segment_pointer($segment)}]
}
incr idx
}
set overwrite_dec_hex {}
foreach val $overwrite {
set val [format %X $val]
if {[string length $val] < 4} {
set val "[string repeat 0 [expr {4 - [string length $val]}]]$val"
}
append overwrite_dec_hex { 0x} $val
}
Warning $lineNum $fileNum [mc "Overwriting reserved memory -- in %s area at addresses: %s" $area_name $overwrite_dec_hex]
}
# Adjust map of reserved memory
set memory_reservation_map($segment) \
[string replace $memory_reservation_map($segment) \
$segment_pointer($segment) $end [string repeat 1 $value] \
]
# Abort if there is no label
if {$label == {}} {return}
# Check for label validity
if {![regexp {^[a-zA-Z_]\w*:$} $label]} {
SyntaxError $lineNum $fileNum [mc "Invalid label: `%s'" $label]
return 1
}
# Determinate name of the constant
set const [string trimright $label {:}]
# Assing block pointer to symbolic name specified by label
if {[lsearch -exact -ascii [subst -nocommands "\$defined_$const_type"] $const] != -1} {
SyntaxError $lineNum $fileNum [mc "Unable redefine constant: %s" $const]
return 1
} else {
# Check if this symbol is not already defined
if {[isConstAlreadyDefined $const]} {
Warning $lineNum $fileNum [mc "Ambiguous symbol definition: %s" $const]
}
# Adjust code listing
CodeListing::set_addr $idx $segment_pointer($segment)
# Define the symbolic name
set const_${const_type}($const) $segment_pointer($segment)
lappend defined_${const_type} $const
# Adjust segment pointer
incr segment_pointer($segment) $value
}
return 0
}
## Determinate whether the given symbolic name is aleady defined
# @parm String const_name - Symbolic name to evaluate
# @return Bool - result (1 == aleady defined; 0 == not defined yet)
proc isConstAlreadyDefined {const_name} {
variable defined_BIT ;# List of defined bits (directove 'BIT')
variable defined_CODE ;# List of constants defined by 'CODE'
variable defined_DATA ;# List of constants defined by 'DATA'
variable defined_IDATA ;# List of constants defined by 'IDATA'
variable defined_XDATA ;# List of constants defined by 'XDATA'
variable defined_SET ;# List of variables defined by 'SET'
variable defined_EQU ;# List of constants defined by 'EQU'
variable defined_MACRO ;# List of defined macro instructions
variable defined_SET_SPEC ;# List of special variables defined by 'SET'
variable defined_EQU_SPEC ;# List of special constants defined by 'EQU'
# Adjust symbolic name
set const_name [string tolower $const_name]
# Search all lists of symbolic names
if {
[lsearch -exact -ascii [concat \
$defined_BIT $defined_CODE $defined_DATA \
$defined_IDATA $defined_XDATA $defined_SET \
$defined_EQU $defined_MACRO $defined_SET_SPEC \
$defined_EQU_SPEC \
${::CompilerConsts::defined_progVectors} \
${::CompilerConsts::defined_SFRBitArea} \
${::CompilerConsts::defined_SFR} \
] $const_name] != -1
} then {
return 1
}
return 0
}
## Change selected data memory segment
# --auxiliary procedure for proc. 'parse_Consts_and_ConditionalCompilation'
# @parm String directive - Directive of segment selection
# @parm String operator - Operator (should be 'AT')
# @parm String line - Code of the current line
# @parm Int idx - Current index in the code list
# @parm Bool ignore_undefined - Ignore undefined symbolic names in declaration
# @return Bool - 0 == Resolved; 1 == Unresolved (discard line); 2 == Unresolved (keep line)
proc data_segment_selection {directive operator line idx ignore_undefined} {
variable lineNum ;# Number of the current line
variable fileNum ;# Number of the current file
variable selected_segment ;# Current memory segment (one of {cseg bseg dseg iseg xseg})
variable segment_pointer ;# Current memory segment pointer
# Change memory segment
set selected_segment $directive
if {[regsub {^\.} [string tolower $line] {}] == $directive} {
return 0
}
# Check for operator validity
if {$operator != {at}} {
SyntaxError $lineNum $fileNum [mc "Unknown operator: `%s', should be `%s at <address>', e.g. `%s at X+0FFh'" $operator $directive $directive]
return 1
}
# Determinate and evaluate expression
regsub {^\.?\w+\s+\w+\s*} $line {} expr
set value [ComputeExpr $expr $ignore_undefined]
if {$value == {}} {
if {$ignore_undefined} {
return 2
}
SyntaxError $lineNum $fileNum [mc "Invalid expression `%s'" $expr]
return 1
}
# Determinate maximum value of the segment pointer
switch -- $selected_segment {
{bseg} {set max 127}
{dseg} {set max 255}
{iseg} {set max 255}
{xseg} {set max 65535}
default {
return 1
CompilationError $lineNum $fileNum "Unknown error 6"
}
}
# Check for valid pointer value
if {$value > $max} {
SyntaxError $lineNum $fileNum [mc "Segment pointer is too high: %s / %s" $value $max]
} elseif {$value < 0} {
SyntaxError $lineNum $fileNum [mc "Segment pointer cannot be negative: `%s'" $value]
} else {
set segment_pointer($selected_segment) $value
CodeListing::set_addr $idx $value
if {$ignore_undefined} {
return 2
} else {
return 0
}
}
return 1
}
## Take care of conditional compilation control directives (IF, ELSE, ENDIF, IFN, IFDEF, IFNDEF, ELSEIF ELSEIFN ELSEIFDEF ELSEIFNDEF)
# --auxiliary procedure for 'parse_Consts_and_ConditionalCompilation'
# @parm String directive - Directive
# @parm String cond - Expression of the condition
# @return void
proc If_Else_Endif {directive cond} {
variable lineNum ;# Number of the current line
variable fileNum ;# Number of the current file
variable IfElse_map ;# Array: Conditional compilation map ($IfElse_map($level) == $bool)
variable IfElse_pcam ;# Array: Conditional compilation -- Positive condition already met ($IfElse_pcam($level) == $bool)
variable IfElse_level ;# Current level of conditional compilation evaluation
variable Enable ;# Bool: Compilation enabled (conditional compilation)
set cond_orig $cond
switch -- $directive {
{if} {
# Missing condition expression
if {![string length $cond]} {
SyntaxError $lineNum $fileNum [mc "Missing condition"]
set cond 1
}
# Evaluate the condition expression
if {$Enable} {
set cond [ComputeExpr $cond]
if {$cond == {}} {
SyntaxError $lineNum $fileNum [mc "Invalid expression `%s'" $cond_orig]
set cond 1
}
} else {
set cond 0
}
# Increment counter of nested block level
incr IfElse_level
# Adjust map of conditional compilation map and flag "Enable"
set IfElse_map($IfElse_level) $cond
set IfElse_pcam($IfElse_level) $cond
if {!$Enable || !$cond} {
set Enable 0
}
}
{ifn} { ;# IF Not
# Missing condition expression
if {![string length $cond]} {
SyntaxError $lineNum $fileNum [mc "Missing condition"]
set cond 1
}
# Evaluate the condition expression
if {$Enable} {
set cond [ComputeExpr $cond]
if {$cond == {}} {
SyntaxError $lineNum $fileNum [mc "Invalid expression `%s'" $cond_orig]
set cond 1
}
} else {
set cond 1
}
# Invert the condition
set cond [expr {!$cond}]
# Increment counter of nested block level
incr IfElse_level
# Adjust map of conditional compilation map and flag "Enable"
set IfElse_map($IfElse_level) $cond
set IfElse_pcam($IfElse_level) $cond
if {!$Enable || !$cond} {
set Enable 0
}
}
{ifdef} { ;# IF DEFined
# Remove brackets
set cond [string trim $cond {()}]
# Missing condition expression
if {![string length $cond]} {
SyntaxError $lineNum $fileNum [mc "Missing condition"]
set cond 1
}
# Evaluate the condition expression
set cond [expr {$Enable && [isConstAlreadyDefined $cond]}]
# Increment counter of nested block level
incr IfElse_level
# Adjust map of conditional compilation map and flag "Enable"
set IfElse_map($IfElse_level) $cond
set IfElse_pcam($IfElse_level) $cond
if {!$Enable || !$cond} {
set Enable 0
}
}
{ifndef} { ;# IF Not DEFined
# Remove brackets
set cond [string trim $cond {()}]
# Missing condition expression
if {![string length $cond]} {
SyntaxError $lineNum $fileNum [mc "Missing condition"]
set cond 1
}
# Evaluate the condition expression
set cond [expr {$Enable && ![isConstAlreadyDefined $cond]}]
# Increment counter of nested block level
incr IfElse_level
# Adjust map of conditional compilation map and flag "Enable"
set IfElse_map($IfElse_level) $cond
set IfElse_pcam($IfElse_level) $cond
if {!$Enable || !$cond} {
set Enable 0
}
}
{else} {
if {[llength [array names IfElse_map $IfElse_level]] == 0} {
SyntaxError $lineNum $fileNum [mc "Unexpected `ELSE'"]
} else {
set IfElse_map($IfElse_level) [expr {!$IfElse_pcam($IfElse_level)}]
set Enable 1
for {set i 1} {$i <= $IfElse_level} {incr i} {
set Enable [expr {$IfElse_map($i) && $Enable}]
}
}
}
{elseifn} -
{elseifdef} -
{elseifndef} -
{elseif} {
if {[llength [array names IfElse_map $IfElse_level]] == 0} {
SyntaxError $lineNum $fileNum [mc "Unexpected `ELSEIF'"]
} else {
# Missing condition expression
if {![string length $cond]} {
SyntaxError $lineNum $fileNum [mc "Missing condition"]
set cond 1
}
# Evaluate the condition expression
if {
!$IfElse_pcam($IfElse_level)
&&
($IfElse_level == 1 || $IfElse_map([expr {$IfElse_level - 1}]))
} then {
switch -- $directive {
{elseif} {
set cond [ComputeExpr $cond]
}
{elseifn} {
set cond [ComputeExpr $cond]
if {$cond != {}} {
set cond [expr {!$cond}]
}
}
{elseifdef} {
set cond [isConstAlreadyDefined $cond]
}
{elseifndef} {
set cond [expr {![isConstAlreadyDefined $cond]}]
}
}
if {$cond == {}} {
SyntaxError $lineNum $fileNum [mc "Invalid expression `%s'" $cond_orig]
set cond 1
}
} else {
set cond 0
}
if {$cond} {
set IfElse_pcam($IfElse_level) 1
}
set IfElse_map($IfElse_level) $cond
set Enable 1
for {set i 1} {$i <= $IfElse_level} {incr i} {
set Enable [expr {$IfElse_map($i) && $Enable}]
}
}
}
{endif} {
incr IfElse_level -1 ;# Decrement counter of nested block level
set Enable 1
# End of nested statement
if {$IfElse_level >= 0} {
for {set i 1} {$i <= $IfElse_level} {incr i} {
set Enable [expr {$IfElse_map($i) && $Enable}]
}
# Invalid directive usage
} else {
incr IfElse_level
SyntaxError $lineNum $fileNum [mc "Unexpected `ENDIF'"]
}
}
default {
CompilationError $lineNum $fileNum "`$directive' is not a if/else/endif/ifn/ifdef/ifndef/elseif directive (procedure: If_Else_Endif)"
}
}
}
## Define symbolic name
# --auxiliary procedure for 'parse_Consts_and_ConditionalCompilation'
# @parm String directive - Definition directive
# @parm String line - Line of source code
# @parm Int idx - Current index in the code list
# @parm Bool ignore_undefined - Ignore undefined symbolic names in declaration
# @return Bool - 0 == Resolved; 1 == Unresolved (discard line); 2 == Unresolved (keep line)
proc define_const {directive line idx ignore_undefined} {
variable const_BIT ;# Array: Bit values -- ($const_BIT($bit_name) == $value)
variable const_CODE ;# Array: Constants defined by directive 'CODE'
variable const_DATA ;# Array: Constants defined by directive 'DATA'
variable const_IDATA ;# Array: Constants defined by directive 'IDATA'
variable const_XDATA ;# Array: Constants defined by directive 'XDATA'
variable const_SET ;# Array: Constants defined by directive 'CODE'
variable const_EQU ;# Array: Constants defined by directive 'EQU'
variable defined_BIT ;# List of defined bits (directove 'BIT')
variable defined_CODE ;# List of constants defined by 'CODE'
variable defined_DATA ;# List of constants defined by 'DATA'
variable defined_IDATA ;# List of constants defined by 'IDATA'
variable defined_XDATA ;# List of constants defined by 'XDATA'
variable defined_SET ;# List of variables defined by 'SET'
variable defined_EQU ;# List of constants defined by 'EQU'
variable const_SET_SPEC ;# Array: Special constants defined by directive 'CODE'
variable const_EQU_SPEC ;# Array: Special constants defined by directive 'EQU'
variable defined_SET_SPEC ;# List of special variables defined by 'SET'
variable defined_EQU_SPEC ;# List of special constants defined by 'EQU'
variable lineNum ;# Number of the current line
variable fileNum ;# Number of the current file
variable ErrorAtLine ;# Bool: Error occurred on the current line
# Handle directive "FLAG", which has the same meaning as "BIT"
if {$directive == {flag}} {
set directive {bit}
}
# Detrminate 1st field and the last (3rd) field
if {![regexp {^\s*\w+} $line const]} {
set const {} ;# symbolic name
} else {
set const [string tolower [string trim $const]] ;# symbolic name
}
if {![regsub {^\w+\s+\.?\w+\s+} $line {} value]} {
SyntaxError $lineNum $fileNum [mc "Missing expression"]
return 1
}
# Check for symbolic name validity
if {![regexp {^[a-zA-Z_]\w*$} $const]} {
SyntaxError $lineNum $fileNum [mc "Invalid symbolic name: %s" $const]
return 1
}
# Does value field contain comma ?
if {[string first {,} $value] != -1} {
# Is const field an instruction ?
if {[lsearch -exact -ascii ${::CompilerConsts::AllInstructions} $const] != -1} {
# yes -> skip this line
if {$ignore_undefined} {
return 2
} else {
return 1
}
} else {
# no -> remove line & report syntax error
SyntaxError $lineNum $fileNum [mc "Invalid expression: `%s'" $value]
return 1
}
}
# Is the 1st field a label ? (label:)
if {[regexp {^\w+:$} $const]} {
SyntaxError $lineNum $fileNum [mc "Expected symbol to define, but got label: `%s'" $const]
return 1
}
# Check if the 1st field contain only allowed symbols
if {![regexp {^[a-zA-Z_]\w*$} $const]} {
SyntaxError $lineNum $fileNum [mc "Invalid symbol name: `%s'" $const]
return 1
}
# Determinate value of expression
set special_value 0
if {[regexp {^\w+\.\w+$} $value]} {
set value [getBitAddr $value $ignore_undefined]
if {$value == {}} {
set value 0
}
} elseif {
[lsearch -ascii -exact ${::CompilerConsts::FixedOperands} [string tolower $value]] != -1
&& ($directive == {equ} || $directive == {set})
} then {
Notice $lineNum $fileNum [mc "Special value (with no numerical representation) assigned to constant: %s <- %s" [string toupper $const] [string toupper $value]]
set special_value 1
} else {
set value_orig $value
set value [ComputeExpr $value $ignore_undefined]
}
# Check for value validity
if {$value == {}} {
if {$ignore_undefined} {
return 2
}
SyntaxError $lineNum $fileNum [mc "Invalid expression `%s'" $value_orig]
return 1
}
# Adjust code listing
if {$special_value} {
CodeListing::set_spec_value $idx $value
} else {
CodeListing::set_value $idx $value
}
# Define symbolic name
switch -- $directive {
{bit} {
if {[lsearch -exact -ascii $defined_BIT $const] != -1} {
SyntaxError $lineNum $fileNum [mc "Trying to overwrite constant: %s" $const]
return 1
}
if {$value > 255} {
SyntaxError $lineNum $fileNum [mc "Expression out of range"]
return 1
}
if {[isConstAlreadyDefined $const]} {
Warning $lineNum $fileNum [mc "Ambiguous symbol definition: %s" $const]
}
set const_BIT($const) $value
lappend defined_BIT $const
}
{code} {
if {[lsearch -exact -ascii $defined_CODE $const] != -1} {
SyntaxError $lineNum $fileNum [mc "Trying to overwrite constant: %s" $const]
return 1
}
if {$value > 0xFFFF} {
SyntaxError $lineNum $fileNum [mc "Expression out of range"]
return 1
} elseif {$value >= ${::Compiler::Settings::code_size}} {
Warning $lineNum $fileNum [mc "Exceeding code memory capacity: %s <- %s" $const $value]
}
if {[isConstAlreadyDefined $const]} {
Warning $lineNum $fileNum [mc "Ambiguous symbol definition: %s" $const]
}
set const_CODE($const) $value
lappend defined_CODE $const
}
{data} {
if {
([lsearch -exact -ascii $defined_IDATA $const] != -1)
||
([lsearch -exact -ascii $defined_DATA $const] != -1)
} then {
SyntaxError $lineNum $fileNum [mc "Trying to overwrite constant: %s" $const]
return 1
}
if {$value > 0xFF} {
SyntaxError $lineNum $fileNum [mc "Expression out of range"]
return 1
} elseif {$value >= ${::Compiler::Settings::iram_size}} {
Warning $lineNum $fileNum [mc "Exceeding internal data memory capacity: %s <- %s" $const $value]
}
if {[isConstAlreadyDefined $const]} {
Warning $lineNum $fileNum [mc "Ambiguous symbol definition: %s" $const]
}
set const_DATA($const) $value
lappend defined_DATA $const
}
{idata} {
if {
([lsearch -exact -ascii $defined_IDATA $const] != -1)
||
([lsearch -exact -ascii $defined_DATA $const] != -1)
} then {
SyntaxError $lineNum $fileNum [mc "Trying to overwrite constant: %s" $const]
return 1
}
if {$value > 0xFF} {
SyntaxError $lineNum $fileNum [mc "Expression out of range"]
return 1
} elseif {$value >= ${::Compiler::Settings::iram_size}} {
Warning $lineNum $fileNum [mc "Exceeding internal data memory capacity: %s <- %s" $const $value]
}
if {[isConstAlreadyDefined $const]} {
Warning $lineNum $fileNum [mc "Ambiguous symbol definition: %s" $const]
}
set const_IDATA($const) $value
lappend defined_IDATA $const
}
{xdata} {
if {[lsearch -exact -ascii $defined_XDATA $const] != -1} {
SyntaxError $lineNum $fileNum [mc "Trying to overwrite constant: %s" $const]
return 1
}
if {$value > 0xFFFF} {
SyntaxError $lineNum $fileNum [mc "Expression out of range"]
} elseif {$value >= ${::Compiler::Settings::xram_size}} {
Warning $lineNum $fileNum [mc "Exceeding external data memory capacity: %s <- %s" $const $value]
}
if {[isConstAlreadyDefined $const]} {
Warning $lineNum $fileNum [mc "Ambiguous symbol definition: %s" $const]
}
set const_XDATA($const) $value
lappend defined_XDATA $const
}
{equ} {
if {[lsearch -exact -ascii $defined_EQU $const] != -1 || [lsearch -exact -ascii $defined_EQU_SPEC $const] != -1} {
SyntaxError $lineNum $fileNum [mc "Trying to overwrite constant: %s" $const]
return 1
}
if {[lsearch -exact -ascii $defined_SET $const] != -1 || [lsearch -exact -ascii $defined_SET_SPEC $const] != -1} {
SyntaxError $lineNum $fileNum [mc "Trying to change variable `%s' with wrong directive (EQU)" $const]
set idx [lsearch -exact -ascii $defined_SET $const]
if {$idx != -1} {
set defined_SET [lreplace $defined_SET $idx $idx]
} else {
set idx [lsearch -exact -ascii $defined_SET_SPEC $const]
if {$idx != -1} {
set defined_SET_SPEC [lreplace $defined_SET_SPEC $idx $idx]
}
}
return 1
}
if {[isConstAlreadyDefined $const]} {
Warning $lineNum $fileNum [mc "Ambiguous symbol definition: %s" $const]
}
if {$special_value} {
set const_EQU_SPEC($const) [string tolower $value]
lappend defined_EQU_SPEC $const
} else {
set const_EQU($const) $value
lappend defined_EQU $const
}
}
{set} {
# note:
# $const_SET($const) == { { line value } ... }
#
return [define_variable $const $value $special_value]
}
}
return 0
}
## Define variable (directive 'SET')
# --auxiliary procedure for 'define_const'
# @parm String const - Name of the variable
# @parm Int value - Current value of the variable
# @parm Bool special_value - Assign special value like (A, AB, R0, etc.)
# @return Bool - 0 == Resolved; 1 == Unresolved
proc define_variable {const value special_value} {
variable defined_EQU ;# List of constants defined by 'EQU'
variable defined_SET ;# List of variables defined by 'SET'
variable const_SET ;# Array: Constants defined by directive 'CODE'
variable lineNum ;# Number of the current line
variable fileNum ;# Number of the current file
variable const_SET_SPEC ;# Array: Special constants defined by directive 'CODE'
variable const_EQU_SPEC ;# Array: Special constants defined by directive 'EQU'
variable defined_SET_SPEC ;# List of special variables defined by 'SET'
variable defined_EQU_SPEC ;# List of special constants defined by 'EQU'
# Check if the variable is not already defined as a constant
if {[lsearch -exact -ascii $defined_EQU $const] != -1} {
SyntaxError $lineNum $fileNum [mc "Trying to overwrite constant: %s" $const]
return 1
}
# Set (new) variable value
if {[lsearch -exact -ascii $defined_SET $const] != -1} {
Notice $lineNum $fileNum [mc "Setting new variable value: %s <- %s" $const $value]
} else {
if {[isConstAlreadyDefined $const]} {
Warning $lineNum $fileNum [mc "Ambiguous symbol definition: %s" $const]
}
if {$special_value} {
lappend defined_SET_SPEC $const
} else {
lappend defined_SET $const
}
}
if {$special_value} {
lappend const_SET_SPEC($const) [list $lineNum $value]
} else {
lappend const_SET($const) [list $lineNum $value]
}
return 0
}
# Check if given constant/variable is defined
# @parm string const - constant/variable name
# @return bool
proc const_exists {const} {
variable defined_SET ;# List of variables defined by 'SET'
variable defined_EQU ;# List of constants defined by 'EQU'
if {
([lsearch -exact -ascii $defined_SET $const] != -1) ||
([lsearch -exact -ascii $defined_EQU $const] != -1)
} then {
return 1
} else {
return 0
}
}
## Get constant/variable value
# @parm String const - const_name
# @parm Int line={} -lineNumber
# @parm Bool special_value=0 - Allow special values like (A, AB, R0, etc.)
# @return mixed - value or emty string if nothing found
proc const_value {const {line {}} {special_value 0}} {
variable defined_SET ;# List of variables defined by 'SET'
variable defined_EQU ;# List of constants defined by 'EQU'
variable const_SET ;# Array: Constants defined by directive 'CODE'
variable const_EQU ;# Array: Constants defined by directive 'EQU'
variable const_SET_SPEC ;# Array: Special constants defined by directive 'CODE'
variable const_EQU_SPEC ;# Array: Special constants defined by directive 'EQU'
variable defined_SET_SPEC ;# List of special variables defined by 'SET'
variable defined_EQU_SPEC ;# List of special constants defined by 'EQU'
# Constants defined by directive 'EQU'
if {[lsearch -exact -ascii $defined_EQU $const] != -1} {
return $const_EQU($const)
}
# Constants defined by directive 'EQU'
if {$special_value && [lsearch -exact -ascii $defined_EQU_SPEC $const] != -1} {
return $const_EQU_SPEC($const)
}
# Variables defined by directive 'SET'
if {$line != {}} {
# Know line number ... search
if {[lsearch -exact -ascii $defined_SET $const] != -1} {
set value {}
# Iterate over definitions
foreach item $const_SET($const) {
if {[lindex $item 0] > $line} {break}
set value [lindex $item 1]
}
return $value
}
}
# Special variables defined by directive 'SET'
if {$special_value && $line != {}} {
# Know line number ... search
if {[lsearch -exact -ascii $defined_SET_SPEC $const] != -1} {
set value {}
# Iterate over definitions
foreach item $const_SET_SPEC($const) {
if {[lindex $item 0] > $line} {break}
set value [lindex $item 1]
}
return $value
}
}
# Nothing found -> failure
return {}
}
## Compute value of the given expression
# @parm String expression - Expression to evaluate
# @parm Bool ignore_undefined=0 - Ignore undefined symbolic names
# @parm Int address={} - Current instruction address (for `$' expansion)
# @return Int - result or {}
proc ComputeExpr {expression {ignore_undefined 0} {address {}}} {
variable lineNum ;# Number of the current line
variable fileNum ;# Number of the current file
variable original_expression ;# Auxiliary variable (see proc. 'ComputeExpr')
variable tmp ;# General purpose tempotary variable
variable ErrorAtLine ;# Bool: Error occurred on the current line
variable check_sfr_usage ;# Bool: Check for legal usage of SFR and SFB
variable available_SFR ;# List: available SFR and SFB on the target MCU
variable const_BIT ;# Array: Bit values -- ($const_BIT($bit_name) == $value)
variable const_CODE ;# Array: Constants defined by directive 'CODE'
variable const_DATA ;# Array: Constants defined by directive 'DATA'
variable const_IDATA ;# Array: Constants defined by directive 'IDATA'
variable const_XDATA ;# Array: Constants defined by directive 'XDATA'
variable const_SET ;# Array: Constants defined by directive 'CODE'
variable const_EQU ;# Array: Constants defined by directive 'EQU'
variable defined_BIT ;# List of defined bits (directove 'BIT')
variable defined_CODE ;# List of constants defined by 'CODE'
variable defined_DATA ;# List of constants defined by 'DATA'
variable defined_IDATA ;# List of constants defined by 'IDATA'
variable defined_XDATA ;# List of constants defined by 'XDATA'
variable defined_SET ;# List of variables defined by 'SET'
variable defined_EQU ;# List of constants defined by 'EQU'
variable labels ;# Array: Values of defined labels ($labels($label) == $address)
variable defined_LABEL ;# List of defined labels
variable selected_segment ;# Current memory segment (one of {cseg bseg dseg iseg xseg})
variable segment_pointer ;# Current memory segment pointer
set ErrorAtLine 0
# Make backup copy of the original expression
set original_expression $expression
set expression " $expression "
# Hide parantesis in strings
set expression [replace_in_strings $expression {\(} "\a"]
set expression [replace_in_strings $expression {\)} "\b"]
# Check if parantesis are balanced
if {[regexp {[\(\)]} $expression]} {
set left_p 0
set idx 0
while {1} {
set idx [string first {(} $expression $idx]
if {$idx == -1} {break}
incr idx
incr left_p
}
set right_p 0
set idx 0
while {1} {
set idx [string first {)} $expression $idx]
if {$idx == -1} {break}
incr idx
incr right_p
}
if {$right_p != $left_p} {
SyntaxError $lineNum $fileNum [mc "Invalid expression - parentheses are not balanced: `%s'" $original_expression]
}
}
## Operators replacement
# symbol operators (like % or >=)
foreach ASM_operator {\\=\\= !\\= \\= <> % \\* / \\- \\+ > < >\\= <\\= \\( \\) } \
TCL_operator {== != == != % * / - + > < >= <= ( ) } {
regsub -all -- $ASM_operator $expression " $TCL_operator " expression
}
# word operators (like MOD or GE)
foreach ASM_oprator {mod xor or and not eq ne gt ge lt le shr shl } \
TCL_operator { % \^ | \\& \~ == != > >= < <= >> << } {
regsub -all -nocase -- \
"\[\\s \]$ASM_oprator\[\\s \]" $expression \
" $TCL_operator " expression
}
# operators "HIGH" and "LOW" (case-insensitive)
if {
([string first {low} [string tolower $expression]] != -1)
||
([string first {high} [string tolower $expression]] != -1)
} then {
foreach operator {low high} \
before {0xFF&int( int(} \
after {) )/0x100} \
{
while {1} {
if {![regexp -nocase -- "\\s$operator\\s+((\\w+)|(\\(\[^\\(\\)\]+\\)))" $expression str]} {
break
}
set idx [string first $str $expression]
set len [string length $str]
set str [string replace $str 0 4]
set str " (${before} ${str} ${after})"
set expression [string replace $expression $idx [expr {$idx + $len - 1}] $str]
}
}
}
# Unhide parantesis in strings
regsub -all "\a" $expression {(} expression
regsub -all "\b" $expression {)} expression
# Split expression into a list
set expression [split [string trim $expression]]
set tmp {}
# Convert all numbers to decimal
foreach word [replace_in_strings $expression { } "\a"] {
if {$word == {}} {continue}
# Handle prefix notation for hexadecimal numbers, like 0xfa
if {
[string index $word 0] == {0}
&&
([string index $word 1] == {x} || [string index $word 1] == {X})
&&
[string is xdigit [string index $word 2]]
} then {
set word [string replace $word 0 1]
if {![string is digit [string index $word 0]]} {
set word "0${word}"
}
append word {h}
}
if {[regexp {^\d\w+$} $word] && ![regexp {^\d+$} $word]} {
set base [string index $word end]
set word [string range $word 0 {end-1}]
switch -- [string tolower $base] {
{d} {
if {![NumSystem::isdec $word]} {
SyntaxError $lineNum $fileNum [mc "Invalid numeric value: %s (should be decimal number)" "${word}d"]
}
}
{h} {
if {![NumSystem::ishex $word]} {
SyntaxError $lineNum $fileNum [mc "Invalid numeric value: %s (should be hexadecimal number)" "${word}h"]
} else {
set word [expr "0x$word"]
}
}
{b} {
if {![NumSystem::isbin $word]} {
SyntaxError $lineNum $fileNum [mc "Invalid numeric value: %s (should be binary number)" "${word}b"]
} else {
set word [NumSystem::bin2dec $word]
}
}
{o} {
if {![NumSystem::isoct $word]} {
SyntaxError $lineNum $fileNum [mc "Invalid numeric value: %s (should be octal number)" "${word}o"]
} else {
set word [NumSystem::oct2dec $word]
}
}
{q} {
if {![NumSystem::isoct $word]} {
SyntaxError $lineNum $fileNum [mc "Invalid numeric value: %s (should be octal number)" "${word}q"]
} else {
set word [NumSystem::oct2dec $word]
}
}
}
} else {
if {[string index $word end] == {'}} {
if {[string index $word 0] != {'}} {
SyntaxError $lineNum $fileNum [mc "Invalid value: `%s' (should be char)" $word]
} else {
set word [string range $word 1 end-1]
regsub -all "\a" $word { } word
set word [character2number [subst -nocommands -novariables $word]]
}
}
}
lappend tmp $word
}
set expression $tmp
set tmp {}
# Expand possible constants and variables
foreach word $expression {
if {$word == {}} {continue}
# Dollar sign (`$')
if {$word == {$}} {
# Current instruction address
if {$address != {}} {
set word $address
# Address pointer in the selected memory segment
} elseif {$selected_segment != {cseg}} {
set word $segment_pointer($selected_segment)
} elseif {!$ignore_undefined} {
SyntaxError $lineNum $fileNum [mc "Value of `\$' is unknown at this point" $word]
set ErrorAtLine 1
}
lappend tmp $word
continue
}
# Normal symbolic name
if {![regexp {^(\?\?)?[A-Za-z_].*$} $word]} {
set word [string trimleft $word 0]
if {$word == {}} {
set word 0
}
lappend tmp $word
continue
}
set word [string tolower $word]
# Search in SET and EQU
if {[const_exists $word]} {
CodeListing::symbol_used $word {equset}
set word [const_value $word $lineNum]
# Search in DATA
} elseif {[lsearch -exact -ascii $defined_DATA $word] != -1} {
if {$check_sfr_usage} {
if {
[lsearch -ascii -exact $::CompilerConsts::defined_SFR $word] != -1
&&
[lsearch -ascii -exact $available_SFR $word] == -1
} then {
Warning $lineNum $fileNum [mc "Special function register \"%s\" is not available on the target MCU" [string toupper $word]]
}
}
set word $const_DATA($word)
# Search in IDATA
} elseif {[lsearch -exact -ascii $defined_IDATA $word] != -1} {
CodeListing::symbol_used $word {idata}
set word $const_IDATA($word)
# Search in XDATA
} elseif {[lsearch -exact -ascii $defined_XDATA $word] != -1} {
CodeListing::symbol_used $word {xdata}
set word $const_XDATA($word)
# Search in CODE
} elseif {[lsearch -exact -ascii $defined_CODE $word] != -1} {
CodeListing::symbol_used $word {code}
set word $const_CODE($word)
# Search in BIT
} elseif {[lsearch -exact -ascii $defined_BIT $word] != -1} {
if {$check_sfr_usage} {
if {
[lsearch -ascii -exact $::CompilerConsts::defined_SFRBitArea $word] != -1
&&
[lsearch -ascii -exact $available_SFR $word] == -1
} then {
Warning $lineNum $fileNum [mc "Special function bit \"%s\" is not available on the target MCU" [string toupper $word]]
}
}
CodeListing::symbol_used $word {bit}
set word $const_BIT($word)
# Search in LABEL
} elseif {[lsearch -exact -ascii $defined_LABEL $word] != -1} {
CodeListing::symbol_used $word {label}
set word $labels($word)
# Requeted symb. name not fount -> syntax error
} else {
if {$ignore_undefined} {
return {}
}
SyntaxError $lineNum $fileNum [mc "Undefined symbol name: %s" $word]
set ErrorAtLine 1
set word 1
}
lappend tmp $word
}
set expression $tmp
set tmp {}
# Return empty string if evaluation is incomplete
if {$ErrorAtLine} {return {}}
# Compute expression and return possible result
if {[catch {
set expression [expr "$expression"]
}]} then {
return {}
}
if {[catch {
set tmp [expr {int($expression)}]
}]} then {
return {}
}
if {($tmp - $expression) != 0} {
Notice $lineNum $fileNum [mc "Floating point value converted to integer value `%s' -> `%s'" $expression $tmp]
}
set expression $tmp
set tmp $expression
while {$expression < 0} {
incr expression 0x10000
}
while {$expression >= 0x10000} {
incr expression -0x10000
}
if {$tmp != $expression} {
Notice $lineNum $fileNum [mc "Overflow `%s' -> `%s'" $tmp $expression]
}
return $expression
}
## Remove comments and redutant white space
# @return void
proc trim_code {} {
variable asm ;# Resulting pre-compiled code
variable tmp_asm ;# Temporary auxiliary pre-compiled code
variable lineNum ;# Number of the current line
variable fileNum ;# Number of the current file
variable idx ;# Current position in asm list
# Reset NS variables
set tmp_asm {}
set tmp_line {}
set idx -1
# Iterate over the code
foreach line $asm {
incr idx
# Update after each 25 iterations
if {[expr {$idx % 25}] == 0} {
${::Compiler::Settings::UPDATE_COMMAND}
}
if {${::Compiler::Settings::ABORT_VARIABLE}} {
${::Compiler::Settings::TEXT_OUPUT_COMMAND} [mc "Aborted"]
free_resources
return
}
# Determinate line number and line content
set lineNum [lindex $line 0]
set fileNum [lindex $line 1]
set line [lindex $line 2]
# Skip empty lines
if {[regexp {^\s*$} $line]} {
CodeListing::delete_line $idx
incr idx -1
continue
}
# Remove comment
set tmp_line $line
while {1} {
if {[regexp {'[^']*'} $tmp_line str]} {
regsub {'[^']*'} $tmp_line [string repeat {_} [string length $str]] tmp_line
} else {
break
}
}
set semicolon_idx [string first {;} $tmp_line]
if {$semicolon_idx == 0} {
CodeListing::delete_line $idx
incr idx -1
continue
}
if {$semicolon_idx > 0} {
incr semicolon_idx -1
set line [string range $line 0 $semicolon_idx]
}
# Remove leading and trainling white space
regsub {^\s+} $line {} line
regsub {\s+$} $line {} line
lappend tmp_asm [list $lineNum $fileNum $line]
}
# Replace old code with the new one
set asm $tmp_asm
}
## Replace certain character by another character only within strings
# For instance replace_in_strings("a 'a a' a", "a", "b") --> "a 'b b' a"
# @parm String string - Source string
# @parm String search - Character or substring to replace
# @parm String replacement - Replacement
# @return String - result
proc replace_in_strings {string search replacement} {
set idx 0
while {1} {
if {![regexp -start $idx -- {'[^']*'} $string str]} {
break
}
set len [string length $str]
set idx [string first $str $string $idx]
regsub -all $search [string range $str 1 end-1] $replacement str
set string [string replace $string $idx [expr {$idx + $len - 1}] "'$str'"]
incr idx [expr {[string length $str] + 2}]
}
return $string
}
## Convert one logical character to a number
# It can translate even characters like `''', `\t', `X'
# @parm String value - Character to translate
# @return Int - Value
proc character2number {value} {
variable lineNum ;# Number of the current line
variable fileNum ;# Number of the current file
regsub -all {''} $value {'} value
if {[string length $value] == 1} {
binary scan $value c value
return $value
} else {
if {[string index $value 0] == "\\"} {
set value [string range $value 1 end]
switch -- $value {
{0} {return 0}
{a} {return 7}
{b} {return 8}
{t} {return 9}
{n} {return 10}
{v} {return 11}
{f} {return 12}
{r} {return 13}
{e} {return 101}
default {
set next [string index $value 0]
if {$next == {x}} {
set value [string range $value 1 end]
if {[string is xdigit -strict $value]} {
return [expr "0x$value"]
}
} elseif {[regexp {^[0-7]+$} $value]} {
return [expr "0$value"]
} elseif {$next == {c}} {
set value [string range $value 1 end]
if {[string length $value] == 1} {
binary scan $value c value
return [expr {$value & 0x1F}]
}
}
SyntaxError $lineNum $fileNum [mc "Cannot to use string `%s' as a valid value" $value]
return {}
}
}
} else {
SyntaxError $lineNum $fileNum [mc "Cannot to use string `%s' as value" $value]
return {}
}
}
}
## Report error message -- compilation error (bug in compiler ?)
# @parm Int LineNumber - Number of line where the error occurred
# @parm Int FileNumber - Number of file where the error occurred, {} == unknown
# @parm String ErrorInfo - Error string
# @return void
proc CompilationError {LineNumber FileNumber ErrorInfo} {
variable included_files ;# List: Unique unsorted list of included files
variable working_dir ;# String: Current working directory
variable idx ;# Current position in asm list
variable error_count ;# Number of errors occurred
# Increment error counter
incr error_count
# Adjust code listing
CodeListing::Error $idx $ErrorInfo
# Report the error
if {$FileNumber != {}} {
set filename [lindex $included_files $FileNumber]
if {![string first $working_dir $filename]} {
set filename [string replace $filename 0 [string length $working_dir]]
}
if {[regexp {\s} $filename]} {
set filename "\"$filename\""
}
set filename [mc " in %s" $filename]
} else {
set filename {}
}
if {${::Compiler::Settings::WARNING_LEVEL} < 3} {
if {${::Compiler::Settings::NOCOLOR}} {
${::Compiler::Settings::TEXT_OUPUT_COMMAND} \
[::Compiler::msgc {EL}][mc "Compilation error at %s: %s" "$LineNumber$filename" $ErrorInfo]
} else {
${::Compiler::Settings::TEXT_OUPUT_COMMAND} \
[mc "\033\[31;1mCompilation error\033\[m at \033\[31;1;4m%s\033\[m%s: %s" $LineNumber $filename $ErrorInfo]
}
}
}
## Report notice
# @parm Int LineNumber - Number of line where it occurred
# @parm Int FileNumber - Number of file where the error occurred, {} == unknown
# @parm String ErrorInfo - Text of the notice
# @return void
proc Notice {LineNumber FileNumber ErrorInfo} {
variable working_dir ;# String: Current working directory
variable included_files ;# List: Unique unsorted list of included files
if {$FileNumber != {}} {
set filename [lindex $included_files $FileNumber]
if {![string first $working_dir $filename]} {
set filename [string replace $filename 0 [string length $working_dir]]
}
if {[regexp {\s} $filename]} {
set filename "\"$filename\""
}
set filename [mc " in %s" $filename]
} else {
set filename {}
}
if {${::Compiler::Settings::WARNING_LEVEL} < 1} {
if {${::Compiler::Settings::NOCOLOR}} {
${::Compiler::Settings::TEXT_OUPUT_COMMAND} \
[::Compiler::msgc {WL}][mc "Notice at %s: %s" "$LineNumber$filename" $ErrorInfo]
} else {
${::Compiler::Settings::TEXT_OUPUT_COMMAND} \
[mc "\033\[33;1mNotice\033\[m at \033\[33;1;4m%s\033\[m%s: %s" $LineNumber $filename $ErrorInfo]
}
}
}
## Report warning message
# @parm Int LineNumber - Number of line where it occurred
# @parm Int FileNumber - Number of file where the error occurred, {} == unknown
# @parm String ErrorInfo - Text of the warning
# @return void
proc Warning {LineNumber FileNumber ErrorInfo} {
variable working_dir ;# String: Current working directory
variable included_files ;# List: Unique unsorted list of included files
variable idx ;# Current position in asm list
variable warning_count ;# Number of warnings occurred
# Increment warning counter
incr warning_count
# Adjust code listing
CodeListing::Warning $idx $ErrorInfo
# Report the warning
if {$FileNumber != {}} {
set filename [lindex $included_files $FileNumber]
if {![string first $working_dir $filename]} {
set filename [string replace $filename 0 [string length $working_dir]]
}
if {[regexp {\s} $filename]} {
set filename "\"$filename\""
}
set filename [mc " in %s" $filename]
} else {
set filename {}
}
if {${::Compiler::Settings::WARNING_LEVEL} < 2} {
if {${::Compiler::Settings::NOCOLOR}} {
${::Compiler::Settings::TEXT_OUPUT_COMMAND} \
[::Compiler::msgc {WL}][mc "Warning at %s: %s" "$LineNumber$filename" $ErrorInfo]
} else {
${::Compiler::Settings::TEXT_OUPUT_COMMAND} \
[mc "\033\[33mWarning\033\[m at \033\[33;4m%s\033\[m%s: %s" $LineNumber $filename $ErrorInfo]
}
}
}
## Report error message -- syntax error (badly formatted input code)
# @parm Int LineNumber - Number of line where the error occurred
# @parm Int FileNumber - Number of file where the error occurred, {} == unknown
# @parm String ErrorInfo - Error string
# @return void
proc SyntaxError {LineNumber FileNumber ErrorInfo} {
variable working_dir ;# String: Current working directory
variable included_files ;# List: Unique unsorted list of included files
variable idx ;# Current position in asm list
variable error_count ;# Number of errors occurred
variable ErrorAtLine ;# Bool: Error occurred on the current line
variable Error ;# Bool: An error occurred during precompilation
# Adjust NS variable
incr error_count
set ErrorAtLine 1
set Error 1
# Adjust code listing
CodeListing::Error $idx $ErrorInfo
# Report the error
if {$FileNumber != {}} {
set filename [lindex $included_files $FileNumber]
if {![string first $working_dir $filename]} {
set filename [string replace $filename 0 [string length $working_dir]]
}
if {[regexp {\s} $filename]} {
set filename "\"$filename\""
}
set filename [mc " in %s" $filename]
} else {
set filename {}
}
if {${::Compiler::Settings::WARNING_LEVEL} < 3} {
if {${::Compiler::Settings::NOCOLOR}} {
${::Compiler::Settings::TEXT_OUPUT_COMMAND} \
[::Compiler::msgc {EL}][mc "Syntax error at %s: %s" "$LineNumber$filename" $ErrorInfo]
} else {
${::Compiler::Settings::TEXT_OUPUT_COMMAND} \
[mc "\033\[31;1mSyntax error\033\[m at \033\[31;1;4m%s\033\[m%s: %s" $LineNumber $filename $ErrorInfo]
}
}
}
}
# >>> File inclusion guard
}
# <<< File inclusion guard
|