1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729
|
%
% $Id: ref.tex,v 1.52 2005/03/13 00:31:55 michael Exp $
% This file is part of the FPC documentation.
% Copyright (C) 1997, by Michael Van Canneyt
%
% The FPC documentation is free text; you can redistribute it and/or
% modify it under the terms of the GNU Library General Public License as
% published by the Free Software Foundation; either version 2 of the
% License, or (at your option) any later version.
%
% The FPC Documentation 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
% Library General Public License for more details.
%
% You should have received a copy of the GNU Library General Public
% License along with the FPC documentation; see the file COPYING.LIB. If not,
% write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
% Boston, MA 02111-1307, USA.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Preamble.
\input{preamble.inc}
\begin{latexonly}
\ifpdf
\pdfinfo{/Author(Michael Van Canneyt)
/Title(Free Pascal Language Reference Guide)
/Subject(Free Pascal Reference guide)
/Keywords(Free Pascal, Language)
}
\fi
\end{latexonly}
%
% Settings
%
\makeindex
%
% Syntax style
%
\usepackage{syntax}
\input{syntax/diagram.tex}
%
% Start of document.
%
\begin{document}
\title{Free Pascal :\\ Reference guide.}
\docdescription{Reference guide for Free Pascal, version \fpcversion}
\docversion{2.4}
\input{date.inc}
\author{Micha\"el Van Canneyt}
\maketitle
\tableofcontents
\newpage
\listoftables
\newpage
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Introduction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% About this guide
\section*{About this guide}
This document serves as the reference for the Pascal langauge as implemented
by the \fpc compiler. It describes all Pascal constructs supported by
\fpc, and lists all supported data types. It does not, however, give a
detailed explanation of the Pascal language: it is not a tutorial.
The aim is to list which Pascal constructs are supported, and to show
where the \fpc implementation differs from the \tp or \delphi
implementations.
The \tp and \delphi Pascal compilers introduced various features in the
Pascal language. The Free Pascal compiler emulates these compilers in the
appropriate mode of the compiler: certain features are available only
if the compiler is switched to the appropriate mode. When required for
a certain feature, the use of the \var{-M} command-line switch or
\var{\{\$MODE \}} directive will be indicated in the text. More information
about the various modes can be found in the user's manual and the
programmer's manual.
Earlier versions of this document also contained the reference documentation
of the \file{system} unit and \file{objpas} unit. This has been moved to the
RTL reference guide.
\subsection*{Notations}
Throughout this document, we will refer to functions, types and variables
with \var{typewriter} font. Files are referred to with a sans font:
\file{filename}.
\subsection*{Syntax diagrams}
All elements of the Pascal language are explained in \index{Syntax diagrams}syntax diagrams.
Syntax diagrams are like flow charts. Reading a syntax diagram means getting
from the left side to the right side, following the arrows.
When the right side of a syntax diagram is reached, and it ends with a single
arrow, this means the syntax diagram is continued on the next line. If
the line ends on 2 arrows pointing to each other, then the diagram is
ended.
Syntactical elements are written like this
\begin{mysyntdiag}
\synt{syntactical\ elements\ are\ like\ this}
\end{mysyntdiag}
Keywords which must be typed exactly as in the diagram:
\begin{mysyntdiag}
\lit*{keywords\ are\ like\ this}
\end{mysyntdiag}
When something can be repeated, there is an arrow around it:
\begin{mysyntdiag}
\begin{rep}[b] \synt{this\ can\ be\ repeated} \\ \end{rep}
\end{mysyntdiag}
When there are different possibilities, they are listed in rows:
\begin{mysyntdiag}
\begin{stack}
\synt{First\ possibility} \\
\synt{Second\ possibility}
\end{stack}
\end{mysyntdiag}
Note, that one of the possibilities can be empty:
\begin{mysyntdiag}
\begin{stack}\\
\synt{First\ possibility} \\
\synt{Second\ possibility}
\end{stack}
\end{mysyntdiag}
This means that both the first or second possibility are optional.
Of course, all these elements can be combined and nested.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% About the pascal language
\section*{About the Pascal language}
The language Pascal was originally designed by Niklaus Wirth around 1970.
It has evolved significantly since that day, with a lot of contributions
by the various compiler constructors (Notably: Borland). The basic elements
have been kept throughout the years:
\begin{itemize}
\item Easy syntax, rather verbose, yet easy to read. Ideal for teaching.
\item Strongly typed.
\item Procedural.
\item Case insensitive.
\item Allows nested procedures.
\item Easy input/output routines built-in.
\end{itemize}
The \tp and \delphi Pascal compilers introduced various features in the
Pascal language, most notably easier string handling and object orientedness.
The Free Pascal compiler initially emulated most of \tp and later on
\delphi. It emulates these compilers in the appropriate mode of the compiler:
certain features are available only if the compiler is switched to the appropriate
mode. When required for a certain feature, the use of the \var{-M} command-line
switch or \var{\{\$MODE \}} directive will be indicated in the text. More information
about the various modes can be found in the user's manual and the
programmer's manual.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% The Pascal language
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\chapter{Pascal Tokens}
\index{Tokens}
Tokens are the basic lexical building blocks of source code: they are the
'words' of the language: characters are combined into tokens according to
the rules of the programming language. There are five classes of tokens:
\begin{description}
\item[reserved words] These are words which have a fixed meaning in the
language. They cannot be changed or redefined.
\item[identifiers] These are names of symbols that the programmer defines.
They can be changed and re-used. They are subject to the scope rules of the
language.
\item[operators] These are usually symbols for mathematical or other
operations: +, -, * and so on.
\item[separators] This is usually white-space.
\item[constants] Numerical or character constants are used to denote actual
values in the source code, such as 1 (integer constant) or 2.3 (float
constant) or 'String constant' (a string: a piece of text).
\end{description}
In this chapter we describe all the Pascal reserved words, as well as the
various ways to denote strings, numbers, identifiers etc.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Symbols
\section{Symbols}
\index{Symbols}\index{Tokens!Symbols}
Free Pascal allows all characters, digits and some special character symbols
in a Pascal source file.
\input{syntax/symbol.syn}
The following characters have a special meaning:
\begin{verbatim}
+ - * / = < > [ ] . , ( ) : ^ @ { } $ #
\end{verbatim}
and the following character pairs too:
\begin{verbatim}
<= >= := += -= *= /= (* *) (. .) //
\end{verbatim}
When used in a range specifier, the character pair \var{(.} is equivalent to
the left square bracket \var{[}. Likewise, the character pair \var{.)} is
equivalent to the right square bracket \var{]}.
When used for comment delimiters, the character pair \var{(*} is equivalent
to the left brace \var{\{} and the character pair \var{*)} is equivalent
to the right brace \var{\}}.
These character pairs retain their normal meaning in string expressions.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Comments
\section{Comments}
\index{Comments}\index{Tokens!Symbols}\keywordlink{Comment}
Comments are pieces of the source code which are completely discarded by the
compiler. They exist only for the benefit of the programmer, so he can
explain certain pieces of code. For the compiler, it is as if the comments
were not present.
The following piece of code demonstrates a comment:
\begin{verbatim}
(* My beautiful function returns an interesting result *)
Function Beautiful : Integer;
\end{verbatim}
The use of \var{(*} and \var{*)} as comment delimiters dates from the very
first days of the Pascal language. It has been replaced mostly by the
use of \var{\{} and \var{\}} as comment delimiters, as in the following
example:
\begin{verbatim}
{ My beautiful function returns an interesting result }
Function Beautiful : Integer;
\end{verbatim}
The comment can also span multiple lines:
\begin{verbatim}
{
My beautiful function returns an interesting result,
but only if the argument A is less than B.
}
Function Beautiful (A,B : Integer): Integer;
\end{verbatim}
Single line comments can also be made with the \var{//} delimiter:
\begin{verbatim}
// My beautiful function returns an interesting result
Function Beautiful : Integer;
\end{verbatim}
The comment extends from the // character till the end of the line.
This kind of comment was introduced by Borland in the Delphi Pascal
compiler.
\fpc supports the use of nested comments. The following constructs are valid
comments:
\begin{verbatim}
(* This is an old style comment *)
{ This is a Turbo Pascal comment }
// This is a Delphi comment. All is ignored till the end of the line.
\end{verbatim}
The following are valid ways of nesting comments:
\begin{verbatim}
{ Comment 1 (* comment 2 *) }
(* Comment 1 { comment 2 } *)
{ comment 1 // Comment 2 }
(* comment 1 // Comment 2 *)
// comment 1 (* comment 2 *)
// comment 1 { comment 2 }
\end{verbatim}
The last two comments {\em must} be on one line. The following two will give
errors:
\begin{verbatim}
// Valid comment { No longer valid comment !!
}
\end{verbatim}
and
\begin{verbatim}
// Valid comment (* No longer valid comment !!
*)
\end{verbatim}
The compiler will react with a 'invalid character' error when it encounters
such constructs, regardless of the \var{-Mturbo} switch.
\begin{remark}
In \var{TP} and \var{Delphi} mode, nested comments are not allowed, for
maximum compatibility with existing code for those compilers.
\end{remark}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Reserved words
\section{Reserved words}
\index{Reserved words}\index{Tokens!Reserved words}
Reserved words are part of the Pascal language, and as such, cannot be redefined
by the programmer. Throughout the syntax diagrams they will be denoted using
a {\sffamily\bfseries bold} typeface. Pascal is not case sensitive so the compiler
will accept any combination of upper or lower case letters for reserved words.
We make a distinction between \tp and \delphi reserved words. In \var{TP} mode,
only the \tp reserved words are recognised, but the \delphi ones can be redefined.
By default, \fpc recognises the \delphi reserved words.
\subsection{Turbo Pascal reserved words}
\index{Reserved words!Turbo Pascal}
The following keywords exist in \tp mode
\begin{multicols}{4}
\begin{verbatim}
absolute
and
array
asm
begin
case
const
constructor
destructor
div
do
downto
else
end
file
for
function
goto
if
implementation
in
inherited
inline
interface
label
mod
nil
not
object
of
on
operator
or
packed
procedure
program
record
reintroduce
repeat
self
set
shl
shr
string
then
to
type
unit
until
uses
var
while
with
xor
\end{verbatim}
\end{multicols}
\subsection{\fpc reserved words}
\index{Reserved words!Free Pascal}
On top of the \tp reserved words, \fpc also considers
the following as reserved words:
\begin{multicols}{4}
\begin{verbatim}
dispose
exit
false
new
true
\end{verbatim}
\end{multicols}
\subsection{Object Pascal reserved words}
\index{Reserved words!Delphi}
The reserved words of Object Pascal (used in \delphi or \var{ObjPas} mode)
are the same as the \tp ones, with the following additional keywords:
\begin{multicols}{4}
\begin{verbatim}
as
class
dispinterface
except
exports
finalization
finally
initialization
inline
is
library
on
out
packed
property
raise
resourcestring
threadvar
try
\end{verbatim}
\end{multicols}
\subsection{Modifiers}
\index{Modifiers}\index{Reserved words!Modifiers}
The following is a list of all modifiers. They are not exactly reserved
words in the sense that they can be used as identifiers, but in specific
places, they have a special meaning for the compiler, i.e., the compiler
considers them as part of the Pascal language.
\begin{multicols}{4}
\begin{verbatim}
absolute
abstract
alias
assembler
cdecl
cppdecl
default
export
external
far
far16
forward
index
local
name
near
nostackframe
oldfpccall
override
pascal
private
protected
public
published
read
register
reintroduce
safecall
softfloat
stdcall
virtual
write
\end{verbatim}
\end{multicols}
\begin{remark}
Predefined types such as \var{Byte}, \var{Boolean} and constants
such as \var{maxint} are {\em not} reserved words. They are
identifiers, declared in the system unit. This means that these types
can be redefined in other units. The programmer is however not
encouraged to do this, as it will cause a lot of confusion.
\end{remark}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Identifiers
\section{Identifiers}
\index{Identifiers}\index{Tokens!Identifiers}
Identifiers denote programmer defined names for specific constants, types,
variables, procedures and functions, units, and programs. All programmer
defined names in the source code --excluding reserved words-- are designated as
identifiers.
Identifiers consist of between 1 and 127 significant characters (letters, digits and
the underscore character), of which the first must be an alphanumeric character,
or an underscore (\var{\_}).
The following diagram gives the basic syntax for identifiers.
\input{syntax/identifier.syn}
Like Pascal reserved words, identifiers are case insensitive, that is, both
\begin{verbatim}
myprocedure;
\end{verbatim}
and
\begin{verbatim}
MyProcedure;
\end{verbatim}
refer to the same procedure.
\begin{remark}
As of version 2.5.1 it is possible to specify a reserved word as an identifier by
prepending it with an ampersand (\&). This means that the following is possible:
\begin{verbatim}
program testdo;
procedure &do;
begin
end;
begin
&do;
end.
\end{verbatim}
The reserved word \var{do} is used as an identifier for the declaration as
well as the invocation of the procedure 'do'.
\end{remark}
\section{Hint directives}
\index{Hint directives}\index{Directives!Hint}
Most identifiers (constants, variables, functions or methods, properties) can have a
hint directive appended to their definition:
\input{syntax/hintdirective.syn}
Whenever an identifier marked with a hint directive is later encountered by
the compiler, then a warning will be displayed, corresponding to the
specified hint.
\begin{description}
\item[deprecated] The use of this identifier is deprecated, use an
alternative instead. \keywordlink{deprecated}
\item[experimental] The use of this identifier is experimental: this can be
used to flag new features that should be used with caution.
\keywordlink{experimental}
\item[platform] This is a platform-dependent identifier: it may not be
defined on all platforms. \keywordlink{platform}
\item[unimplemented] This should be used on functions and procedures only.
It should be used to signal that a particular feature has not yet been
implemented. \keywordlink{unimplemented}
\end{description}
The following are examples:
\begin{verbatim}
Const
AConst = 12 deprecated;
var
p : integer platform;
Function Something : Integer; experimental;
begin
Something:=P+AConst;
end;
begin
Something;
end.
\end{verbatim}
This would result in the following output:
\begin{verbatim}
testhd.pp(11,15) Warning: Symbol "p" is not portable
testhd.pp(11,22) Warning: Symbol "AConst" is deprecated
testhd.pp(15,3) Warning: Symbol "Something" is experimental
\end{verbatim}
Hint directives can follow all kinds of identifiers:
units, constants, types, variables, functions, procedures and methods.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Numbers
\section{Numbers}
\index{Numbers}\index{Tokens!Numbers}\index{Numbers!Real}\keywordlink{numbers}
Numbers are by default denoted in decimal notation.
Real (or decimal) numbers are written using engineering or scientific
notation (e.g. \var{0.314E1}).
For integer type constants, \fpc supports 4 formats:
\begin{enumerate}
\item Normal, decimal format (base 10). This is the standard
format.\index{Numbers!Decimal}
\item Hexadecimal format (base 16), in the same way as \tp does.
To specify a constant value in hexadecimal format, prepend it with a dollar
sign (\var{\$}). Thus, the hexadecimal \var{\$FF} equals 255 decimal.
Note that case is insignificant when using hexadecimal constants.\index{Numbers!Hexadecimal}
\item As of version 1.0.7, Octal format (base 8) is also supported.
To specify a constant in octal format, prepend it with a ampersand (\&).
For instance 15 is specified in octal notation as
\var{\&17}.\index{Numbers!Octal}
\item Binary notation (base 2). A binary number can be specified
by preceding it with a percent sign (\var{\%}). Thus, \var{255} can be
specified in binary notation as \var{\%11111111}.\index{Numbers!Binary}
\end{enumerate}
The following diagrams show the syntax for numbers.
\input{syntax/numbers.syn}
\begin{remark}
Octal and Binary notation are not supported in \var{TP} or \var{Delphi}
compatibility mode.
\end{remark}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Labels
\section{Labels}
\index{Labels} \keywordlink{label}
A label is a name for a location in the source code to which can be
jumped to from another location with a \var{goto} statement. A Label is a
standard identifier with the exception that it can start with a digit.
\keywordlink{label}
\input{syntax/label.syn}
\begin{remark}
The \var{-Sg} or \var{-Mtp} switches must be specified before
labels can be used. By default, \fpc doesn't support \var{label} and
\var{goto} statements. The \var{\{\$GOTO ON\}} directive can also be used
to allow use of labels and the goto statement.
\end{remark}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Character strings
\section{Character strings}
\index{String}\index{Constants!String}\index{Tokens!Strings}
A character string (or string for short) is a sequence of zero or more
characters (byte sized), enclosed in single quotes, and on a single
line of the program source code: no literal carriage return or linefeed
characters can appear in the string.
A character set with nothing between the quotes (\var{'{}'}) is an empty string.
\input{syntax/string.syn}
The string consists of standard, 8-bit ASCII characters or Unicode (normally
UTF-8 encoded) characters. The \var{control string} can be used to specify
characters which cannot be typed on a keyboard, such as \var{\#27} for
the escape character.
The single quote character can be embedded in the string by typing it twice.
The C construct of escaping characters in the string (using a backslash)
is not supported in Pascal.
The following are valid string constants:
\begin{verbatim}
'This is a pascal string'
''
'a'
'A tabulator character: '#9' is easy to embed'
\end{verbatim}
The following is an invalid string:
\begin{verbatim}
'the string starts here
and continues here'
\end{verbatim}
The above string must be typed as:
\begin{verbatim}
'the string starts here'#13#10' and continues here'
\end{verbatim}
or
\begin{verbatim}
'the string starts here'#10' and continues here'
\end{verbatim}
on unices (including Mac OS X), and as
\begin{verbatim}
'the string starts here'#13' and continues here'
\end{verbatim}
on a classic Mac-like operating system.
It is possible to use other character sets in strings: in that case the
codepage of the source file must be specified with the \var{\{\$CODEPAGE XXX\}}
directive or with the \var{-Fc} command line option for the compiler. In that
case the characters in a string will be interpreted as characters from the
specified codepage.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Constants
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\chapter{Constants}
\index{Constants} \keywordlink{const}
Just as in \tp, \fpc supports both ordinary and typed constants.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Ordinary constants
\section{Ordinary constants}
\index{Constants!Ordinary} \keywordlink{const}
Ordinary constants declarations are constructed using an identifier name
followed by an "=" token, and followed by an optional expression consisting
of legal combinations of numbers, characters, boolean values or enumerated
values as appropriate. The following syntax diagram shows how to construct
a legal declaration of an ordinary constant.
\input{syntax/const.syn}
The compiler must be able to evaluate the expression in a constant
declaration at compile time. This means that most of the functions
in the Run-Time library cannot be used in a constant
declaration.\index{Operators}
Operators such as \var{+, -, *, /, not, and, or, div, mod, ord, chr,
sizeof, pi, int, trunc, round, frac, odd} can be used, however.
For more information on expressions, see \seec{Expressions}.
Only constants of the following types can be declared: \var{Ordinal
types}, \var{Real types}, \var{Char}, and \var{String}.\index{Constants!String}
The following are all valid constant declarations:
\begin{verbatim}
Const
e = 2.7182818; { Real type constant. }
a = 2; { Ordinal (Integer) type constant. }
c = '4'; { Character type constant. }
s = 'This is a constant string'; {String type constant.}
s = chr(32)
ls = SizeOf(Longint);
\end{verbatim}
Assigning a value to an ordinary constant is not permitted.
Thus, given the previous declaration, the following will result
in a compiler error:
\begin{verbatim}
s := 'some other string';
\end{verbatim}
For string constants, the type of the string is dependent on some compiler
switches. If a specific type is desired, a typed constant should be used,
as explained in the following section.
Prior to version 1.9, \fpc did not correctly support 64-bit constants. As
of version 1.9, 64-bit constants can be specified.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Typed constants
\section{Typed constants}
\label{se:typedconstants}
\index{Constants!Typed}\index{Variables!Initialized}
Sometimes it is necessary to specify the type of a constant, for instance
for constants of complex structures (defined later in the manual).
Their definition is quite simple.
\input{syntax/tconst.syn}
Contrary to ordinary constants, a value can be assigned to them at
run-time. This is an old concept from \tp, which has been
replaced with support for initialized variables: For a detailed
description, see \sees{initializedvars}.
Support for assigning values to typed constants is controlled by the
\var{\{\$J\}} directive: it can be switched off, but is on by default
(for \tp compatibility). Initialized variables are always allowed.
\begin{remark}
It should be stressed that typed constants are automatically initialized at program start.
This is also true for \em{local} typed constants and initialized variables.
Local typed constants are also initialized at program start. If their value was
changed during previous invocations of the function, they will retain their
changed value, i.e. they are not initialized each time the function is invoked.
\end{remark}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% resource strings
\section{Resource strings}
\label{se:resourcestring}\index{Resourcestring}\index{Const}\index{Const!String}\keywordlink{resourcestring}
A special kind of constant declaration block is the \var{Resourcestring}
block. Resourcestring declarations are much like constant string
declarations: resource strings act as constant strings, but they
can be localized by means of a set of special routines in the
\file{objpas} unit. A resource string declaration block
is only allowed in the \var{Delphi} or \var{Objfpc} modes.
The following is an example of a resourcestring definition:
\begin{verbatim}
Resourcestring
FileMenu = '&File...';
EditMenu = '&Edit...';
\end{verbatim}
All string constants defined in the resourcestring section are stored
in special tables. The strings in these tables can be manipulated
at runtime with some special mechanisms in the \file{objpas} unit.
Semantically, the strings act like ordinary constants; It is not allowed
to assign values to them (except through the special mechanisms in the
objpas unit). However, they can be used in assignments or expressions as
ordinary string constants. The main use of the resourcestring section is
to provide an easy means of internationalization.
More on the subject of resourcestrings can be found in the \progref, and
in the \file{objpas} unit reference.
\begin{remark}
Note that a resource string which is given as an expression will not change if
the parts of the expression are changed:
\begin{verbatim}
resourcestring
Part1 = 'First part of a long string.';
Part2 = 'Second part of a long string.';
Sentence = Part1+' '+Part2;
\end{verbatim}
If the localization routines translate \var{Part1} and \var{Part2}, the
\var{Sentence} constant will not be translated automatically: it has a
separate entry in the resource string tables, and must therefor be
translated separately. The above construct simply says that the
initial value of \var{Sentence} equals \var{Part1+' '+Part2}.
\end{remark}
\begin{remark}
Likewise, when using resource strings in a constant array, only the initial
values of the resource strings will be used in the array: when the
individual constants are translated, the elements in the array will retain
their original value.
\begin{verbatim}
resourcestring
Yes = 'Yes.';
No = 'No.';
Var
YesNo : Array[Boolean] of string = (No,Yes);
B : Boolean;
begin
Writeln(YesNo[B]);
end.
\end{verbatim}
This will print 'Yes.' or 'No.' depending on the value of B, even if the
constants Yes and No have been localized by some localization mechanism.
\end{remark}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Types
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\chapter{Types}
\index{Types}
All variables have a type. \fpc supports the same basic types as \tp, with
some extra types from \delphi.
The programmer can declare his own types, which is in essence defining an identifier
that can be used to denote this custom type when declaring variables further
in the source code.\index{Type}\keywordlink{type}
\input{syntax/typedecl.syn}
There are 7 major type classes :
\input{syntax/type.syn}
The last case, \sffamily{type identifier}, is just a means to give another
name to a type. This presents a way to make types platform independent, by
only using these types, and then defining these types for each platform
individually. Any programmer who then uses these custom types doesn't have to worry
about the underlying type size: it is opaque to him. It also allows to use shortcut names
for fully qualified type names. e.g. define \var{system.longint} as
\var{Olongint} and then redefine \var{longint}.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Base types
\section{Base types}
\index{Types!Base}
The base or simple types of \fpc are the \delphi types.
We will discuss each type separately.
\input{syntax/typesim.syn}
\subsection{Ordinal types}
\index{Types!Ordinal}
With the exception of \var{int64}, \var{qword} and Real types,
all base types are ordinal types. Ordinal types have the following
characteristics:
\begin{enumerate}
\item Ordinal types are countable and ordered, i.e. it is, in principle,
possible to start counting them one by one, in a specified order.
This property allows the operation of functions as \var{Inc}, \var{Ord},
\var{Dec}
on ordinal types to be defined.
\item Ordinal values have a smallest possible value. Trying to apply the
\var{Pred} function on the smallest possible value will generate a range
check error if range checking is enabled.
\item Ordinal values have a largest possible value. Trying to apply the
\var{Succ} function on the largest possible value will generate a range
check error if range checking is enabled.
\end{enumerate}
\subsubsection{Integers}
\index{Types!Integer}
A list of pre-defined integer types is presented in \seet{integerstyp}.
\keywordlink{Integer} \keywordlink{Shortint}
\keywordlink{SmallInt} \keywordlink{Longint}
\keywordlink{Longword} \keywordlink{Int64}
\keywordlink{Byte} \keywordlink{Word}
\keywordlink{Cardinal} \keywordlink{QWord}
\keywordlink{Boolean} \keywordlink{ByteBool}
\keywordlink{WordBool}
\keywordlink{LongBool} \keywordlink{Char}
%\index{Keyword!Integer}
%
\begin{table}[ht]
\caption{Predefined integer types}
\label{tab:integerstyp}
\begin{center}
\begin{tabular}{l}
%\begin{FPCltable}{l}{Predefined integer types}{integerstyp}
Name\\ \hline
Integer \\
Shortint \\
SmallInt \\
Longint \\
Longword \\
Int64 \\
Byte \\
Word \\
Cardinal \\
QWord \\
Boolean \\
ByteBool \\
WordBool \\
LongBool \\
Char \\ \hline
\end{tabular}
\end{center}
\end{table}
%\end{FPCltable}
The integer types, and their ranges and sizes, that are predefined in
\fpc are listed in \seet{integersranges}. Please note that
the \var{qword} and \var{int64} types are not true ordinals, so
some Pascal constructs will not work with these two integer types.
\begin{FPCltable}{lcr}{Predefined integer types}{integersranges}
Type & Range & Size in bytes \\ \hline
Byte & 0 .. 255 & 1 \\
Shortint & -128 .. 127 & 1\\
Smallint & -32768 .. 32767 & 2\\
Word & 0 .. 65535 & 2 \\
Integer & either smallint or longint & size 2 or 4 \\
Cardinal & longword & 4 \\
Longint & -2147483648 .. 2147483647 & 4\\
Longword & 0 .. 4294967295 & 4 \\
Int64 & -9223372036854775808 .. 9223372036854775807 & 8 \\
QWord & 0 .. 18446744073709551615 & 8 \\ \hline
\end{FPCltable}
The \var{integer} type maps to the smallint type in the default\keywordlink{integer}
\fpc mode. It maps to either a longint in either Delphi or ObjFPC
mode. The \var{cardinal} type is currently always mapped to the
longword type.
\begin{remark}
All decimal constants which do no fit within the -2147483648..2147483647 range
are silently and automatically parsed as 64-bit integer constants as of version
1.9.0. Earlier versions would convert it to a real-typed constant.
\end{remark}
% This IS NOT TRUE, this is a 32-bit compiler, so the integer type
% will always be the same independently the CPU type.
%This is summarized in \seet{integer32type} for 32-bit processors
%(such as Intel 80x86, Motorola 680x0, PowerPC 32-bit, SPARC v7, MIPS32), and
%in \seet{integer64type} for 64-bit processors (such as Alpha AXP,
%SPARC v9 or later, Intel Itanium, MIPS64).
%\begin{FPCltable}{lcr}{\var{Integer} type mapping for 32-bit processors}{integer32type}
%Compiler mode & Range & Size in bytes \\ \hline
%<default> & -32768 .. 32767 & 2\\
%tp & -32768 .. 32767 & 2\\
%Delphi & -2147483648 .. 2147483647 & 4\\
%ObjFPC & -2147483648 .. 2147483647 & 4\\
%\end{FPCltable}
%\begin{FPCltable}{lcr}{\var{Integer} type mapping for 64-bit processors}{integer64type}
%Compiler mode & Range & Size in bytes \\ \hline
%<default> & -32768 .. 32767 & 2\\
%tp & -32768 .. 32767 & 2\\
%Delphi & -9223372036854775808 .. 9223372036854775807 & 8 \\
%ObjFPC & -9223372036854775808 .. 9223372036854775807 & 8 \\
%\end{FPCltable}
\fpc does automatic type conversion in expressions where different kinds of
integer types are used.
%
%
\subsubsection{Boolean types}
\index{Types!Boolean}\index{Boolean}
\fpc supports the \var{Boolean} type, with its two pre-defined possible
values \var{True} and \var{False}. These are the only two values that can be
assigned to a \var{Boolean} type. Of course, any expression that resolves
to a \var{boolean} value, can also be assigned to a boolean type.
\begin{FPCltable}{lll}{Boolean types}{booleantypes}
Name & Size & Ord(True) \\ \hline
Boolean & 1 & 1 \\
ByteBool & 1 & Any nonzero value \\
WordBool & 2 & Any nonzero value \\
LongBool & 4 & Any nonzero value \\ \hline
\end{FPCltable}
\fpc also supports the \var{ByteBool}, \var{WordBool} and \var{LongBool} types.
These are of type \var{Byte}, \var{Word} or \var{Longint}, but are
assignment compatible with a \var{Boolean}: the value \var{False} is
equivalent to 0 (zero) and any nonzero value is considered \var{True} when
converting to a boolean value. A boolean value of \var{True} is converted
to -1 in case it is assigned to a variable of type \var{LongBool}.
Assuming \var{B} to be of type \var{Boolean}, the following are valid
assignments:
\begin{verbatim}
B := True;
B := False;
B := 1<>2; { Results in B := True }
\end{verbatim}
Boolean expressions are also used in conditions.
\begin{remark}
In \fpc, boolean expressions are by default always evaluated in such a
way that when the result is known, the rest of the expression will no longer
be evaluated: this is called short-cut boolean evaluation.
In the following example, the function \var{Func} will never be called,
which may have strange side-effects.
\begin{verbatim}
...
B := False;
A := B and Func;
\end{verbatim}
Here \var{Func} is a function which returns a \var{Boolean} type.
This behaviour is controllable by the \var{\{\$B \}} compiler directive.
\end{remark}
\subsubsection{Enumeration types}
\index{Types!Enumeration}
Enumeration types are supported in \fpc. On top of the \tp
implementation, \fpc allows also a C-style extension of the
enumeration type, where a value is assigned to a particular element of
the enumeration list.
\input{syntax/typeenum.syn}
(see \seec{Expressions} for how to use expressions)
When using assigned enumerated types, the assigned elements must be in
ascending numerical order in the list, or the compiler will complain.
The expressions used in assigned enumerated elements must be known at
compile time.
So the following is a correct enumerated type declaration:
\begin{verbatim}
Type
Direction = ( North, East, South, West );
\end{verbatim}
A C-style enumeration type looks as follows:
\begin{verbatim}
Type
EnumType = (one, two, three, forty := 40,fortyone);
\end{verbatim}
As a result, the ordinal number of \var{forty} is \var{40}, and not \var{3},
as it would be when the \var{':= 40'} wasn't present.
The ordinal value of \var{fortyone} is then {41}, and not \var{4}, as it
would be when the assignment wasn't present. After an assignment in an
enumerated definition the compiler adds 1 to the assigned value to assign to
the next enumerated value.
When specifying such an enumeration type, it is important to keep in mind
that the enumerated elements should be kept in ascending order. The
following will produce a compiler error:
\begin{verbatim}
Type
EnumType = (one, two, three, forty := 40, thirty := 30);
\end{verbatim}
It is necessary to keep \var{forty} and \var{thirty} in the correct order.
When using enumeration types it is important to keep the following points
in mind:
\begin{enumerate}
\item The \var{Pred} and \var{Succ} functions cannot be used on
this kind of enumeration types. Trying to do this anyhow will result in a
compiler error.
\item Enumeration types are stored using a default, independent of the
actual number of values: the compiler does not try to optimize for space.
This behaviour can be changed with the \var{\{\$PACKENUM n\}} compiler
directive, which tells the compiler the minimal number of bytes to be
used for enumeration types.
For instance
\begin{verbatim}
Type
{$PACKENUM 4}
LargeEnum = ( BigOne, BigTwo, BigThree );
{$PACKENUM 1}
SmallEnum = ( one, two, three );
Var S : SmallEnum;
L : LargeEnum;
begin
WriteLn ('Small enum : ',SizeOf(S));
WriteLn ('Large enum : ',SizeOf(L));
end.
\end{verbatim}
will, when run, print the following:
\begin{verbatim}
Small enum : 1
Large enum : 4
\end{verbatim}
\end{enumerate}
More information can be found in the \progref, in the compiler directives
section.
%
%
\subsubsection{Subrange types}
\index{Types!Subrange}
A subrange type is a range of values from an ordinal type (the {\em host}
type). To define a subrange type, one must specify its limiting values:
the highest and lowest value of the type.
\input{syntax/typesubr.syn}
Some of the predefined \var{integer} types are defined as subrange types:
\begin{verbatim}
Type
Longint = $80000000..$7fffffff;
Integer = -32768..32767;
shortint = -128..127;
byte = 0..255;
Word = 0..65535;
\end{verbatim}
Subrange types of enumeration types can also be defined:
\begin{verbatim}
Type
Days = (monday,tuesday,wednesday,thursday,friday,
saturday,sunday);
WorkDays = monday .. friday;
WeekEnd = Saturday .. Sunday;
\end{verbatim}
%
\subsection{Real types}
\index{Types!Real}
\fpc uses the math coprocessor (or emulation) for all its floating-point
calculations. The Real native type is processor dependent,
but it is either Single or Double. Only the IEEE floating point types are
supported, and these depend on the target processor and emulation options.
The true \tp compatible types are listed in
\seet{Reals}.\index{Real}\index{Single}\index{Double}\index{Extended}\index{Comp}\index{Currency}
\keywordlink{Real}\keywordlink{Single}\keywordlink{Double}\keywordlink{Extended}\keywordlink{Comp}\keywordlink{Currency}
\begin{FPCltable}{lccr}{Supported Real types}{Reals}
Type & Range & Significant digits & Size \\ \hline
Real & platform dependant & ??? & 4 or 8 \\
Single & 1.5E-45 .. 3.4E38 & 7-8 & 4 \\
Double & 5.0E-324 .. 1.7E308 & 15-16 & 8 \\
Extended & 1.9E-4932 .. 1.1E4932 & 19-20 & 10\\
Comp & -2E64+1 .. 2E63-1 & 19-20 & 8 \\
Currency & -922337203685477.5808 & 922337203685477.5807 & 8 \\
\end{FPCltable}
The \var{Comp} type is, in effect, a 64-bit integer and is not available
on all target platforms. To get more information on the supported types
for each platform, refer to the \progref.
The currency type is a fixed-point real data type which is internally used
as an 64-bit integer type (automatically scaled with a factor 10000), this
minimalizes rounding errors.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Character types
\section{Character types}
\index{Types!Char}
\subsection{Char}
\index{Char} \keywordlink{char}
\fpc supports the type \var{Char}. A \var{Char} is exactly 1 byte in
size, and contains one ASCII character.
A character constant can be specified by enclosing the character in single
quotes, as follows : 'a' or 'A' are both character constants.
A character can also be specified by its character
value (commonly an ASCII code), by preceding the ordinal value with the
number symbol (\#). For example specifying \var{\#65} would be the same as \var{'A'}.
Also, the caret character (\verb+^+) can be used in combination with a letter to
specify a character with ASCII value less than 27. Thus \verb+^G+ equals
\var{\#7} - G is the seventh letter in the alphabet.
When the single quote character must be represented, it should be typed
two times successively, thus \var{''''} represents the single quote character.
\subsection{Strings}
\index{Types!String} \keywordlink{String}
\fpc supports the \var{String} type as it is defined in \tp:
a sequence of characters with an optional size specification.
It also supports ansistrings (with unlimited length) as in Delphi.
To declare a variable as a string, use the following type specification:
\input{syntax/sstring.syn}
If there is a size specifier, then its maximum value - indicating the maximum
size of the string - is 255.
The meaning of a string declaration statement without size indicator is
interpreted differently depending on the \var{\{\$H\}} switch. If no size
indication is present, the above declaration can declare an ansistring or
a short string.
Whatever the actual type, ansistrings and short strings can be used
interchangeably. The compiler always takes care of the necessary type
conversions. Note, however, that the result of an expression that contains
ansistrings and short strings will always be an ansistring.
\subsection{Short strings}
\index{Shortstring} \keywordlink{ShortString}
A string declaration declares a short string in the following cases:
\begin{enumerate}
\item If the switch is off: \var{\{\$H-\}}, the string declaration
will always be a short string declaration.
\item If the switch is on \var{\{\$H+\}}, and there is a maximum length (the
size) specifier, the declaration is a short string declaration.
\end{enumerate}
The predefined type \var{ShortString} is defined as a string of size 255:
\begin{verbatim}
ShortString = String[255];
\end{verbatim}
If the size of the string is not specified, \var{255} is taken as a
default. The actual length of the string can be obtained with the
\var{Length} standard runtime routine.
For example in
\begin{verbatim}
{$H-}
Type
NameString = String[10];
StreetString = String;
\end{verbatim}
\var{NameString} can contain a maximum of 10 characters. While
\var{StreetString} can contain up to 255 characters.
\begin{remark}
Short strings have a maximum length of 255 characters: when specifying a
maximum length, the maximum length may not exceed 255. If a length larger
than 255 is attempted, then the compiler will give an error message:
\begin{verbatim}
Error: string length must be a value from 1 to 255
\end{verbatim}
For short strings, the length is stored in the character at index 0. Old
\tp code relies on this, and it is implemented similarly in Free
Pascal.
Despite this, to write portable code, it is best to set the length of a
shortstring with the \var{SetLength} call, and to retrieve
it with the \var{Length} call. These functions will always work, whatever
the internal representation of the shortstrings or other strings in use:
this allows easy switching between the various string types.
\end{remark}
\subsection{Ansistrings}
\index{Ansistring}\index{Types!Ansistring}\index{Types!Reference counted}
\keywordlink{AnsiString}
Ansistrings are strings that have no length limit. They are reference
counted and are guaranteed to be null terminated. Internally, an ansistring is treated as
a pointer: the actual content of the string is stored on the heap, as much
memory as needed to store the string content is allocated.
This is all handled transparantly, i.e. they can be manipulated as a normal
short string. Ansistrings can be defined using the predefined \var{AnsiString}
type.
\begin{remark}
The null-termination does not mean that null characters (char(0) or \#0)
cannot be used: the null-termination is not used internally, but is there for
convenience when dealing with external routines that expect a
null-terminated string (as most C routines do).
\end{remark}
If the \var{\{\$H\}} switch is on, then a string definition using the
regular \var{String} keyword and that doesn't contain a length specifier,
will be regarded as an ansistring as well. If a length specifier is present,
a short string will be used, regardless of the \var{\{\$H\}} setting.
\keywordlink{nil}
If the string is empty (\var{''}), then the internal pointer representation
of the string pointer is \var{Nil}. If the string is not empty, then the
pointer points to a structure in heap memory.
The internal representation as a pointer, and the automatic null-termination
make it possible to typecast\index{Typecast} an ansistring to a pchar. If the string is empty
(so the pointer is \var{Nil}) then the compiler makes sure that the typecasted
pchar will point to a null byte.
Assigning one ansistring to another doesn't involve moving the actual
string. A statement
\begin{verbatim}
S2:=S1;
\end{verbatim}
results in the reference count of \var{S2} being decreased with 1,
The reference count of \var{S1} is increased by 1, and finally \var{S1}
(as a pointer) is copied to \var{S2}. This is a significant speed-up in
the code.
If the reference count of a string reaches zero, then the memory occupied
by the string is deallocated automatically, and the pointer is set to
\var{Nil}, so no memory leaks arise.
When an ansistring is declared, the \fpc compiler initially
allocates just memory for a pointer, not more. This pointer is guaranteed
to be \var{Nil}, meaning that the string is initially empty. This is
true for local and global ansistrings or anstrings that are part of a
structure (arrays, records or objects).
This does introduce an overhead. For instance, declaring
\begin{verbatim}
Var
A : Array[1..100000] of string;
\end{verbatim}
Will copy the value \var{Nil} 100,000 times into \var{A}.
When \var{A} goes out of scope\index{Scope}, then the reference
count of the 100,000 strings will be decreased by 1 for each
of these strings. All this happens invisible to the programmer,
but when considering performance issues, this is important.
Memory for the string content will be allocated only when the string is
assigned a value. If the string goes out of scope, then its reference
count is automatically decreased by 1. If the reference count reaches
zero, the memory reserved for the string is released.
If a value is assigned to a character of a string that has a reference count
greater than 1, such as in the following
statements:
\begin{verbatim}
S:=T; { reference count for S and T is now 2 }
S[I]:='@';
\end{verbatim}
then a copy of the string is created before the assignment. This is known
as {\em copy-on-write} semantics. It is possible to force a string to have
reference count equal to 1 with the \var{UniqueString} call:
\begin{verbatim}
S:=T;
R:=T; // Reference count of T is at least 3
UniqueString(T);
// Reference count of T is quaranteed 1
\end{verbatim}
It's recommended to do this e.g. when typecasting an ansistring to a PChar var
and passing it to a C routine that modifies the string.
The \var{Length} function must be used to get the length of an
ansistring: the length is not stored at character 0 of the ansistring.
The construct
\begin{verbatim}
L:=ord(S[0]);
\end{verbatim}
which was valid for \tp shortstrings, is no longer correct for
Ansistrings. The compiler will warn if such a construct is encountered.
To set the length of an ansistring, the \var{SetLength} function must be used.
Constant ansistrings have a reference count of -1 and are treated specially,
The same remark as for \var{Length} must be given: The construct
\begin{verbatim}
L:=12;
S[0]:=Char(L);
\end{verbatim}
which was valid for \tp shortstrings, is no longer correct for
Ansistrings. The compiler will warn if such a construct is encountered.
Ansistrings are converted to short strings by the compiler if needed,
this means that the use of ansistrings and short strings can be mixed
without problems.
Ansistrings can be typecasted\index{Typecast} to \var{PChar} or \var{Pointer} types:
\index{Types!PChar}\index{PChar}
\begin{verbatim}
Var P : Pointer;
PC : PChar;
S : AnsiString;
begin
S :='This is an ansistring';
PC:=Pchar(S);
P :=Pointer(S);
\end{verbatim}
There is a difference between the two typecasts. When an empty
ansistring is typecasted to a pointer, the pointer wil be \var{Nil}. If an
empty ansistring is typecasted to a \var{PChar}, then the result will be a pointer to a
zero byte (an empty string).
The result of such a typecast must be used with care. In general, it is best
to consider the result of such a typecast as read-only, i.e. only suitable for
passing to a procedure that needs a constant pchar argument.
It is therefore {\em not} advisable to typecast one of the following:
\begin{enumerate}
\item Expressions.
\item Strings that have reference count larger than 1.
In this case you should call \var{Uniquestring} to ensure the
string has reference count 1.
\end{enumerate}
\subsection{WideStrings}
\index{Widestring}\index{Types!Widestring}\index{Types!Reference counted}
\keywordlink{Widestring}
Widestrings (used to represent unicode character strings) are implemented in much
the same way as ansistrings: reference counted, null-terminated arrays, only they
are implemented as arrays of \var{WideChars} instead of regular \var{Chars}.
A \var{WideChar} is a two-byte character (an element of a DBCS: Double Byte
Character Set). Mostly the same rules apply for \var{WideStrings} as for
\var{AnsiStrings}. The compiler transparantly converts WideStrings to
AnsiStrings and vice versa. \index{Ansistring}
Similarly to the typecast\index{Typecast} of an Ansistring to a \var{PChar} null-terminated
\index{PChar}\index{PWideChar}%
array of characters, a WideString can be converted to a \var{PWideChar}
null-terminated array of characters.
Note that the \var{PWideChar} array is terminated by 2 null bytes instead of
1, so a typecast to a pchar is not automatic.
The compiler itself provides no support for any conversion from Unicode to
ansistrings or vice versa. The \file{system} unit has a widestring manager
record, which can be initialized with some OS-specific unicode handling
routines. For more information, see the \file{system} unit reference.
% Constant strings
\subsection{Constant strings}
\index{Constants!String}
To specify a constant string, it must be enclosed in single-quotes, just
as a \var{Char} type, only now more than one character is allowed.
Given that \var{S} is of type \var{String}, the following are valid assignments:
\begin{verbatim}
S := 'This is a string.';
S := 'One'+', Two'+', Three';
S := 'This isn''t difficult !';
S := 'This is a weird character : '#145' !';
\end{verbatim}
As can be seen, the single quote character is represented by 2 single-quote
characters next to each other. Strange characters can be specified by their
character value (usually an ASCII code).
The example shows also that two strings can be added. The resulting string is
just the concatenation of the first with the second string, without spaces in
between them. Strings can not be substracted, however.
Whether the constant string is stored as an ansistring or a short string
depends on the settings of the \var{\{\$H\}} switch.
% PChar
\subsection{PChar - Null terminated strings}
\index{Types!PChar}\index{Types!Pointer} \keywordlink{PChar}
\fpc supports the Delphi implementation of the \var{PChar} type. \var{PChar}
is defined as a pointer to a \var{Char} type, but allows additional
operations.
The \var{PChar} type can be understood best as the Pascal equivalent of a
C-style null-terminated string, i.e. a variable of type \var{PChar} is a
pointer that points to an array of type \var{Char}, which is ended by a
null-character (\var{\#0}).
\fpc supports initializing of \var{PChar} typed constants, or a direct
assignment. For example, the following pieces of code are equivalent:
\begin{verbatim}
program one;
var p : PChar;
begin
P := 'This is a null-terminated string.';
WriteLn (P);
end.
\end{verbatim}
Results in the same as
\begin{verbatim}
program two;
const P : PChar = 'This is a null-terminated string.'
begin
WriteLn (P);
end.
\end{verbatim}
These examples also show that it is possible to write {\em the contents} of
the string to a file of type \var{Text}.
The \seestrings unit contains procedures and functions that manipulate the
\var{PChar} type as in the standard C library.
Since it is equivalent to a pointer to a type \var{Char} variable, it is
also possible to do the following:
\begin{verbatim}
Program three;
Var S : String[30];
P : PChar;
begin
S := 'This is a null-terminated string.'#0;
P := @S[1];
WriteLn (P);
end.
\end{verbatim}
This will have the same result as the previous two examples.
Null-terminated strings cannot be added as normal Pascal
strings. If two \var{PChar} strings must be concatenated; the functions from
the unit \seestrings must be used.
However, it is possible to do some pointer arithmetic. The \index{Operators}
operators \var{+} and \var{-} can be used to do operations on \var{PChar} pointers.
In \seet{PCharMath}, \var{P} and \var{Q} are of type \var{PChar}, and
\var{I} is of type \var{Longint}.
\begin{FPCltable}{lr}{\var{PChar} pointer arithmetic}{PCharMath}
Operation & Result \\ \hline
\var{P + I} & Adds \var{I} to the address pointed to by \var{P}. \\
\var{I + P} & Adds \var{I} to the address pointed to by \var{P}. \\
\var{P - I} & Substracts \var{I} from the address pointed to by \var{P}. \\
\var{P - Q} & Returns, as an integer, the distance between 2 addresses \\
& (or the number of characters between \var{P} and \var{Q}) \\
\hline
\end{FPCltable}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Structured Types
\section{Structured Types}
\index{Types!Structured}
A structured type is a type that can hold multiple values in one variable.
Stuctured types can be nested to unlimited levels.
\input{syntax/typestru.syn}
Unlike Delphi, \fpc does not support the keyword \var{Packed} for all
structured types. In the following sections each of the possible
structured types is discussed. It will be mentioned when a type supports
the \var{packed} keyword.
%
%
\subsubsection{Packed structured types}
When a structured type is declared, no assumptions should be made about
the internal position of the elements in the type. The compiler will lay
out the elements of the structure in memory as it thinks will be most
suitable. That is, the order of the elements will be kept, but the location
of the elements are not guaranteed, and is partially governed by the \var{\$PACKRECORDS}
directive (this directive is explained in the \progref).
\keywordlink{packed} \keywordlink{bitpacked}
However, \fpc allows controlling the layout with the \var{Packed} and
\var{Bitpacked} keywords. The meaning of these words depends on the context:
\begin{description}
\item[Bitpacked] In this case, the compiler will attempt to align ordinal
types on bit boundaries, as explained below.
\item[Packed] The meaning of the \var{Packed} keyword depends on the
situation:
\begin{enumerate}
\item In \var{MACPAS} mode, it is equivalent to the \var{Bitpacked} keyword.
\item In other modes, with the \var{\$BITPACKING} directive set to \var{ON},
it is also equivalent to the \var{Bitpacked} keyword.
\item In other modes, with the \var{\$BITPACKING} directive set to \var{OFF},
it signifies normal packing on byte boundaries.
\end{enumerate}
Packing on byte boundaries means that each new element of a structured type
starts on a byte boundary.
\end{description}
The byte packing mechanism is simple: the compiler aligns each element of
the structure on the first available byte boundary, even if the size of the
previous element (small enumerated types, subrange types) is less than a
byte.
When using the bit packing mechanism, the compiler calculates for each
ordinal type how many bits are needed to store it. The next ordinal type
is then stored on the next free bit. Non-ordinal types - which include but
are not limited to - sets, floats, strings, (bitpacked) records, (bitpacked)
arrays, pointers, classes, objects, and procedural variables, are stored
on the first available byte boundary.
Note that the internals of the bitpacking are opaque: they can change
at any time in the future. What is more: the internal packing depends
on the endianness of the platform for which the compilation is done,
and no conversion between platforms are possible. This makes bitpacked
structures unsuitable for storing on disk or transport over networks.
The format is however the same as the one used by the GNU Pascal
Compiler, and the \fpc team aims to retain this compatibility in the future.
There are some more restrictions to elements of bitpacked structures:
\begin{itemize}
\item The address cannot be retrieved, unless the bit size is a multiple of
8 and the element happens to be stored on a byte boundary.
\item An element of a bitpacked structure cannot be used as a var parameter,
unless the bit size is a multiple of 8 and the element happens to be stored
on a byte boundary.
\end{itemize}
To determine the size of an element in a bitpacked structure, there is the
\var{BitSizeOf} function. It returns the size - in bits - of the element.
For other types or elements of structures which are not bitpacked, this will
simply return the size in bytes multiplied by 8, i.e., the return value is
then the same as \var{8*SizeOf}.
The size of bitpacked records and arrays is limited:
\begin{itemize}
\item On 32 bit systems the maximal size is $2^{29}$ bytes (512 MB).
\item On 64 bit systems the maximal size is $2^{61}$ bytes.
\end{itemize}
The reason is that the offset of an element must be calculated with
the maximum integer size of the system.
%
\subsection{Arrays}
\index{Types!Array}\index{Array}
\fpc supports arrays as in \tp. Multi-dimensional arrays and (bit)packed
arrays are also supported, as well as the dynamic arrays of \delphi:
\input{syntax/typearr.syn}
%
\subsubsection{Static arrays}
\index{Types!Array}\index{Array!Static}\keywordlink{array} \keywordlink{of}
When the range of the array is included in the array definition, it is
called a static array. Trying to access an element with an index that is
outside the declared range will generate a run-time error (if range checking
is on). The following is an example of a valid array declaration:
\begin{verbatim}
Type
RealArray = Array [1..100] of Real;
\end{verbatim}
Valid indexes for accessing an element of the array are between 1 and 100,
where the borders 1 and 100 are included.
As in \tp, if the array component type is in itself an array, it is
possible to combine the two arrays into one multi-dimensional array. The
following declaration:
\begin{verbatim}
Type
APoints = array[1..100] of Array[1..3] of Real;
\end{verbatim}
is equivalent to the declaration:
\begin{verbatim}
Type
APoints = array[1..100,1..3] of Real;
\end{verbatim}
The functions \var{High} and \var{Low} return the high and low bounds of
the leftmost index type of the array. In the above case, this would be 100
and 1. You should use them whenever possible, since it improves maintainability
of your code. The use of both functions is just as efficient as using
constants, because they are evaluated at compile time.
When static array-type variables are assigned to each other, the contents of the
whole array is copied. This is also true for multi-dimensional arrays:
\begin{verbatim}
program testarray1;
Type
TA = Array[0..9,0..9] of Integer;
var
A,B : TA;
I,J : Integer;
begin
For I:=0 to 9 do
For J:=0 to 9 do
A[I,J]:=I*J;
For I:=0 to 9 do
begin
For J:=0 to 9 do
Write(A[I,J]:2,' ');
Writeln;
end;
B:=A;
Writeln;
For I:=0 to 9 do
For J:=0 to 9 do
A[9-I,9-J]:=I*J;
For I:=0 to 9 do
begin
For J:=0 to 9 do
Write(B[I,J]:2,' ');
Writeln;
end;
end.
\end{verbatim}
The output of this program will be 2 identical matrices.
\subsubsection{Dynamic arrays}
\index{Types!Array}\index{Array!Dynamic}\index{Types!Reference counted}
As of version 1.1, \fpc also knows dynamic arrays: In that case the array
range is omitted, as in the following example:
\begin{verbatim}
Type
TByteArray = Array of Byte;
\end{verbatim}
When declaring a variable of a dynamic array type, the initial length of the
array is zero. The actual length of the array must be set with the standard
\var{SetLength} function, which will allocate the necessary memory to contain
the array elements on the heap. The following example will set the length to
1000:
\begin{verbatim}
Var
A : TByteArray;
begin
SetLength(A,1000);
\end{verbatim}
After a call to \var{SetLength}, valid array indexes are 0 to 999: the array
index is always zero-based.
Note that the length of the array is set in elements, not in bytes of
allocated memory (although these may be the same). The amount of
memory allocated is the size of the array multiplied by the size of
1 element in the array. The memory will be disposed of at the exit of the
current procedure or function.
It is also possible to resize the array: in that case, as much of the
elements in the array as will fit in the new size, will be kept. The array
can be resized to zero, which effectively resets the variable.
At all times, trying to access an element of the array with an index
that is not in the current length of the array will generate a run-time
error.
Dynamic arrays are reference counted: assignment of one dynamic array-type
variable to another will let both variables point to the same array.
Contrary to ansistrings, an assignment to an element of one array will
be reflected in the other: there is no copy-on-write. Consider the following
example:
\begin{verbatim}
Var
A,B : TByteArray;
begin
SetLength(A,10);
A[0]:=33;
B:=A;
A[0]:=31;
\end{verbatim}
After the second assignment, the first element in B will also contain 31.
It can also be seen from the output of the following example:
\begin{verbatim}
program testarray1;
Type
TA = Array of array of Integer;
var
A,B : TA;
I,J : Integer;
begin
Setlength(A,10,10);
For I:=0 to 9 do
For J:=0 to 9 do
A[I,J]:=I*J;
For I:=0 to 9 do
begin
For J:=0 to 9 do
Write(A[I,J]:2,' ');
Writeln;
end;
B:=A;
Writeln;
For I:=0 to 9 do
For J:=0 to 9 do
A[9-I,9-J]:=I*J;
For I:=0 to 9 do
begin
For J:=0 to 9 do
Write(B[I,J]:2,' ');
Writeln;
end;
end.
\end{verbatim}
The output of this program will be a matrix of numbers, and then the same matrix, mirrorred.
\index{Types!Reference counted}
As remarked earlier, dynamic arrays are reference counted: if in one of the previous examples A
goes out of \index{Scope} scope and B does not, then the array is not yet disposed of: the
reference count of A (and B) is decreased with 1. As soon as the reference
count reaches zero the memory, allocated for the contents of the array, is disposed of.
It is also possible to copy and/or resize the array with the standard
\var{Copy} function, which acts as the copy function for strings:
\begin{verbatim}
program testarray3;
Type
TA = array of Integer;
var
A,B : TA;
I : Integer;
begin
Setlength(A,10);
For I:=0 to 9 do
A[I]:=I;
B:=Copy(A,3,6);
For I:=0 to 5 do
Writeln(B[I]);
end.
\end{verbatim}
The \var{Copy} function will copy 6 elements of the array to a new array.
Starting at the element at index 3 (i.e. the fourth element) of the array.
The \var{Length} function will return the number of elements in the array.
The \var{Low} function on a dynamic array will always return 0, and the
\var{High} function will return the value \var{Length-1}, i.e., the value of the
highest allowed array index.
\subsubsection{Packing and unpacking an array}
Arrays can be packed and bitpacked. 2 array types which have the same index
type and element type, but which are differently packed are not assignment
compatible.
However, it is possible to convert a normal array to a bitpacked array with the
\var{pack} routine. The reverse operation is possible as well; a bitpacked
array can be converted to a normally packed array using the \var{unpack}
routine, as in the following example:
\begin{verbatim}
Var
foo : array [ 'a'..'f' ] of Boolean
= ( false, false, true, false, false, false );
bar : packed array [ 42..47 ] of Boolean;
baz : array [ '0'..'5' ] of Boolean;
begin
pack(foo,'a',bar);
unpack(bar,baz,'0');
end.
\end{verbatim}
More information about the pack and unpack routines can be found in the
\file{system} unit reference.
%
\subsection{Record types}
\index{Record}\index{Types!Record}\index{Fields}\keywordlink{record}
\fpc supports fixed records and records with variant parts.
The syntax diagram for a record type is
\input{syntax/typerec.syn}
\index{Packed} So the following are valid record type declarations:
\begin{verbatim}
Type
Point = Record
X,Y,Z : Real;
end;
RPoint = Record
Case Boolean of
False : (X,Y,Z : Real);
True : (R,theta,phi : Real);
end;
BetterRPoint = Record
Case UsePolar : Boolean of
False : (X,Y,Z : Real);
True : (R,theta,phi : Real);
end;
\end{verbatim}
The variant part must be last in the record. The optional identifier in the
case statement serves to access the tag field value, which otherwise would
be invisible to the programmer. It can be used to see which variant is
active at a certain time\footnote{However, it is up to the programmer to maintain
this field.}. In effect, it introduces a new field in the record.
\begin{remark}
It is possible to nest variant parts, as in:
\begin{verbatim}
Type
MyRec = Record
X : Longint;
Case byte of
2 : (Y : Longint;
case byte of
3 : (Z : Longint);
);
end;
\end{verbatim}
\end{remark}
By default the size of a record is the sum of the sizes of its fields, each size of a
field is rounded up to a power of two. If the record contains a variant part, the size
of the variant part is the size of the biggest variant, plus the size of the
tag field type {\em if an identifier was declared for it}. Here also, the size of
each part is first rounded up to two. So in the above example:
\begin{itemize}
\item \var{SizeOf} would return 24 for \var{Point},
\item It would result in 24 for \var{RPoint}
\item Finally, 26 would be the size of \var{BetterRPoint}.
\item For \var{MyRec}, the value would be 12.
\end{itemize}
If a typed file with records, produced by a \tp program, must be read,
then chances are that attempting to read that file correctly will fail.
The reason for this is that by default, elements of a record are aligned at
2-byte boundaries, for performance reasons.
This default behaviour can be changed with the \var{\{\$PACKRECORDS N\}}
switch. Possible values for \var{N} are 1, 2, 4, 16 or \var{Default}.\index{Packed}
This switch tells the compiler to align elements of a record or object or
class that have size larger than \var{n} on \var{n} byte boundaries.
Elements that have size smaller or equal than \var{n} are aligned on
natural boundaries, i.e. to the first power of two that is larger than or
equal to the size of the record element.
The keyword \var{Default} selects the default value for the platform
that the code is compiled for (currently, this is 2 on all platforms)
Take a look at the following program:
\begin{verbatim}
Program PackRecordsDemo;
type
{$PackRecords 2}
Trec1 = Record
A : byte;
B : Word;
end;
{$PackRecords 1}
Trec2 = Record
A : Byte;
B : Word;
end;
{$PackRecords 2}
Trec3 = Record
A,B : byte;
end;
{$PackRecords 1}
Trec4 = Record
A,B : Byte;
end;
{$PackRecords 4}
Trec5 = Record
A : Byte;
B : Array[1..3] of byte;
C : byte;
end;
{$PackRecords 8}
Trec6 = Record
A : Byte;
B : Array[1..3] of byte;
C : byte;
end;
{$PackRecords 4}
Trec7 = Record
A : Byte;
B : Array[1..7] of byte;
C : byte;
end;
{$PackRecords 8}
Trec8 = Record
A : Byte;
B : Array[1..7] of byte;
C : byte;
end;
Var rec1 : Trec1;
rec2 : Trec2;
rec3 : TRec3;
rec4 : TRec4;
rec5 : Trec5;
rec6 : TRec6;
rec7 : TRec7;
rec8 : TRec8;
begin
Write ('Size Trec1 : ',SizeOf(Trec1));
Writeln (' Offset B : ',Longint(@rec1.B)-Longint(@rec1));
Write ('Size Trec2 : ',SizeOf(Trec2));
Writeln (' Offset B : ',Longint(@rec2.B)-Longint(@rec2));
Write ('Size Trec3 : ',SizeOf(Trec3));
Writeln (' Offset B : ',Longint(@rec3.B)-Longint(@rec3));
Write ('Size Trec4 : ',SizeOf(Trec4));
Writeln (' Offset B : ',Longint(@rec4.B)-Longint(@rec4));
Write ('Size Trec5 : ',SizeOf(Trec5));
Writeln (' Offset B : ',Longint(@rec5.B)-Longint(@rec5),
' Offset C : ',Longint(@rec5.C)-Longint(@rec5));
Write ('Size Trec6 : ',SizeOf(Trec6));
Writeln (' Offset B : ',Longint(@rec6.B)-Longint(@rec6),
' Offset C : ',Longint(@rec6.C)-Longint(@rec6));
Write ('Size Trec7 : ',SizeOf(Trec7));
Writeln (' Offset B : ',Longint(@rec7.B)-Longint(@rec7),
' Offset C : ',Longint(@rec7.C)-Longint(@rec7));
Write ('Size Trec8 : ',SizeOf(Trec8));
Writeln (' Offset B : ',Longint(@rec8.B)-Longint(@rec8),
' Offset C : ',Longint(@rec8.C)-Longint(@rec8));
end.
\end{verbatim}
The output of this program will be :
\begin{verbatim}
Size Trec1 : 4 Offset B : 2
Size Trec2 : 3 Offset B : 1
Size Trec3 : 2 Offset B : 1
Size Trec4 : 2 Offset B : 1
Size Trec5 : 8 Offset B : 4 Offset C : 7
Size Trec6 : 8 Offset B : 4 Offset C : 7
Size Trec7 : 12 Offset B : 4 Offset C : 11
Size Trec8 : 16 Offset B : 8 Offset C : 15
\end{verbatim}
And this is as expected:
\begin{itemize}
\item In \var{Trec1}, since \var{B} has size 2, it is
aligned on a 2 byte boundary, thus leaving an empty byte between \var{A}
and \var{B}, and making the total size 4. In \var{Trec2}, \var{B} is aligned
on a 1-byte boundary, right after \var{A}, hence, the total size of the
record is 3.
\item For \var{Trec3}, the sizes of \var{A,B} are 1, and hence they are aligned on 1
byte boundaries. The same is true for \var{Trec4}.
\item For \var{Trec5}, since the size of B -- 3 -- is smaller than 4, \var{B} will
be on a 4-byte boundary, as this is the first power of two that is
larger than its size. The same holds for \var{Trec6}.
\item For \var{Trec7}, \var{B} is aligned on a 4 byte boundary, since its size --
7 -- is larger than 4. However, in \var{Trec8}, it is aligned on a 8-byte
boundary, since 8 is the first power of two that is greater than 7, thus
making the total size of the record 16.
\end{itemize}
\fpc supports also the 'packed record', this is a record where all the
elements are byte-aligned. Thus the two following declarations are equivalent:
\begin{verbatim}
{$PackRecords 1}
Trec2 = Record
A : Byte;
B : Word;
end;
{$PackRecords 2}
\end{verbatim}
and
\begin{verbatim}
Trec2 = Packed Record
A : Byte;
B : Word;
end;
\end{verbatim}
Note the \var{\{\$PackRecords 2\}} after the first declaration !
%
\subsection{Set types}
\index{Set}\index{Types!Set}\keywordlink{set}
\fpc supports the set types as in \tp. The prototype of a set
declaration is:
\input{syntax/typeset.syn}
Each of the elements of \var{SetType} must be of type \var{TargetType}.
\var{TargetType} can be any ordinal type with a range between \var{0} and
\var{255}. A set can contain at most \var{255} elements.
The following are valid set declaration:
\begin{verbatim}
Type
Junk = Set of Char;
Days = (Mon, Tue, Wed, Thu, Fri, Sat, Sun);
WorkDays : Set of days;
\end{verbatim}
Given these declarations, the following assignment is legal:
\begin{verbatim}
WorkDays := [Mon, Tue, Wed, Thu, Fri];
\end{verbatim}
The compiler stores small sets (less than 32 elements) in a Longint, if the
type range allows it. This allows for faster processing and decreases
program size. Otherwise, sets are stored in 32 bytes.
Several operations can be done on sets: taking unions or differences, adding
or removing elements, comparisons. These are documented in
\sees{setoperators}
%
%
\subsection{File types}
\index{File}\index{Text}\index{Types!File}\keywordlink{file}
File types are types that store a sequence of some base type, which can be
any type except another file type. It can contain (in principle) an infinite
number of elements.
File types are used commonly to store data on disk. However, nothing prevents the programmer,
from writing a file driver that stores its data for instance in memory.
Here is the type declaration for a file type:
\input{syntax/typefil.syn}
If no type identifier is given, then the file is an untyped file; it can be
considered as equivalent to a file of bytes. Untyped files require special
commands to act on them (see \var{Blockread}, \var{Blockwrite}).
The following declaration declares a file of records:
\begin{verbatim}
Type
Point = Record
X,Y,Z : real;
end;
PointFile = File of Point;
\end{verbatim}
Internally, files are represented by the \var{FileRec} record, which is
declared in the \file{Dos} or \file{SysUtils} units.
\keywordlink{Text}
A special file type is the \var{Text} file type, represented by the
\var{TextRec} record. A file of type \var{Text} uses special input-output
routines. The default \var{Input}, \var{Output} and \var{StdErr} file
types are defined in the system unit: they are all of type \var{Text}, and
are opened by the system unit initialization code.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Pointers
\section{Pointers}
\index{Pointer}\index{Types!Pointer}\keywordlink{pointer}
\fpc supports the use of pointers. A variable of the pointer type
contains an address in memory, where the data of another variable may be
stored. A pointer type can be defined as follows:
\input{syntax/typepoin.syn}
As can be seen from this diagram, pointers are typed, which means that
they point to a particular kind of data. The type of this data must be
known at compile time.
Dereferencing the pointer (denoted by adding \var{\^{}} after the variable
name) behaves then like a variable. This variable has the type declared in
the pointer declaration, and the variable is stored in the address that is
pointed to by the pointer variable.
Consider the following example:
\begin{verbatim}
Program pointers;
type
Buffer = String[255];
BufPtr = ^Buffer;
Var B : Buffer;
BP : BufPtr;
PP : Pointer;
etc..
\end{verbatim}
In this example, \var{BP} {\em is a pointer to} a \var{Buffer} type; while \var{B}
{\em is} a variable of type \var{Buffer}. \var{B} takes 256 bytes memory,
and \var{BP} only takes 4 (or 8) bytes of memory: enough memory to store an
address.
The expression
\begin{verbatim}
BP^
\end{verbatim}
is known as the dereferencing of \var{BP}. The result is of type \var{Buffer}, so
\begin{verbatim}
BP^[23]
\end{verbatim}
Denotes the 23-rd character in the string pointed to by \var{BP}.
\begin{remark} \fpc treats pointers much the same way as C does. This means
that a pointer to some type can be treated as being an array of this type.
From this point of view, the pointer then points to the zeroeth element of this array.
Thus the following pointer declaration
\begin{verbatim}
Var p : ^Longint;
\end{verbatim}
can be considered equivalent to the following array declaration:
\begin{verbatim}
Var p : array[0..Infinity] of Longint;
\end{verbatim}
The difference is that the former declaration allocates memory for the
pointer only (not for the array), and the second declaration allocates
memory for the entire array. If the former is used, the memory must be
allocated manually, using the \var{Getmem} function.
The reference \var{P\^{}} is then the same as \var{p[0]}. The following program
illustrates this maybe more clear:
\begin{verbatim}
program PointerArray;
var i : Longint;
p : ^Longint;
pp : array[0..100] of Longint;
begin
for i := 0 to 100 do pp[i] := i; { Fill array }
p := @pp[0]; { Let p point to pp }
for i := 0 to 100 do
if p[i]<>pp[i] then
WriteLn ('Ohoh, problem !')
end.
\end{verbatim}
\end{remark}
\fpc supports pointer arithmetic as C does. This means that, if \var{P} is a
typed pointer, the instructions
\begin{verbatim}
Inc(P);
Dec(P);
\end{verbatim}
Will increase, respectively decrease the address the pointer points to
with the size of the type \var{P} is a pointer to. For example
\begin{verbatim}
Var P : ^Longint;
...
Inc (p);
\end{verbatim}
will increase \var{P} with 4, because 4 is the size of a longint. If the
pointer is untyped, a size of 1 byte is assumed (i.e. as if the pointer were
a pointer to a byte: \var{\^byte}.)
Normal arithmetic operators \index{Operators} on pointers can also be used,
that is, the following are valid pointer arithmetic operations:
\begin{verbatim}
var p1,p2 : ^Longint;
L : Longint;
begin
P1 := @P2;
P2 := @L;
L := P1-P2;
P1 := P1-4;
P2 := P2+4;
end.
\end{verbatim}
Here, the value that is added or substracted {\em is } multiplied by the
size of the type the pointer points to. In the previous
example \var{P1} will be decremented by 16 bytes, and
\var{P2} will be incremented by 16.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Forward type declarations
\section{Forward type declarations}
\index{Forward}\index{Types!Forward declaration}
Programs often need to maintain a linked list of records. Each record then
contains a pointer to the next record (and possibly to the previous record
as well). For type safety, it is best to define this pointer as a typed
pointer, so the next record can be allocated on the heap using the \var{New}
call. In order to do so, the record should be defined something like this:
\begin{verbatim}
Type
TListItem = Record
Data : Integer;
Next : ^TListItem;
end;
\end{verbatim}
When trying to compile this, the compiler will complain that the
\var{TListItem} type is not yet defined when it encounters the \var{Next}
declaration: This is correct, as the definition is still being parsed.
To be able to have the \var{Next} element as a typed pointer, a 'Forward
type declaration' must be introduced:
\begin{verbatim}
Type
PListItem = ^TListItem;
TListItem = Record
Data : Integer;
Next : PTListItem;
end;
\end{verbatim}
When the compiler encounters a typed pointer declaration where the
referenced type is not yet known, it postpones resolving the reference till
later. The pointer definition is a 'Forward type declaration'.
The referenced type should be introduced later in the same \var{Type} block.
No other block may come between the definition of the pointer type and the referenced type.
Indeed, even the word \var{Type} itself may not re-appear: in effect it
would start a new type-block, causing the compiler to resolve all pending
declarations in the current block.
In most cases, the definition of the referenced type will follow immediatly
after the definition of the pointer type, as shown in the above listing.
The forward defined type can be used in any type definition following its
declaration.
Note that a forward type declaration is only possible with pointer types and
classes, not with other types.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Procedural types
\section{Procedural types}
\index{Procedure}\index{Types!Procedural}\index{Procedural}
\fpc has support for procedural types, although it differs a little from
the \tp or \delphi implementation of them. The type declaration remains the
same, as can be seen in the following syntax diagram:
\input{syntax/typeproc.syn}
For a description of formal parameter lists, see \seec{Procedures}.
The two following examples are valid type declarations:
\begin{verbatim}
Type TOneArg = Procedure (Var X : integer);
TNoArg = Function : Real;
var proc : TOneArg;
func : TNoArg;
\end{verbatim}
One can assign the following values to a procedural type variable:
\begin{enumerate}
\item \var{Nil}, for both normal procedure pointers and method pointers.
\item A variable reference of a procedural type, i.e. another variable of
the same type.
\item A global procedure or function address, with matching function or
procedure header and calling convention.
\item A method address.
\end{enumerate}
Given these declarations, the following assignments are valid:
\begin{verbatim}
Procedure printit (Var X : Integer);
begin
WriteLn (x);
end;
...
Proc := @printit;
Func := @Pi;
\end{verbatim}
From this example, the difference with \tp is clear: In Turbo
Pascal it isn't necessary to use the address operator (\var{@})
when assigning a procedural type variable, whereas in \fpc it is required.
In case the \var{-MDelphi} or \var{-MTP} switches are used, the address
operator can be dropped.
\begin{remark} The modifiers concerning the calling conventions
must be the same as the declaration;
i.e. the following code would give an error:
\begin{verbatim}
Type TOneArgCcall = Procedure (Var X : integer);cdecl;
var proc : TOneArgCcall;
Procedure printit (Var X : Integer);
begin
WriteLn (x);
end;
begin
Proc := @printit;
end.
\end{verbatim}
Because the \var{TOneArgCcall} type is a procedure that uses the cdecl
calling convention.
\end{remark}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Variant types
\section{Variant types}
\index{Variant}\index{Types!Variant} \keywordlink{variant}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Definition
\subsection{Definition}
As of version 1.1, FPC has support for variants. For maximum variant support
it is recommended to add the \file{variants} unit to the uses clause of every
unit that uses variants in some way: the variants unit contains support for
examining and transforming variants other than the default support offered
by the \file{System} or \var{ObjPas} units.
The type of a value stored in a variant is only determined at runtime:
it depends what has been assigned to the to the variant. Almost any simple type
can be assigned to variants: ordinal types, string types, int64 types.
Structured types such as sets, records, arrays, files, objects and classes
are not assignment-compatible with a variant, as well as pointers.
Interfaces and COM or CORBA objects can be assigned to a
variant (basically because they are simply a pointer).\index{Interfaces}\index{COM}\index{CORBA}
This means that the following assignments are valid:
\begin{verbatim}
Type
TMyEnum = (One,Two,Three);
Var
V : Variant;
I : Integer;
B : Byte;
W : Word;
Q : Int64;
E : Extended;
D : Double;
En : TMyEnum;
AS : AnsiString;
WS : WideString;
begin
V:=I;
V:=B;
V:=W;
V:=Q;
V:=E;
V:=En;
V:=D:
V:=AS;
V:=WS;
end;
\end{verbatim}
And of course vice-versa as well.
A variant can hold an an array of values: All elements in the array have
the\index{array} same type (but can be of type 'variant'). For a variant
that contains an array, the variant can be indexed:
\begin{verbatim}
Program testv;
uses variants;
Var
A : Variant;
I : integer;
begin
A:=VarArrayCreate([1,10],varInteger);
For I:=1 to 10 do
A[I]:=I;
end.
\end{verbatim}
For the explanation of \var{VarArrayCreate}, see \unitsref.
Note that when the array contains a string, this is not considered an 'array
of characters', and so the variant cannot be indexed to retrieve a character
at a certain position in the string.
\subsection{Variants in assignments and expressions}
As can be seen from the definition above, most simple types can be assigned
to a variant. Likewise, a variant can be assigned to a simple type: If
possible, the value of the variant will be converted to the type that is
being assigned to. This may fail: Assigning a variant containing a string
to an integer will fail unless the string represents a valid integer. In the
following example, the first assignment will work, the second will fail:
\begin{verbatim}
program testv3;
uses Variants;
Var
V : Variant;
I : Integer;
begin
V:='100';
I:=V;
Writeln('I : ',I);
V:='Something else';
I:=V;
Writeln('I : ',I);
end.
\end{verbatim}
The first assignment will work, but the second will not, as \var{Something else}
cannot be converted to a valid integer value. An \var{EConvertError} exception
will be the result.
The result of an expression involving a variant will be of type variant again,
but this can be assigned to a variable of a different type - if the result
can be converted to a variable of this type.
Note that expressions involving variants take more time to be evaluated, and
should therefore be used with caution. If a lot of calculations need to be
made, it is best to avoid the use of variants.
When considering implicit type conversions (e.g. byte to integer, integer to
double, char to string) the compiler will ignore variants unless a variant
appears explicitly in the expression.
\subsection{Variants and interfaces}
\index{Interfaces}
\begin{remark}
Dispatch interface support for variants is currently broken in the compiler.
\end{remark}
Variants can contain a reference to an interface - a normal interface
(descending from \var{IInterface}) or a dispatchinterface (descending
from \var{IDispatch}). Variants containing a reference to a dispatch
interface can be used to control the object behind it: the compiler will use
late binding to perform the call to the dispatch interface: there will be no
run-time checking of the function names and parameters or arguments given to
the functions. The result type is also not checked. The compiler will simply
insert code to make the dispatch call and retrieve the result.
This means basically, that you can do the following on Windows:
\begin{verbatim}
Var
W : Variant;
V : String;
begin
W:=CreateOleObject('Word.Application');
V:=W.Application.Version;
Writeln('Installed version of MS Word is : ',V);
end;
\end{verbatim}
The line
\begin{verbatim}
V:=W.Application.Version;
\end{verbatim}
is executed by inserting the necessary code to query the dispatch interface
stored in the variant \var{W}, and execute the call if the needed dispatch
information is found.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Variables
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\chapter{Variables}
\index{Variables}\index{Variable}\index{Var}\keywordlink{var}
\label{ch:Variables}
\section{Definition}
Variables are explicitly named memory locations with a certain type. When
assigning values to variables, the \fpc compiler generates machine code
to move the value to the memory location reserved for this variable. Where
this variable is stored depends on where it is declared:
\begin{itemize}
\item Global variables are variables declared in a unit or program, but not
inside a procedure or function. They are stored in fixed memory locations,
and are available during the whole execution time of the program.
\item Local variables are declared inside a procedure or function. Their
value is stored on the program stack, i.e. not at fixed locations.
\end{itemize}
The \fpc compiler handles the allocation of these memory locations
transparantly, although this location can be influenced in the declaration.
The \fpc compiler also handles reading values from or writing values to
the variables transparantly. But even this can be explicitly handled by the
programmer when using properties.
Variables must be explicitly declared when they are needed. No memory is
allocated unless a variable is declared. Using an variable identifier (for
instance, a loop variable) which is not declared first, is an error which
will be reported by the compiler.
\section{Declaration}
The variables must be declared in a variable declaration section of a unit
or a procedure or function. It looks as follows:\index{Var}
\input{syntax/vardecl.syn}
\keywordlink{cvar} \keywordlink{public}
This means that the following are valid variable declarations:
\keywordlink{absolute} \keywordlink{export}
\begin{verbatim}
Var
curterm1 : integer;
curterm2 : integer; cvar;
curterm3 : integer; cvar; external;
curterm4 : integer; external name 'curterm3';
curterm5 : integer; external 'libc' name 'curterm9';
curterm6 : integer absolute curterm1;
curterm7 : integer; cvar; export;
curterm8 : integer; cvar; public;
curterm9 : integer; export name 'me';
curterm10 : integer; public name 'ma';
curterm11 : integer = 1 ;
\end{verbatim}
\index{external}
The difference between these declarations is as follows:
\begin{enumerate}
\item The first form (\var{curterm1}) defines a regular variable. The
compiler manages everything by itself.
\item The second form (\var{curterm2}) declares also a regular variable,
but specifies that the assembler name for this variable equals the name
of the variable as written in the source.
\item The third form (\var{curterm3}) declares a variable which is located
externally: the compiler will assume memory is located elsewhere, and that
the assembler name of this location is specified by the name of the
variable, as written in the source. The name may not be specified.
\item The fourth form is completely equivalent to the third, it declares a
variable which is stored externally, and explicitly gives the assembler
name of the location. If \var{cvar} is not used, the name must be specified.
\item The fifth form is a variant of the fourth form, only the name of the
library in which the memory is reserved is specified as well.
\item The sixth form declares a variable (\var{curterm6}), and tells the compiler that it is
stored in the same location as another variable (\var{curterm1}).
\item The seventh form declares a variable (\var{curterm7}), and tells the
compiler that the assembler label of this variable should be the name of the
variable (case sensitive) and must be made public. i.e. it can be
referenced from other object files.
\item The eighth form (\var{curterm8}) is equivalent to the seventh: 'public'
is an alias for 'export'.
\item The ninth and tenth form are equivalent: they specify the assembler
name of the variable.
\item the elevents form declares a variable (\var{curterm11}) and
initializes it with a value (1 in the above case).
\end{enumerate}
Note that assembler names must be unique. It's not possible to declare or
export 2 variables with the same assembler name.
\section{Scope}
\index{Scope}
Variables, just as any identifier, obey the general rules of scope.
In addition, initialized variables are initialized when they enter scope:
\begin{itemize}
\item Global initialized variables are initialized once, when the program starts.
\item Local initialized variables are initialized each time the procedure is
entered.
\end{itemize}
Note that the behaviour for local initialized variables is different from
the one of a local typed constant. A local typed constant behaves like a
global initialized variable.
\section{Initialized variables}
\label{se:initializedvars}\index{Variables!Initialized}
By default, variables in Pascal are not initialized after their declaration.
Any assumption that they contain 0 or any other default value is erroneous:
They can contain rubbish. To remedy this, the concept of initialized variables
exists. The difference with normal variables is that their declaration includes
an initial value, as can be seen in the diagram in the previous section.
Given the declaration:
\begin{verbatim}
Var
S : String = 'This is an initialized string';
\end{verbatim}
The value of the variable following will be initialized with the provided
value. The following is an even better way of doing this:
\begin{verbatim}
Const
SDefault = This is an initialized string';
Var
S : String = SDefault;
\end{verbatim}
Initialization is often used to initialize arrays and records. For arrays,
the initialized elements must be specified, surrounded by round brackets, and
separated by commas. The number of initialized elements must be exactly the
same as the number of elements in the declaration of the type.
As an example:
\begin{verbatim}
Var
tt : array [1..3] of string[20] = ('ikke', 'gij', 'hij');
ti : array [1..3] of Longint = (1,2,3);
\end{verbatim}
For constant records, each element of the record should be specified, in
the form \var{Field: Value}, separated by semicolons, and surrounded by round
brackets.\index{Record!Constant}
As an example:
\begin{verbatim}
Type
Point = record
X,Y : Real
end;
Var
Origin : Point = (X:0.0; Y:0.0);
\end{verbatim}
The order of the fields in a constant record needs to be the same as in the type
declaration, otherwise a compile-time error will occur.
\begin{remark}
It should be stressed that initialized variables are initialized when they
come into scope, in difference with typed constants, which are initialized
at program start.
This is also true for {\em local} initialized variables. Local initialized are
initialized whenever the routine is called. Any changes that occurred in the
previous invocation of the routine will be undone, because they are again
initialized.
\end{remark}
\section{Thread Variables}
\index{Thread Variables}\index{Threadvar}\keywordlink{threadvar}
For a program which uses threads, the variables can be really global, i.e. the same for all
threads, or thread-local: this means that each thread gets a copy of the variable.
Local variables (defined inside a procedure) are always thread-local. Global
variables are normally the same for all threads. A global variable can be
declared thread-local by replacing the \var{var} keyword at the start of the
variable declaration block with \var{Threadvar}:
\begin{verbatim}
Threadvar
IOResult : Integer;
\end{verbatim}
If no threads are used, the variable behaves as an ordinary variable.
If threads are used then a copy is made
for each thread (including the main thread). Note that the copy is
made with the original value of the variable, {\em not} with the
value of the variable at the time the thread is started.
Threadvars should be used sparingly: There is an overhead for retrieving
or setting the variable's value. If possible at all, consider using local
variables; they are always faster than thread variables.
Threads are not enabled by default. For more information about programming
threads, see the chapter on threads in the \progref.
\section{Properties}
\index{Properties}\keywordlink{property}
A global block can declare properties, just as they could be defined in a
class. The difference is that the global property does not need a class
instance: there is only 1 instance of this property. Other than that, a
global property behaves like a class property. The read/write specifiers for
the global property must also be regular procedures, not methods.
The concept of a global property is specific to \fpc, and does not exist in
Delphi. \var{ObjFPC} mode is required to work with properties.
The concept of a global property can be used to 'hide' the location of the
value, or to calculate the value on the fly, or to check the values which
are written to the property.
The declaration is as follows:
\input{syntax/propvar.syn}
The following is an example:
\begin{verbatim}
{$mode objfpc}
unit testprop;
Interface
Function GetMyInt : Integer;
Procedure SetMyInt(Value : Integer);
Property
MyProp : Integer Read GetMyInt Write SetMyInt;
Implementation
Uses sysutils;
Var
FMyInt : Integer;
Function GetMyInt : Integer;
begin
Result:=FMyInt;
end;
Procedure SetMyInt(Value : Integer);
begin
If ((Value mod 2)=1) then
Raise Exception.Create('MyProp can only contain even value');
FMyInt:=Value;
end;
end.
\end{verbatim}
The read/write specifiers can be hidden by declaring them in another unit
which must be in the \var{uses} clause of the unit. This can be used to hide
the read/write access specifiers for programmers, just as if they were in a
\var{private} section of a class (discussed below). For the previous
example, this could look as follows:
\begin{verbatim}
{$mode objfpc}
unit testrw;
Interface
Function GetMyInt : Integer;
Procedure SetMyInt(Value : Integer);
Implementation
Uses sysutils;
Var
FMyInt : Integer;
Function GetMyInt : Integer;
begin
Result:=FMyInt;
end;
Procedure SetMyInt(Value : Integer);
begin
If ((Value mod 2)=1) then
Raise Exception.Create('Only even values are allowed');
FMyInt:=Value;
end;
end.
\end{verbatim}
The unit \file{testprop} would then look like:
\begin{verbatim}
{$mode objfpc}
unit testprop;
Interface
uses testrw;
Property
MyProp : Integer Read GetMyInt Write SetMyInt;
Implementation
end.
\end{verbatim}
More information about properties can be found in \seec{Classes}.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Objects
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\chapter{Objects}
\label{ch:Objects}
\index{Objects}\index{Types!Object}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Declaration
\section{Declaration}
\fpc supports object oriented programming. In fact, most of the compiler is
written using objects. Here we present some technical questions regarding
object oriented programming in \fpc.
Objects should be treated as a special kind of record. The record contains
all the fields that are declared in the objects definition, and pointers
to the methods that are associated to the objects' type.
An object is declared just as a record would be declared; except that
now, procedures and functions can be declared as if they were part of the record.
Objects can ''inherit'' fields and methods from ''parent'' objects. This means
that these fields and methods can be used as if they were included in the
objects declared as a ''child'' object.
Furthermore, a concept of visibility \index{Visibility} is introduced:
fields, procedures and functions can be declared as \var{public},
\var{protected} or
\var{private}. By default, fields and methods are \var{public}, and
are exported outside the current unit.
\index{Visibility!Public}\index{Visibility!Private}
Fields or methods that are declared \var{private} are only accessible
in the current unit: their scope is limited to the implementation of the
current unit.\index{Scope}
The prototype declaration of an object is as follows:
\index{object}\keywordlink{object}
\input{syntax/typeobj.syn}
As can be seen, as many \var{private} and \var{public} blocks as needed can be
declared.\index{private}\index{public}
The following is a valid definition of an object:
\begin{verbatim}
Type
TObj = object
Private
Caption : ShortString;
Public
Constructor init;
Destructor done;
Procedure SetCaption (AValue : String);
Property GetCaption : String;
end;
\end{verbatim}
It contains a constructor/destructor pair, and a method to get and set a
caption. The \var{Caption} field is private to the object: it cannot be accessed
outside the unit in which \var{TObj} is declared.
\begin{remark}
In MacPas mode, the \var{Object} keyword is replaced by the \var{class}
keyword for compatibility with other pascal compilers available on the Mac.
That means that objects cannot be used in MacPas mode.
\end{remark}
\begin{remark}\index{Packed}
\fpc also supports the packed object. This is the same as an object, only
the elements (fields) of the object are byte-aligned, just as in the packed
record.
The declaration of a packed object is similar to the declaration
of a packed record :
\begin{verbatim}
Type
TObj = packed object
Constructor init;
...
end;
Pobj = ^TObj;
Var PP : Pobj;
\end{verbatim}
Similarly, the \var{\{\$PackRecords \}} directive acts on objects as well.
\end{remark}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Fields
\section{Fields}
\index{Fields}
Object Fields are like record fields. They are accessed in the same way as
a record field would be accessed : by using a qualified identifier. Given the
following declaration:
\begin{verbatim}
Type TAnObject = Object
AField : Longint;
Procedure AMethod;
end;
Var AnObject : TAnObject;
\end{verbatim}
then the following would be a valid assignment:
\begin{verbatim}
AnObject.AField := 0;
\end{verbatim}
Inside methods, fields can be accessed using the short identifier:
\begin{verbatim}
Procedure TAnObject.AMethod;
begin
...
AField := 0;
...
end;
\end{verbatim}
Or, one can use the \var{self} identifier. The \var{self} identifier refers
to the current instance of the object:
\begin{verbatim}
Procedure TAnObject.AMethod;
begin
...
Self.AField := 0;
...
end;
\end{verbatim}
One cannot access fields that are in a private or protected sections of an object from
outside the objects' methods. If this is attempted anyway, the compiler will complain about
an unknown identifier.
It is also possible to use the \var{with} statement with an object instance,
just as with a record:
\begin{verbatim}
With AnObject do
begin
Afield := 12;
AMethod;
end;
\end{verbatim}
In this example, between the \var{begin} and \var{end}, it is as if
\var{AnObject} was prepended to the \var{Afield} and \var{Amethod}
identifiers. More about this in \sees{With}.
\section{Static fields}
\keywordlink{static}
When the \var{\{\$STATIC ON\}} directive is active, then an object
can contain static fields: these fields are global to the object type, and act
like global variables, but are known only as part of the object. They can be
referenced from within the objects methods, but can also be referenced from
outside the object by providing the fully qualified name.
For instance, the output of the following program:
\begin{verbatim}
{$static on}
type
cl=object
l : longint;static;
end;
var
c1,c2 : cl;
begin
c1.l:=2;
writeln(c2.l);
c2.l:=3;
writeln(c1.l);
Writeln(cl.l);
end.
\end{verbatim}
will be the following
\begin{verbatim}
2
3
3
\end{verbatim}
Note that the last line of code references the object type itself (\var{cl}),
and not an instance of the object (\var{cl1} or \var{cl2}).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Constructors and destructors
\section{Constructors and destructors }
\index{Constructor}\index{Destructor} \keywordlink{constructor}
\keywordlink{destructor}
\index{Virtual}
\label{se:constructdestruct}
As can be seen in the syntax diagram for an object declaration, \fpc supports
constructors and destructors. The programmer is responsible for calling the
constructor and the destructor explicitly when using objects.
The declaration of a constructor or destructor is as follows:
\input{syntax/construct.syn}
A constructor/destructor pair is {\em required} if the object uses virtual methods.\index{Virtual}
The reason is that for an object with virtual methods, some internal
housekeeping must be done: this housekeeping is done by the
constructor\footnote{A pointer to the VMT must be set up.}.
In the declaration of the object type, a simple identifier should be used
for the name of the constuctor or destructor. When the constructor or destructor
is implemented, A qualified method identifier should be used,
i.e. an identifier of the form \var{objectidentifier.methodidentifier}.
\fpc supports also the extended syntax of the \var{New} and \var{Dispose}
procedures. In case a dynamic variable of an object type must be allocated
the constructor's name can be specified in the call to \var{New}.
The \var{New} is implemented as a function which returns a pointer to the
instantiated object. Consider the following declarations:
\begin{verbatim}
Type
TObj = object;
Constructor init;
...
end;
Pobj = ^TObj;
Var PP : Pobj;
\end{verbatim}
Then the following 3 calls are equivalent:
\begin{verbatim}
pp := new (Pobj,Init);
\end{verbatim}
and
\begin{verbatim}
new(pp,init);
\end{verbatim}
and also
\begin{verbatim}
new (pp);
pp^.init;
\end{verbatim}
In the last case, the compiler will issue a warning that the
extended syntax of \var{new} and \var{dispose} must be used to generate instances of an
object. It is possible to ignore this warning, but it's better programming practice to
use the extended syntax to create instances of an object.
Similarly, the \var{Dispose} procedure accepts the name of a destructor. The
destructor will then be called, before removing the object from the heap.
In view of the compiler warning remark, the following chapter presents the
Delphi approach to object-oriented programming, and may be considered a
more natural way of object-oriented programming.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Methods
\section{Methods}
\index{Methods}
Object methods are just like ordinary procedures or functions, only they
have an implicit extra parameter : \var{self}. Self points to the object
with which the method was invoked.\index{Self}
When implementing methods, the fully qualified identifier must be given
in the function header. When declaring methods, a normal identifier must be
given.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Method declaration
\subsection{Declaration}
The declaration of a method is much like a normal function or procedure
declaration, with some additional specifiers, as can be seen from the
following diagram, which is part of the object declaration:
\input{syntax/omethods.syn}
from the point of view of declarations, \var{Method definitions} are
normal function or procedure declarations.
Contrary to TP and Delphi, fields can be declared after methods in the same
block, i.e. the following will generate an error when compiling with Delphi
or \tp, but not with FPC:
\begin{verbatim}
Type
MyObj = Object
Procedure Doit;
Field : Longint;
end;
\end{verbatim}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Method invocation
\subsection{Method invocation}
Methods are called just as normal procedures are called, only they have an
object instance identifier prepended to them (see also \seec{Statements}).
To determine which method is called, it is necessary to know the type of
the method. We treat the different types in what follows.
\subsubsection{Static methods}
\index{Methods!Static}
Static methods are methods that have been declared without a \var{abstract}
or \var{virtual} keyword. When calling a static method, the declared (i.e.
compile time) method of the object is used.
For example, consider the following declarations:
\begin{verbatim}
Type
TParent = Object
...
procedure Doit;
...
end;
PParent = ^TParent;
TChild = Object(TParent)
...
procedure Doit;
...
end;
PChild = ^TChild;
\end{verbatim}
As it is visible, both the parent and child objects have a method called
\var{Doit}. Consider now the following declarations and calls:
\begin{verbatim}
Var
ParentA,ParentB : PParent;
Child : PChild;
begin
ParentA := New(PParent,Init);
ParentB := New(PChild,Init);
Child := New(PChild,Init);
ParentA^.Doit;
ParentB^.Doit;
Child^.Doit;
\end{verbatim}
Of the three invocations of \var{Doit}, only the last one will call
\var{TChild.Doit}, the other two calls will call \var{TParent.Doit}.
This is because for static methods, the compiler determines at compile
time which method should be called. Since \var{ParentB} is of type
\var{TParent}, the compiler decides that it must be called with
\var{TParent.Doit}, even though it will be created as a \var{TChild}.
There may be times when the method that is actually called should
depend on the actual type of the object at run-time. If so, the method
cannot be a static method, but must be a virtual method.
\subsubsection{Virtual methods}
\index{Virtual}\index{Methods!Virtual}\keywordlink{virtual}
To remedy the situation in the previous section, \var{virtual} methods are
created. This is simply done by appending the method declaration with the
\var{virtual} modifier. The descendent object can then override the method
with a new implementation by re-declaring the method (with the same
parameter list) using the \var{virtual} keyword.
Going back to the previous example, consider the following alternative
declaration:
\begin{verbatim}
Type
TParent = Object
...
procedure Doit;virtual;
...
end;
PParent = ^TParent;
TChild = Object(TParent)
...
procedure Doit;virtual;
...
end;
PChild = ^TChild;
\end{verbatim}
As it is visible, both the parent and child objects have a method called
\var{Doit}. Consider now the following declarations and calls :
\begin{verbatim}
Var
ParentA,ParentB : PParent;
Child : PChild;
begin
ParentA := New(PParent,Init);
ParentB := New(PChild,Init);
Child := New(PChild,Init);
ParentA^.Doit;
ParentB^.Doit;
Child^.Doit;
\end{verbatim}
Now, different methods will be called, depending on the actual run-time type
of the object. For \var{ParentA}, nothing changes, since it is created as
a \var{TParent} instance. For \var{Child}, the situation also doesn't
change: it is again created as an instance of \var{TChild}.
For \var{ParentB} however, the situation does change: Even though it was
declared as a \var{TParent}, it is created as an instance of \var{TChild}.
Now, when the program runs, before calling \var{Doit}, the program
checks what the actual type of \var{ParentB} is, and only then decides which
method must be called. Seeing that \var{ParentB} is of type \var{TChild},
\var{TChild.Doit} will be called. The code for this run-time checking of the actual type of an object is
inserted by the compiler at compile time.
The \var{TChild.Doit} is said to {\em override} the
\var{TParent.Doit}.\index{override} \index{inherited} \keywordlink{override}
\keywordlink{inherited}
It is possible to acces the \var{TParent.Doit} from within the
var{TChild.Doit}, with the \var{inherited} keyword:
\begin{verbatim}
Procedure TChild.Doit;
begin
inherited Doit;
...
end;
\end{verbatim}
In the above example, when \var{TChild.Doit} is called, the first thing it
does is call \var{TParent.Doit}. The inherited keyword cannot be used in
static methods, only on virtual methods.
To be able to do this, the compiler keeps - per object type - a table with
virtual methods: the VMT (Virtual Method Table). This is simply a table
with pointers to each of the virtual methods: each virtual method has its
fixed location in this table (an index). The compiler uses this table to
look up the actual method that must be used. When a descendent object
overrides a method, the entry of the parent method is overwritten in the
VMT. More information about the VMT can be found in \progref.
As remarked earlier, objects that have a VMT must be initialized with a
constructor: the object variable must be initialized with a pointer to
the VMT of the actual type that it was created with.
%
\subsubsection{Abstract methods}
\index{Abstract}\index{Methods!Abstract}\index{Methods!Virtual}\keywordlink{abstract}
An abstract method is a special kind of virtual method. A method that is
declared \var{abstract} does not have an implementation for this method.
It is up to inherited objects to override and implement this method.
From this it follows that a method can not be abstract if it is not virtual
(this can be seen from the syntax diagram). A second consequence is that
an instance of an object that has an abstract method cannot be created
directly.
The reason is obvious: there is no method where the compiler could jump to !
A method that is declared \var{abstract} does not have an implementation for
this method. It is up to inherited objects to override and implement this
method. Continuing our example, take a look at this:
\begin{verbatim}
Type
TParent = Object
...
procedure Doit;virtual;abstract;
...
end;
PParent=^TParent;
TChild = Object(TParent)
...
procedure Doit;virtual;
...
end;
PChild = ^TChild;
\end{verbatim}
As it is visible, both the parent and child objects have a method called
\var{Doit}. Consider now the following declarations and calls :
\begin{verbatim}
Var
ParentA,ParentB : PParent;
Child : PChild;
begin
ParentA := New(PParent,Init);
ParentB := New(PChild,Init);
Child := New(PChild,Init);
ParentA^.Doit;
ParentB^.Doit;
Child^.Doit;
\end{verbatim}
First of all, Line 3 will generate a compiler error, stating that one cannot
generate instances of objects with abstract methods: The compiler has
detected that \var{PParent} points to an object which has an abstract
method. Commenting line 3 would allow compilation of the program.
\begin{remark}
If an abstract method is overridden, The parent method cannot be called
with \var{inherited}, since there is no parent method; The compiler
will detect this, and complain about it, like this:
\begin{verbatim}
testo.pp(32,3) Error: Abstract methods can't be called directly
\end{verbatim}
If, through some mechanism, an abstract method is called at run-time,
then a run-time error will occur. (run-time error 211, to be precise)
\end{remark}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Visibility
\section{Visibility}
\index{Visibility}\index{Scope}\index{Private}\index{Protected}\index{Public}
For objects, 3 visibility specifiers exist : \var{private}, \var{protected} and
\var{public}. If a visibility specifier is not specified, \var{public}
is assumed.
Both methods and fields can be hidden from a programmer by putting them
in a \var{private} section. The exact visibility rule is as follows:
\begin{description}
\item [Private\ ] All fields and methods that are in a \var{private} block,
can only be accessed in the module (i.e. unit or program) that contains
the object definition.\keywordlink{private}
They can be accessed from inside the object's methods or from outside them
e.g. from other objects' methods, or global functions.
\item [Protected\ ] Is the same as \var{Private}, except that the members of
a \var{Protected} section are also accessible to descendent types, even if
they are implemented in other modules.\keywordlink{private}
\item [Public\ ] fields and methods are always accessible, from everywhere.
Fields and methods in a \var{public} section behave as though they were part
of an ordinary \var{record} type.\keywordlink{public}
\end{description}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Classes
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\chapter{Classes}
\label{ch:Classes}\index{Classes}\index{Types!Class}\keywordlink{class}
In the Delphi approach to Object Oriented Programming, everything revolves
around the concept of 'Classes'. A class can be seen as a pointer to an
object, or a pointer to a record, with methods associated with it.
The difference between objects and classes is mainly that an object
is allocated on the stack, as an ordinary record would be, and that
classes are always allocated on the heap. In the following example:
\begin{verbatim}
Var
A : TSomeObject; // an Object
B : TSomeClass; // a Class
\end{verbatim}
The main difference is that the variable \var{A} will take up as much
space on the stack as the size of the object (\var{TSomeObject}). The
variable \var{B}, on the other hand, will always take just the size of
a pointer on the stack. The actual class data is on the heap.
From this, a second difference follows: a class must {\em always} be initialized
through its constructor, whereas for an object, this is not necessary.
Calling the constructor allocates the necessary memory on the heap for the
class instance data.
\begin{remark}
In earlier versions of \fpc it was necessary, in order to use classes,
to put the \file{objpas} unit in the uses clause of a unit or program.
{\em This is no longer needed} as of version 0.99.12. As of this version,
the unit will be loaded automatically when the \var{-MObjfpc} or
\var{-MDelphi} options are specified, or their corresponding directives are
used:
\begin{verbatim}
{$mode objfpc}
{$mode delphi}
\end{verbatim}
In fact, the compiler will give a warning if it encounters the
\file{objpas} unit in a uses clause.
\end{remark}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Class definitions
\section{Class definitions}
The prototype declaration of a class is as follows:\index{Class}
\input{syntax/typeclas.syn}
\begin{remark}
In MacPas mode, the \var{Object} keyword is replaced by the \var{class}
keyword for compatibility with other pascal compilers available on the Mac.
That means that in MacPas mode, the reserved word 'class' in the above
diagram may be replaced by the reserved word 'object'.
\end{remark}
In a class declaration, as many \var{private}, \var{protected}, \var{published}
and \var{public} blocks as needed can be used: the various blocks can be
repeated, and there is no special order in which they must appear.
Methods are normal function or procedure declarations.
As can be seen, the declaration of a class is almost identical to the
declaration of an object. The real difference between objects and classes
is in the way they are created (see further in this chapter).
The visibility of the different sections is as follows:\index{Scope}
\begin{description}
\item [Private\ ] \index{Private}\index{Visibility!Protected} All fields and methods that are in a \var{private} block, can
only be accessed in the module (i.e. unit) that contains the class definition.
They can be accessed from inside the classes' methods or from outside them
(e.g. from other classes' methods)\keywordlink{private}
\item [Protected\ ] \index{Protected}\index{Visibility!Protected}%
Is the same as \var{Private}, except that the members of
a \var{Protected} section are also accessible to descendent types, even if
they are implemented in other modules.\keywordlink{protected}
\item [Public\ ] \index{Public}\index{Visibility!Public} sections are always
accessible.\keywordlink{public}
\item [Published\ ] \index{Published}\index{Visibility!Published} Is the same as a \var{Public} section, but the compiler
generates also type information that is needed for automatic streaming of
these classes if the compiler is in the \var{\{\$M+\}} state. Fields defined in a \var{published} section must be of class type.
Array properties cannot be in a \var{published}
section.\keywordlink{published}
\end{description}
In the syntax diagram, it can be seen that a class can list implemented
interfaces. This feature will be discussed in the next chapter.
Classes can contain \var{Class} methods: these are functions that do not
require an instance. The \var{Self} identifier is valid in such methods,
but refers to the class pointer (the VMT).
Similar to objects, if the \var{\{\$STATIC ON\}} directive is active, then a class
can contain static fields: these fields are global to the class, and act
like global variables, but are known only as part of the class. They can be
referenced from within the classes' methods, but can also be referenced from
outside the class by providing the fully qualified name.
For instance, the output of the following program:
\begin{verbatim}
{$mode objfpc}
{$static on}
type
cl=class
l : longint;static;
end;
var
c1,c2 : cl;
begin
c1:=cl.create;
c2:=cl.create;
c1.l:=2;
writeln(c2.l);
c2.l:=3;
writeln(c1.l);
Writeln(cl.l);
end.
\end{verbatim}
will be the following
\begin{verbatim}
2
3
3
\end{verbatim}
Note that the last line of code references the class type itself (\var{cl}),
and not an instance of the class (\var{cl1} or \var{cl2}).
It is also possible to define class reference types:
\input{syntax/classref.syn}
Class reference types are used to create instances of a certain class, which
is not yet known at compile time, but which is specified at run time.
Essentially, a variable of a class reference type contains a pointer to the
definition of the speficied class. This can be used to construct an instance
of the class corresponding to the definition, or to check inheritance.
The following example shows how it works:
\begin{verbatim}
Type
TComponentClass = Class of TComponent;
Function CreateComponent(AClass: TComponentClass;
AOwner: TComponent): TComponent;
begin
// ...
Result:=AClass.Create(AOwner);
// ...
end;
\end{verbatim}
This function can be passed a class reference of any class that descends
from \var{TComponent}. The following is a valid call:
\begin{verbatim}
Var
C : TComponent;
begin
C:=CreateComponent(TEdit,Form1);
end;
\end{verbatim}
On return of the \var{CreateComponent} function, \var{C} will contain an
instance of the class \var{TEdit}. Note that the following call will fail to
compile:
\begin{verbatim}
Var
C : TComponent;
begin
C:=CreateComponent(TStream,Form1);
end;
\end{verbatim}
because \var{TStream} does not descend from \var{TComponent}, and
\var{AClass} refers to a \var{TComponent} class. The compiler can
(and will) check this at compile time, and will produce an error.
References to classes can also be used to check inheritance:
\begin{verbatim}
TMinClass = Class of TMyClass;
TMaxClass = Class of TMyClassChild;
Function CheckObjectBetween(Instance : TObject) : boolean;
begin
If not (Instance is TMinClass)
or ((Instance is TMaxClass)
and (Instance.ClassType<>TMaxClass)) then
Raise Exception.Create(SomeError)
end;
\end{verbatim}
The above example will raise an exception if the passed instance
is not a descendent of \var{TMinClass} or a descendent if \var{TMaxClass}.
More about instantiating a class can be found in the next section.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Class instantiation
\section{Class instantiation}
\index{Constructor}\keywordlink{constructor}
Classes must be created using one of their constructors (there can be
multiple constructors). Remember that a class is a pointer to an object on
the heap. When a variable of some class is declared, the compiler just
allocates room for this pointer, not the entire object. The constructor of
a class returns a pointer to an initialized instance of the object on the
heap. So, to initialize an instance of some class, one would do the following :
\begin{verbatim}
ClassVar := ClassType.ConstructorName;
\end{verbatim}
The extended syntax of \var{new} and \var{dispose} can {\em not} be used to
instantiate and destroy class instances.
That construct is reserved for use with objects only.
Calling the constructor will provoke a call to \var{getmem}, to allocate
enough space to hold the class instance data.
After that, the constuctor's code is executed.
The constructor has a pointer to its data, in \var{Self}.
\begin{remark}
\begin{itemize}\index{Packed}
\item The \var{\{\$PackRecords \}} directive also affects classes.
i.e. the alignment in memory of the different fields depends on the
value of the \var{\{\$PackRecords \}} directive.
\item Just as for objects and records, a packed class can be declared.
This has the same effect as on an object, or record, namely that the
elements are aligned on 1-byte boundaries. i.e. as close as possible.
\item \var{SizeOf(class)} will return the same as \var{SizeOf(Pointer)},
since a class is but a pointer to an object. To get the size of the class
instance data, use the \var{TObject.InstanceSize} method.
\end{itemize}
\end{remark}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Methods
\section{Methods}
\index{Methods}
\subsection{Declaration}
Declaration of methods in classes follows the same rules as method
declarations in objects:
\input{syntax/cmethods.syn}
\subsection{invocation}
Method invocation for classes is no different than for objects. The
following is a valid method invocation:
\begin{verbatim}
Var AnObject : TAnObject;
begin
AnObject := TAnObject.Create;
ANobject.AMethod;
\end{verbatim}
\subsection{Virtual methods}
\index{Methods!Virtual}\index{Virtual}
Classes have virtual methods, just as objects do. There is however a
difference between the two. For objects, it is sufficient to redeclare the
same method in a descendent object with the keyword \var{virtual} to
override it. For classes, the situation is different: virtual methods
{\em must} be overridden with the \var{override} keyword. Failing to do so,
will start a {\em new} batch of virtual methods, hiding the previous
one. The \var{Inherited} keyword will not jump to the inherited method, if
\var{Virtual} was used.
The following code is {\em wrong}:
\begin{verbatim}
Type
ObjParent = Class
Procedure MyProc; virtual;
end;
ObjChild = Class(ObjPArent)
Procedure MyProc; virtual;
end;
\end{verbatim}
The compiler will produce a warning:
\begin{verbatim}
Warning: An inherited method is hidden by OBJCHILD.MYPROC
\end{verbatim}
The compiler will compile it, but using \var{Inherited} can\index{Inherited}
produce strange effects.
The correct declaration is as follows:
\begin{verbatim}
Type
ObjParent = Class
Procedure MyProc; virtual;
end;
ObjChild = Class(ObjPArent)
Procedure MyProc; override;
end;
\end{verbatim}
This will compile and run without warnings or errors.\index{Override}
If the virtual method should really be replaced with a method with the
same name, then the \var{reintroduce} keyword can be used:\index{reintroduce}
\keywordlink{reintroduce}
\begin{verbatim}
Type
ObjParent = Class
Procedure MyProc; virtual;
end;
ObjChild = Class(ObjPArent)
Procedure MyProc; reintroduce;
end;
\end{verbatim}
This new method is no longer virtual.
To be able to do this, the compiler keeps - per class type - a table with
virtual methods: the VMT (Virtual Method Table). This is simply a table
with pointers to each of the virtual methods: each virtual method has its
fixed location in this table (an index). The compiler uses this table to
look up the actual method that must be used at runtime. When a descendent object
overrides a method, the entry of the parent method is overwritten in the
VMT. More information about the VMT can be found in \progref.
\begin{remark}
The keyword 'virtual' can be replaced with the 'dynamic' keyword: dynamic
methods behave the same as virtual methods. Unlike in Delphi, in FPC the
implementation of dynamic methods is equal to the implementation of virtual
methods.
\end{remark}
\subsection{Class methods}
\index{Class}\index{Methods!Class}
Class methods are identified by the keyword \var{Class} in front of the
procedure or function declaration, as in the following example:
\begin{verbatim}
Class Function ClassName : String;
\end{verbatim}
Class methods are methods that do not have an instance (i.e. Self does not
point to a class instance) but which follow the scoping and inheritance
rules of a class. They can be used to return information about the current
class, for instance for registration or use in a class factory. Since no
instance is available, no information available in instances can be used.
Class methods can be called from inside a regular method, but can also be called
using a class identifier:
\begin{verbatim}
Var
AClass : TClass;
begin
..
if CompareText(AClass.ClassName,'TCOMPONENT')=0 then
...
\end{verbatim}
But calling them from an instance is also possible:
\begin{verbatim}
Var
MyClass : TObject;
begin
..
if MyClass.ClassNameis('TCOMPONENT') then
...
\end{verbatim}
The reverse is not possible: Inside a class method, the \var{Self} identifier
points to the VMT\index{Self} table of the class. No fields, properties or
regular methods are available inside a class method. Accessing a regular
property or method will result in a compiler error.
Note that class methods can be virtual, and can be overridden.
Class methods cannot be used as read or write specifiers for a
property.\index{Property}
\subsection{Message methods}
\index{Methods!Message}
New in classes are \var{message} methods. Pointers to message methods are
stored in a special table, together with the integer or string cnstant that
they were declared with. They are primarily intended to ease programming of
callback functions in several \var{GUI} toolkits, such as \var{Win32} or
\var{GTK}. In difference with Delphi, \fpc also accepts strings as message
identifiers. Message methods are always virtual.
\index{Virtual}\index{message} \keywordlink{message}
As can be seen in the class declaration diagram, message methods are
declared with a \var{Message} keyword, followed by an integer constant
expression.
Additionally, they can take only one var argument (typed or not):\index{Message}
\begin{verbatim}
Procedure TMyObject.MyHandler(Var Msg); Message 1;
\end{verbatim}
The method implementation of a message function is not different from an
ordinary method. It is also possible to call a message method directly,
but this should not be done. Instead, the \var{TObject.Dispatch} method
should be used.\index{Dispatch} Message methods are automatically virtual,
i.e. they can be overridden in descendent classes.
The \var{TOBject.Dispatch} method can be used to call a
\var{message}\index{Message}
handler. It is declared in the \file{system} unit and will accept a var
parameter which must have at the first position a cardinal with the
message ID that should be called. For example:
\begin{verbatim}
Type
TMsg = Record
MSGID : Cardinal
Data : Pointer;
Var
Msg : TMSg;
MyObject.Dispatch (Msg);
\end{verbatim}
In this example, the \var{Dispatch} method will look at the object and all
its ancestors (starting at the object, and searching up the inheritance
class tree), to see if a message method with message \var{MSGID} has been
declared. If such a method is found, it is called, and passed the
\var{Msg} parameter.
If no such method is found, \var{DefaultHandler} is called.
\var{DefaultHandler} is a virtual method of \var{TObject} that doesn't do
anything, but which can be overridden to provide any processing that might be
needed. \var{DefaultHandler} is declared as follows:
\begin{verbatim}
procedure defaulthandler(var message);virtual;
\end{verbatim}
In addition to the message method with a \var{Integer} identifier,
\fpc also supports a message method with a string identifier:
\begin{verbatim}
Procedure TMyObject.MyStrHandler(Var Msg); Message 'OnClick';
\end{verbatim}
The working of the string message handler is the same as the ordinary
integer message handler:
The \var{TOBject.DispatchStr} \index{DispatchStr} method can be used to call a \var{message}
handler. It is declared in the system unit and will accept one parameter
which must have at the first position a short string with the message ID that
should be called. For example:
\begin{verbatim}
Type
TMsg = Record
MsgStr : String[10]; // Arbitrary length up to 255 characters.
Data : Pointer;
Var
Msg : TMSg;
MyObject.DispatchStr (Msg);
\end{verbatim}
In this example, the \var{DispatchStr} method will look at the object and
all its ancestors (starting at the object, and searching up the inheritance
class tree), to see if a message method with message \var{MsgStr} has been
declared. If such a method is found, it is called, and passed the
\var{Msg} parameter.
If no such method is found, \var{DefaultHandlerStr} is called.
\var{DefaultHandlerStr} is a virtual method of \var{TObject} that doesn't do
anything, but which can be overridden to provide any processing that might be
needed. \var{DefaultHandlerStr} is declared as follows:
\begin{verbatim}
procedure DefaultHandlerStr(var message);virtual;
\end{verbatim}
In addition to this mechanism, a string message method accepts a \var{self}
parameter:
\begin{verbatim}
Procedure StrMsgHandler(Data: Pointer;
Self: TMyObject); Message 'OnClick';
\end{verbatim}
When encountering such a method, the compiler will generate code that loads
the \var{Self} parameter into the object instance pointer. The result of
this is that it is possible to pass \var{Self} as a parameter to such a
method.
\begin{remark}
The type of the \var{Self} \index{Self}parameter must be of the same class
as the class the method is defined in.
\end{remark}
\subsection{Using inherited}
In an overridden virtual method, it is often necessary to call the parent
class' implementation of the virtual method. This can be done with the
\var{inherited} keyword. Likewise, the \var{inherited} keyword can be used
to call any method of the parent class.
The first case is the simplest:
\begin{verbatim}
Type
TMyClass = Class(TComponent)
Constructor Create(AOwner : TComponent); override;
end;
Constructor TMyClass.Create(AOwner : TComponent);
begin
Inherited;
// Do more things
end;
\end{verbatim}
In the above example, the \var{Inherited} statement will call \var{Create}
of \var{TComponent}, passing it \var{AOwner} as a parameter: the same
parameters that were passed to the current method will be passed to the
parent's method. They must not be specified again: if none are specified,
the compiler will pass the same arguments as the ones received.
The second case is slightly more complicated:
\begin{verbatim}
Type
TMyClass = Class(TComponent)
Constructor Create(AOwner : TComponent); override;
Constructor CreateNew(AOwner : TComponent; DoExtra : Boolean);
end;
Constructor TMyClass.Create(AOwner : TComponent);
begin
Inherited;
end;
Constructor TMyClass.CreateNew(AOwner : TComponent; DoExtra);
begin
Inherited Create(AOwner);
// Do stuff
end;
\end{verbatim}
The \var{CreateNew} method will first call \var{TComponent.Create} and
will pass it \var{AOwner} as a parameter. It will not call
\var{TMyClass.Create}.
Although the examples were given using constructors, the use of
\var{inherited} is not restricted to constructors, it can be used
for any procedure or function or destructor as well.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Properties
\section{Properties}
\index{Properties}\keywordlink{property}
\subsection{Definition}
Classes can contain properties as part of their fields list. A property
acts like a normal field, i.e. its value can be retrieved or set, but it
allows to redirect the access of the field through functions and
procedures. They provide a means to associate an action with an assignment
of or a reading from a class 'field'. This allows for e.g. checking that a
value is valid when assigning, or, when reading, it allows to construct the
value on the fly. Moreover, properties can be read-only or write only.
The prototype declaration of a property is as follows:\index{Property}
\input{syntax/property.syn}
A \var{read specifier} \index{Read} is either the name of a field that contains the
property, or the name of a method function that has the same return type as
the property type. In the case of a simple type, this
function must not accept an argument. In case of an array property, the
function must accept a single argument of the same type as the index.
In case of an indexed property, it must accept a integer as an argument.
A \var{read specifier} is optional, making the property write-only.
Note that class methods cannot be used as read specifiers.
A \var{write specifier} \index{Write} is optional: If there is no \var{write specifier}, the
property is read-only. A write specifier is either the name of a field, or
the name of a method procedure that accepts as a sole argument a variable of
the same type as the property. In case of an array property, the procedure
must accept 2 arguments: the first argument must have the same type as the
index, the second argument must be of the same type as the property.
Similarly, in case of an indexed property, the first parameter must be an integer.
The section \index{Private}\index{Published} (\var{private}, \var{published})
in which the specified function or procedure resides is irrelevant. Usually,
however, this will be a protected or private method.
For example, given the following declaration:
\begin{verbatim}
Type
MyClass = Class
Private
Field1 : Longint;
Field2 : Longint;
Field3 : Longint;
Procedure Sety (value : Longint);
Function Gety : Longint;
Function Getz : Longint;
Public
Property X : Longint Read Field1 write Field2;
Property Y : Longint Read GetY Write Sety;
Property Z : Longint Read GetZ;
end;
Var
MyClass : TMyClass;
\end{verbatim}
The following are valid statements:
\begin{verbatim}
WriteLn ('X : ',MyClass.X);
WriteLn ('Y : ',MyClass.Y);
WriteLn ('Z : ',MyClass.Z);
MyClass.X := 0;
MyClass.Y := 0;
\end{verbatim}
But the following would generate an error:
\begin{verbatim}
MyClass.Z := 0;
\end{verbatim}
because Z is a read-only property.
What happens in the above statements is that when a value needs to be read,
the compiler inserts a call to the various \var{getNNN} methods of the
object, and the result of this call is used. When an assignment is made,
the compiler passes the value that must be assigned as a paramater to
the various \var{setNNN} methods.
Because of this mechanism, properties cannot be passed as var arguments to a
function or procedure, since there is no known address of the property (at
least, not always).\index{Parameters!Var}
\subsection{Indexed properties}
\index{Properties!Indexed}\keywordlink{index}
If the property definition contains an index, \index{index} then the read and write
specifiers must be a function and a procedure. Moreover, these functions
require an additional parameter : An integer parameter. This allows to read
or write several properties with the same function. For this, the properties
must have the same type.
The following is an example of a property with an index:
\begin{verbatim}
{$mode objfpc}
Type
TPoint = Class(TObject)
Private
FX,FY : Longint;
Function GetCoord (Index : Integer): Longint;
Procedure SetCoord (Index : Integer; Value : longint);
Public
Property X : Longint index 1 read GetCoord Write SetCoord;
Property Y : Longint index 2 read GetCoord Write SetCoord;
Property Coords[Index : Integer]:Longint Read GetCoord;
end;
Procedure TPoint.SetCoord (Index : Integer; Value : Longint);
begin
Case Index of
1 : FX := Value;
2 : FY := Value;
end;
end;
Function TPoint.GetCoord (INdex : Integer) : Longint;
begin
Case Index of
1 : Result := FX;
2 : Result := FY;
end;
end;
Var
P : TPoint;
begin
P := TPoint.create;
P.X := 2;
P.Y := 3;
With P do
WriteLn ('X=',X,' Y=',Y);
end.
\end{verbatim}
When the compiler encounters an assignment to \var{X}, then \var{SetCoord}
is called with as first parameter the index (1 in the above case) and with
as a second parameter the value to be set.
Conversely, when reading the value of \var{X}, the compiler calls
\var{GetCoord} and passes it index 1.
Indexes can only be integer values.
\subsection{Array properties}
Array properties also exist.\index{Properties!Array} These are properties that accept an
index, just as an array does. Only now the index doesn't have to be an
ordinal type, but can be any type.
A \var{read specifier} for an array property is the name method function
that has the same return type as the property type.
The function must accept as a sole arguent a variable of the same type as
the index type. For an array property, one cannot specify fields as \var{read
specifiers}.
A \var{write specifier} for an array property is the name of a method
procedure that accepts two arguments: The first argument has the same
type as the index, and the second argument is a parameter of the same
type as the property type.
As an example, see the following declaration:
\begin{verbatim}
Type
TIntList = Class
Private
Function GetInt (I : Longint) : longint;
Function GetAsString (A : String) : String;
Procedure SetInt (I : Longint; Value : Longint;);
Procedure SetAsString (A : String; Value : String);
Public
Property Items [i : Longint] : Longint Read GetInt
Write SetInt;
Property StrItems [S : String] : String Read GetAsString
Write SetAsstring;
end;
Var
AIntList : TIntList;
\end{verbatim}
Then the following statements would be valid:
\begin{verbatim}
AIntList.Items[26] := 1;
AIntList.StrItems['twenty-five'] := 'zero';
WriteLn ('Item 26 : ',AIntList.Items[26]);
WriteLn ('Item 25 : ',AIntList.StrItems['twenty-five']);
\end{verbatim}
While the following statements would generate errors:
\begin{verbatim}
AIntList.Items['twenty-five'] := 1;
AIntList.StrItems[26] := 'zero';
\end{verbatim}
Because the index types are wrong.
\subsection{Default properties}
Array properties can be declared as \var{default} properties. This means that
it is not necessary to specify the property name when assigning or reading
it. In the previous example, if the definition of the items property would
have been
\begin{verbatim}
Property Items[i : Longint]: Longint Read GetInt
Write SetInt; Default;
\end{verbatim}
Then the assignment
\begin{verbatim}
AIntList.Items[26] := 1;
\end{verbatim}
Would be equivalent to the following abbreviation.
\begin{verbatim}
AIntList[26] := 1;
\end{verbatim}
Only one default property per class is allowed, and descendent classes
cannot redeclare the default property.
\subsection{Storage information}
The {\em stored specifier} should be either a boolean constant, a boolean
field of the class, or a parameterless function which returns a boolean
result. This specifier has no result on the class behaviour. It is an aid
for the streaming system: the stored specifier is specified in the RTTI
generated for a class (it can only be streamed if RTTI is generated),
and is used to determine whether a property should be streamed or not:
it saves space in a stream. It is not possible to specify the 'Stored'
directive for array properties.
The {\em default specifier} can be specified for ordinal types and sets.
It serves the same purpose as the {\em stored specifier}: Properties that
have as value their default value, will not be written to the stream by the
streaming system. The default value is stored in the RTTI that is generated
for the class. Note that
\begin{enumerate}
\item When the class is instantiated, the default value is not automatically
applied to the property, it is the responsability of the programmer to do
this in the constructor of the class.
\item The value 2147483648 cannot be used as a default value, as it is used
internally to denote 'nodefault'.
\item It is not possible to specify a default for array properties.
\end{enumerate}
\subsection{Overriding properties}
Properties can be overridden in descendent classes, just like methods. The
difference is that for properties, the overriding can always be done:
properties should not be marked 'virtual' so they can be overridden, they
are always overridable (in this sense, properties are always 'virtual').
The type of the overridden property does not have to be the same as the
parents class property type.
Since they can be overridden, the keyword 'inherited' \index{inherited} can
also be used to refer to the parent definition of the property. For example
consider the following code:
\begin{verbatim}
type
TAncestor = class
private
FP1 : Integer;
public
property P: integer Read FP1 write FP1;
end;
TClassA = class(TAncestor)
private
procedure SetP(const AValue: char);
function getP : Char;
public
constructor Create;
property P: char Read GetP write SetP;
end;
procedure TClassA.SetP(const AValue: char);
begin
Inherited P:=Ord(AValue);
end;
procedure TClassA.GetP : char;
begin
Result:=Char((Inherited P) and $FF);
end;
\end{verbatim}
TClassA redefines \var{P} as a character property instead of an integer
property, but uses the parents \var{P} property to store the value.
Care must be taken when using virtual get/set routines for a property:
setting the inherited propert still observes the normal rules of inheritance
for methods. Consider the following example:
\begin{verbatim}
type
TAncestor = class
private
procedure SetP1(const AValue: integer); virtual;
public
property P: integer write SetP1;
end;
TClassA = class(TAncestor)
private
procedure SetP1(const AValue: integer); override;
procedure SetP2(const AValue: char);
public
constructor Create;
property P: char write SetP2;
end;
constructor TClassA.Create;
begin
inherited P:=3;
end;
\end{verbatim}
In this case, when setting the inherited property \var{P}, the
implementation \var{TClassA.SetP1} will be called, because the
\var{SetP1} method is overridden.
If the parent class implementation of \var{SetP1} must be called,
then this must be called explicitly:
\begin{verbatim}
constructor TClassA.Create;
begin
inherited SetP1(3);
end;
\end{verbatim}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Interfaces
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\chapter{Interfaces}
\label{ch:Interfaces}\index{Interfaces}
\section{Definition}
As of version 1.1, FPC supports interfaces. Interfaces are an
alternative to multiple inheritance (where a class can have multiple
parent classes) as implemented for instance in C++. An interface is
basically a named set of methods and properties: A class that
{\em implements} the interface provides {\em all} the methods as
they are enumerated in the Interface definition. It is not possible for a
class to implement only part of the interface: it is all or nothing.
Interfaces can also be ordered in a hierarchy, exactly as classes:
An interface definition that inherits from another interface definition
contains all the methods from the parent interface, as well as the methods
explicitly named in the interface definition. A class implementing an
interface must then implement all members of the interface as well as the
methods of the parent interface(s).
An interface can be uniquely identified by a GUID. GUID is an acronym for
Globally Unique Identifier, a 128-bit integer guaranteed always to be
unique\footnote{In theory, of course.}. Especially on Windows systems,
the GUID of an interface can and must be used when using COM.
The definition of an Interface has the following
form:\index{interface}\keywordlink{interface}
\input{syntax/typeintf.syn}
Along with this definition the following must be noted:
\begin{itemize}
\item Interfaces can only be used in \var{DELPHI} mode or in \var{OBJFPC}
mode.
\item There are no visibility specifiers. All members are public (indeed,
it would make little sense to make them private or
protected).\index{Visibility}
\item The properties declared in an interface can only have methods as read and
write specifiers.
\item There are no constructors or destructors. Instances of interfaces
cannot be created directly: instead, an instance of a class implementing
the interface must be created.
\item Only calling convention modifiers may be present in the definition of
a method. Modifiers as \var{virtual}, \var{abstract} or \var{dynamic}, and
hence also \var{override} cannot be present in the definition of a interface
definition.
\end{itemize}
The following are examples of interfaces:
\begin{verbatim}
IUnknown = interface ['{00000000-0000-0000-C000-000000000046}']
function QueryInterface(const iid : tguid;out obj) : longint;
function _AddRef : longint;
function _Release : longint;
end;
IInterface = IUnknown;
IMyInterface = Interface
Function MyFunc : Integer;
Function MySecondFunc : Integer;
end;
\end{verbatim}
As can be seen, the GUID identifying the interface is optional.
\section{Interface identification: A GUID}
An interface can be identified by a GUID. This is a 128-bit number, which is
represented in a text representation (a string literal):
\begin{verbatim}
['{HHHHHHHH-HHHH-HHHH-HHHH-HHHHHHHHHHHH}']
\end{verbatim}
Each \var{H} character represents a hexadecimal number (0-9,A-F). The format
contains 8-4-4-4-12 numbers. A GUID can also be represented by the following
record, defined in the \file{objpas} unit (included automatically when in
\var{DELPHI} or \var{OBJFPC} mode):
\begin{verbatim}
PGuid = ^TGuid;
TGuid = packed record
case integer of
1 : (
Data1 : DWord;
Data2 : word;
Data3 : word;
Data4 : array[0..7] of byte;
);
2 : (
D1 : DWord;
D2 : word;
D3 : word;
D4 : array[0..7] of byte;
);
end;
\end{verbatim}
A constant of type TGUID can be specified using a string literal:
\begin{verbatim}
{$mode objfpc}
program testuid;
Const
MyGUID : TGUID = '{10101010-1010-0101-1001-110110110110}';
begin
end.
\end{verbatim}
Normally, the GUIDs are only used in Windows, when using COM interfaces.
More on this in the next section.
\section{Interface implementations}
\index{Interfaces!Implementations}
When a class implements an interface, it should implement all methods of the
interface. If a method of an interface is not implemented, then the compiler
will give an error. For example:
\begin{verbatim}
Type
IMyInterface = Interface
Function MyFunc : Integer;
Function MySecondFunc : Integer;
end;
TMyClass = Class(TInterfacedObject,IMyInterface)
Function MyFunc : Integer;
Function MyOtherFunc : Integer;
end;
Function TMyClass.MyFunc : Integer;
begin
Result:=23;
end;
Function TMyClass.MyOtherFunc : Integer;
begin
Result:=24;
end;
\end{verbatim}
will result in a compiler error:
\begin{verbatim}
Error: No matching implementation for interface method
"IMyInterface.MySecondFunc:LongInt" found
\end{verbatim}
Normally, the names of the methods that implement an interface, must
equal the names of the methods in the interface definition.
However, it is possible to provide aliases for methods that make up an
interface: that is, the compiler can be told that a method of an interface
is implemented by an existing method with a different name.
This is done as follows:
\begin{verbatim}
Type
IMyInterface = Interface
Function MyFunc : Integer;
end;
TMyClass = Class(TInterfacedObject,IMyInterface)
Function MyOtherFunction : Integer;
// The following fails in FPC.
Function IMyInterface.MyFunc = MyOtherFunction;
end;
\end{verbatim}
This declaration tells the compiler that the \var{MyFunc} method of
the \var{IMyInterface} interface is implemented in the \var{MyOtherFunction}
method of the \var{TMyClass} class.
\section{Interfaces and COM}
\index{COM}\index{Interfaces!COM}
When using interfaces on Windows which should be available to the COM
subsystem, the calling convention should be \var{stdcall} - this is not the
default \fpc calling convention, so it should be specified explicitly.
COM does not know properties. It only knows methods. So when specifying
property definitions as part of an interface definition, be aware that the
properties will only be known in the \fpc compiled program: other Windows
programs will not be aware of the property definitions.
\section{CORBA and other Interfaces}
\index{CORBA}\index{COM}\index{Interfaces!CORBA}
COM is not the only architecture where interfaces are used. CORBA knows
interfaces, UNO (the OpenOffice API) uses interfaces, and Java as well.
These languages do not know the \var{IUnknown} interface used as the basis of
all interfaces in COM. It would therefore be a bad idea if an interface
automatically descended from \var{IUnknown} if no parent interface was
specified. Therefore, a directive \var{\{\$INTERFACES\}} was introduced in
\fpc: it specifies what the parent interface is of an interface, declared
without parent. More information about this directive can be found in the
\progref.
Note that COM interfaces are by default reference counted, because they
descend from \var{IUnknown}.\index{Types!Reference counted}
Corba interfaces are identified by a simple string so they are assignment
compatible with strings and not with \var{TGUID}. The compiler does not do
any automatic reference counting for the CORBA interfaces, so the programmer
is responsible for any reference bookkeeping.
\section{Reference counting}
All COM interfaces use reference counting. This means that whenever an
interface is assigned to a variable, it's reference count is updated.
Whenever the variable goes out of scope, the reference count is
automatically decreased. When the reference count reaches zero, usually the
instance of the class that implements the interface, is freed.
Care must be taken with this mechanism. The compiler may or may not create
temporary variables when evaluating expressions, and assign the interface
to a temporary variable, and only then assign the temporary variable to
the actual result variable. No assumptions should be made about the number
of temporary variables or the time when they are finalized - this may
(and indeed does) differ from the way other compilers (e.g. Delphi) handle
expressions with interfaces. e.g. a type cast is also an expression:
\begin{verbatim}
Var
B : AClass;
begin
// ...
AInterface(B.intf).testproc;
// ...
end;
\end{verbatim}
Assume the interface \var{intf} is reference counted. When the compiler
evaluates B.Intf, it creates a temporary variable. This variable may be
released only when the procedure exits: it is therefor invalid to e.g.
free the instance B prior to the exit of the procedure, since when the
temporary variable is finalized, it will attempt to free B again.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Generics
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\chapter{Generics}
\label{ch:generics}
\index{Generics}
\section{Introduction}
Generics are templates for generating classes. It is a concept that
comes from C++, where it is deeply integrated in the language. As of
version 2.2, Free Pascal also officially has support for templates or
Generics. They are implemented as a kind of macro which is stored in the
unit files that the compiler generates, and which is replayed as soon
as a generic class is specialized.
Currently, only generic classes can be defined. Later, support for
generic records, functions and arrays may be introduced.
Creating and using generics is a 2-phase process.
\begin{enumerate}
\item The definition of the generic class is defined as a new type:
this is a code template, a macro which can be replayed by the compiler
at a later stage.
\item A generic class is specialized: this defines a second class,
which is a specific implementation of the generic class: the compiler
replays the macro which was stored when the generic class was defined.
\end{enumerate}
\section{Generic class definition}
A generic class definition is much like a class definition, with the
exception that it contains a list of placeholders for types, and can
contain a series of local variable blocks or local type blocks, as can be
seen in the following syntax diagram:
\input{syntax/generic.syn}
The generic class declaration should be followed by a class implementation.
It is the same as a normal class implementation with a single exception,
namely that any identifier with the same name as one of the template
identifiers must be a type identifier.
The generic class declaration is much like a normal class declaration,
except for the local variable and local type block. The local type block
defines types that are type placeholders: they are not actualized until
the class is specialized.
The local variable block is just an alternate syntax for ordinary class fields.
The reason for introducing is the introduction of the \var{Type} block: just
as in a unit or function declaration, a class declaration can now have a
local type and variable block definition.
The following is a valid generic class definition:
\begin{verbatim}
Type
generic TList<_T>=class(TObject)
type public
TCompareFunc = function(const Item1, Item2: _T): Integer;
var public
data : _T;
procedure Add(item: _T);
procedure Sort(compare: TCompareFunc);
end;
\end{verbatim}
This class could be followed by an implementation as follows:
\begin{verbatim}
procedure TList.Add(item: _T);
begin
data:=item;
end;
procedure TList.Sort(compare: TCompareFunc);
begin
if compare(data, 20) <= 0 then
halt(1);
end;
\end{verbatim}
There are some noteworthy things about this declaration and implementation:
\begin{enumerate}
\item There is a single placeholder \var{\_T}. It will be substituted by a
type identifier when the generic class is specialized. The identifier
\var{\_T} may not be used for anything else than a placehoder. This means
that the following would be invalid:
\begin{verbatim}
procedure TList.Sort(compare: TCompareFunc);
Var
_t : integer;
begin
// do something.
end;
\end{verbatim}
\item The local type block contains a single type \var{TCompareFunc}. Note
that the actual type is not yet known inside the generic class definition:
the definition contains a reference to the placeholder \var{\_T}. All other
identifier references must be known when the generic class is defined, {\em not}
when the generic class is specialized.
\item The local variable block is equivalent to the following:
\begin{verbatim}
generic TList<_T>=class(TObject)
type public
TCompareFunc = function(const Item1, Item2: _T): Integer;
Public
data : _T;
procedure Add(item: _T);
procedure Sort(compare: TCompareFunc);
end;
\end{verbatim}
\item Both the local variable block and local type block have a visibility
specifier. This is optional; if it is omitted, the current visibility is
used.
\end{enumerate}
\section{Generic class specialization}
Once a generic class is defined, it can be used to generate other classes:
this is like replaying the definition of the class, with the template
placeholders filled in with actual type definitions.
This can be done in any \var{Type} definition block. The specialized type
looks as follows:
\input{syntax/specialize.syn}
Which is a very simple definition. Given the declaration of \var{TList} in
the previous section, the following would be a valid type definition:
\begin{verbatim}
Type
TPointerList = specialize TList<Pointer>;
TIntegerList = specialize TList<Integer>;
\end{verbatim}
The following is not allowed:
\begin{verbatim}
Var
P : specialize TList<Pointer>;
\end{verbatim}
that is, a variable cannot be directly declared using a specialization.
The type in the specialize statement must be known. Given the 2 generic
class definitions:
\begin{verbatim}
type
Generic TMyFirstType<T1> = Class(TMyObject);
Generic TMySecondType<T2> = Class(TMyOtherObject);
\end{verbatim}
Then the following specialization is not valid:
\begin{verbatim}
type
TMySpecialType = specialize TMySecondType<TMyFirstType>;
\end{verbatim}
because the type \var{TMyFirstType} is a generic type, and thus
not fully defined. However, the following is allowed:
\begin{verbatim}
type
TA = specialize TMyFirstType<Atype>;
TB = specialize TMySecondType<TA>;
\end{verbatim}
because \var{TA} is already fully defined when \var{TB} is specialized.
Note that 2 specializations of a generic type with the same types in a
placeholder are not assignment compatible. In the following example:
\begin{verbatim}
type
TA = specialize TList<Pointer>;
TB = specialize TList<Pointer>;
\end{verbatim}
variables of types \var{TA} and \var{TB} cannot be assigned to each other,
i.e the following assignment will be invalid:
\begin{verbatim}
Var
A : TA;
B : TB;
begin
A:=B;
\end{verbatim}
\begin{remark}
It is not possible to make a forward definition of a generic class. The
compiler will generate an error if a forward declaration of a class is
later defined as a generic specialization.
\end{remark}
\section{A word about scope}
It should be stressed that all identifiers other than the template placeholders
should be known when the generic class is declared. This works in 2 ways.
First, all types must be known, that is, a type identifier with the same name
must exist. The following unit will produce an error:
\begin{verbatim}
unit myunit;
interface
type
Generic TMyClass<T> = Class(TObject)
Procedure DoSomething(A : T; B : TSomeType);
end;
Type
TSomeType = Integer;
TSomeTypeClass = specialize TMyClass<TSomeType>;
Implementation
Procedure TMyClass.DoSomething(A : T; B : TSomeType);
begin
// Some code.
end;
end.
\end{verbatim}
The above code will result in an error, because the type \var{TSomeType} is
not known when the declaration is parsed:
\begin{verbatim}
home: >fpc myunit.pp
myunit.pp(8,47) Error: Identifier not found "TSomeType"
myunit.pp(11,1) Fatal: There were 1 errors compiling module, stopping
\end{verbatim}
The second way in which this is visible, is the following. Assume a unit
\begin{verbatim}
unit mya;
interface
type
Generic TMyClass<T> = Class(TObject)
Procedure DoSomething(A : T);
end;
Implementation
Procedure DoLocalThings;
begin
Writeln('mya.DoLocalThings');
end;
Procedure TMyClass.DoSomething(A : T);
begin
DoLocalThings;
end;
end.
\end{verbatim}
and a program
\begin{verbatim}
program myb;
uses mya;
procedure DoLocalThings;
begin
Writeln('myb.DoLocalThings');
end;
Type
TB = specialize TMyClass<Integer>;
Var
B : TB;
begin
B:=TB.Create;
B.DoSomething(1);
end.
\end{verbatim}
Despite the fact that generics act as a macro which is replayed at
specialization time, the reference to \var{DoLocalThings} is resolved
when \var{TMyClass} is defined, not when TB is defined. This means that the
output of the program is:
\begin{verbatim}
home: >fpc -S2 myb.pp
home: >myb
mya.DoLocalThings
\end{verbatim}
This is dictated by safety and necessity:
\begin{enumerate}
\item A programmer specializing a class has no way of knowing which local
procedures are used, so he cannot accidentally 'override' it.
\item A programmer specializing a class has no way of knowing which local
procedures are used, so he cannot implement it either, since he does not
know the parameters.
\item If implementation procedures are used as in the example above, they
cannot be referenced from outside the unit. They could be in another unit
altogether, and the programmer has no way of knowing he should include them
before specializing his class.
\end{enumerate}
%\section{Operator overloading and generics}
%Operator overloading and generics are closely related. Imagine a generic
%class that has the following definition:
%\begin{verbatim}
%unit mya;
%
%interface
%
%type
% Generic TMyClass<T> = Class(TObject)
% Function Add(A,B : T) : T;
% end;
%
%
%Implementation
%
%Function TMyClass.Add(A,B : T) : T;
%
%begin
% Result:=A+B;
%end;
%
%end.
%\end{verbatim}
%When the compiler replays the generics macro, the addition must be possible.
%For a specialization like this:
%\begin{verbatim}
%TMyIntegerClass = specialize TMyClass<integer>;
%\end{verbatim}
%This is not a problem, as the \var{Add} method would become:
%\begin{verbatim}
%Procedure TMyIntegerClass.Add(A,B : Integer) : Integer;
%
%begin
% Result:=A+B;
%end;
%\end{verbatim}
%The compiler knows how to add 2 integers, so this code will compile without
%problems. But the following code:
%\begin{verbatim}
%Type
% TComplex = record
% Re,Im : Double;
% end;
%
%Type
% TMyIntegerClass = specialize TMyClass<TComplex>;
%\end{verbatim}
%Will not compile, unless the addition of 2 \var{TComplex} types is defined.
%Luckily, this can be done using operator overloading.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Expressions
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\chapter{Expressions}
\label{ch:Expressions}
\index{Expressions}
Expressions occur in assignments or in tests. Expressions produce a value
of a certain type.
Expressions are built with two components: Operators and their operands.
Usually an operator is binary, i.e. it requires 2 operands. Binary operators
occur always between the operands (as in \var{X/Y}). Sometimes an
operator is unary, i.e. it requires only one argument. A unary operator
occurs always before the operand, as in \var{-X}.
When using multiple operands in an expression, the precedence rules of
\seet{OperatorPrecedence} are used.\index{Operators}
\begin{FPCltable}{lll}{Precedence of operators}{OperatorPrecedence}
Operator & Precedence & Category \\ \hline
\var{Not, @} & Highest (first) & Unary operators\\
\var{* / div mod and shl shr as << >>} & Second & Multiplying operators\\
\var{+ - or xor} & Third & Adding operators \\
\var{< <> < > <= >= in is} & Lowest (Last) & relational operators \\
\hline
\end{FPCltable}
When determining the precedence, the compiler uses the following rules:
\begin{enumerate}
\item In operations with unequal precedences the operands belong to the
operater with the highest precedence. For example, in \var{5*3+7}, the
multiplication is higher in precedence than the addition, so it is
executed first. The result would be 22.
\item If parentheses are used in an expression, their contents is evaluated
first. Thus, \var {5*(3+7)} would result in 50.
\end{enumerate}
\begin{remark}
The order in which expressions of the same precedence are evaluated is not
guaranteed to be left-to-right. In general, no assumptions on which expression
is evaluated first should be made in such a case.
The compiler will decide which expression to evaluate first based on
optimization rules. Thus, in the following expression:
\begin{verbatim}
a := g(3) + f(2);
\end{verbatim}
\var{f(2)} may be executed before \var{g(3)}. This behaviour is distinctly
different from \delphi{} or \tp{}.
If one expression {\em must} be executed before the other, it is necessary
to split up the statement using temporary results:
\begin{verbatim}
e1 := g(3);
a := e1 + f(2);
\end{verbatim}
\end{remark}
\begin{remark}
The exponentiation operator (\var{**}) is available for overloading, but is
not defined on any of the standard Pascal types (floats and/or integers).
\end{remark}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Expression syntax
\section{Expression syntax}
An expression applies relational operators to simple expressions. Simple
expressions are a series of terms (what a term is, is explained below), joined by
adding operators.
\input{syntax/expsimpl.syn}
The following are valid expressions:
\begin{verbatim}
GraphResult<>grError
(DoItToday=Yes) and (DoItTomorrow=No);
Day in Weekend
\end{verbatim}
And here are some simple expressions:
\begin{verbatim}
A + B
-Pi
ToBe or NotToBe
\end{verbatim}
Terms consist of factors, connected by multiplication operators.
\input{syntax/expterm.syn}
Here are some valid terms:
\begin{verbatim}
2 * Pi
A Div B
(DoItToday=Yes) and (DoItTomorrow=No);
\end{verbatim}
Factors are all other constructions:
\input{syntax/expfact.syn}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Function calls
\section{Function calls}
Function calls are part of expressions (although, using extended syntax,
they can be statements too). They are constructed as follows:
\input{syntax/fcall.syn}
The \synt{variable reference} must be a procedural type variable reference.
A method designator can only be used inside the method of an object. A
qualified method designator can be used outside object methods too.
The function that will get called is the function with a declared parameter
list that matches the actual parameter list. This means that
\begin{enumerate}
\item The number of actual parameters must equal the number of declared
parameters (unless default parameter values are used).
\item The types of the parameters must be compatible. For variable
reference parameters, the parameter types must be exactly the same.
\end{enumerate}
If no matching function is found, then the compiler will generate an error.
Which error depends - among other things - on whether the function is overloaded
or not: i.e. multiple functions with the same name, but different parameter
lists.
There are cases when the compiler will not execute the function call in an
expression. This is the case when assigning a value to a procedural
type variable, as in the following example:
\begin{verbatim}
Type
FuncType = Function: Integer;
Var A : Integer;
Function AddOne : Integer;
begin
A := A+1;
AddOne := A;
end;
Var F : FuncType;
N : Integer;
begin
A := 0;
F := AddOne; { Assign AddOne to F, Don't call AddOne}
N := AddOne; { N := 1 !!}
end.
\end{verbatim}
In the above listing, the assigment to \var{F} will not cause the function
\var{AddOne} to be called. The assignment to \var{N}, however, will call
\var{AddOne}.
A problem with this syntax is the following construction:
\begin{verbatim}
If F = AddOne Then
DoSomethingHorrible;
\end{verbatim}
Should the compiler compare the addresses of \var{F} and \var{AddOne},
or should it call both functions, and compare the result? \fpc solves this
by deciding that a procedural variable is equivalent to a pointer. Thus the
compiler will give a type mismatch error, since \var{AddOne} is considered a
call to a function with integer result, and \var{F} is a pointer, hence a type
mismatch occurs.
How then, should one check whether \var{F} points to the function
\var{AddOne}? To do this, one should use the address operator \var{@}:
\begin{verbatim}
If F = @AddOne Then
WriteLn ('Functions are equal');
\end{verbatim}
The left hand side of the boolean expression is an address. The right hand
side also, and so the compiler compares 2 addresses.
How to compare the values that both functions return ? By adding an empty
parameter list:
\begin{verbatim}
If F()=Addone then
WriteLn ('Functions return same values ');
\end{verbatim}
Remark that this behaviour is not compatible with \delphi syntax.
Switching on \var{Delphi} mode will allow you to use \delphi syntax.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Set constructors
\section{Set constructors}
\index{Constructor}
When a set-type constant must be entered in an expression, a
set constructor must be given. In essence this is the same thing as when a
type is defined, only there is no identifier to identify the set with.
A set constructor is a comma separated list of expressions, enclosed in
square brackets.
\input{syntax/setconst.syn}
All set groups and set elements must be of the same ordinal type.
The empty set is denoted by \var{[]}, and it can be assigned to any type of
set. A set group with a range \var{[A..Z]} makes all values in the range a
set element.
The following are valid set constructors:
\begin{verbatim}
[today,tomorrow]
[Monday..Friday,Sunday]
[ 2, 3*2, 6*2, 9*2 ]
['A'..'Z','a'..'z','0'..'9']
\end{verbatim}
\begin{remark}
If the first range specifier has a bigger ordinal value than
the second, the resulting set will be empty, e.g., \var{['Z'..'A']}
denotes an empty set. One should be careful when denoting a range.
\end{remark}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Value typecasts
\section{Value typecasts}
\index{Typecast}\index{Typecast!Value}
Sometimes it is necessary to change the type of an expression, or a part of
the expression, to be able to be assignment compatible. This is done through
a value typecast. The syntax diagram for a value typecast is as follows:
\input{syntax/tcast.syn}
Value typecasts cannot be used on the left side of assignments, as variable
typecasts.
Here are some valid typecasts:
\begin{verbatim}
Byte('A')
Char(48)
boolean(1)
longint(@Buffer)
\end{verbatim}
In general, the type size of the expression and the size of the type cast
must be the same. However, for ordinal types (byte, char, word, boolean,
enumerateds) this is not so, they can be used interchangeably.
That is, the following will work, although the sizes do not match.
\begin{verbatim}
Integer('A');
Char(4875);
boolean(100);
Word(@Buffer);
\end{verbatim}
This is compatible with \delphi or \tp behaviour.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Variable typecasts
\section{Variable typecasts}
\index{Typecast}\index{Typecast!Variable}
A variable can be considered a single factor in an expression. It can
therefore be typecast as well. A variable can be typecast to any type,
provided the type has the same size as the original variable.
It is a bad idea to typecast integer types to real types and vice versa.
It's better to rely on type assignment compatibility and using some of the
standard type changing functions.
Note that variable typecasts can occur on either side of an assignment,
i.e. the following are both valid typecasts:
\begin{verbatim}
Var
C : Char;
B : Byte;
begin
B:=Byte(C);
Char(B):=C;
end;
\end{verbatim}
Pointer variables can be typecasted to procedural types, but not
to method pointers.
A typecast is an expression of the given type, which means the
typecast can be followed by a qualifier:
\begin{verbatim}
Type
TWordRec = Packed Record
L,H : Byte;
end;
Var
P : Pointer;
W : Word;
S : String;
begin
TWordRec(W).L:=$FF;
TWordRec(W).H:=0;
S:=TObject(P).ClassName;
\end{verbatim}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% aligned typecasts
\section{Unaligned typecasts}
\index{Typecast}\index{Typecast!Unaligned}
A special typecast is the \var{Unaligned} typecast of a variable or
expression. This is not a real typecast, but is rather a hint for the
compiler that the expression may be misaligned (i.e. not on an aligned
memory address). Some processors do not allow direct access to misaligned
data structures, and therefor must access the data byte per byte.
Typecasting an expression with the unaligned keyword signals the compiler
that it should access the data byte per byte.
Example:
\begin{verbatim}
program me;
Var
A : packed Array[1..20] of Byte;
I : LongInt;
begin
For I:=1 to 20 do
A[i]:=I;
I:=PInteger(Unaligned(@A[13]))^;
end.
\end{verbatim}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% The @ operator
\section{The @ operator}
\index{Operators}\index{Address}
The address operator \var{@} returns the address of a variable, procedure
or function. It is used as follows:
\input{syntax/address.syn}
The \var{@} operator returns a typed pointer if the \var{\$T} switch is on.
If the \var{\$T} switch is off then the address operator returns an untyped
pointer, which is assigment compatible with all pointer types. The type of
the pointer is \var{\^{}T}, where \var{T} is the type of the variable
reference.
For example, the following will compile
\begin{verbatim}
Program tcast;
{$T-} { @ returns untyped pointer }
Type art = Array[1..100] of byte;
Var Buffer : longint;
PLargeBuffer : ^art;
begin
PLargeBuffer := @Buffer;
end.
\end{verbatim}
Changing the \var{\{\$T-\}} to \var{\{\$T+\}} will prevent the compiler from
compiling this. It will give a type mismatch error.
By default, the address operator returns an untyped pointer: applying
the address operator to a function, method, or procedure identifier
will give a pointer to the entry point of that function.
The result is an untyped pointer.
This means that the following will work:
\begin{verbatim}
Procedure MyProc;
begin
end;
Var
P : PChar;
begin
P:=@MyProc;
end;
\end{verbatim}
By default, the address operator must be used if a value must be assigned
to a procedural type variable. This behaviour can be avoided by using the
\var{-Mtp} or \var{-MDelphi} switches, which result in a more compatible
\delphi or \tp syntax.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Operators
\section{Operators}
\index{Operators}
Operators can be classified according to the type of expression they
operate on. We will discuss them type by type.
%
\subsection{Arithmetic operators}
\index{Operators!Arithmetic}
Arithmetic operators occur in arithmetic operations, i.e. in expressions
that contain integers or reals. There are 2 kinds of operators : Binary and
unary arithmetic operators.
Binary operators are listed in \seet{binaroperators}, unary operators are
listed in \seet{unaroperators}.
\begin{FPCltable}{ll}{Binary arithmetic operators}{binaroperators}
Operator & Operation \\ \hline
\var{+} & Addition\\
\var{-} & Subtraction\\
\var{*} & Multiplication \\
\var{/} & Division \\
\var{Div} & Integer division \\
\var{Mod} & Remainder \\ \hline
\end{FPCltable}
With the exception of \var{Div} and \var{Mod}, which accept only integer
expressions as operands, all operators accept real and integer expressions as
operands.
For binary operators, the result type will be integer if both operands are
integer type expressions. If one of the operands is a real type expression,
then the result is real.
As an exception, division (\var{/}) results always in real values.
\index{Operators!Unary}
\begin{FPCltable}{ll}{Unary arithmetic operators}{unaroperators}
Operator & Operation \\ \hline
\var{+} & Sign identity\\
\var{-} & Sign inversion \\ \hline
\end{FPCltable}
For unary operators, the result type is always equal to the expression type.
The division (\var{/}) and \var{Mod} operator will cause run-time errors if
the second argument is zero.
The sign of the result of a \var{Mod} operator is the same as the sign of
the left side operand of the \var{Mod} operator. In fact, the \var{Mod}
operator is equivalent to the following operation :
\begin{verbatim}
I mod J = I - (I div J) * J
\end{verbatim}
But it executes faster than the right hand side expression.
%
\subsection{Logical operators}
\index{Operators!Logical} \keywordlink{not} \keywordlink{and}
\keywordlink{or} \keywordlink{xor} \keywordlink{shl} \keywordlink{shr}
Logical operators act on the individual bits of ordinal expressions.
Logical operators require operands that are of an integer type, and produce
an integer type result. The possible logical operators are listed in
\seet{logicoperations}.
\begin{FPCltable}{ll}{Logical operators}{logicoperations}
Operator & Operation \\ \hline
\var{not} & Bitwise negation (unary) \\
\var{and} & Bitwise and \\
\var{or} & Bitwise or \\
\var{xor} & Bitwise xor \\
\var{shl} & Bitwise shift to the left \\
\var{shr} & Bitwise shift to the right \\ \hline
\var{<<} & Bitwise shift to the left (same as shl)\\
\var{>>} & Bitwise shift to the right (same as shr) \\ \hline
\end{FPCltable}
The following are valid logical expressions:
\begin{verbatim}
A shr 1 { same as A div 2, but faster}
Not 1 { equals -2 }
Not 0 { equals -1 }
Not -1 { equals 0 }
B shl 2 { same as B * 4 for integers }
1 or 2 { equals 3 }
3 xor 1 { equals 2 }
\end{verbatim}
%
\subsection{Boolean operators}
\index{Operators!Boolean}
Boolean operators can be considered logical operations on a type with 1 bit
size. Therefore the \var{shl} and \var{shr} operations have little sense.
Boolean operators can only have boolean type operands, and the resulting
type is always boolean. The possible operators are listed in
\seet{booleanoperators}
\begin{FPCltable}{ll}{Boolean operators}{booleanoperators}
Operator & Operation \\ \hline
\var{not} & logical negation (unary) \\
\var{and} & logical and \\
\var{or} & logical or \\
\var{xor} & logical xor \\ \hline
\end{FPCltable}
\begin{remark} By default, boolean expressions are evaluated with short-circuit
evaluation. This means that from the moment the result of the complete
expression is known, evaluation is stopped and the result is returned.
For instance, in the following expression:
\begin{verbatim}
B := True or MaybeTrue;
\end{verbatim}
The compiler will never look at the value of \var{MaybeTrue}, since it is
obvious that the expression will always be \var{True}. As a result of this
strategy, if \var{MaybeTrue} is a function, it will not get called !
(This can have surprising effects when used in conjunction with properties)
\end{remark}
%
\subsection{String operators}
\index{Operators!String}
There is only one string operator: \var{+}. Its action is to concatenate
the contents of the two strings (or characters) it acts on.
One cannot use \var{+} to concatenate null-terminated (\var{PChar}) strings.
The following are valid string operations:
\begin{verbatim}
'This is ' + 'VERY ' + 'easy !'
Dirname+'\'
\end{verbatim}
The following is not:
\begin{verbatim}
Var
Dirname = Pchar;
...
Dirname := Dirname+'\';
\end{verbatim}
Because \var{Dirname} is a null-terminated string.
Note that if all strings in a string expressions are short strings, the
resulting string is also a short string. Thus, a truncation may occur:
there is no automatic upscaling to ansistring.
If all strings in a string expression are ansistrings, then the result is an
ansistring.
If the expression contains a mix of ansistrings and shortstrings, the result
is an ansistring.
The value of the \var{\{\$H\}} switch can be used to control the type of
constant strings; By default, they are short strings (and thus limited to
255 characters).
%
\subsection{Set operators}
\label{se:setoperators}
\index{Operators!Set}
The following operations on sets can be performed with operators:
Union, difference, symmetric difference, inclusion and intersection.
Elements can be aded or removed from the set with the \var{Include} or
\var{Exclude} operators. The operators needed for this are listed
in \seet{setoperators}.
\keywordlink{in}
\begin{FPCltable}{ll}{Set operators}{setoperators}
Operator & Action \\ \hline
\var{+} & Union \\
\var{-} & Difference \\
\var{*} & Intersection \\
\var{$><$} & Symmetric difference \\
\var{$<=$} & Contains \\
\var{include} & include an element in the set\\
\var{exclude} & exclude an element from the set\\
\var{in} & check wether an element is in a set\\ \hline
\end{FPCltable}
The set type of the operands must be the same, or an error will be
generated by the compiler.
The following program gives some valid examples of set operations:
\begin{verbatim}
Type
Day = (mon,tue,wed,thu,fri,sat,sun);
Days = set of Day;
Procedure PrintDays(W : Days);
Const
DayNames : array [Day] of String[3]
= ('mon','tue','wed','thu',
'fri','sat','sun');
Var
D : Day;
S : String;
begin
S:='';
For D:=Mon to Sun do
if D in W then
begin
If (S<>'') then S:=S+',';
S:=S+DayNames[D];
end;
Writeln('[',S,']');
end;
Var
W : Days;
begin
W:=[mon,tue]+[wed,thu,fri]; // equals [mon,tue,wed,thu,fri]
PrintDays(W);
W:=[mon,tue,wed]-[wed]; // equals [mon,tue]
PrintDays(W);
W:=[mon,tue,wed]-[wed,thu]; // also equals [mon,tue]
PrintDays(W);
W:=[mon,tue,wed]*[wed,thu,fri]; // equals [wed]
PrintDays(W);
W:=[mon,tue,wed]><[wed,thu,fri]; // equals [mon,tue,thu,fri]
PrintDays(W);
end.
\end{verbatim}
As can be seen, the union is equivalent to a binary OR, while the
intersection is equivalent to a binary AND, and the summetric difference
equals a XOR operation.
The \var{Include} and \var{Exclude} operations are equivalent to a union
or a difference with a set of 1 element. Thus,
\begin{verbatim}
Include(W,wed);
\end{verbatim}
is equivalent to
\begin{verbatim}
W:=W+[wed];
\end{verbatim}
and
\begin{verbatim}
Exclude(W,wed);
\end{verbatim}
is equivalent to
\begin{verbatim}
W:=W-[wed];
\end{verbatim}
The \var{In} operation results in a \var{True} if the left operand
(an element) is included of the right operand (a set), the result
will be \var{False} otherwise.
%
\subsection{Relational operators}
\index{Operators!Relational}
The relational operators are listed in \seet{relationoperators}
\begin{FPCltable}{ll}{Relational operators}{relationoperators}
Operator & Action \\ \hline
\var{=} & Equal \\
\var{<>} & Not equal \\
\var{<} & Stricty less than\\
\var{>} & Strictly greater than\\
\var{<=} & Less than or equal \\
\var{>=} & Greater than or equal \\
\var{in} & Element of \\ \hline
\end{FPCltable}
Normally, left and right operands must be of the same type. There are some
notable exceptions, where the compiler can handle mixed expressions:
\begin{enumerate}
\item Integer and real types can be mixed in relational expressions.
\item If the operator is overloaded, and an overloaded version exists whose
arguments types match the types in the expression.
\item Short-, Ansi- and widestring types can be mixed.
\end{enumerate}
Comparing strings is done on the basis of their character code representation.
When comparing pointers, the addresses to which they point are compared.
This also is true for \var{PChar} type pointers. To compare the strings
the \var{Pchar} point to, the \var{StrComp} function
from the \file{strings} unit must be used.
The \var{in} returns \var{True} if the left operand (which must have the same
ordinal type as the set type, and which must be in the range 0..255) is an
element of the set which is the right operand, otherwise it returns \var{False}
\subsection{Class operators}
Class operators are slightly different from the operators above in the sense
that they can only be used in class expressions which return a class. There
are only 2 class operators, as can be seen in \seet{classoperators}.
\keywordlink{as} \keywordlink{is}
\begin{FPCltable}{ll}{Class operators}{classoperators}
Operator & Action \\ \hline
\var{is} & Checks class type \\
\var{as} & Conditional typecast \\
\end{FPCltable}
An expression containing the \var{is} operator results in a boolean type.
The \var{is} operator can only be used with a class reference or a class
instance. The usage of this operator is as follows:
\begin{verbatim}
Object is Class
\end{verbatim}
This expression is completely equivalent to
\begin{verbatim}
Object.InheritsFrom(Class)
\end{verbatim}
If \var{Object} is \var{Nil}, \var{False} will be returned.
The following are examples:
\begin{verbatim}
Var
A : TObject;
B : TClass;
begin
if A is TComponent then ;
If A is B then;
end;
\end{verbatim}
The \var{as} operator performs a conditional typecast. It results in an
expression that has the type of the class:
\begin{verbatim}
Object as Class
\end{verbatim}
This is equivalent to the following statements:
\begin{verbatim}
If Object=Nil then
Result:=Nil
else if Object is Class then
Result:=Class(Object)
else
Raise Exception.Create(SErrInvalidTypeCast);
\end{verbatim}
Note that if the object is \var{nil}, the \var{as} operator does not
generate an exception.
The following are some examples of the use of the \var{as} operator:
\begin{verbatim}
Var
C : TComponent;
O : TObject;
begin
(C as TEdit).Text:='Some text';
C:=O as TComponent;
end;
\end{verbatim}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Statements
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\chapter{Statements}
\label{ch:Statements}\index{Statements}
The heart of each algorithm are the actions it takes. These actions are
contained in the statements of a program or unit. Each statement can be
labeled and jumped to (within certain limits) with \var{Goto} statements.
This can be seen in the following syntax diagram:
\input{syntax/statement.syn}
A label can be an identifier or an integer digit.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Simple statements
\section{Simple statements}
\index{Statements!Simple}
A simple statement cannot be decomposed in separate statements. There are
basically 4 kinds of simple statements:
\input{syntax/simstate.syn}
Of these statements, the {\em raise statement} will be explained in the
chapter on Exceptions (\seec{Exceptions})
\subsection{Assignments}
\index{Statements!Assignment}
Assignments give a value to a variable, replacing any previous value the
variable might have had:
\input{syntax/assign.syn}
In addition to the standard Pascal assignment operator (\var{ := }), which
simply replaces the value of the varable with the value resulting from the
expression on the right of the { := } operator, \fpc
supports some C-style constructions. All available constructs are listed in
\seet{assignments}.
\begin{FPCltable}{lr}{Allowed C constructs in \fpc}{assignments}
Assignment & Result \\ \hline
a += b & Adds \var{b} to \var{a}, and stores the result in \var{a}.\\
a -= b & Substracts \var{b} from \var{a}, and stores the result in
\var{a}. \\
a *= b & Multiplies \var{a} with \var{b}, and stores the result in
\var{a}. \\
a /= b & Divides \var{a} through \var{b}, and stores the result in
\var{a}. \\ \hline
\end{FPCltable}
For these constructs to work, the \var{-Sc} command-line switch must
be specified.
\begin{remark}
These constructions are just for typing convenience, they
don't generate different code.
Here are some examples of valid assignment statements:
\begin{verbatim}
X := X+Y;
X+=Y; { Same as X := X+Y, needs -Sc command line switch}
X/=2; { Same as X := X/2, needs -Sc command line switch}
Done := False;
Weather := Good;
MyPi := 4* Tan(1);
\end{verbatim}
\end{remark}
Keeping in mind that the dereferencing of a typed pointer results
in a variable of the type the pointer points to, the following are
also valid assignments:
\begin{verbatim}
Var
L : ^Longint;
P : PPChar;
begin
L^:=3;
P^^:='A';
\end{verbatim}
Note the double dereferencing in the second assignment.
\subsection{Procedure statements}
\index{Statements!Procedure}
Procedure statements are calls to subroutines. There are
different possibilities for procedure calls:
\begin{itemize}
\item A normal procedure call.
\item An object method call (fully qualified or not).
\item Or even a call to a procedural type variable.
\end{itemize}
All types are present in the following diagram:
\input{syntax/procedure.syn}
The \fpc compiler will look for a procedure with the same name as given in
the procedure statement, and with a declared parameter list that matches the
actual parameter list.
The following are valid procedure statements:
\begin{verbatim}
Usage;
WriteLn('Pascal is an easy language !');
Doit();
\end{verbatim}
\begin{remark}
When looking for a function that matches the parameter list of the call,
the parameter types should be assignment-compatible for value and const
parameters, and should match exactly for parameters that are passed by
reference.
\end{remark}
\subsection{Goto statements}
\index{Statements!Goto}\keywordlink{goto}
\fpc supports the \var{goto} jump statement. Its prototype syntax is
\input{syntax/goto.syn}
When using \var{goto} statements, the following must be kept in mind:
\begin{enumerate}
\item The jump label must be defined in the same block as the \var{Goto}
statement.
\item Jumping from outside a loop to the inside of a loop or vice versa can
have strange effects.
\item To be able to use the \var{Goto} statement, the \var{-Sg} compiler
switch must be used, or \var{\{\$GOTO ON\}} must be used.
\end{enumerate}
\var{Goto} statements are considered bad practice and should be avoided as
much as possible. It is always possible to replace a \var{goto} statement by a
construction that doesn't need a \var{goto}, although this construction may
not be as clear as a goto statement.
For instance, the following is an allowed goto statement:
\begin{verbatim}
label
jumpto;
...
Jumpto :
Statement;
...
Goto jumpto;
...
\end{verbatim}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Structured statements
\section{Structured statements}
\index{Statements!Structured}
Structured statements can be broken into smaller simple statements, which
should be executed repeatedly, conditionally or sequentially:
\input{syntax/struct.syn}
Conditional statements come in 2 flavours :
\input{syntax/conditio.syn}
Repetitive statements come in 3 flavours:
\input{syntax/repetiti.syn}
The following sections deal with each of these statements.
\subsection{Compound statements}
\index{Statements!Compound}
\keywordlink{begin} \keywordlink{end}
Compound statements are a group of statements, separated by semicolons,
that are surrounded by the keywords \var{Begin} and \var{End}. The
last statement - before the \var{End} keyword - doesn't need to be followed by a semicolon, although it is
allowed. A compound statement is a way of grouping statements together,
executing the statements sequentially. They are treated as one statement
in cases where Pascal syntax expects 1 statement, such as in
\var{if...then...else} statements.
\input{syntax/compound.syn}
\subsection{The \var{Case} statement}
\index{Statements!Case}\index{Case}\keywordlink{case}
\fpc supports the \var{case} statement. Its syntax diagram is
\input{syntax/case.syn}
The constants appearing in the various case parts must be known at
compile-time, and can be of the following types : enumeration types,
Ordinal types (except boolean), and chars. The case expression must be also of
this type, or a compiler error will occur. All case constants must
have the same type.
The compiler will evaluate the case expression. If one of the case
constants' value matches the value of the expression, the statement that follows
this constant is executed. After that, the program continues after the final
\var{end}. \keywordlink{else} \keywordlink{otherwise}
If none of the case constants match the expression value, the statement
list after the \var{else} \index{else} or \var{otherwise}\index{otherwise}
keyword is executed. This can be an empty statement list.
If no else part is present, and no case constant matches the expression
value, program flow continues after the final \var{end}.
The case statements can be compound statements (i.e. a \var{Begin..End} block).
\begin{remark}
Contrary to \tp, duplicate case labels are not
allowed in \fpc, so the following code will generate an error when
compiling:
\begin{verbatim}
Var i : integer;
...
Case i of
3 : DoSomething;
1..5 : DoSomethingElse;
end;
\end{verbatim}
The compiler will generate a \var{Duplicate case label} error when compiling
this, because the 3 also appears (implicitly) in the range \var{1..5}. This
is similar to Delphi syntax.
\end{remark}
The following are valid case statements:
\begin{verbatim}
Case C of
'a' : WriteLn ('A pressed');
'b' : WriteLn ('B pressed');
'c' : WriteLn ('C pressed');
else
WriteLn ('unknown letter pressed : ',C);
end;
\end{verbatim}
Or
\begin{verbatim}
Case C of
'a','e','i','o','u' : WriteLn ('vowel pressed');
'y' : WriteLn ('This one depends on the language');
else
WriteLn ('Consonant pressed');
end;
\end{verbatim}
\begin{verbatim}
Case Number of
1..10 : WriteLn ('Small number');
11..100 : WriteLn ('Normal, medium number');
else
WriteLn ('HUGE number');
end;
\end{verbatim}
\subsection{The \var{If..then..else} statement}
\index{Statements!if}\index{If}\index{then}\index{else}\keywordlink{if}\keywordlink{then}\keywordlink{else}
The \var{If .. then .. else..} prototype syntax is
\input{syntax/ifthen.syn}
The expression between the \var{if} and \var{then} keywords must have a
\var{Boolean} result type. If the expression evaluates to \var{True} then the
statement following the \var{then} keyword is executed.
If the expression evaluates to \var{False}, then the statement following
the \var{else} keyword is executed, if it is present.
Some points to note:
\begin{itemize}
\item
Be aware of the fact that the boolean expression by default will be
short-cut evaluated, meaning that the evaluation will be stopped at
the point where the outcome is known with certainty.
\item
Also, before the \var {else} keyword, no semicolon (\var{;}) is allowed,
but all statements can be compound statements.
\item
In nested \var{If.. then .. else} constructs, some ambiguity may araise as
to which \var{else} statement pairs with which \var{if} statement. The rule
is that the \var{else } keyword matches the first \var{if} keyword
(searching backwards) not already matched by an \var{else} keyword.
\end{itemize}
For example:
\begin{verbatim}
If exp1 Then
If exp2 then
Stat1
else
stat2;
\end{verbatim}
Despite its appearance, the statement is syntactically equivalent to
\begin{verbatim}
If exp1 Then
begin
If exp2 then
Stat1
else
stat2
end;
\end{verbatim}
and not to
\begin{verbatim}
{ NOT EQUIVALENT }
If exp1 Then
begin
If exp2 then
Stat1
end
else
stat2;
\end{verbatim}
If it is this latter construct which is needed, the \var{begin} and \var{end}
keywords must be present. When in doubt, it is better to add them.
The following is a valid statement:
\begin{verbatim}
If Today in [Monday..Friday] then
WriteLn ('Must work harder')
else
WriteLn ('Take a day off.');
\end{verbatim}
\subsection{The \var{For..to/downto..do} statement}
\index{Statements!For}\index{Statements!Loop}\index{For}
\keywordlink{for}\keywordlink{do}\keywordlink{downto}
\fpc supports the \var{For} loop construction. A for loop is used in case
one wants to calculated something a fixed number of times.
The prototype syntax is as follows:
\input{syntax/for.syn}
Here, \var{Statement} can be a compound statement.
When the \var{For} statement is encountered, the control variable is initialized with
the initial value, and is compared with the final value.
What happens next depends on whether \var{to} or \var{downto} is used:
\begin{enumerate}
\item In the case \var{To} is used, if the initial value is larger than the final
value then \var{Statement} will never be executed.
\item In the case \var{DownTo} is used, if the initial value is less than the final
value then \var{Statement} will never be executed.
\end{enumerate}
After this check, the statement after \var{Do} is executed. After the
execution of the statement, the control variable is increased or decreased
with 1, depending on whether \var{To} or \var{Downto} is used.
The control variable must be an ordinal type, no other
types can be used as counters in a loop.
\begin{remark}
\fpc always calculates the upper bound before initializing
the counter variable with the initial value.
\end{remark}
\begin{remark}
It is not allowed to change (i.e. assign a value to) the value of a
loop variable inside the loop.
\end{remark}
The following are valid loops:
\begin{verbatim}
For Day := Monday to Friday do Work;
For I := 100 downto 1 do
WriteLn ('Counting down : ',i);
For I := 1 to 7*dwarfs do KissDwarf(i);
\end{verbatim}
The following will generate an error:
\begin{verbatim}
For I:=0 to 100 do
begin
DoSomething;
I:=I*2;
end;
\end{verbatim}
because the loop variable \var{I} cannot be assigned to inside the loop.
If the statement is a compound statement, then the \var{Break} and
\var{Continue} reserved words can be used to jump to the end or just
after the end of the \var{For} statement.
\subsection{The \var{Repeat..until} statement}
\index{Statements!Repeat}\index{Statements!Loop}\index{Repeat}
\keywordlink{repeat} \keywordlink{until}
The \var{repeat} statement is used to execute a statement until a certain
condition is reached. The statement will be executed at least once.
The prototype syntax of the \var{Repeat..until} statement is
\input{syntax/repeat.syn}
This will execute the statements between \var{repeat} and \var{until} up to
the moment when \var{Expression}\index{Expression} evaluates to \var{True}.
Since the \var{expression} is evaluated {\em after} the execution of the
statements, they are executed at least once.
Be aware of the fact that the boolean expression \var{Expression} will be
short-cut evaluated by default, meaning that the evaluation will be stopped
at the point where the outcome is known with certainty.
The following are valid \var{repeat} statements
\begin{verbatim}
repeat
WriteLn ('I =',i);
I := I+2;
until I>100;
repeat
X := X/2
until x<10e-3;
\end{verbatim}
Note that the last statement before the \var{until} keyword does not need
a terminating semicolon, but it is allowed.
The \var{Break} and \var{Continue} reserved words can be used to jump to
the end or just after the end of the \var{repeat .. until} statement.
\subsection{The \var{While..do} statement}
\index{Statements!While}\index{Statements!Loop}\index{While}
A \var{while} statement is used to execute a statement as long as a certain
condition holds. In difference with the \var{repeat} loop, this may imply
that the statement is never executed.
The prototype syntax of the \var{While..do} statement is
\input{syntax/while.syn}
This will execute \var{Statement} as long as \var{Expression} evaluates
to\index{Expression}\var{True}. Since \var{Expression} is evaluated {\em before} the execution
of \var{Statement}, it is possible that \var{Statement} isn't executed at
all. \var{Statement} can be a compound statement.
Be aware of the fact that the boolean expression \var{Expression} will be
short-cut evaluated by default, meaning that the evaluation will be stopped
at the point where the outcome is known with certainty.
The following are valid \var{while} statements:
\begin{verbatim}
I := I+2;
while i<=100 do
begin
WriteLn ('I =',i);
I := I+2;
end;
X := X/2;
while x>=10e-3 do
X := X/2;
\end{verbatim}
They correspond to the example loops for the \var{repeat} statements.
If the statement is a compound statement, then the \var{Break} and
\var{Continue} reserved words can be used to jump to the end or just
after the end of the \var{While} statement.
\subsection{The \var{With} statement}
\label{se:With}\index{With}\index{Statements!With} \keywordlink{with}
The \var{with} statement serves to access the elements of a record
or object or class, without having to specify the name of the each time.
The syntax for a \var{with} statement is
\input{syntax/with.syn}
The variable reference must be a variable of a record, object or class type.
In the \var{with} statement, any variable reference, or method reference is
checked to see if it is a field or method of the record or object or class.
If so, then that field is accessed, or that method is called.
Given the declaration:
\begin{verbatim}
Type
Passenger = Record
Name : String[30];
Flight : String[10];
end;
Var
TheCustomer : Passenger;
\end{verbatim}
The following statements are completely equivalent:
\begin{verbatim}
TheCustomer.Name := 'Michael';
TheCustomer.Flight := 'PS901';
\end{verbatim}
and
\begin{verbatim}
With TheCustomer do
begin
Name := 'Michael';
Flight := 'PS901';
end;
\end{verbatim}
The statement
\begin{verbatim}
With A,B,C,D do Statement;
\end{verbatim}
is equivalent to
\begin{verbatim}
With A do
With B do
With C do
With D do Statement;
\end{verbatim}
This also is a clear example of the fact that the variables are tried {\em last
to first}, i.e., when the compiler encounters a variable reference, it will
first check if it is a field or method of the last variable. If not, then it
will check the last-but-one, and so on.
The following example shows this;
\begin{verbatim}
Program testw;
Type AR = record
X,Y : Longint;
end;
PAR = ^Ar;
Var S,T : Ar;
begin
S.X := 1;S.Y := 1;
T.X := 2;T.Y := 2;
With S,T do
WriteLn (X,' ',Y);
end.
\end{verbatim}
The output of this program is
\begin{verbatim}
2 2
\end{verbatim}
Showing thus that the \var{X,Y} in the \var{WriteLn} statement match the
\var{T} record variable.
\begin{remark}
When using a \var{With} statement with a pointer, or a class, it is not
permitted to change the pointer or the class in the \var{With} block.
With the definitions of the previous example, the following illustrates
what it is about:
\begin{verbatim}
Var p : PAR;
begin
With P^ do
begin
// Do some operations
P:=OtherP;
X:=0.0; // Wrong X will be used !!
end;
\end{verbatim}
The reason the pointer cannot be changed is that the address is stored
by the compiler in a temporary register. Changing the pointer won't change
the temporary address. The same is true for classes.
\end{remark}
\subsection{Exception Statements}
\index{Statements!Exception}
\fpc supports exceptions. Exceptions provide a convenient way to
program error and error-recovery mechanisms, and are
closely related to classes.
Exception support is explained in \seec{Exceptions}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Assembler statements
\section{Assembler statements}
\index{Statements!Assembler}\index{Asm}\index{Assembler}
An assembler statement allows to insert assembler code right in the
Pascal code.
\input{syntax/statasm.syn}
More information about assembler blocks can be found in the \progref.
The register list is used to indicate the registers that are modified by an
assembler statement in the assembler block. The compiler stores certain results in the
registers. If the registers are modified in an assembler statement, the compiler
should, sometimes, be told about it. The registers are denoted with their
Intel names for the I386 processor, i.e., \var{'EAX'}, \var{'ESI'} etc...
As an example, consider the following assembler code:
\begin{verbatim}
asm
Movl $1,%ebx
Movl $0,%eax
addl %eax,%ebx
end; ['EAX','EBX'];
\end{verbatim}
This will tell the compiler that it should save and restore the contents of
the \var{EAX} and \var{EBX} registers when it encounters this asm statement.
\fpc supports various styles of assembler syntax. By default, \var{AT\&T}
syntax is assumed for the 80386 and compatibles platform.
The default assembler style can be changed with the \var{\{\$asmmode xxx\}}
switch in the code, or the \var{-R} command-line option. More about this can
be found in the \progref.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Using functions and procedures.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\chapter{Using functions and procedures}
\label{ch:Procedures}\index{Functions}\index{Procedures}
\fpc supports the use of functions and procedures. It supports
\begin{itemize}
\item Function overloading, i.e. functions with the same name but different
parameter lists.
\item \var{Const} parameters.
\item Open arrays (i.e. arrays without bounds).
\item Variable number of arguments as in C.
\item Return-like construct as in C, through the \var{Exit} keyword.
\end{itemize}
\begin{remark} In many of the subsequent paragraphs the words \var{procedure}
and \var{function} will be used interchangeably. The statements made are
valid for both, except when indicated otherwise.
\end{remark}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Procedure declaration
\section{Procedure declaration}
A procedure declaration defines an identifier and associates it with a
block of code. The procedure can then be called with a procedure statement.
\input{syntax/procedur.syn}
See \sees{Parameters} for the list of parameters.\index{Procedure}
\keywordlink{procedure}
A procedure declaration that is followed by a block implements the action of
the procedure in that block.
The following is a valid procedure :
\begin{verbatim}
Procedure DoSomething (Para : String);
begin
Writeln ('Got parameter : ',Para);
Writeln ('Parameter in upper case : ',Upper(Para));
end;
\end{verbatim}
Note that it is possible that a procedure calls itself.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Function declaration
\section{Function declaration}
\keywordlink{function}
A function declaration defines an identifier and associates it with a
block of code. The block of code will return a result.
The function can then be called inside an expression, or with a procedure
statement, if extended syntax is on.
\input{syntax/function.syn}
\index{Function}The result type of a function can be any previously declared type.
contrary to Turbo Pascal, where only simple types could be returned.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Function results
\section{Function results}
The result of a function can be set by setting the result variable:
this can be the function identifier or, (only in ObjFPC or Delphi mode)
the special \var{Result} identifier:
\begin{verbatim}
Function MyFunction : Integer;
begin
MyFunction:=12; // Return 12
end;
\end{verbatim}
In \var{Delphi} or \var{ObjPas} mode, the above can also be coded as:
\begin{verbatim}
Function MyFunction : Integer;
begin
Result:=12;
end;
\end{verbatim}
As an extension to \delphi syntax, the ObjFPC mode also supports a special
extension of the \var{Exit} procedure:
\begin{verbatim}
Function MyFunction : Integer;
begin
Exit(12);
end;
\end{verbatim}
The \var{Exit} call sets the result of the function and jumps to the final
\var{End} of the function declaration block. It can be seen as the equivalent
of the C \var{return} instruction.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Parameter lists
\section{Parameter lists}
\label{se:Parameters}\index{Parameters}
When arguments must be passed to a function or procedure, these parameters
must be declared in the formal parameter list of that function or procedure.
The parameter list is a declaration of identifiers that can be referred to
only in that procedure or function's block.
\input{syntax/params.syn}
Constant parameters, out parameters and variable parameters can also be \var{untyped}
parameters if they have no type
identifier.\index{Parameters!Untypes}\index{Parameters!Constant}\index{Parameters!Var}
As of version 1.1, \fpc supports default values for both constant parameters
and value parameters, but only for simple types. The compiler must be in
\var{OBJFPC} or \var{DELPHI} mode to accept default values.
\subsection{Value parameters}
Value parameters are declared as follows:\index{Parameters!Value}
\input{syntax/paramval.syn}
When parameters are declared as value parameters, the procedure gets {\em
a copy} of the parameters that the calling statement passes. Any modifications
to these parameters are purely local to the procedure's block, and do not
propagate back to the calling block.
A block that wishes to call a procedure with value parameters must pass
assignment compatible parameters to the procedure. This means that the types
should not match exactly, but can be converted to the actual parameter
types. This conversion code is inserted by the compiler itself.
Care must be taken when using value parameters: Value parameters makes heavy
use of the stack, especially when using large parameters. The total size of
all parameters in the formal parameter list should be below 32K for
portability's sake (the Intel version limits this to 64K).
Open arrays can be passed as value parameters. See \sees{openarray} for
more information on using open arrays.
For a parameter of a simple type (i.e. not a structured type), a default
value can be specified. This can be an untyped constant. If the function
call omits the parameter, the default value will be passed on to the
function. For dynamic arrays or other types that can be considered as
equivalent to a pointer, the only possible default value is \var{Nil}.
The following example will print 20 on the screen:
\begin{verbatim}
program testp;
Const
MyConst = 20;
Procedure MyRealFunc(I : Integer = MyConst);
begin
Writeln('Function received : ',I);
end;
begin
MyRealFunc;
end.
\end{verbatim}
\subsection{Variable parameters}
\label{se:varparams}\index{Parameters!Var}\keywordlink{var}
Variable parameters are declared as follows:
\input{syntax/paramvar.syn}
When parameters are declared as variable parameters, the procedure or
function accesses immediatly the variable that the calling block passed in
its parameter list. The procedure gets a pointer to the variable that was
passed, and uses this pointer to access the variable's value.
From this, it follows that any changes made to the parameter, will
propagate back to the calling block. This mechanism can be used to pass
values back in procedures.
Because of this, the calling block must pass a parameter of {\em exactly}
the same type as the declared parameter's type. If it does not, the compiler
will generate an error.
Variable and constant parameters can be untyped. In that case the variable has no type,
and hence is incompatible with all other types. However, the address operator
can be used on it, or it can be can passed to a function that has also an
untyped parameter. If an untyped parameter is used in an assigment,
or a value must be assigned to it, a typecast must be used.
File type variables must always be passed as variable parameters.
Open arrays can be passed as variable parameters. See \sees{openarray} for
more information on using open arrays.
Note that default values are not supported for variable parameters. This
would make little sense since it defeats the purpose of being able to pass a
value back to the caller.
\subsection{Out parameters}
\label{se:outparams}\index{Parameters!Out}\keywordlink{out}
Out parameters (output parameters) are declared as follows:
\input{syntax/paramout.syn}
The purpose of an \var{out} parameter is to pass values back to the calling
routine: The variable is passed by reference. The initial value of the
parameter on function entry is discarded, and should not be used.
If a variable must be used to pass a value to a function and retrieve data
from the function, then a variable parameter must be used. If only a value
must be retrieved, a \var{out} parameter can be used.
Needless to say, default values are not supported for \var{out} parameters.
The difference of out parameters and parameters by reference is very small:
the former gives the compiler more information about what happens to the
arguments when passed to the procedure: It knows that the variable does not
have to be initialized prior to the call. The following example illustrates
this:
\begin{verbatim}
Procedure DoA(Var A : Integer);
begin
A:=2;
Writeln('A is ',A);
end;
Procedure DoB(Out B : Integer);
begin
B:=2;
Writeln('B is ',B);
end;
Var
C,D : Integer;
begin
DoA(C);
DoB(D);
end.
\end{verbatim}
Both procedures \var{DoA} and \var{DoB} do practically the same. But
\var{DoB}'s declaration gives more information to the compiler, allowing
it to detect that \var{D} does not have to initialized before \var{DoB}
is called. Since the parameter \var{A} in \var{DoA} can receive a value as
well as return one, the compiler notices that \var{C} was not initialized
prior to the call to \var{DoA}:
\begin{verbatim}
home: >fpc -S2 -vwhn testo.pp
testo.pp(19,8) Hint: Variable "C" does not seem to be initialized
\end{verbatim}
This shows that it is better to use \var{out} parameters when the parameter
is used only to return a value.
\begin{remark}
Out parameters are only supported in Delphi and ObjFPC mode. For the other
modes, \var{out} is a valid identifier.
\end{remark}
%
\subsection{Constant parameters}\index{Parameters!Constant}\keywordlink{const}
In addition to variable parameters and value parameters \fpc also supports
Constant parameters. A constant parameter as can be specified as follows:
\input{syntax/paramcon.syn}
A constant argument is passed by reference if its size is larger than a
pointer. It is passed by value if the size is equal or is less then the
size of a native pointer.
This means that the function or procedure receives a pointer to the passed
argument, but it cannot be assigned to, this will result in a
compiler error. Furthermore a const parameter cannot be passed on to another
function that requires a variable parameter.
The main use for this is reducing the stack size, hence improving
performance, and still retaining the semantics of passing by value...
Constant parameters can also be untyped. See \sees{varparams} for more
information about untyped parameters.
As for value parameters, constant parameters can get default values.
Open arrays can be passed as constant parameters. See \sees{openarray} for
more information on using open arrays.
\subsection{Open array parameters}
\index{Parameters!Open Array}\index{Array}
\label{se:openarray}
\fpc supports the passing of open arrays, i.e. a procedure can be declared
with an array of unspecified length as a parameter, as in Delphi.
Open array parameters can be accessed in the procedure or function as an
array that is declared with starting index 0, and last element
index \var{High(paremeter)}.
For example, the parameter
\begin{verbatim}
Row : Array of Integer;
\end{verbatim}
would be equivalent to
\begin{verbatim}
Row : Array[0..N-1] of Integer;
\end{verbatim}
Where \var{N} would be the actual size of the array that is passed to the
function. \var{N-1} can be calculated as \var{High(Row)}.
Open parameters can be passed by value, by reference or as a constant
parameter. In the latter cases the procedure receives a pointer to the
actual array. In the former case, it receives a copy of the array.
In a function or procedure, open arrays can only be passed to functions which
are also declared with open arrays as parameters, {\em not} to functions or
procedures which accept arrays of fixed length.
The following is an example of a function using an open array:
\begin{verbatim}
Function Average (Row : Array of integer) : Real;
Var I : longint;
Temp : Real;
begin
Temp := Row[0];
For I := 1 to High(Row) do
Temp := Temp + Row[i];
Average := Temp / (High(Row)+1);
end;
\end{verbatim}
As of FPC 2.2, it is also possible to pass partial arrays to a function that
accepts an open array. This can be done by specifying the range of the array
which should be passed to the open array.
Given the declaration
\begin{verbatim}
Var
A : Array[1..100];
\end{verbatim}
the following call will compute and print the average of the 100 numbers:
\begin{verbatim}
Writeln('Average of 100 numbers: ',Average(A));
\end{verbatim}
But the following will compute and print the average of the first and second
half:
\begin{verbatim}
Writeln('Average of first 50 numbers: ',Average(A[1..50]));
Writeln('Average of last 50 numbers: ',Average(A[51..100]));
\end{verbatim}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% The array of const construct
\subsection{Array of const}
\index{Parameters!Open Array}\index{Array}\index{Array!Of const}
In Object Pascal or Delphi mode, \fpc supports the \var{Array of Const}
construction to pass parameters to a subroutine.
This is a special case of the \var{Open array} construction, where it is
allowed to pass any expression in an array to a function or procedure.
The expression must have a simple result type: structures cannot be passed
as an argument. This means that all ordinal, float or string types can be
passed, as well as pointers, classes and interfaces.
The elements of the array of const are converted to a a special variant record:
\begin{verbatim}
Type
PVarRec = ^TVarRec;
TVarRec = record
case VType : Ptrint of
vtInteger : (VInteger: Longint);
vtBoolean : (VBoolean: Boolean);
vtChar : (VChar: Char);
vtWideChar : (VWideChar: WideChar);
vtExtended : (VExtended: PExtended);
vtString : (VString: PShortString);
vtPointer : (VPointer: Pointer);
vtPChar : (VPChar: PChar);
vtObject : (VObject: TObject);
vtClass : (VClass: TClass);
vtPWideChar : (VPWideChar: PWideChar);
vtAnsiString : (VAnsiString: Pointer);
vtCurrency : (VCurrency: PCurrency);
vtVariant : (VVariant: PVariant);
vtInterface : (VInterface: Pointer);
vtWideString : (VWideString: Pointer);
vtInt64 : (VInt64: PInt64);
vtQWord : (VQWord: PQWord);
end;
\end{verbatim}
Therefor, inside the procedure body, the \var{array of const} argument is equivalent to
an open array of \var{TVarRec}:
\begin{verbatim}
Procedure Testit (Args: Array of const);
Var I : longint;
begin
If High(Args)<0 then
begin
Writeln ('No aguments');
exit;
end;
Writeln ('Got ',High(Args)+1,' arguments :');
For i:=0 to High(Args) do
begin
write ('Argument ',i,' has type ');
case Args[i].vtype of
vtinteger :
Writeln ('Integer, Value :',args[i].vinteger);
vtboolean :
Writeln ('Boolean, Value :',args[i].vboolean);
vtchar :
Writeln ('Char, value : ',args[i].vchar);
vtextended :
Writeln ('Extended, value : ',args[i].VExtended^);
vtString :
Writeln ('ShortString, value :',args[i].VString^);
vtPointer :
Writeln ('Pointer, value : ',Longint(Args[i].VPointer));
vtPChar :
Writeln ('PCHar, value : ',Args[i].VPChar);
vtObject :
Writeln ('Object, name : ',Args[i].VObject.Classname);
vtClass :
Writeln ('Class reference, name :',Args[i].VClass.Classname);
vtAnsiString :
Writeln ('AnsiString, value :',AnsiString(Args[I].VAnsiStr
else
Writeln ('(Unknown) : ',args[i].vtype);
end;
end;
end;
\end{verbatim}
In code, it is possible to pass an arbitrary array of elements
to this procedure:
\begin{verbatim}
S:='Ansistring 1';
T:='AnsiString 2';
Testit ([]);
Testit ([1,2]);
Testit (['A','B']);
Testit ([TRUE,FALSE,TRUE]);
Testit (['String','Another string']);
Testit ([S,T]) ;
Testit ([P1,P2]);
Testit ([@testit,Nil]);
Testit ([ObjA,ObjB]);
Testit ([1.234,1.234]);
TestIt ([AClass]);
\end{verbatim}
If the procedure is declared with the \var{cdecl} modifier, then the
compiler will pass the array as a C compiler would pass it. This, in effect,
emulates the C construct of a variable number of arguments, as the following
example will show:
\begin{verbatim}
program testaocc;
{$mode objfpc}
Const
P : Pchar = 'example';
Fmt : PChar =
'This %s uses printf to print numbers (%d) and strings.'#10;
// Declaration of standard C function printf:
procedure printf (fm : pchar; args : array of const);cdecl; external 'c';
begin
printf(Fmt,[P,123]);
end.
\end{verbatim}
Remark that this is not true for Delphi, so code relying on this feature
will not be portable.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Function overloading
\section{Function overloading}
\index{Functions!Overloaded}
Function overloading simply means that the same function is defined more
than once, but each time with a different formal parameter list.
The parameter lists must differ at least in one of its elements type.
When the compiler encounters a function call, it will look at the function
parameters to decide which one of the defined functions it should call.
This can be useful when the same function must be defined for different
types. For example, in the RTL, the \var{Dec} procedure could be
defined as:
\begin{verbatim}
...
Dec(Var I : Longint;decrement : Longint);
Dec(Var I : Longint);
Dec(Var I : Byte;decrement : Longint);
Dec(Var I : Byte);
...
\end{verbatim}
When the compiler encounters a call to the \var{Dec} function, it will first search
which function it should use. It therefore checks the parameters in a
function call, and looks if there is a function definition which matches the
specified parameter list. If the compiler finds such a function, a call is
inserted to that function. If no such function is found, a compiler error is
generated.
functions that have a \var{cdecl} modifier cannot be overloaded.
(Technically, because this modifier prevents the mangling of
the function name by the compiler).
Prior to version 1.9 of the compiler, the overloaded functions needed to be
in the same unit. Now the compiler will continue searching in other units if
it doesn't find a matching version of an overloaded function in one unit,
and if the \var{overload} keyword is present.
If the \var{overload} keyword is not present, then all overloaded versions
must reside in the same unit, and if it concerns methods part of a class,
they must be in the same class, i.e. the compiler will not look for
overloaded methods in parent classes if the \var{overload} keyword was not
specified.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% forward defined functions
\section{Forward defined functions}
\index{Functions!Forward}\index{Forward} \keywordlink{forward}
A function can be declared without having it followed by its implementation,
by having it followed by the \var{forward} procedure. The effective
implementation of that function must follow later in the module.
The function can be used after a \var{forward} declaration as if it had been
implemented already.
The following is an example of a forward declaration.
\begin{verbatim}
Program testforward;
Procedure First (n : longint); forward;
Procedure Second;
begin
WriteLn ('In second. Calling first...');
First (1);
end;
Procedure First (n : longint);
begin
WriteLn ('First received : ',n);
end;
begin
Second;
end.
\end{verbatim}
A function can be defined as forward only once.
Likewise, in units, it is not allowed to have a forward declared function
of a function that has been declared in the interface part. The interface
declaration counts as a \var{forward} declaration.
The following unit will give an error when compiled:
\begin{verbatim}
Unit testforward;
interface
Procedure First (n : longint);
Procedure Second;
implementation
Procedure First (n : longint); forward;
Procedure Second;
begin
WriteLn ('In second. Calling first...');
First (1);
end;
Procedure First (n : longint);
begin
WriteLn ('First received : ',n);
end;
end.
\end{verbatim}
Reversely, functions declared in the interface section cannot be declared
forward in the implementation section. Logically, since they already have
been declared.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% External functions
\section{External functions}
\label{se:external}\index{External}\index{Functions!External}\keywordlink{external}
The \var{external} modifier can be used to declare a function that resides in
an external object file. It allows to use the function in some code, and at
linking time, the object file containing the implementation of the function
or procedure must be linked in.
\input{syntax/external.syn}
It replaces, in effect, the function or procedure code block.
As an example:
\begin{verbatim}
program CmodDemo;
{$Linklib c}
Const P : PChar = 'This is fun !';
Function strlen (P : PChar) : Longint; cdecl; external;
begin
WriteLn ('Length of (',p,') : ',strlen(p))
end.
\end{verbatim}
\begin{remark}
The parameters in the declaration of the \var{external} function
should match exactly the ones in the declaration in the object file.
\end{remark}
If the \var{external} modifier is followed by a string constant:
\begin{verbatim}
external 'lname';
\end{verbatim}
Then this tells the compiler that the function resides in library
'lname'. The compiler will then automatically link this library to
the program.
The name that the function has in the library can also be specified:
\begin{verbatim}
external 'lname' name 'Fname';
\end{verbatim}
\index{name}This tells the compiler that the function resides in library 'lname',
but with name 'Fname'.The compiler will then automatically link this
library to the program, and use the correct name for the function.
Under \windows and \ostwo, the following form can also be used:
\begin{verbatim}
external 'lname' Index Ind;
\end{verbatim}
\index{index}This tells the compiler that the function resides in library 'lname',
but with index \var{Ind}. The compiler will then automatically
link this library to the program, and use the correct index for the
function.
Finally, the external directive can be used to specify the external name
of the function :
\begin{verbatim}
external name 'Fname';
{$L myfunc.o}
\end{verbatim}
\index{external}%
This tells the compiler that the function has the name 'Fname'. The
correct library or object file (in this case myfunc.o) must still be linked,
ensuring that the function 'Fname' is indeed included in the linking stage.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Assembler functions
\section{Assembler functions}
\index{Assembler}\index{Functions!Assembler}\keywordlink{assembler}
Functions and procedures can be completely implemented in assembly
language. To indicate this, use the \var{assembler} keyword:
\input{syntax/asm.syn}
Contrary to Delphi, the assembler keyword must be present to indicate an
assembler function.
For more information about assembler functions, see the chapter on using
assembler in the \progref.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Modifiers
\section{Modifiers}
\index{Modifiers}\index{Functions!Modifiers}
A function or procedure declaration can contain modifiers. Here we list the
various possibilities:
\input{syntax/modifiers.syn}
\fpc doesn't support all \tp modifiers (although it parses them for
compatibility), but does support a number of additional modifiers.
They are used mainly for assembler and reference to C object files.
\subsection{alias}
\label{se:alias}
\index{Alias}\index{Modifiers!Alias}\keywordlink{alias}
The \var{alias} modifier allows the programmer to specify a different name for a
procedure or function. This is mostly useful for referring to this procedure
from assembly language constructs or from another object file. As an example,
consider the following program:
\begin{verbatim}
Program Aliases;
Procedure Printit;alias : 'DOIT';
begin
WriteLn ('In Printit (alias : "DOIT")');
end;
begin
asm
call DOIT
end;
end.
\end{verbatim}
\begin{remark} The specified alias is inserted straight into the assembly
code, thus it is case sensitive.
\end{remark}
The \var{alias} modifier does not make the symbol public to other modules,
unless the routine is also declared in the interface part of a unit, or
the \var{public} modifier is used to force it as public. Consider the
following:
\begin{verbatim}
unit testalias;
interface
procedure testroutine;
implementation
procedure testroutine;alias:'ARoutine';
begin
WriteLn('Hello world');
end;
end.
\end{verbatim}
This will make the routine \var{testroutine} available publicly to
external object files under the label name \var{ARoutine}.
\begin{remark}
The \var{alias} directive is considered deprecated. Please use the
\var{public name} directive. See \sees{public}.
\end{remark}
\subsection{cdecl}
\label{se:cdecl}\index{cdecl}\index{Modifiers!cdecl}\keywordlink{cdecl}
The \var{cdecl} modifier can be used to declare a function that uses a C
type calling convention. This must be used when accessing functions residing in
an object file generated by standard C compilers, but must also be used for
Pascal functions that are to be used as callbacks for C libraries.
The \var{cdecl} modifier allows to use C function in the code.
For external C functions, the object file containing the \var{C}
implementation of the function or procedure must be linked in.
As an example:
\begin{verbatim}
program CmodDemo;
{$LINKLIB c}
Const P : PChar = 'This is fun !';
Function StrLen(P: PChar): Longint;cdecl; external name 'strlen';
begin
WriteLn ('Length of (',p,') : ',StrLen(p));
end.
\end{verbatim}
When compiling this, and linking to the C-library, the \var{strlen} function
can be called throughout the program. The \var{external} directive tells
the compiler that the function resides in an external object file or library
with the 'strlen' name (see \ref{se:external}).
\begin{remark}
The parameters in our declaration of the \var{C} function should
match exactly the ones in the declaration in \var{C}.
\end{remark}
For functions that are not external, but which are declared using
\var{cdecl}, no external linking is needed. These functions have some
restrictions, for instance the \var{array of const} construct can not be
used (due the the way this uses the stack). On the other hand, the
\var{cdecl} modifier allows these functions to be used as callbacks for
routines written in C, as the latter expect the 'cdecl' calling convention.
\subsection{export}\keywordlink{export}
\index{export}\index{Modifiers!export}
The \var{export} modifier is used to export names when creating a shared library
or an executable program. This means that the symbol will be publicly
available, and can be imported from other programs. For more information
on this modifier, consult the section on Programming dynamic libraries
in the \progref.
\subsection{inline}\keywordlink{inline}
\index{inline}\index{Modifiers!inline}
\label{se:inline}
Procedures that are declared \var{inline} are copied to the places where they
are called. This has the effect that there is no actual procedure call,
the code of the procedure is just copied to where the procedure is needed,
this results in faster execution speed if the function or procedure is
used a lot. It is obvious that inlining large functions does not make sense.
By default, \var{inline} procedures are not allowed. Inline code must be enabled
using the command-line switch \var{-Si} or \var{\{\$inline on\}}
directive.
\begin{remark}
\begin{enumerate}
\item \var{inline} is only a hint for the compiler. This does {\em not}
automatically mean that all calls are inlined; sometimes the compiler
may decide that a function simply cannot be inlined, or that a particular call
to the function cannot be inlined. If so, the compiler will emit a warning.
\item In old versions of \fpc, inline code was {\em not} exported from a unit. This
meant that when calling an inline procedure from another unit, a normal procedure
call will be performed. Only inside units, \var{Inline} procedures are really inlined.
As of version 2.0.2, inline works accross units.
\item Recursive inline functions are not allowed. i.e. an inline function
that calls itself is not allowed.
\end{enumerate}
\end{remark}
\subsection{interrupt}
\label{se:interrupt}\index{interrupt}\index{Mofidiers!interrupt}\keywordlink{interrupt}
The \var{interrupt} keyword is used to declare a routine which will
be used as an interrupt handler. On entry to this routine, all the registers
will be saved and on exit, all registers will be restored
and an interrupt or trap return will be executed (instead of the normal return
from subroutine instruction).
On platforms where a return from interrupt does not exist, the normal exit
code of routines will be done instead. For more information on the generated
code, consult the \progref.
\subsection{local}
\label{se:local}\index{local}\index{Mofidiers!local}\keywordlink{local}
The \var{local} modifier allows the compiler to optimize the function: a local
function cannot be in the interface section of a unit: it is always in the
implementation section of the unit. From this it follows that the function
cannot be exported from a library.
On Linux, the local directive results in some optimizations. On Windows, it
has no effect. It was introduced for Kylix compatibility.
\subsection{nostackframe}
\label{se:nostackframe}\index{nostackframe}\index{Modifiers!nostackframe}\keywordlink{nostackframe}
The \var{nostackframe} modifier can be used to tell the compiler it should
not generate a stack frame for this procedure or function. By default, a
stack frame is always generated for each procedure or function.
One should be extremely careful when using this modifier: most procedures or
functions need a stack frame. Particularly for debugging they are needed.
\subsection{overload}
\label{se:overload}\index{overload}\index{Modifiers!overload}\keywordlink{overload}
The \var{overload} modifier tells the compiler that this function is
overloaded. It is mainly for \delphi compatibility, as in \fpc, all
functions and procedures can be overloaded without this modifier.
There is only one case where the \var{overload} modifier is mandatory:
if a function must be overloaded that resides in another unit. Both
functions must be declared with the \var{overload} modifier: the
\var{overload} modifier tells the compiler that it should continue
looking for overloaded versions in other units.
The following example illustrates this. Take the first unit:
\begin{verbatim}
unit ua;
interface
procedure DoIt(A : String); overload;
implementation
procedure DoIt(A : String);
begin
Writeln('ua.DoIt received ',A)
end;
end.
\end{verbatim}
And a second unit, which contains an overloaded version:
\begin{verbatim}
unit ub;
interface
procedure DoIt(A : Integer); overload;
implementation
procedure DoIt(A : integer);
begin
Writeln('ub.DoIt received ',A)
end;
end.
\end{verbatim}
And the following program, which uses both units:
\begin{verbatim}
program uab;
uses ua,ub;
begin
DoIt('Some string');
end.
\end{verbatim}
When the compiler starts looking for the declaration of \var{DoIt}, it will
find one in the \file{ub} unit. Without the \var{overload} directive, the
compiler would give an argument mismatch error:
\begin{verbatim}
home: >fpc uab.pp
uab.pp(6,21) Error: Incompatible type for arg no. 1:
Got "Constant String", expected "SmallInt"
\end{verbatim}
With the \var{overload} directive in place at both locations, the compiler
knows it must continue searching for an overloaded version with matching
parameter list. Note that {\em both} declarations must have the
\var{overload} modifier specified; It is not enough to have the modifier in
unit \file{ub}. This is to prevent unwanted overloading: The programmer who
implemented the \var{ua} unit must mark the procedure as fit for overloading.
%
%
\subsection{pascal}
\label{se:pascal}\index{pascal}\index{Modifiers!pascal}\keywordlink{pascal}
The \var{pascal} modifier can be used to declare a function that uses the
classic Pascal type calling convention (passing parameters from left to right).
For more information on the Pascal calling convention, consult the \progref.
\subsection{public}
\label{se:public}\index{Modifiers!public}\index{public}\keywordlink{public}
The \var{Public} keyword is used to declare a function globally in a unit.
This is useful if the function should not be accessible from the unit
file (i.e. another unit/program using the unit doesn't see the function),
but must be accessible from the object file. as an example:
\begin{verbatim}
Unit someunit;
interface
Function First : Real;
Implementation
Function First : Real;
begin
First := 0;
end;
Function Second : Real; [Public];
begin
Second := 1;
end;
end.
\end{verbatim}
If another program or unit uses this unit, it will not be able to use the
function \var{Second}, since it isn't declared in the interface part.
However, it will be possible to access the function \var{Second} at the
assembly-language level, by using its mangled name (see the \progref).
The \var{public} modifier can also be followed by a \var{name} directive to
specify the assembler name, as follows:
\begin{verbatim}
Unit someunit;
interface
Function First : Real;
Implementation
Function First : Real;
begin
First := 0;
end;
Function Second : Real; Public name 'second';
begin
Second := 1;
end;
end.
\end{verbatim}
The assembler symbol as specified by the 'public name' directive will
be 'second', in all lowercase letters.
\subsection{register}
\label{se:register}\index{register}\index{Modifiers!register}\keywordlink{register}
The \var{register} keyword is used for compatibility with Delphi. In
version 1.0.x of the compiler, this directive has no effect on the
generated code. As of the 1.9.X versions, this directive is supported. The
first three arguments are passed in registers EAX,ECX and EDX.
\subsection{safecall}
\index{safecall}\index{Modifiers!safecall}\keywordlink{savecall}
The \var{safecall} modifier ressembles closely the \var{stdcall} modifier.
It sends parameters from right to left on the stack. Additionally, the
called procedure saves and restores all registers.
More information about this modifier can be found in the \progref, in the
section on the calling mechanism and the chapter on linking.
\subsection{saveregisters}
\index{saveregisters}\index{Modifiers!saveregisters}\keywordlink{saveregisters}
The \var{saveregisters} modifier tells the compiler that all CPU registers should be
saved prior to calling this routine. Which CPU registers are saved, depends
entirely on the CPU.
\subsection{softfloat}
\index{softfloat}\index{Modifiers!softfloat}\keywordlink{softfloat}
The \var{softfloat} modifier makes sense only on the ARM architecture.
\subsection{stdcall}
\index{stdcall}\index{Modifiers!stdcall}\keywordlink{stdcall}
The \var{stdcall} modifier pushes the parameters from right to left on the stack,
it also aligns all the parameters to a default alignment.
More information about this modifier can be found in the \progref, in the
section on the calling mechanism and the chapter on linking.
\subsection{varargs}
\index{varargs}\index{Modifiers!varargs}\keywordlink{varargs}
This modifier can only be used together with the \var{cdecl} modifier, for
external C procedures. It indicates that the procedure accepts a variable
number of arguments after the last declared variable. These arguments are
passed on without any type checking. It is equivalent to using the
\var{array of const} construction for \var{cdecl} procedures, without having
to declare the \var{array of const}. The square brackets around the variable
arguments do not need to be used when this form of declaration is used.
The following declarations are 2 ways of referring to the same function
in the C library:
\begin{verbatim}
Function PrintF1(fmt : pchar); cdecl; varargs;
external 'c' name 'printf';
Function PrintF2(fmt : pchar; Args : Array of const); cdecl;
external 'c' name 'printf';
\end{verbatim}
But they must be called differently:
\begin{verbatim}
PrintF1('%d %d\n',1,1);
PrintF2('%d %d\n',[1,1]);
\end{verbatim}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Unsupported Turbo Pascal modifiers
\section{Unsupported Turbo Pascal modifiers}
\index{Modifiers}\keywordlink{far}\keywordlink{near}
The modifiers that exist in \tp, but aren't supported by \fpc, are
listed in \seet{Modifs}.
\begin{FPCltable}{lr}{Unsupported modifiers}{Modifs}
Modifier & Why not supported ? \\ \hline
Near & \fpc is a 32-bit compiler.\\
Far & \fpc is a 32-bit compiler. \\
\end{FPCltable}
The compiler will give a warning when it encounters these modifiers, but
will otherwise completely ignore them.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Operator overloading
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\chapter{Operator overloading}
\label{ch:operatoroverloading}
\index{overloading!operators}
\section{Introduction}
\fpc supports operator overloading. This means that it is possible to
define the action of some operators on self-defined types, and thus allow
the use of these types in mathematical expressions.
Defining the action of an operator is much like the definition of a
function or procedure, only there are some restrictions on the possible
definitions, as will be shown in the subsequent.
Operator overloading is, in essence, a powerful notational tool;
but it is also not more than that, since the same results can be
obtained with regular function calls. When using operator overloading,
It is important to keep in mind that some implicit rules may produce
some unexpected results. This will be indicated.
\section{Operator declarations}
\index{operators}
To define the action of an operator is much like defining a function:
\input{syntax/operator.syn}
The parameter list for a comparision operator or an arithmetic operator
must always contain 2 parameters, with the exception of the unary minus,
where only 1 parameters is needed. The result type of the comparision
operator must be \var{Boolean}.
\begin{remark}
When compiling in \var{Delphi} mode or \var{Objfpc} mode, the result
identifier may be dropped. The result can then be accessed through
the standard \var{Result} symbol.
If the result identifier is dropped and the compiler is not in one
of these modes, a syntax error will occur.
\end{remark}
The statement block contains the necessary statements to determine the
result of the operation. It can contain arbitrary large pieces of code;
it is executed whenever the operation is encountered in some expression.
The result of the statement block must always be defined; error conditions
are not checked by the compiler, and the code must take care of all possible
cases, throwing a run-time error if some error condition is encountered.
In the following, the three types of operator definitions will be examined.
As an example, throughout this chapter the following type will be used to
define overloaded operators on :
\begin{verbatim}
type
complex = record
re : real;
im : real;
end;
\end{verbatim}
This type will be used in all examples.
The sources of the Run-Time Library contain 2 units that heavily use
operator overloading:
\begin{description}
\item[ucomplex] This unit contains a complete calculus for complex numbers.
\item[matrix] This unit contains a complete calculus for matrices.
\end{description}
\section{Assignment operators}
\index{Operators!Assignment}\keywordlink{operator}
The assignment operator defines the action of a assignent of one type of
variable to another. The result type must match the type of the variable
at the left of the assignment statement, the single parameter to the
assignment operator must have the same type as the expression at the
right of the assignment operator.
This system can be used to declare a new type, and define an assignment for
that type. For instance, to be able to assign a newly defined type 'Complex'
\begin{verbatim}
Var
C,Z : Complex; // New type complex
begin
Z:=C; // assignments between complex types.
end;
\end{verbatim}
The following assignment operator would have to be defined:
\begin{verbatim}
Operator := (C : Complex) z : complex;
\end{verbatim}
To be able to assign a real type to a complex type as follows:
\begin{verbatim}
var
R : real;
C : complex;
begin
C:=R;
end;
\end{verbatim}
the following assignment operator must be defined:
\begin{verbatim}
Operator := (r : real) z : complex;
\end{verbatim}
As can be seen from this statement, it defines the action of the operator
\var{:=} with at the right a real expression, and at the left a complex
expression.
An example implementation of this could be as follows:
\begin{verbatim}
operator := (r : real) z : complex;
begin
z.re:=r;
z.im:=0.0;
end;
\end{verbatim}
As can be seen in the example, the result identifier (\var{z} in this case)
is used to store the result of the assignment. When compiling in Delphi mode
or objfpc mode, the use of the special identifier \var{Result} is also
allowed, and can be substituted for the \var{z}, so the above would be
equivalent to
\begin{verbatim}
operator := (r : real) z : complex;
begin
Result.re:=r;
Result.im:=0.0;
end;
\end{verbatim}
The assignment operator is also used to convert types from one type to
another. The compiler will consider all overloaded assignment operators
till it finds one that matches the types of the left hand and right hand
expressions. If no such operator is found, a 'type mismatch' error
is given.
\begin{remark}
The assignment operator is not commutative; the compiler will never reverse
the role of the two arguments. in other words, given the above definition of
the assignment operator, the following is {\em not} possible:
\begin{verbatim}
var
R : real;
C : complex;
begin
R:=C;
end;
\end{verbatim}
If the reverse assignment should be possible then the assigment operator
must be defined for that as well.
(This is not so for reals and complex numbers.)
\end{remark}
\begin{remark}
The assignment operator is also used in implicit type conversions. This can
have unwanted effects. Consider the following definitions:
\begin{verbatim}
operator := (r : real) z : complex;
function exp(c : complex) : complex;
\end{verbatim}
Then the following assignment will give a type mismatch:
\begin{verbatim}
Var
r1,r2 : real;
begin
r1:=exp(r2);
end;
\end{verbatim}
The mismatch occurs because the compiler will encounter the definition of the \var{exp} function
with the complex argument. It implicitly converts \var{r2} to a complex, so it can
use the above \var{exp} function. The result of this function is a complex,
which cannot be assigned to \var{r1}, so the compiler will give a 'type mismatch'
error. The compiler will not look further for another \var{exp} which has
the correct arguments.
It is possible to avoid this particular problem by specifying
\begin{verbatim}
r1:=system.exp(r2);
\end{verbatim}
An experimental solution for this problem exists in the compiler, but is
not enabled by default. Maybe someday it will be.
\end{remark}
\section{Arithmetic operators}
\index{Operators!Arithmetic}\index{Operators!Binary}
Arithmetic operators define the action of a binary operator. Possible
operations are:
\begin{description}
\item[multiplication] To multiply two types, the \var{*} multiplication
operator must be overloaded.
\item[division] To divide two types, the \var{/} division
operator must be overloaded.
\item[addition] To add two types, the \var{+} addition
operator must be overloaded.
\item[substraction] To substract two types, the \var{-} substraction
operator must be overloaded.
\item[exponentiation] To exponentiate two types, the \var{**} exponentiation
operator must be overloaded.
\item[Unary minus] is used to take the negative of the argument following
it.
\item[Symmetric Difference] To take the symmetric difference of 2
structures, the \var{><} operator must be overloaded.
\end{description}
The definition of an arithmetic operator takes two parameters, except for
unary minus, which needs only 1 parameter. The first parameter must be of
the type that occurs at the left of the operator, the second parameter must
be of the type that is at the right of the arithmetic operator. The result
type must match the type that results after the arithmetic operation.
To compile an expression as
\begin{verbatim}
var
R : real;
C,Z : complex;
begin
C:=R*Z;
end;
\end{verbatim}
One needs a definition of the multiplication operator as:
\begin{verbatim}
Operator * (r : real; z1 : complex) z : complex;
begin
z.re := z1.re * r;
z.im := z1.im * r;
end;
\end{verbatim}
As can be seen, the first operator is a real, and the second is
a complex. The result type is complex.
Multiplication and addition of reals and complexes are commutative
operations. The compiler, however, has no notion of this fact so even
if a multiplication between a real and a complex is defined, the
compiler will not use that definition when it encounters a complex
and a real (in that order). It is necessary to define both operations.
So, given the above definition of the multiplication,
the compiler will not accept the following statement:
\begin{verbatim}
var
R : real;
C,Z : complex;
begin
C:=Z*R;
end;
\end{verbatim}
Since the types of \var{Z} and \var{R} don't match the types in the
operator definition.
The reason for this behaviour is that it is possible that a multiplication
is not always commutative. e.g. the multiplication of a \var{(n,m)} with a
\var{(m,n)} matrix will result in a \var{(n,n)} matrix, while the
mutiplication of a \var{(m,n)} with a \var{(n,m)} matrix is a \var{(m,m)}
matrix, which needn't be the same in all cases.
\section{Comparision operator}
\index{Operators!Comparison}
The comparision operator can be overloaded to compare two different types
or to compare two equal types that are not basic types. The result type of
a comparision operator is always a boolean.
The comparision operators that can be overloaded are:
\begin{description}
\item[equal to] (=) To determine if two variables are equal.
\item[less than] ($<$) To determine if one variable is less than another.
\item[greater than] ($>$) To determine if one variable is greater than another.
\item[greater than or equal to] ($>=$) To determine if one variable is greater than
or equal to another.
\item[less than or equal to] ($<=$) To determine if one variable is greater
than or equal to another.
\end{description}
There is no separate operator for {\em unequal to} ($<>$). To evaluate a
statement that contans the {\em unequal to} operator, the compiler uses the
{\em equal to} operator (=), and negates the result.
As an example, the following opetrator allows to compare two complex
numbers:
\begin{verbatim}
operator = (z1, z2 : complex) b : boolean;
\end{verbatim}
the above definition allows comparisions of the following form:
\begin{verbatim}
Var
C1,C2 : Complex;
begin
If C1=C2 then
Writeln('C1 and C2 are equal');
end;
\end{verbatim}
The comparision operator definition needs 2 parameters, with the types that
the operator is meant to compare. Here also, the compiler doesn't apply
commutativity: if the two types are different, then it is necessary to
define 2 comparision operators.
In the case of complex numbers, it is, for instance necessary to define
2 comparsions: one with the complex type first, and one with the real type
first.
Given the definitions
\begin{verbatim}
operator = (z1 : complex;r : real) b : boolean;
operator = (r : real; z1 : complex) b : boolean;
\end{verbatim}
the following two comparisions are possible:
\begin{verbatim}
Var
R,S : Real;
C : Complex;
begin
If (C=R) or (S=C) then
Writeln ('Ok');
end;
\end{verbatim}
Note that the order of the real and complex type in the two comparisions
is reversed.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Programs, Units, Blocks
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\chapter{Programs, units, blocks}
A Pascal program can consist of modules called \var{units}. A unit can be used
to group pieces of code together, or to give someone code without giving
the sources.
Both programs and units consist of code blocks, which are mixtures of
statements, procedures, and variable or type declarations.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Programs
\section{Programs}
\index{program}\index{uses}\keywordlink{program}\keywordlink{uses}
A Pascal program consists of the program header, followed possibly by a
'uses' clause, and a block.
\input{syntax/program.syn}
The program header is provided for backwards compatibility, and is ignored
by the compiler.
The uses clause serves to identify all units that are needed by the program.
All identifiers which are declared in the the interface section of the units
in the uses clause are added to the known identifiers of the program.
The system unit doesn't have to be in this list, since it is always loaded
by the compiler.
The order in which the units appear is significant, it determines in
which order they are initialized. Units are initialized in the same order
as they appear in the uses clause. Identifiers are searched in the opposite
order, i.e. when the compiler searches for an identifier, then it looks
first in the last unit in the uses clause, then the last but one, and so on.
This is important in case two units declare different types with the same
identifier.
When the compiler looks for unit files, it adds the extension \file{.ppu}
to the name of the unit. On \linux and in operating systems where filenames
are case sensitive when looking for a unit, the following mechanism is
used:
\begin{enumerate}
\item The unit is first looked for in the original case.
\item The unit is looked for in all-lowercase letters.
\item The unit is looked for in all-uppercase letters.
\end{enumerate}
Additionally, If a unit name is longer than 8 characters, the compiler
will first look for a unit name with this length, and then it will
truncate the name to 8 characters and look for it again.
For compatibility reasons, this is also true on platforms that
support long file names.
Note that the above search is performed in each directory in the search
path.
The program block contains the statements that will be executed when the
program is started. Note that these statements need not necessarily be the
first statements that are executed: the initialization code of the units
may also contain statements that are executed prior to the program code.
The structure of a program block is discussed below.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Units
\section{Units}
\index{unit}\keywordlink{unit}
A unit contains a set of declarations, procedures and functions that can be
used by a program or another unit.
The syntax for a unit is as follows:
\input{syntax/unit.syn}
As can be seen from the syntax diagram, a unit always consists of a
interface and an implementation part. Optionally, there is an initialization
block and a finalization block, containing code that will be executed when
the program is started, and when the program stops, respectively.
\keywordlink{interface}\keywordlink{implementation}
Both the interface part or implementation part can be empty, but the
keywords \var{Interface} and \var{implementation} must be specified.
The following is a completely valid unit;
\begin{verbatim}
unit a;
interface
implementation
end.
\end{verbatim}
The interface part declares all identifiers that must be exported from the
unit. This can be constant, type or variable identifiers, and also procedure
or function identifier declarations. The interface part cannot contain code
that is executed: only declarations are allowed. The following is a valid
interface part:
\begin{verbatim}
unit a;
interface
uses b;
Function MyFunction : SomeBType;
Implementation
\end{verbatim}
The type \var{SomeBType} is defined in unit \var{b}.
All functions and methods that are declared in the interface part must
be implemented in the implementation part of the unit, except for
declarations of external functions or procedures. If a declared method
or function is not implemented in the implementation part, the compiler
will give an error, for example the following:
\begin{verbatim}
unit unita;
interface
Function MyFunction : Integer;
implementation
end.
\end{verbatim}
Will result in the following error:
\begin{verbatim}
unita.pp(5,10) Error: Forward declaration not solved "MyFunction:SmallInt;"
\end{verbatim}
The implementation part is primarily intended for the implementation of the
functions and procedures declared in the interface part. However, it can
also contain declarations of it's own: The declarations inside the
implementation part are {\em not} accessible outside the unit.
The initialization and finalization part of a unit are optional:
The initialization block is used to initialize certain variables or
execute code that is necessary for the correct functioning of the unit.
The initialization parts of the units
are executed in the order that the compiler loaded the units when compiling
a program. They are executed before the first statement of the program is
executed.
The finalization part of the units are executed in the reverse order of the
initialization execution. They are used for instance to clean up any resources
allocated in the initialization part of the unit, or during the lifetime of
the program. The finalization part is always executed in the case of a
normal program termination: whether it is because the final \var{end} is
reached in the program code or because a \var{Halt} instruction was executed
somewhere.
In case the program stops during the execution of the initialization blocks
of one of the units, only the units that were already initialized will be
finalized.
\keywordlink{initialization}\keywordlink{finalization}
Note that if a \var{finalization} block is present, an \var{Initialization}
block must be present, but it can be empty:
\begin{verbatim}
Initialization
Finalization
CleanupUnit;
end.
\end{verbatim}
An initialization section by itself (i.e. without finalization) may simply be
replaced by a statement block. That is, the following:
\begin{verbatim}
Initialization
InitializeUnit;
end.
\end{verbatim}
is completely equivalent to
\begin{verbatim}
Begin
InitializeUnit;
end.
\end{verbatim}
\section{Unit dependencies}
When a program uses a unit (say \file{unitA}) and this units uses a second
unit, say \file{unitB}, then the program depends indirectly also on
\var{unitB}. This means that the compiler must have access to \file{unitB} when
trying to compile the program. If the unit is not present at compile time,
an error occurs.
Note that the identifiers from a unit on which a program depends indirectly,
are not accessible to the program. To have access to the identifiers of a
unit, the unit must be in the uses clause of the program or unit where the
identifiers are needed.
Units can be mutually dependent, that is, they can reference each other in
their uses clauses. This is allowed, on the condition that at least one of
the references is in the implementation section of the unit. This also holds
for indirect mutually dependent units.
If it is possible to start from one interface uses clause of a unit, and to return
there via uses clauses of interfaces only, then there is circular unit
dependence, and the compiler will generate an error.
For example, the following is not allowed:
\begin{verbatim}
Unit UnitA;
interface
Uses UnitB;
implementation
end.
Unit UnitB
interface
Uses UnitA;
implementation
end.
\end{verbatim}
But this is allowed :
\begin{verbatim}
Unit UnitA;
interface
Uses UnitB;
implementation
end.
Unit UnitB
implementation
Uses UnitA;
end.
\end{verbatim}
Because \file{UnitB} uses \file{UnitA} only in its implentation section.
In general, it is a bad idea to have unit interdependencies, even if it is
only in implementation sections.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Blocks
\section{Blocks}
\index{block}
Units and programs are made of blocks. A block is made of declarations of
labels, constants, types variables and functions or procedures. Blocks can
be nested in certain ways, i.e., a procedure or function declaration can
have blocks in themselves.
A block looks like the following:
\input{syntax/block.syn}
Labels that can be used to identify statements in a block are declared in
the label declaration part of that block. Each label can only identify one
statement.
Constants that are to be used only in one block should be declared in that
block's constant declaration part.
Variables that are to be used only in one block should be declared in that
block's variable declaration part.
Types that are to be used only in one block should be declared in that
block's type declaration part.
Lastly, functions and procedures that will be used in that block can be
declared in the procedure/function declaration part.
These 4 declaration parts can be intermixed, there is no required order
other than that you cannot use (or refer to) identifiers that have not
yet been declared.
After the different declaration parts comes the statement part. This
contains any actions that the block should execute. All identifiers
declared before the statement part can be used in that statement part.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Scope
\section{Scope}
\index{Scope}
Identifiers are valid from the point of their declaration until the end of
the block in which the declaration occurred. The range where the identifier
is known is the {\em scope} of the identifier. The exact scope of an
identifier depends on the way it was defined.
\subsection{Block scope}
\index{Scope!block}
The {\em scope} of a variable declared in the declaration part of a block,
is valid from the point of declaration until the end of the block.
If a block contains a second block, in which the identfier is
redeclared, then inside this block, the second declaration will be valid.
Upon leaving the inner block, the first declaration is valid again.
Consider the following example:
\begin{verbatim}
Program Demo;
Var X : Real;
{ X is real variable }
Procedure NewDeclaration
Var X : Integer; { Redeclare X as integer}
begin
// X := 1.234; {would give an error when trying to compile}
X := 10; { Correct assigment}
end;
{ From here on, X is Real again}
begin
X := 2.468;
end.
\end{verbatim}
In this example, inside the procedure, \var{X} denotes an integer variable.
It has its own storage space, independent of the variable \var{X} outside
the procedure.
\subsection{Record scope}
\index{Scope!record}
The field identifiers inside a record definition are valid in the following
places:
\begin{enumerate}
\item To the end of the record definition.
\item Field designators of a variable of the given record type.
\item Identifiers inside a \var{With} statement that operates on a variable
of the given record type.
\end{enumerate}
\subsection{Class scope}
\index{Scope!Class}
A component identifier (one of the items in the class' component list)
is valid in the following places:
\begin{enumerate}
\item From the point of declaration to the end of the class definition.
\item In all descendent types of this class, unless it is in the private
part of the class declaration.
\item In all method declaration blocks of this class and descendent classes.
\item In a with statement that operators on a variable of the given class's
definition.
\end{enumerate}
Note that method designators are also considered identifiers.
\subsection{Unit scope}
\index{Scope!unit}\index{unit}
All identifiers in the interface part of a unit are valid from the point of
declaration, until the end of the unit. Furthermore, the identifiers are
known in programs or units that have the unit in their uses clause.
Identifiers from indirectly dependent units are {\em not} available.
Identifiers declared in the implementation part of a unit are valid from the
point of declaration to the end of the unit.
The \file{system} unit is automatically used in all units and programs.
Its identifiers are therefore always known, in each Pascal program, library
or unit.
The rules of unit scope imply that an identifier of a unit can be redefined.
To have access to an identifier of another unit that was redeclared in
the current unit, precede it with that other units name, as in the following
example:
\begin{verbatim}
unit unitA;
interface
Type
MyType = Real;
implementation
end.
Program prog;
Uses UnitA;
{ Redeclaration of MyType}
Type MyType = Integer;
Var A : Mytype; { Will be Integer }
B : UnitA.MyType { Will be real }
begin
end.
\end{verbatim}
This is especially useful when redeclaring the system unit's identifiers.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Libraries
\section{Libraries}
\index{Libraries}\index{library} \keywordlink{library}
\fpc supports making of dynamic libraries (DLLs under Win32 and \ostwo) trough
the use of the \var{Library} keyword.
A Library is just like a unit or a program:
\input{syntax/library.syn}
By default, functions and procedures that are declared and implemented in
library are not available to a programmer that wishes to use this library.
In order to make functions or procedures available from the library,
they must be exported in an exports clause:
\input{syntax/exports.syn}
Under Win32, an index clause can be added to an exports entry.
An index entry must be a positive number larger or equal than 1, and less
than \var{MaxInt}.
Optionally, an exports entry can have a name specifier. If present, the name
specifier gives the exact name (case sensitive) by which the function will
be exported from the library.
If neither of these constructs is present, the functions or procedures
are exported with the exact names as specified in the exports clause.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Exceptions
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\chapter{Exceptions}
\label{ch:Exceptions}\index{Exceptions}\index{Exception}
Exceptions provide a convenient way to program error and error-recovery
mechanisms, and are closely related to classes.
Exception support is based on 3 constructs:
\begin{description}
\item [Raise\ ] statements. To raise an exeption. This is usually done to signal an
error condition.\index{Exceptions!Raising} It is however also usable to
abort execution and immediatly return to a well-known point in the
executable.
\item [Try ... Except\ ] blocks. These block serve to catch exceptions
raised within the scope of the block, and to provide exception-recovery
code.\index{Exceptions!Catching}
\item [Try ... Finally\ ] blocks. These block serve to force code to be
executed irrespective of an exception occurrence or not. They generally
serve to clean up memory or close files in case an exception occurs.
The compiler generates many implicit \var{Try ... Finally} blocks around
procedure, to force memory consistency.
\end{description}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% The raise statement
\section{The raise statement}
\index{Raise}\index{Exceptions!Raising}
\keywordlink{raise}
The \var{raise} statement is as follows:
\input{syntax/raise.syn}
This statement will raise an exception. If it is specified, the exception
instance must be an initialized instance of any class, which is the raise
type. The exception address is optional. If it is not specified, the compiler
will provide the address by itself. If the exception instance is omitted,
then the current exception is re-raised. This construct can only be used
in an exception handling block (see further).
\begin{remark} Control {\em never} returns after an exception block. The
control is transferred to the first \var{try...finally} or
\var{try...except} statement that is encountered when unwinding the stack.
If no such statement is found, the \fpc Run-Time Library will generate a
run-time error 217 (see also \sees{exceptclasses}). The exception address
will be printed by the default exception handling routines.
\end{remark}
As an example: The following division checks whether the denominator is
zero, and if so, raises an exception of type \var{EDivException}
\begin{verbatim}
Type EDivException = Class(Exception);
Function DoDiv (X,Y : Longint) : Integer;
begin
If Y=0 then
Raise EDivException.Create ('Division by Zero would occur');
Result := X Div Y;
end;
\end{verbatim}
The class \var{Exception} is defined in the \file{Sysutils} unit of the rtl.
(\sees{exceptclasses})
\begin{remark}
Although the \var{Exception} class is used as the base class for exceptions
throughout the code, this is just an unwritten agreement: the class can
be of any type, and need not be a descendent of the \var{Exception} class.
Of course, most code depends on the unwritten agreement that an exception
class descends from \var{Exception}.
\end{remark}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% The try...except statement
\section{The try...except statement}
\index{except}\index{Exceptions!Catching}
\keywordlink{try} \keywordlink{except} \keywordlink{on} \keywordlink{do}
A \var{try...except} exception handling block is of the following form :
\input{syntax/try.syn}
If no exception is raised during the execution of the \var{statement list},
then all statements in the list will be executed sequentially, and the
except block will be skipped, transferring program flow to the statement
after the final \var{end}.
If an exception occurs during the execution of the \var{statement list}, the
program flow will be transferred to the except block. Statements in the
statement list between the place where the exception was raised and the
exception block are ignored.
In the exception handling block, the type of the exception is checked,
and if there is an exception handler where the class type matches the
exception object type, or is a parent type of
the exception object type, then the statement following the corresponding
\var{Do} will be executed. The first matching type is used. After the
\var{Do} block was executed, the program continues after the \var{End}
statement.
The identifier in an exception handling statement is optional, and declares
an exception object. It can be used to manipulate the exception object in
the exception handling code. The scope of this declaration is the statement
block foillowing the \var{Do} keyword.
If none of the \var{On} handlers matches the exception object type, then the
statement list after \var{else} is executed. If no such list is
found, then the exception is automatically re-raised. This process allows
to nest \var{try...except} blocks.
If, on the other hand, the exception was caught, then the exception object is
destroyed at the end of the exception handling block, before program flow
continues. The exception is destroyed through a call to the object's
\var{Destroy} destructor.
As an example, given the previous declaration of the \var{DoDiv} function,
consider the following
\begin{verbatim}
Try
Z := DoDiv (X,Y);
Except
On EDivException do Z := 0;
end;
\end{verbatim}
If \var{Y} happens to be zero, then the DoDiv function code will raise an
exception. When this happens, program flow is transferred to the except
statement, where the Exception handler will set the value of \var{Z} to
zero. If no exception is raised, then program flow continues past the last
\var{end} statement.
To allow error recovery, the \var{Try ... Finally} block is supported.
A \var{Try...Finally} block ensures that the statements following the
\var{Finally} keyword are guaranteed to be executed, even if an exception
occurs.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% The try...finally statement
\section{The try...finally statement}
\index{finally}\index{try}\index{Exceptions!Handling}
\keywordlink{try} \keywordlink{finally}
A \var{Try..Finally} statement has the following form:
\input{syntax/finally.syn}
If no exception occurs inside the \var{statement List}, then the program
runs as if the \var{Try}, \var{Finally} and \var{End} keywords were not
present.
If, however, an exception occurs, the program flow is immediatly
transferred from the point where the excepion was raised to the first
statement of the \var{Finally statements}.
All statements after the finally keyword will be executed, and then
the exception will be automatically re-raised. Any statements between the
place where the exception was raised and the first statement of the
\var{Finally Statements} are skipped.
As an example consider the following routine:
\begin{verbatim}
Procedure Doit (Name : string);
Var F : Text;
begin
Try
Assign (F,Name);
Rewrite (name);
... File handling ...
Finally
Close(F);
end;
\end{verbatim}
If during the execution of the file handling an execption occurs, then
program flow will continue at the \var{close(F)} statement, skipping any
file operations that might follow between the place where the exception
was raised, and the \var{Close} statement.
If no exception occurred, all file operations will be executed, and the file
will be closed at the end.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Exception handling nesting
\section{Exception handling nesting}
\index{finally}\index{except}\index{try}\index{Exceptions!Handling}
It is possible to nest \var{Try...Except} blocks with \var{Try...Finally}
blocks. Program flow will be done according to a \var{lifo} (last in, first
out) principle: The code of the last encountered \var{Try...Except} or
\var{Try...Finally} block will be executed first. If the exception is not
caught, or it was a finally statement, program flow will be transferred to
the last-but-one block, {\em ad infinitum}.
If an exception occurs, and there is no exception handler present which
handles this exception, then a run-time error 217 will be generated.
When using the \file{SysUtils} unit, a default handler is installed which will show the exception object message, and the
address where the exception occurred, after which the program will exit with
a \var{Halt} instruction.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Exception classes
\section{Exception classes}
\index{Exceptions!Classes}
\label{se:exceptclasses}
The \file{sysutils} unit contains a great deal of exception handling.
It defines the base exception class, \var{Exception}
\begin{verbatim}
Exception = class(TObject)
private
fmessage : string;
fhelpcontext : longint;
public
constructor create(const msg : string);
constructor createres(indent : longint);
property helpcontext : longint read fhelpcontext write fhelpcontext;
property message : string read fmessage write fmessage;
end;
ExceptClass = Class of Exception;
\end{verbatim}
And uses this declaration to define quite a number of exceptions, for
instance:
\begin{verbatim}
{ mathematical exceptions }
EIntError = class(Exception);
EDivByZero = class(EIntError);
ERangeError = class(EIntError);
EIntOverflow = class(EIntError);
EMathError = class(Exception);
\end{verbatim}
The \file{SysUtils} unit also installs an exception handler. If an exception is
unhandled by any exception handling block, this handler is called by the
Run-Time library. Basically, it prints the exception address, and it prints
the message of the Exception object, and exits with a exit code of 217.
If the exception object is not a descendent object of the \var{Exception}
object, then the class name is printed instead of the exception message.
It is recommended to use the \var{Exception} object or a descendant class
for all \var{raise} statements, since then the message
field of the exception object can be used.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Using Assembler
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\chapter{Using assembler}
\index{Assembler}
\fpc supports the use of assembler in code, but not inline
assembler macros. To have more information on the processor
specific assembler syntax and its limitations, see the \progref.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Assembler statements
\section{Assembler statements }
\index{Statements!Assembler} \keywordlink{asm}
The following is an example of assembler inclusion in Pascal code.
\begin{verbatim}
...
Statements;
...
Asm
the asm code here
...
end;
...
Statements;
\end{verbatim}
The assembler instructions between the \var{Asm} and \var{end} keywords will
be inserted in the assembler generated by the compiler.
Conditionals can be used in assembler code, the compiler will recognise them,
and treat them as any other conditionals.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Assembler procedures and functions
\section{Assembler procedures and functions}
\index{Functions!Assembler} \keywordlink{assembler}
Assembler procedures and functions are declared using the
\var{Assembler} directive. This permits the code generator to make a number
of code generation optimizations.
The code generator does not generate any stack frame (entry and exit
code for the routine) if it contains no local variables and no
parameters. In the case of functions, ordinal values must be returned
in the accumulator. In the case of floating point values, these depend
on the target processor and emulation options.
%
% The index.
%
\printindex
\end{document}
|