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
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
16946
16947
16948
16949
16950
16951
16952
16953
16954
16955
16956
16957
16958
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969
16970
16971
16972
16973
16974
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986
16987
16988
16989
16990
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000
17001
17002
17003
17004
17005
17006
17007
17008
17009
17010
17011
17012
17013
17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029
17030
17031
17032
17033
17034
17035
17036
17037
17038
17039
17040
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052
17053
17054
17055
17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067
17068
17069
17070
17071
17072
17073
17074
17075
17076
17077
17078
17079
17080
17081
17082
17083
17084
17085
17086
17087
17088
17089
17090
17091
17092
17093
17094
17095
17096
17097
17098
17099
17100
17101
17102
17103
17104
17105
17106
17107
17108
17109
17110
17111
17112
17113
17114
17115
17116
17117
17118
17119
17120
17121
17122
17123
17124
17125
17126
17127
17128
17129
17130
17131
17132
17133
17134
17135
17136
17137
17138
17139
17140
17141
17142
17143
17144
17145
17146
17147
17148
17149
17150
17151
17152
17153
17154
17155
17156
17157
17158
17159
17160
17161
17162
17163
17164
17165
17166
17167
17168
17169
17170
17171
17172
17173
17174
17175
17176
17177
17178
17179
17180
17181
17182
17183
17184
17185
17186
17187
17188
17189
17190
17191
17192
17193
17194
17195
17196
17197
17198
17199
17200
17201
17202
17203
17204
17205
17206
17207
17208
17209
17210
17211
17212
17213
17214
17215
17216
17217
17218
17219
17220
17221
17222
17223
17224
17225
17226
17227
17228
17229
17230
17231
17232
17233
17234
17235
17236
17237
17238
17239
17240
17241
17242
17243
17244
17245
17246
17247
17248
17249
17250
17251
17252
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
17264
17265
17266
17267
17268
17269
17270
17271
17272
17273
17274
17275
17276
17277
17278
17279
17280
17281
17282
17283
17284
17285
17286
17287
17288
17289
17290
17291
17292
17293
17294
17295
17296
17297
17298
17299
17300
17301
17302
17303
17304
17305
17306
17307
17308
17309
17310
17311
17312
17313
17314
17315
17316
17317
17318
17319
17320
17321
17322
17323
17324
17325
17326
17327
17328
17329
17330
17331
17332
17333
17334
17335
17336
17337
17338
17339
17340
17341
17342
17343
17344
17345
17346
17347
17348
17349
17350
17351
17352
17353
17354
17355
17356
17357
17358
17359
17360
17361
17362
17363
17364
17365
17366
17367
17368
17369
17370
17371
17372
17373
17374
17375
17376
17377
17378
17379
17380
17381
17382
17383
17384
17385
17386
17387
17388
17389
17390
17391
17392
17393
17394
17395
17396
17397
17398
17399
17400
17401
17402
17403
17404
17405
17406
17407
17408
17409
17410
17411
17412
17413
17414
17415
17416
17417
17418
17419
17420
17421
17422
17423
17424
17425
17426
17427
17428
17429
17430
17431
17432
17433
17434
17435
17436
17437
17438
17439
17440
17441
17442
17443
17444
17445
17446
17447
17448
17449
17450
17451
17452
17453
17454
17455
17456
17457
17458
17459
17460
17461
17462
17463
17464
17465
17466
17467
17468
17469
17470
17471
17472
17473
17474
17475
17476
17477
17478
17479
17480
17481
17482
17483
17484
17485
17486
17487
17488
17489
17490
17491
17492
17493
17494
17495
17496
17497
17498
17499
17500
17501
17502
17503
17504
17505
17506
17507
17508
17509
17510
17511
17512
17513
17514
17515
17516
17517
17518
17519
17520
17521
17522
17523
17524
17525
17526
17527
17528
17529
17530
17531
17532
17533
17534
17535
17536
17537
17538
17539
17540
17541
17542
17543
17544
17545
17546
17547
17548
17549
17550
17551
17552
17553
17554
17555
17556
17557
17558
17559
17560
17561
17562
17563
17564
17565
17566
17567
17568
17569
17570
17571
17572
17573
17574
17575
17576
17577
17578
17579
17580
17581
17582
17583
17584
17585
17586
17587
17588
17589
17590
17591
17592
17593
17594
17595
17596
17597
17598
17599
17600
17601
17602
17603
17604
17605
17606
17607
17608
17609
17610
17611
17612
17613
17614
17615
17616
17617
17618
17619
17620
17621
17622
17623
17624
17625
17626
17627
17628
17629
17630
17631
17632
17633
17634
17635
17636
17637
17638
17639
17640
17641
17642
17643
17644
17645
17646
17647
17648
17649
17650
17651
17652
17653
17654
17655
17656
17657
17658
17659
17660
17661
17662
17663
17664
17665
17666
17667
17668
17669
17670
17671
17672
17673
17674
17675
17676
17677
17678
17679
17680
17681
17682
17683
17684
17685
17686
17687
17688
17689
17690
17691
17692
17693
17694
17695
17696
17697
17698
17699
17700
17701
17702
17703
17704
17705
17706
17707
17708
17709
17710
17711
17712
17713
17714
17715
17716
17717
17718
17719
17720
17721
17722
17723
17724
17725
17726
17727
17728
17729
17730
17731
17732
17733
17734
17735
17736
17737
17738
17739
17740
17741
17742
17743
17744
17745
17746
17747
17748
17749
17750
17751
17752
17753
17754
17755
17756
17757
17758
17759
17760
17761
17762
17763
17764
17765
17766
17767
17768
17769
17770
17771
17772
17773
17774
17775
17776
17777
17778
17779
17780
17781
17782
17783
17784
17785
17786
17787
17788
17789
17790
17791
17792
17793
17794
17795
17796
17797
17798
17799
17800
17801
17802
17803
17804
17805
17806
17807
17808
17809
17810
17811
17812
17813
17814
17815
17816
17817
17818
17819
17820
17821
17822
17823
17824
17825
17826
17827
17828
17829
17830
17831
17832
17833
17834
17835
17836
17837
17838
17839
17840
17841
17842
17843
17844
17845
17846
17847
17848
17849
17850
17851
17852
17853
17854
17855
17856
17857
17858
17859
17860
17861
17862
17863
17864
17865
17866
17867
17868
17869
17870
17871
17872
17873
17874
17875
17876
17877
17878
17879
17880
17881
17882
17883
17884
17885
17886
17887
17888
17889
17890
17891
17892
17893
17894
17895
17896
17897
17898
17899
17900
17901
17902
17903
17904
17905
17906
17907
17908
17909
17910
17911
17912
17913
17914
17915
17916
17917
17918
17919
17920
17921
17922
17923
17924
17925
17926
17927
17928
17929
17930
17931
17932
17933
17934
17935
17936
17937
17938
17939
17940
17941
17942
17943
17944
17945
17946
17947
17948
17949
17950
17951
17952
17953
17954
17955
17956
17957
17958
17959
17960
17961
17962
17963
17964
17965
17966
17967
17968
17969
17970
17971
17972
17973
17974
17975
17976
17977
17978
17979
17980
17981
17982
17983
17984
17985
17986
17987
17988
17989
17990
17991
17992
17993
17994
17995
17996
17997
17998
17999
18000
18001
18002
18003
18004
18005
18006
18007
18008
18009
18010
18011
18012
18013
18014
18015
18016
18017
18018
18019
18020
18021
18022
18023
18024
18025
18026
18027
18028
18029
18030
18031
18032
18033
18034
18035
18036
18037
18038
18039
18040
18041
18042
18043
18044
18045
18046
18047
18048
18049
18050
18051
18052
18053
18054
18055
18056
18057
18058
18059
18060
18061
18062
18063
18064
18065
18066
18067
18068
18069
18070
18071
18072
18073
18074
18075
18076
18077
18078
18079
18080
18081
18082
18083
18084
18085
18086
18087
18088
18089
18090
18091
18092
18093
18094
18095
18096
18097
18098
18099
18100
18101
18102
18103
18104
18105
18106
18107
18108
18109
18110
18111
18112
18113
18114
18115
18116
18117
18118
18119
18120
18121
18122
18123
18124
18125
18126
18127
18128
18129
18130
18131
18132
18133
18134
18135
18136
18137
18138
18139
18140
18141
18142
18143
18144
18145
18146
18147
18148
18149
18150
18151
18152
18153
18154
18155
18156
18157
18158
18159
18160
18161
18162
18163
18164
18165
18166
18167
18168
18169
18170
18171
18172
18173
18174
18175
18176
18177
18178
18179
18180
18181
18182
18183
18184
18185
18186
18187
18188
18189
18190
18191
18192
18193
18194
18195
18196
18197
18198
18199
18200
18201
18202
18203
18204
18205
18206
18207
18208
18209
18210
18211
18212
18213
18214
18215
18216
18217
18218
18219
18220
18221
18222
18223
18224
18225
18226
18227
18228
18229
18230
18231
18232
18233
18234
18235
18236
18237
18238
18239
18240
18241
18242
18243
18244
18245
18246
18247
18248
18249
18250
18251
18252
18253
18254
18255
18256
18257
18258
18259
18260
18261
18262
18263
18264
18265
18266
18267
18268
18269
18270
18271
18272
18273
18274
18275
18276
18277
18278
18279
18280
18281
18282
18283
18284
18285
18286
18287
18288
18289
18290
18291
18292
18293
18294
18295
18296
18297
18298
18299
18300
18301
18302
18303
18304
18305
18306
18307
18308
18309
18310
18311
18312
18313
18314
18315
18316
18317
18318
18319
18320
18321
18322
18323
18324
18325
18326
18327
18328
18329
18330
18331
18332
18333
18334
18335
18336
18337
18338
18339
18340
18341
18342
18343
18344
18345
18346
18347
18348
18349
18350
18351
18352
18353
18354
18355
18356
18357
18358
18359
18360
18361
18362
18363
18364
18365
18366
18367
18368
18369
18370
18371
18372
18373
18374
18375
18376
18377
18378
18379
18380
18381
18382
18383
18384
18385
18386
18387
18388
18389
18390
18391
18392
18393
18394
18395
18396
18397
18398
18399
18400
18401
18402
18403
18404
18405
18406
18407
18408
18409
18410
18411
18412
18413
18414
18415
18416
18417
18418
18419
18420
18421
18422
18423
18424
18425
18426
18427
18428
18429
18430
18431
18432
18433
18434
18435
18436
18437
18438
18439
18440
18441
18442
18443
18444
18445
18446
18447
18448
18449
18450
18451
18452
18453
18454
18455
18456
18457
18458
18459
18460
18461
18462
18463
18464
18465
18466
18467
18468
18469
18470
18471
18472
18473
18474
18475
18476
18477
18478
18479
18480
18481
18482
18483
18484
18485
18486
18487
18488
18489
18490
18491
18492
18493
18494
18495
18496
18497
18498
18499
18500
18501
18502
18503
18504
18505
18506
18507
18508
18509
18510
18511
18512
18513
18514
18515
18516
18517
18518
18519
18520
18521
18522
18523
18524
18525
18526
18527
18528
18529
18530
18531
18532
18533
18534
18535
18536
18537
18538
18539
18540
18541
18542
18543
18544
18545
18546
18547
18548
18549
18550
18551
18552
18553
18554
18555
18556
18557
18558
18559
18560
18561
18562
18563
18564
18565
18566
18567
18568
18569
18570
18571
18572
18573
18574
18575
18576
18577
18578
18579
18580
18581
18582
18583
18584
18585
18586
18587
18588
18589
18590
18591
18592
18593
18594
18595
18596
18597
18598
18599
18600
18601
18602
18603
18604
18605
18606
18607
18608
18609
18610
18611
18612
18613
18614
18615
18616
18617
18618
18619
18620
18621
18622
18623
18624
18625
18626
18627
18628
18629
18630
18631
18632
18633
18634
18635
18636
18637
18638
18639
18640
18641
18642
18643
18644
18645
18646
18647
18648
18649
18650
18651
18652
18653
18654
18655
18656
18657
18658
18659
18660
18661
18662
18663
18664
18665
18666
18667
18668
18669
18670
18671
18672
18673
18674
18675
18676
18677
18678
18679
18680
18681
18682
18683
18684
18685
18686
18687
18688
18689
18690
18691
18692
18693
18694
18695
18696
18697
18698
18699
18700
18701
18702
18703
18704
18705
18706
18707
18708
18709
18710
18711
18712
18713
18714
18715
18716
18717
18718
18719
18720
18721
18722
18723
18724
18725
18726
18727
18728
18729
18730
18731
18732
18733
18734
18735
18736
18737
18738
18739
18740
18741
18742
18743
18744
18745
18746
18747
18748
18749
18750
18751
18752
18753
18754
18755
18756
18757
18758
18759
18760
18761
18762
18763
18764
18765
18766
18767
18768
18769
18770
18771
18772
18773
18774
18775
18776
18777
18778
18779
18780
18781
18782
18783
18784
18785
18786
18787
18788
18789
18790
18791
18792
18793
18794
18795
18796
18797
18798
18799
18800
18801
18802
18803
18804
18805
18806
18807
18808
18809
18810
18811
18812
18813
18814
18815
18816
18817
18818
18819
18820
18821
18822
18823
18824
18825
18826
18827
18828
18829
18830
18831
18832
18833
18834
18835
18836
18837
18838
18839
18840
18841
18842
18843
18844
18845
18846
18847
18848
18849
18850
18851
18852
18853
18854
18855
18856
18857
18858
18859
18860
18861
18862
18863
18864
18865
18866
18867
18868
18869
18870
18871
18872
18873
18874
18875
18876
18877
18878
18879
18880
18881
18882
18883
18884
18885
18886
18887
18888
18889
18890
18891
18892
18893
18894
18895
18896
18897
18898
18899
18900
18901
18902
18903
18904
18905
18906
18907
18908
18909
18910
18911
18912
18913
18914
18915
18916
18917
18918
18919
18920
18921
18922
18923
18924
18925
18926
18927
18928
18929
18930
18931
18932
18933
18934
18935
18936
18937
18938
18939
18940
18941
18942
18943
18944
18945
18946
18947
18948
18949
18950
18951
18952
18953
18954
18955
18956
18957
18958
18959
18960
18961
18962
18963
18964
18965
18966
18967
18968
18969
18970
18971
18972
18973
18974
18975
18976
18977
18978
18979
18980
18981
18982
18983
18984
18985
18986
18987
18988
18989
18990
18991
18992
18993
18994
18995
18996
18997
18998
18999
19000
19001
19002
19003
19004
19005
19006
19007
19008
19009
19010
19011
19012
19013
19014
19015
19016
19017
19018
19019
19020
19021
19022
19023
19024
19025
19026
19027
19028
19029
19030
19031
19032
19033
19034
19035
19036
19037
19038
19039
19040
19041
19042
19043
19044
19045
19046
19047
19048
19049
19050
19051
19052
19053
19054
19055
19056
19057
19058
19059
19060
19061
19062
19063
19064
19065
19066
19067
19068
19069
19070
19071
19072
19073
19074
19075
19076
19077
19078
19079
19080
19081
19082
19083
19084
19085
19086
19087
19088
19089
19090
19091
19092
19093
19094
19095
19096
19097
19098
19099
19100
19101
19102
19103
19104
19105
19106
19107
19108
19109
19110
19111
19112
19113
19114
19115
19116
19117
19118
19119
19120
19121
19122
19123
19124
19125
19126
19127
19128
19129
19130
19131
19132
19133
19134
19135
19136
19137
19138
19139
19140
19141
19142
19143
19144
19145
19146
19147
19148
19149
19150
19151
19152
19153
19154
19155
19156
19157
19158
19159
19160
19161
19162
19163
19164
19165
19166
19167
19168
19169
19170
19171
19172
19173
19174
19175
19176
19177
19178
19179
19180
19181
19182
19183
19184
19185
19186
19187
19188
19189
19190
19191
19192
19193
19194
19195
19196
19197
19198
19199
19200
19201
19202
19203
19204
19205
19206
19207
19208
19209
19210
19211
19212
19213
19214
19215
19216
19217
19218
19219
19220
19221
19222
19223
19224
19225
19226
19227
19228
19229
19230
19231
19232
19233
19234
19235
19236
19237
19238
19239
19240
19241
19242
19243
19244
19245
19246
19247
19248
19249
19250
19251
19252
19253
19254
19255
19256
19257
19258
19259
19260
19261
19262
19263
19264
19265
19266
19267
19268
19269
19270
19271
19272
19273
19274
19275
19276
19277
19278
19279
19280
19281
19282
19283
19284
19285
19286
19287
19288
19289
19290
19291
19292
19293
19294
19295
19296
19297
19298
19299
19300
19301
19302
19303
19304
19305
19306
19307
19308
19309
19310
19311
19312
19313
19314
19315
19316
19317
19318
19319
19320
19321
19322
19323
19324
19325
19326
19327
19328
19329
19330
19331
19332
19333
19334
19335
19336
19337
19338
19339
19340
19341
19342
19343
19344
19345
19346
19347
19348
19349
19350
19351
19352
19353
19354
19355
19356
19357
19358
19359
19360
19361
19362
19363
19364
19365
19366
19367
19368
19369
19370
19371
19372
19373
19374
19375
19376
19377
19378
19379
19380
19381
19382
19383
19384
19385
19386
19387
19388
19389
19390
19391
19392
19393
19394
19395
19396
19397
19398
19399
19400
19401
19402
19403
19404
19405
19406
19407
19408
19409
19410
19411
19412
19413
19414
19415
19416
19417
19418
19419
19420
19421
19422
19423
19424
19425
19426
19427
19428
19429
19430
19431
19432
19433
19434
19435
19436
19437
19438
19439
19440
19441
19442
19443
19444
19445
19446
19447
19448
19449
19450
19451
19452
19453
19454
19455
19456
19457
19458
19459
19460
19461
19462
19463
19464
19465
19466
19467
19468
19469
19470
19471
19472
19473
19474
19475
19476
19477
19478
19479
19480
19481
19482
19483
19484
19485
19486
19487
19488
19489
19490
19491
19492
19493
19494
19495
19496
19497
19498
19499
19500
19501
19502
19503
19504
19505
19506
19507
19508
19509
19510
19511
19512
19513
19514
19515
19516
19517
19518
19519
19520
19521
19522
19523
19524
19525
19526
19527
19528
19529
19530
19531
19532
19533
19534
19535
19536
19537
19538
19539
19540
19541
19542
19543
19544
19545
19546
19547
19548
19549
19550
19551
19552
19553
19554
19555
19556
19557
19558
19559
19560
19561
19562
19563
19564
19565
19566
19567
19568
19569
19570
19571
19572
19573
19574
19575
19576
19577
19578
19579
19580
19581
19582
19583
19584
19585
19586
19587
19588
19589
19590
19591
19592
19593
19594
19595
19596
19597
19598
19599
19600
19601
19602
19603
19604
19605
19606
19607
19608
19609
19610
19611
19612
19613
19614
19615
19616
19617
19618
19619
19620
19621
19622
19623
19624
19625
19626
19627
19628
19629
19630
19631
19632
19633
19634
19635
19636
19637
19638
19639
19640
19641
19642
19643
19644
19645
19646
19647
19648
19649
19650
19651
19652
19653
19654
19655
19656
19657
19658
19659
19660
19661
19662
19663
19664
19665
19666
19667
19668
19669
19670
19671
19672
19673
19674
19675
19676
19677
19678
19679
19680
19681
19682
19683
19684
19685
19686
19687
19688
19689
19690
19691
19692
19693
19694
19695
19696
19697
19698
19699
19700
19701
19702
19703
19704
19705
19706
19707
19708
19709
19710
19711
19712
19713
19714
19715
19716
19717
19718
19719
19720
19721
19722
19723
19724
19725
19726
19727
19728
19729
19730
19731
19732
19733
19734
19735
19736
19737
19738
19739
19740
19741
19742
19743
19744
19745
19746
19747
19748
19749
19750
19751
19752
19753
19754
19755
19756
19757
19758
19759
19760
19761
19762
19763
19764
19765
19766
19767
19768
19769
19770
19771
19772
19773
19774
19775
19776
19777
19778
19779
19780
19781
19782
19783
19784
19785
19786
19787
19788
19789
19790
19791
19792
19793
19794
19795
19796
19797
19798
19799
19800
19801
19802
19803
19804
19805
19806
19807
19808
19809
19810
19811
19812
19813
19814
19815
19816
19817
19818
19819
19820
19821
19822
19823
19824
19825
19826
19827
19828
19829
19830
19831
19832
19833
19834
19835
19836
19837
19838
19839
19840
19841
19842
19843
19844
19845
19846
19847
19848
19849
19850
19851
19852
19853
19854
19855
19856
19857
19858
19859
19860
19861
19862
19863
19864
19865
19866
19867
19868
19869
19870
19871
19872
19873
19874
19875
19876
19877
19878
19879
19880
19881
19882
19883
19884
19885
19886
19887
19888
19889
19890
19891
19892
19893
19894
19895
19896
19897
19898
19899
19900
19901
19902
19903
19904
19905
19906
19907
19908
19909
19910
19911
19912
19913
19914
19915
19916
19917
19918
19919
19920
19921
19922
19923
19924
19925
19926
19927
19928
19929
19930
19931
19932
19933
19934
19935
19936
19937
19938
19939
19940
19941
19942
19943
19944
19945
19946
19947
19948
19949
19950
19951
19952
19953
19954
19955
19956
19957
19958
19959
19960
19961
19962
19963
19964
19965
19966
19967
19968
19969
19970
19971
19972
19973
19974
19975
19976
19977
19978
19979
19980
19981
19982
19983
19984
19985
19986
19987
19988
19989
19990
19991
19992
19993
19994
19995
19996
19997
19998
19999
20000
20001
20002
20003
20004
20005
20006
20007
20008
20009
20010
20011
20012
20013
20014
20015
20016
20017
20018
20019
20020
20021
20022
20023
20024
20025
20026
20027
20028
20029
20030
20031
20032
20033
20034
20035
20036
20037
20038
20039
20040
20041
20042
20043
20044
20045
20046
20047
20048
20049
20050
20051
20052
20053
20054
20055
20056
20057
20058
20059
20060
20061
20062
20063
20064
20065
20066
20067
20068
20069
20070
20071
20072
20073
20074
20075
20076
20077
20078
20079
20080
20081
20082
20083
20084
20085
20086
20087
20088
20089
20090
20091
20092
20093
20094
20095
20096
20097
20098
20099
20100
20101
20102
20103
20104
20105
20106
20107
20108
20109
20110
20111
20112
20113
20114
20115
20116
20117
20118
20119
20120
20121
20122
20123
20124
20125
20126
20127
20128
20129
20130
20131
20132
20133
20134
20135
20136
20137
20138
20139
20140
20141
20142
20143
20144
20145
20146
20147
20148
20149
20150
20151
20152
20153
20154
20155
20156
20157
20158
20159
20160
20161
20162
20163
20164
20165
20166
20167
20168
20169
20170
20171
20172
20173
20174
20175
20176
20177
20178
20179
20180
20181
20182
20183
20184
20185
20186
20187
20188
20189
20190
20191
20192
20193
20194
20195
20196
20197
20198
20199
20200
20201
20202
20203
20204
20205
20206
20207
20208
20209
20210
20211
20212
20213
20214
20215
20216
20217
20218
20219
20220
20221
20222
20223
20224
20225
20226
20227
20228
20229
20230
20231
20232
20233
20234
20235
20236
20237
20238
20239
20240
20241
20242
20243
20244
20245
20246
20247
20248
20249
20250
20251
20252
20253
20254
20255
20256
20257
20258
20259
20260
20261
20262
20263
20264
20265
20266
20267
20268
20269
20270
20271
20272
20273
20274
20275
20276
20277
20278
20279
20280
20281
20282
20283
20284
20285
20286
20287
20288
20289
20290
20291
20292
20293
20294
20295
20296
20297
20298
20299
20300
20301
20302
20303
20304
20305
20306
20307
20308
20309
20310
20311
20312
20313
20314
20315
20316
20317
20318
20319
20320
20321
20322
20323
20324
20325
20326
20327
20328
20329
20330
20331
20332
20333
20334
20335
20336
20337
20338
20339
20340
20341
20342
20343
20344
20345
20346
20347
20348
20349
20350
20351
20352
20353
20354
20355
20356
20357
20358
20359
20360
20361
20362
20363
20364
20365
20366
20367
20368
20369
20370
20371
20372
20373
20374
20375
20376
20377
20378
20379
20380
20381
20382
20383
20384
20385
20386
20387
20388
20389
20390
20391
20392
20393
20394
20395
20396
20397
20398
20399
20400
20401
20402
20403
20404
20405
20406
20407
20408
20409
20410
20411
20412
20413
20414
20415
20416
20417
20418
20419
20420
20421
20422
20423
20424
20425
20426
20427
20428
20429
20430
20431
20432
20433
20434
20435
20436
20437
20438
20439
20440
20441
20442
20443
20444
20445
20446
20447
20448
20449
20450
20451
20452
20453
20454
20455
20456
20457
20458
20459
20460
20461
20462
20463
20464
20465
20466
20467
20468
20469
20470
20471
20472
20473
20474
20475
20476
20477
20478
20479
20480
20481
20482
20483
20484
20485
20486
20487
20488
20489
20490
20491
20492
20493
20494
20495
20496
20497
20498
20499
20500
20501
20502
20503
20504
20505
20506
20507
20508
20509
20510
20511
20512
20513
20514
20515
20516
20517
20518
20519
20520
20521
20522
20523
20524
20525
20526
20527
20528
20529
20530
20531
20532
20533
20534
20535
20536
20537
20538
20539
20540
20541
20542
20543
20544
20545
20546
20547
20548
20549
20550
20551
20552
20553
20554
20555
20556
20557
20558
20559
20560
20561
20562
20563
20564
20565
20566
20567
20568
20569
20570
20571
20572
20573
20574
20575
20576
20577
20578
20579
20580
20581
20582
20583
20584
20585
20586
20587
20588
20589
20590
20591
20592
20593
20594
20595
20596
20597
20598
20599
20600
20601
20602
20603
20604
20605
20606
20607
20608
20609
20610
20611
20612
20613
20614
20615
20616
20617
20618
20619
20620
20621
20622
20623
20624
20625
20626
20627
20628
20629
20630
20631
20632
20633
20634
20635
20636
20637
20638
20639
20640
20641
20642
20643
20644
20645
20646
20647
20648
20649
20650
20651
20652
20653
20654
20655
20656
20657
20658
20659
20660
20661
20662
20663
20664
20665
20666
20667
20668
20669
20670
20671
20672
20673
20674
20675
20676
20677
20678
20679
20680
20681
20682
20683
20684
20685
20686
20687
20688
20689
20690
20691
20692
20693
20694
20695
20696
20697
20698
20699
20700
20701
20702
20703
20704
20705
20706
20707
20708
20709
20710
20711
20712
20713
20714
20715
20716
20717
20718
20719
20720
20721
20722
20723
20724
20725
20726
20727
20728
20729
20730
20731
20732
20733
20734
20735
20736
20737
20738
20739
20740
20741
20742
20743
20744
20745
20746
20747
20748
20749
20750
20751
20752
20753
20754
20755
20756
20757
20758
20759
20760
20761
20762
20763
20764
20765
20766
20767
20768
20769
20770
20771
20772
20773
20774
20775
20776
20777
20778
20779
20780
20781
20782
20783
20784
20785
20786
20787
20788
20789
20790
20791
20792
20793
20794
20795
20796
20797
20798
20799
20800
20801
20802
20803
20804
20805
20806
20807
20808
20809
20810
20811
20812
20813
20814
20815
20816
20817
20818
20819
20820
20821
20822
20823
20824
20825
20826
20827
20828
20829
20830
20831
20832
20833
20834
20835
20836
20837
20838
20839
20840
20841
20842
20843
20844
20845
20846
20847
20848
20849
20850
20851
20852
20853
20854
20855
20856
20857
20858
20859
20860
20861
20862
20863
20864
20865
20866
20867
20868
20869
20870
20871
20872
20873
20874
20875
20876
20877
20878
20879
20880
20881
20882
20883
20884
20885
20886
20887
20888
20889
20890
20891
20892
20893
20894
20895
20896
20897
20898
20899
20900
20901
20902
20903
20904
20905
20906
20907
20908
20909
20910
20911
20912
20913
20914
20915
20916
20917
20918
20919
20920
20921
20922
20923
20924
20925
20926
20927
20928
20929
20930
20931
20932
20933
20934
20935
20936
20937
20938
20939
20940
20941
20942
20943
20944
20945
20946
20947
20948
20949
20950
20951
20952
20953
20954
20955
20956
20957
20958
20959
20960
20961
20962
20963
20964
20965
20966
20967
20968
20969
20970
20971
20972
20973
20974
20975
20976
20977
20978
20979
20980
20981
20982
20983
20984
20985
20986
20987
20988
20989
20990
20991
20992
20993
20994
20995
20996
20997
20998
20999
21000
21001
21002
21003
21004
21005
21006
21007
21008
21009
21010
21011
21012
21013
21014
21015
21016
21017
21018
21019
21020
21021
21022
21023
21024
21025
21026
21027
21028
21029
21030
21031
21032
21033
21034
21035
21036
21037
21038
21039
21040
21041
21042
21043
21044
21045
21046
21047
21048
21049
21050
21051
21052
21053
21054
21055
21056
21057
21058
21059
21060
21061
21062
21063
21064
21065
21066
21067
21068
21069
21070
21071
21072
21073
21074
21075
21076
21077
21078
21079
21080
21081
21082
21083
21084
21085
21086
21087
21088
21089
21090
21091
21092
21093
21094
21095
21096
21097
21098
21099
21100
21101
21102
21103
21104
21105
21106
21107
21108
21109
21110
21111
21112
21113
21114
21115
21116
21117
21118
21119
21120
21121
21122
21123
21124
21125
21126
21127
21128
21129
21130
21131
21132
21133
21134
21135
21136
21137
21138
21139
21140
21141
21142
21143
21144
21145
21146
21147
21148
21149
21150
21151
21152
21153
21154
21155
21156
21157
21158
21159
21160
21161
21162
21163
21164
21165
21166
21167
21168
21169
21170
21171
21172
21173
21174
21175
21176
21177
21178
21179
21180
21181
21182
21183
21184
21185
21186
21187
21188
21189
21190
21191
21192
21193
21194
21195
21196
21197
21198
21199
21200
21201
21202
21203
21204
21205
21206
21207
21208
21209
21210
21211
21212
21213
21214
21215
21216
21217
21218
21219
21220
21221
21222
21223
21224
21225
21226
21227
21228
21229
21230
21231
21232
21233
21234
21235
21236
21237
21238
21239
21240
21241
21242
21243
21244
21245
21246
21247
21248
21249
21250
21251
21252
21253
21254
21255
21256
21257
21258
21259
21260
21261
21262
21263
21264
21265
21266
21267
21268
21269
21270
21271
21272
21273
21274
21275
21276
21277
21278
21279
21280
21281
21282
21283
21284
21285
21286
21287
21288
21289
21290
21291
21292
21293
21294
21295
21296
21297
21298
21299
21300
21301
21302
21303
21304
21305
21306
21307
21308
21309
21310
21311
21312
21313
21314
21315
21316
21317
21318
21319
21320
21321
21322
21323
21324
21325
21326
21327
21328
21329
21330
21331
21332
21333
21334
21335
21336
21337
21338
21339
21340
21341
21342
21343
21344
21345
21346
21347
21348
21349
21350
21351
21352
21353
21354
21355
21356
21357
21358
21359
21360
21361
21362
21363
21364
21365
21366
21367
21368
21369
21370
21371
21372
21373
21374
21375
21376
21377
21378
21379
21380
21381
21382
21383
21384
21385
21386
21387
21388
21389
21390
21391
21392
21393
21394
21395
21396
21397
21398
21399
21400
21401
21402
21403
21404
21405
21406
21407
21408
21409
21410
21411
21412
21413
21414
21415
21416
21417
21418
21419
21420
21421
21422
21423
21424
21425
21426
21427
21428
21429
21430
21431
21432
21433
21434
21435
21436
21437
21438
21439
21440
21441
21442
21443
21444
21445
21446
21447
21448
21449
21450
21451
21452
21453
21454
21455
21456
21457
21458
21459
21460
21461
21462
21463
21464
21465
21466
21467
21468
21469
21470
21471
21472
21473
21474
21475
21476
21477
21478
21479
21480
21481
21482
21483
21484
21485
21486
21487
21488
21489
21490
21491
21492
21493
21494
21495
21496
21497
21498
21499
21500
21501
21502
21503
21504
21505
21506
21507
21508
21509
21510
21511
21512
21513
21514
21515
21516
21517
21518
21519
21520
21521
21522
21523
21524
21525
21526
21527
21528
21529
21530
21531
21532
21533
21534
21535
21536
21537
21538
21539
21540
21541
21542
21543
21544
21545
21546
21547
21548
21549
21550
21551
21552
21553
21554
21555
21556
21557
21558
21559
21560
21561
21562
21563
21564
21565
21566
21567
21568
21569
21570
21571
21572
21573
21574
21575
21576
21577
21578
21579
21580
21581
21582
21583
21584
21585
21586
21587
21588
21589
21590
21591
21592
21593
21594
21595
21596
21597
21598
21599
21600
21601
21602
21603
21604
21605
21606
21607
21608
21609
21610
21611
21612
21613
21614
21615
21616
21617
21618
21619
21620
21621
21622
21623
21624
21625
21626
21627
21628
21629
21630
21631
21632
21633
21634
21635
21636
21637
21638
21639
21640
21641
21642
21643
21644
21645
21646
21647
21648
21649
21650
21651
21652
21653
21654
21655
21656
21657
21658
21659
21660
21661
21662
21663
21664
21665
21666
21667
21668
21669
21670
21671
21672
21673
21674
21675
21676
21677
21678
21679
21680
21681
21682
21683
21684
21685
21686
21687
21688
21689
21690
21691
21692
21693
21694
21695
21696
21697
21698
21699
21700
21701
21702
21703
21704
21705
21706
21707
21708
21709
21710
21711
21712
21713
21714
21715
21716
21717
21718
21719
21720
21721
21722
21723
21724
21725
21726
21727
21728
21729
21730
21731
21732
21733
21734
21735
21736
21737
21738
21739
21740
21741
21742
21743
21744
21745
21746
21747
21748
21749
21750
21751
21752
21753
21754
21755
21756
21757
21758
21759
21760
21761
21762
21763
21764
21765
21766
21767
21768
21769
21770
21771
21772
21773
21774
21775
21776
21777
21778
21779
21780
21781
21782
21783
21784
21785
21786
21787
21788
21789
21790
21791
21792
21793
21794
21795
21796
21797
21798
21799
21800
21801
21802
21803
21804
21805
21806
21807
21808
21809
21810
21811
21812
21813
21814
21815
21816
21817
21818
21819
21820
21821
21822
21823
21824
21825
21826
21827
21828
21829
21830
21831
21832
21833
21834
21835
21836
21837
21838
21839
21840
21841
21842
21843
21844
21845
21846
21847
21848
21849
21850
21851
21852
21853
21854
21855
21856
21857
21858
21859
21860
21861
21862
21863
21864
21865
21866
21867
21868
21869
21870
21871
21872
21873
21874
21875
21876
21877
21878
21879
21880
21881
21882
21883
21884
21885
21886
21887
21888
21889
21890
21891
21892
21893
21894
21895
21896
21897
21898
21899
21900
21901
21902
21903
21904
21905
21906
21907
21908
21909
21910
21911
21912
21913
21914
21915
21916
21917
21918
21919
21920
21921
21922
21923
21924
21925
21926
21927
21928
21929
21930
21931
21932
21933
21934
21935
21936
21937
21938
21939
21940
21941
21942
21943
21944
21945
21946
21947
21948
21949
21950
21951
21952
21953
21954
21955
21956
21957
21958
21959
21960
21961
21962
21963
21964
21965
21966
21967
21968
21969
21970
21971
21972
21973
21974
21975
21976
21977
21978
21979
21980
21981
21982
21983
21984
21985
21986
21987
21988
21989
21990
21991
21992
21993
21994
21995
21996
21997
21998
21999
22000
22001
22002
22003
22004
22005
22006
22007
22008
22009
22010
22011
22012
22013
22014
22015
22016
22017
22018
22019
22020
22021
22022
22023
22024
22025
22026
22027
22028
22029
22030
22031
22032
22033
22034
22035
22036
22037
22038
22039
22040
22041
22042
22043
22044
22045
22046
22047
22048
22049
22050
22051
22052
22053
22054
22055
22056
22057
22058
22059
22060
22061
22062
22063
22064
22065
22066
22067
22068
22069
22070
22071
22072
22073
22074
22075
22076
22077
22078
22079
22080
22081
22082
22083
22084
22085
22086
22087
22088
22089
22090
22091
22092
22093
22094
22095
22096
22097
22098
22099
22100
22101
22102
22103
22104
22105
22106
22107
22108
22109
22110
22111
22112
22113
22114
22115
22116
22117
22118
22119
22120
22121
22122
22123
22124
22125
22126
22127
22128
22129
22130
22131
22132
22133
22134
22135
22136
22137
22138
22139
22140
22141
22142
22143
22144
22145
22146
22147
22148
22149
22150
22151
22152
22153
22154
22155
22156
22157
22158
22159
22160
22161
22162
22163
22164
22165
22166
22167
22168
22169
22170
22171
22172
22173
22174
22175
22176
22177
22178
22179
22180
22181
22182
22183
22184
22185
22186
22187
22188
22189
22190
22191
22192
22193
22194
22195
22196
22197
22198
22199
22200
22201
22202
22203
22204
22205
22206
22207
22208
22209
22210
22211
22212
22213
22214
22215
22216
22217
22218
22219
22220
22221
22222
22223
22224
22225
22226
22227
22228
22229
22230
22231
22232
22233
22234
22235
22236
22237
22238
22239
22240
22241
22242
22243
22244
22245
22246
22247
22248
22249
22250
22251
22252
22253
22254
22255
22256
22257
22258
22259
22260
22261
22262
22263
22264
22265
22266
22267
22268
22269
22270
22271
22272
22273
22274
22275
22276
22277
22278
22279
22280
22281
22282
22283
22284
22285
22286
22287
22288
22289
22290
22291
22292
22293
22294
22295
22296
22297
22298
22299
22300
22301
22302
22303
22304
22305
22306
22307
22308
22309
22310
22311
22312
22313
22314
22315
22316
22317
22318
22319
22320
22321
22322
22323
22324
22325
22326
22327
22328
22329
22330
22331
22332
22333
22334
22335
22336
22337
22338
22339
22340
22341
22342
22343
22344
22345
22346
22347
22348
22349
22350
22351
22352
22353
22354
22355
22356
22357
22358
22359
22360
22361
22362
22363
22364
22365
22366
22367
22368
22369
22370
22371
22372
22373
22374
22375
22376
22377
22378
22379
22380
22381
22382
22383
22384
22385
22386
22387
22388
22389
22390
22391
22392
22393
22394
22395
22396
22397
22398
22399
22400
22401
22402
22403
22404
22405
22406
22407
22408
22409
22410
22411
22412
22413
22414
22415
22416
22417
22418
22419
22420
22421
22422
22423
22424
22425
22426
22427
22428
22429
22430
22431
22432
22433
22434
22435
22436
22437
22438
22439
22440
22441
22442
22443
22444
22445
22446
22447
22448
22449
22450
22451
22452
22453
22454
22455
22456
22457
22458
22459
22460
22461
22462
22463
22464
22465
22466
22467
22468
22469
22470
22471
22472
22473
22474
22475
22476
22477
22478
22479
22480
22481
22482
22483
22484
22485
22486
22487
22488
22489
22490
22491
22492
22493
22494
22495
22496
22497
22498
22499
22500
22501
22502
22503
22504
22505
22506
22507
22508
22509
22510
22511
22512
22513
22514
22515
22516
22517
22518
22519
22520
22521
22522
22523
22524
22525
22526
22527
22528
22529
22530
22531
22532
22533
22534
22535
22536
22537
22538
22539
22540
22541
22542
22543
22544
22545
22546
22547
22548
22549
22550
22551
22552
22553
22554
22555
22556
22557
22558
22559
22560
22561
22562
22563
22564
22565
22566
22567
22568
22569
22570
22571
22572
22573
22574
22575
22576
22577
22578
22579
22580
22581
22582
22583
22584
22585
22586
22587
22588
22589
22590
22591
22592
22593
22594
22595
22596
22597
22598
22599
22600
22601
22602
22603
22604
22605
22606
22607
22608
22609
22610
22611
22612
22613
22614
22615
22616
22617
22618
22619
22620
22621
22622
22623
22624
22625
22626
22627
22628
22629
22630
22631
22632
22633
22634
22635
22636
22637
22638
22639
22640
22641
22642
22643
22644
22645
22646
22647
22648
22649
22650
22651
22652
22653
22654
22655
22656
22657
22658
22659
22660
22661
22662
22663
22664
22665
22666
22667
22668
22669
22670
22671
22672
22673
22674
22675
22676
22677
22678
22679
22680
22681
22682
22683
22684
22685
22686
22687
22688
22689
22690
22691
22692
22693
22694
22695
22696
22697
22698
22699
22700
22701
22702
22703
22704
22705
22706
22707
22708
22709
22710
22711
22712
22713
22714
22715
22716
22717
22718
22719
22720
22721
22722
22723
22724
22725
22726
22727
22728
22729
22730
22731
22732
22733
22734
22735
22736
22737
22738
22739
22740
22741
22742
22743
22744
22745
22746
22747
22748
22749
22750
22751
22752
22753
22754
22755
22756
22757
22758
22759
22760
22761
22762
22763
22764
22765
22766
22767
22768
22769
22770
22771
22772
22773
22774
22775
22776
22777
22778
22779
22780
22781
22782
22783
22784
22785
22786
22787
22788
22789
22790
22791
22792
22793
22794
22795
22796
22797
22798
22799
22800
22801
22802
22803
22804
22805
22806
22807
22808
22809
22810
22811
22812
22813
22814
22815
22816
22817
22818
22819
22820
22821
22822
22823
22824
22825
22826
22827
22828
22829
22830
22831
22832
22833
22834
22835
22836
22837
22838
22839
22840
22841
22842
22843
22844
22845
22846
22847
22848
22849
22850
22851
22852
22853
22854
22855
22856
22857
22858
22859
22860
22861
22862
22863
22864
22865
22866
22867
22868
22869
22870
22871
22872
22873
22874
22875
22876
22877
22878
22879
22880
22881
22882
22883
22884
22885
22886
22887
22888
22889
22890
22891
22892
22893
22894
22895
22896
22897
22898
22899
22900
22901
22902
22903
22904
22905
22906
22907
22908
22909
22910
22911
22912
22913
22914
22915
22916
22917
22918
22919
22920
22921
22922
22923
22924
22925
22926
22927
22928
22929
22930
22931
22932
22933
22934
22935
22936
22937
22938
22939
22940
22941
22942
22943
22944
22945
22946
22947
22948
22949
22950
22951
22952
22953
22954
22955
22956
22957
22958
22959
22960
22961
22962
22963
22964
22965
22966
22967
22968
22969
22970
22971
22972
22973
22974
22975
22976
22977
22978
22979
22980
22981
22982
22983
22984
22985
22986
22987
22988
22989
22990
22991
22992
22993
22994
22995
22996
22997
22998
22999
23000
23001
23002
23003
23004
23005
23006
23007
23008
23009
23010
23011
23012
23013
23014
23015
23016
23017
23018
23019
23020
23021
23022
23023
23024
23025
23026
23027
23028
23029
23030
23031
23032
23033
23034
23035
23036
23037
23038
23039
23040
23041
23042
23043
23044
23045
23046
23047
23048
23049
23050
23051
23052
23053
23054
23055
23056
23057
23058
23059
23060
23061
23062
23063
23064
23065
23066
23067
23068
23069
23070
23071
23072
23073
23074
23075
23076
23077
23078
23079
23080
23081
23082
23083
23084
23085
23086
23087
23088
23089
23090
23091
23092
23093
23094
23095
23096
23097
23098
23099
23100
23101
23102
23103
23104
23105
23106
23107
23108
23109
23110
23111
23112
23113
23114
23115
23116
23117
23118
23119
23120
23121
23122
23123
23124
23125
23126
23127
23128
23129
23130
23131
23132
23133
23134
23135
23136
23137
23138
23139
23140
23141
23142
23143
23144
23145
23146
23147
23148
23149
23150
23151
23152
23153
23154
23155
23156
23157
23158
23159
23160
23161
23162
23163
23164
23165
23166
23167
23168
23169
23170
23171
23172
23173
23174
23175
23176
23177
23178
23179
23180
23181
23182
23183
23184
23185
23186
23187
23188
23189
23190
23191
23192
23193
23194
23195
23196
23197
23198
23199
23200
23201
23202
23203
23204
23205
23206
23207
23208
23209
23210
23211
23212
23213
23214
23215
23216
23217
23218
23219
23220
23221
23222
23223
23224
23225
23226
23227
23228
23229
23230
23231
23232
23233
23234
23235
23236
23237
23238
23239
23240
23241
23242
23243
23244
23245
23246
23247
23248
23249
23250
23251
23252
23253
23254
23255
23256
23257
23258
23259
23260
23261
23262
23263
23264
23265
23266
23267
23268
23269
23270
23271
23272
23273
23274
23275
23276
23277
23278
23279
23280
23281
23282
23283
23284
23285
23286
23287
23288
23289
23290
23291
23292
23293
23294
23295
23296
23297
23298
23299
23300
23301
23302
23303
23304
23305
23306
23307
23308
23309
23310
23311
23312
23313
23314
23315
23316
23317
23318
23319
23320
23321
23322
23323
23324
23325
23326
23327
23328
23329
23330
23331
23332
23333
23334
23335
23336
23337
23338
23339
23340
23341
23342
23343
23344
23345
23346
23347
23348
23349
23350
23351
23352
23353
23354
23355
23356
23357
23358
23359
23360
23361
23362
23363
23364
23365
23366
23367
23368
23369
23370
23371
23372
23373
23374
23375
23376
23377
23378
23379
23380
23381
23382
23383
23384
23385
23386
23387
23388
23389
23390
23391
23392
23393
23394
23395
23396
23397
23398
23399
23400
23401
23402
23403
23404
23405
23406
23407
23408
23409
23410
23411
23412
23413
23414
23415
23416
23417
23418
23419
23420
23421
23422
23423
23424
23425
23426
23427
23428
23429
23430
23431
23432
23433
23434
23435
23436
23437
23438
23439
23440
23441
23442
23443
23444
23445
23446
23447
23448
23449
23450
23451
23452
23453
23454
23455
23456
23457
23458
23459
23460
23461
23462
23463
23464
23465
23466
23467
23468
23469
23470
23471
23472
23473
23474
23475
23476
23477
23478
23479
23480
23481
23482
23483
23484
23485
23486
23487
23488
23489
23490
23491
23492
23493
23494
23495
23496
23497
23498
23499
23500
23501
23502
23503
23504
23505
23506
23507
23508
23509
23510
23511
23512
23513
23514
23515
23516
23517
23518
23519
23520
23521
23522
23523
23524
23525
23526
23527
23528
23529
23530
23531
23532
23533
23534
23535
23536
23537
23538
23539
23540
23541
23542
23543
23544
23545
23546
23547
23548
23549
23550
23551
23552
23553
23554
23555
23556
23557
23558
23559
23560
23561
23562
23563
23564
23565
23566
23567
23568
23569
23570
23571
23572
23573
23574
23575
23576
23577
23578
23579
23580
23581
23582
23583
23584
23585
23586
23587
23588
23589
23590
23591
23592
23593
23594
23595
23596
23597
23598
23599
23600
23601
23602
23603
23604
23605
23606
23607
23608
23609
23610
23611
23612
23613
23614
23615
23616
23617
23618
23619
23620
23621
23622
23623
23624
23625
23626
23627
23628
23629
23630
23631
23632
23633
23634
23635
23636
23637
23638
23639
23640
23641
23642
23643
23644
23645
23646
23647
23648
23649
23650
23651
23652
23653
23654
23655
23656
23657
23658
23659
23660
23661
23662
23663
23664
23665
23666
23667
23668
23669
23670
23671
23672
23673
23674
23675
23676
23677
23678
23679
23680
23681
23682
23683
23684
23685
23686
23687
23688
23689
23690
23691
23692
23693
23694
23695
23696
23697
23698
23699
23700
23701
23702
23703
23704
23705
23706
23707
23708
23709
23710
23711
23712
23713
23714
23715
23716
23717
23718
23719
23720
23721
23722
23723
23724
23725
23726
23727
23728
23729
23730
23731
23732
23733
23734
23735
23736
23737
23738
23739
23740
23741
23742
23743
23744
23745
23746
23747
23748
23749
23750
23751
23752
23753
23754
23755
23756
23757
23758
23759
23760
23761
23762
23763
23764
23765
23766
23767
23768
23769
23770
23771
23772
23773
23774
23775
23776
23777
23778
23779
23780
23781
23782
23783
23784
23785
23786
23787
23788
23789
23790
23791
23792
23793
23794
23795
23796
23797
23798
23799
23800
23801
23802
23803
23804
23805
23806
23807
23808
23809
23810
23811
23812
23813
23814
23815
23816
23817
23818
23819
23820
23821
23822
23823
23824
23825
23826
23827
23828
23829
23830
23831
23832
23833
23834
23835
23836
23837
23838
23839
23840
23841
23842
23843
23844
23845
23846
23847
23848
23849
23850
23851
23852
23853
23854
23855
23856
23857
23858
23859
23860
23861
23862
23863
23864
23865
23866
23867
23868
23869
23870
23871
23872
23873
23874
23875
23876
23877
23878
23879
23880
23881
23882
23883
23884
23885
23886
23887
23888
23889
23890
23891
23892
23893
23894
23895
23896
23897
23898
23899
23900
23901
23902
23903
23904
23905
23906
23907
23908
23909
23910
23911
23912
23913
23914
23915
23916
23917
23918
23919
23920
23921
23922
23923
23924
23925
23926
23927
23928
23929
23930
23931
23932
23933
23934
23935
23936
23937
23938
23939
23940
23941
23942
23943
23944
23945
23946
23947
23948
23949
23950
23951
23952
23953
23954
23955
23956
23957
23958
23959
23960
23961
23962
23963
23964
23965
23966
23967
23968
23969
23970
23971
23972
23973
23974
23975
23976
23977
23978
23979
23980
23981
23982
23983
23984
23985
23986
23987
23988
23989
23990
23991
23992
23993
23994
23995
23996
23997
23998
23999
24000
24001
24002
24003
24004
24005
24006
24007
24008
24009
24010
24011
24012
24013
24014
24015
24016
24017
24018
24019
24020
24021
24022
24023
24024
24025
24026
24027
24028
24029
24030
24031
24032
24033
24034
24035
24036
24037
24038
24039
24040
24041
24042
24043
24044
24045
24046
24047
24048
24049
24050
24051
24052
24053
24054
24055
24056
24057
24058
24059
24060
24061
24062
24063
24064
24065
24066
24067
24068
24069
24070
24071
24072
24073
24074
24075
24076
24077
24078
24079
24080
24081
24082
24083
24084
24085
24086
24087
24088
24089
24090
24091
24092
24093
24094
24095
24096
24097
24098
24099
24100
24101
24102
24103
24104
24105
24106
24107
24108
24109
24110
24111
24112
24113
24114
24115
24116
24117
24118
24119
24120
24121
24122
24123
24124
24125
24126
24127
24128
24129
24130
24131
24132
24133
24134
24135
24136
24137
24138
24139
24140
24141
24142
24143
24144
24145
24146
24147
24148
24149
24150
24151
24152
24153
24154
24155
24156
24157
24158
24159
24160
24161
24162
24163
24164
24165
24166
24167
24168
24169
24170
24171
24172
24173
24174
24175
24176
24177
24178
24179
24180
24181
24182
24183
24184
24185
24186
24187
24188
24189
24190
24191
24192
24193
24194
24195
24196
24197
24198
24199
24200
24201
24202
24203
24204
24205
24206
24207
24208
24209
24210
24211
24212
24213
24214
24215
24216
24217
24218
24219
24220
24221
24222
24223
24224
24225
24226
24227
24228
24229
24230
24231
24232
24233
24234
24235
24236
24237
24238
24239
24240
24241
24242
24243
24244
24245
24246
24247
24248
24249
24250
24251
24252
24253
24254
24255
24256
24257
24258
24259
24260
24261
24262
24263
24264
24265
24266
24267
24268
24269
24270
24271
24272
24273
24274
24275
24276
24277
24278
24279
24280
24281
24282
24283
24284
24285
24286
24287
24288
24289
24290
24291
24292
24293
24294
24295
24296
24297
24298
24299
24300
24301
24302
24303
24304
24305
24306
24307
24308
24309
24310
24311
24312
24313
24314
24315
24316
24317
24318
24319
24320
24321
24322
24323
24324
24325
24326
24327
24328
24329
24330
24331
24332
24333
24334
24335
24336
24337
24338
24339
24340
24341
24342
24343
24344
24345
24346
24347
24348
24349
24350
24351
24352
24353
24354
24355
24356
24357
24358
24359
24360
24361
24362
24363
24364
24365
24366
24367
24368
24369
24370
24371
24372
24373
24374
24375
24376
24377
24378
24379
24380
24381
24382
24383
24384
24385
24386
24387
24388
24389
24390
24391
24392
24393
24394
24395
24396
24397
24398
24399
24400
24401
24402
24403
24404
24405
24406
24407
24408
24409
24410
24411
24412
24413
24414
24415
24416
24417
24418
24419
24420
24421
24422
24423
24424
24425
24426
24427
24428
24429
24430
24431
24432
24433
24434
24435
24436
24437
24438
24439
24440
24441
24442
24443
24444
24445
24446
24447
24448
24449
24450
24451
24452
24453
24454
24455
24456
24457
24458
24459
24460
24461
24462
24463
24464
24465
24466
24467
24468
24469
24470
24471
24472
24473
24474
24475
24476
24477
24478
24479
24480
24481
24482
24483
24484
24485
24486
24487
24488
24489
24490
24491
24492
24493
24494
24495
24496
24497
24498
24499
24500
24501
24502
24503
24504
24505
24506
24507
24508
24509
24510
24511
24512
24513
24514
24515
24516
24517
24518
24519
24520
24521
24522
24523
24524
24525
24526
24527
24528
24529
24530
24531
24532
24533
24534
24535
24536
24537
24538
24539
24540
24541
24542
24543
24544
24545
24546
24547
24548
24549
24550
24551
24552
24553
24554
24555
24556
24557
24558
24559
24560
24561
24562
24563
24564
24565
24566
24567
24568
24569
24570
24571
24572
24573
24574
24575
24576
24577
24578
24579
24580
24581
24582
24583
24584
24585
24586
24587
24588
24589
24590
24591
24592
24593
24594
24595
24596
24597
24598
24599
24600
24601
24602
24603
24604
24605
24606
24607
24608
24609
24610
24611
24612
24613
24614
24615
24616
24617
24618
24619
24620
24621
24622
24623
24624
24625
24626
24627
24628
24629
24630
24631
24632
24633
24634
24635
24636
24637
24638
24639
24640
24641
24642
24643
24644
24645
24646
24647
24648
24649
24650
24651
24652
24653
24654
24655
24656
24657
24658
24659
24660
24661
24662
24663
24664
24665
24666
24667
24668
24669
24670
24671
24672
24673
24674
24675
24676
24677
24678
24679
24680
24681
24682
24683
24684
24685
24686
24687
24688
24689
24690
24691
24692
24693
24694
24695
24696
24697
24698
24699
24700
24701
24702
24703
24704
24705
24706
24707
24708
24709
24710
24711
24712
24713
24714
24715
24716
24717
24718
24719
24720
24721
24722
24723
24724
24725
24726
24727
24728
24729
24730
24731
24732
24733
24734
24735
24736
24737
24738
24739
24740
24741
24742
24743
24744
24745
24746
24747
24748
24749
24750
24751
24752
24753
24754
24755
24756
24757
24758
24759
24760
24761
24762
24763
24764
24765
24766
24767
24768
24769
24770
24771
24772
24773
24774
24775
24776
24777
24778
24779
24780
24781
24782
24783
24784
24785
24786
24787
24788
24789
24790
24791
24792
24793
24794
24795
24796
24797
24798
24799
24800
24801
24802
24803
24804
24805
24806
24807
24808
24809
24810
24811
24812
24813
24814
24815
24816
24817
24818
24819
24820
24821
24822
24823
24824
24825
24826
24827
24828
24829
24830
24831
24832
24833
24834
24835
24836
24837
24838
24839
24840
24841
24842
24843
24844
24845
24846
24847
24848
24849
24850
24851
24852
24853
24854
24855
24856
24857
24858
24859
24860
24861
24862
24863
24864
24865
24866
24867
24868
24869
24870
24871
24872
24873
24874
24875
24876
24877
24878
24879
24880
24881
24882
24883
24884
24885
24886
24887
24888
24889
24890
24891
24892
24893
24894
24895
24896
24897
24898
24899
24900
24901
24902
24903
24904
24905
24906
24907
24908
24909
24910
24911
24912
24913
24914
24915
24916
24917
24918
24919
24920
24921
24922
24923
24924
24925
24926
24927
24928
24929
24930
24931
24932
24933
24934
24935
24936
24937
24938
24939
24940
24941
24942
24943
24944
24945
24946
24947
24948
24949
24950
24951
24952
24953
24954
24955
24956
24957
24958
24959
24960
24961
24962
24963
24964
24965
24966
24967
24968
24969
24970
24971
24972
24973
24974
24975
24976
24977
24978
24979
24980
24981
24982
24983
24984
24985
24986
24987
24988
24989
24990
24991
24992
24993
24994
24995
24996
24997
24998
24999
25000
25001
25002
25003
25004
25005
25006
25007
25008
25009
25010
25011
25012
25013
25014
25015
25016
25017
25018
25019
25020
25021
25022
25023
25024
25025
25026
25027
25028
25029
25030
25031
25032
25033
25034
25035
25036
25037
25038
25039
25040
25041
25042
25043
25044
25045
25046
25047
25048
25049
25050
25051
25052
25053
25054
25055
25056
25057
25058
25059
25060
25061
25062
25063
25064
25065
25066
25067
25068
25069
25070
25071
25072
25073
25074
25075
25076
25077
25078
25079
25080
25081
25082
25083
25084
25085
25086
25087
25088
25089
25090
25091
25092
25093
25094
25095
25096
25097
25098
25099
25100
25101
25102
25103
25104
25105
25106
25107
25108
25109
25110
25111
25112
25113
25114
25115
25116
25117
25118
25119
25120
25121
25122
25123
25124
25125
25126
25127
25128
25129
25130
25131
25132
25133
25134
25135
25136
25137
25138
25139
25140
25141
25142
25143
25144
25145
25146
25147
25148
25149
25150
25151
25152
25153
25154
25155
25156
25157
25158
25159
25160
25161
25162
25163
25164
25165
25166
25167
25168
25169
25170
25171
25172
25173
25174
25175
25176
25177
25178
25179
25180
25181
25182
25183
25184
25185
25186
25187
25188
25189
25190
25191
25192
25193
25194
25195
25196
25197
25198
25199
25200
25201
25202
25203
25204
25205
25206
25207
25208
25209
25210
25211
25212
25213
25214
25215
25216
25217
25218
25219
25220
25221
25222
25223
25224
25225
25226
25227
25228
25229
25230
25231
25232
25233
25234
25235
25236
25237
25238
25239
25240
25241
25242
25243
25244
25245
25246
25247
25248
25249
25250
25251
25252
25253
25254
25255
25256
25257
25258
25259
25260
25261
25262
25263
25264
25265
25266
25267
25268
25269
25270
25271
25272
25273
25274
25275
25276
25277
25278
25279
25280
25281
25282
25283
25284
25285
25286
25287
25288
25289
25290
25291
25292
25293
25294
25295
25296
25297
25298
25299
25300
25301
25302
25303
25304
25305
25306
25307
25308
25309
25310
25311
25312
25313
25314
25315
25316
25317
25318
25319
25320
25321
25322
25323
25324
25325
25326
25327
25328
25329
25330
25331
25332
25333
25334
25335
25336
25337
25338
25339
25340
25341
25342
25343
25344
25345
25346
25347
25348
25349
25350
25351
25352
25353
25354
25355
25356
25357
25358
25359
25360
25361
25362
25363
25364
25365
25366
25367
25368
25369
25370
25371
25372
25373
25374
25375
25376
25377
25378
25379
25380
25381
25382
25383
25384
25385
25386
25387
25388
25389
25390
25391
25392
25393
25394
25395
25396
25397
25398
25399
25400
25401
25402
25403
25404
25405
25406
25407
25408
25409
25410
25411
25412
25413
25414
25415
25416
25417
25418
25419
25420
25421
25422
25423
25424
25425
25426
25427
25428
25429
25430
25431
25432
25433
25434
25435
25436
25437
25438
25439
25440
25441
25442
25443
25444
25445
25446
25447
25448
25449
25450
25451
25452
25453
25454
25455
25456
25457
25458
25459
25460
25461
25462
25463
25464
25465
25466
25467
25468
25469
25470
25471
25472
25473
25474
25475
25476
25477
25478
25479
25480
25481
25482
25483
25484
25485
25486
25487
25488
25489
25490
25491
25492
25493
25494
25495
25496
25497
25498
25499
25500
25501
25502
25503
25504
25505
25506
25507
25508
25509
25510
25511
25512
25513
25514
25515
25516
25517
25518
25519
25520
25521
25522
25523
25524
25525
25526
25527
25528
25529
25530
25531
25532
25533
25534
25535
25536
25537
25538
25539
25540
25541
25542
25543
25544
25545
25546
25547
25548
25549
25550
25551
25552
25553
25554
25555
25556
25557
25558
25559
25560
25561
25562
25563
25564
25565
25566
25567
25568
25569
25570
25571
25572
25573
25574
25575
25576
25577
25578
25579
25580
25581
25582
25583
25584
25585
25586
25587
25588
25589
25590
25591
25592
25593
25594
25595
25596
25597
25598
25599
25600
25601
25602
25603
25604
25605
25606
25607
25608
25609
25610
25611
25612
25613
25614
25615
25616
25617
25618
25619
25620
25621
25622
25623
25624
25625
25626
25627
25628
25629
25630
25631
25632
25633
25634
25635
25636
25637
25638
25639
25640
25641
25642
25643
25644
25645
25646
25647
25648
25649
25650
25651
25652
25653
25654
25655
25656
25657
25658
25659
25660
25661
25662
25663
25664
25665
25666
25667
25668
25669
25670
25671
25672
25673
25674
25675
25676
25677
25678
25679
25680
25681
25682
25683
25684
25685
25686
25687
25688
25689
25690
25691
25692
25693
25694
25695
25696
25697
25698
25699
25700
25701
25702
25703
25704
25705
25706
25707
25708
25709
25710
25711
25712
25713
25714
25715
25716
25717
25718
25719
25720
25721
25722
25723
25724
25725
25726
25727
25728
25729
25730
25731
25732
25733
25734
25735
25736
25737
25738
25739
25740
25741
25742
25743
25744
25745
25746
25747
25748
25749
25750
25751
25752
25753
25754
25755
25756
25757
25758
25759
25760
25761
25762
25763
25764
25765
25766
25767
25768
25769
25770
25771
25772
25773
25774
25775
25776
25777
25778
25779
25780
25781
25782
25783
25784
25785
25786
25787
25788
25789
25790
25791
25792
25793
25794
25795
25796
25797
25798
25799
25800
25801
25802
25803
25804
25805
25806
25807
25808
25809
25810
25811
25812
25813
25814
25815
25816
25817
25818
25819
25820
25821
25822
25823
25824
25825
25826
25827
25828
25829
25830
25831
25832
25833
25834
25835
25836
25837
25838
25839
25840
25841
25842
25843
25844
25845
25846
25847
25848
25849
25850
25851
25852
25853
25854
25855
25856
25857
25858
25859
25860
25861
25862
25863
25864
25865
25866
25867
25868
25869
25870
25871
25872
25873
25874
25875
25876
25877
25878
25879
25880
25881
25882
25883
25884
25885
25886
25887
25888
25889
25890
25891
25892
25893
25894
25895
25896
25897
25898
25899
25900
25901
25902
25903
25904
25905
25906
25907
25908
25909
25910
25911
25912
25913
25914
25915
25916
25917
25918
25919
25920
25921
25922
25923
25924
25925
25926
25927
25928
25929
25930
25931
25932
25933
25934
25935
25936
25937
25938
25939
25940
25941
25942
25943
25944
25945
25946
25947
25948
25949
25950
25951
25952
25953
25954
25955
25956
25957
25958
25959
25960
25961
25962
25963
25964
25965
25966
25967
25968
25969
25970
25971
25972
25973
25974
25975
25976
25977
25978
25979
25980
25981
25982
25983
25984
25985
25986
25987
25988
25989
25990
25991
25992
25993
25994
25995
25996
25997
25998
25999
26000
26001
26002
26003
26004
26005
26006
26007
26008
26009
26010
26011
26012
26013
26014
26015
26016
26017
26018
26019
26020
26021
26022
26023
26024
26025
26026
26027
26028
26029
26030
26031
26032
26033
26034
26035
26036
26037
26038
26039
26040
26041
26042
26043
26044
26045
26046
26047
26048
26049
26050
26051
26052
26053
26054
26055
26056
26057
26058
26059
26060
26061
26062
26063
26064
26065
26066
26067
26068
26069
26070
26071
26072
26073
26074
26075
26076
26077
26078
26079
26080
26081
26082
26083
26084
26085
26086
26087
26088
26089
26090
26091
26092
26093
26094
26095
26096
26097
26098
26099
26100
26101
26102
26103
26104
26105
26106
26107
26108
26109
26110
26111
26112
26113
26114
26115
26116
26117
26118
26119
26120
26121
26122
26123
26124
26125
26126
26127
26128
26129
26130
26131
26132
26133
26134
26135
26136
26137
26138
26139
26140
26141
26142
26143
26144
26145
26146
26147
26148
26149
26150
26151
26152
26153
26154
26155
26156
26157
26158
26159
26160
26161
26162
26163
26164
26165
26166
26167
26168
26169
26170
26171
26172
26173
26174
26175
26176
26177
26178
26179
26180
26181
26182
26183
26184
26185
26186
26187
26188
26189
26190
26191
26192
26193
26194
26195
26196
26197
26198
26199
26200
26201
26202
26203
26204
26205
26206
26207
26208
26209
26210
26211
26212
26213
26214
26215
26216
26217
26218
26219
26220
26221
26222
26223
26224
26225
26226
26227
26228
26229
26230
26231
26232
26233
26234
26235
26236
26237
26238
26239
26240
26241
26242
26243
26244
26245
26246
26247
26248
26249
26250
26251
26252
26253
26254
26255
26256
26257
26258
26259
26260
26261
26262
26263
26264
26265
26266
26267
26268
26269
26270
26271
26272
26273
26274
26275
26276
26277
26278
26279
26280
26281
26282
26283
26284
26285
26286
26287
26288
26289
26290
26291
26292
26293
26294
26295
26296
26297
26298
26299
26300
26301
26302
26303
26304
26305
26306
26307
26308
26309
26310
26311
26312
26313
26314
26315
26316
26317
26318
26319
26320
26321
26322
26323
26324
26325
26326
26327
26328
26329
26330
26331
26332
26333
26334
26335
26336
26337
26338
26339
26340
26341
26342
26343
26344
26345
26346
26347
26348
26349
26350
26351
26352
26353
26354
26355
26356
26357
26358
26359
26360
26361
26362
26363
26364
26365
26366
26367
26368
26369
26370
26371
26372
26373
26374
26375
26376
26377
26378
26379
26380
26381
26382
26383
26384
26385
26386
26387
26388
26389
26390
26391
26392
26393
26394
26395
26396
26397
26398
26399
26400
26401
26402
26403
26404
26405
26406
26407
26408
26409
26410
26411
26412
26413
26414
26415
26416
26417
26418
26419
26420
26421
26422
26423
26424
26425
26426
26427
26428
26429
26430
26431
26432
26433
26434
26435
26436
26437
26438
26439
26440
26441
26442
26443
26444
26445
26446
26447
26448
26449
26450
26451
26452
26453
26454
26455
26456
26457
26458
26459
26460
26461
26462
26463
26464
26465
26466
26467
26468
26469
26470
26471
26472
26473
26474
26475
26476
26477
26478
26479
26480
26481
26482
26483
26484
26485
26486
26487
26488
26489
26490
26491
26492
26493
26494
26495
26496
26497
26498
26499
26500
26501
26502
26503
26504
26505
26506
26507
26508
26509
26510
26511
26512
26513
26514
26515
26516
26517
26518
26519
26520
26521
26522
26523
26524
26525
26526
26527
26528
26529
26530
26531
26532
26533
26534
26535
26536
26537
26538
26539
26540
26541
26542
26543
26544
26545
26546
26547
26548
26549
26550
26551
26552
26553
26554
26555
26556
26557
26558
26559
26560
26561
26562
26563
26564
26565
26566
26567
26568
26569
26570
26571
26572
26573
26574
26575
26576
26577
26578
26579
26580
26581
26582
26583
26584
26585
26586
26587
26588
26589
26590
26591
26592
26593
26594
26595
26596
26597
26598
26599
26600
26601
26602
26603
26604
26605
26606
26607
26608
26609
26610
26611
26612
26613
26614
26615
26616
26617
26618
26619
26620
26621
26622
26623
26624
26625
26626
26627
26628
26629
26630
26631
26632
26633
26634
26635
26636
26637
26638
26639
26640
26641
26642
26643
26644
26645
26646
26647
26648
26649
26650
26651
26652
26653
26654
26655
26656
26657
26658
26659
26660
26661
26662
26663
26664
26665
26666
26667
26668
26669
26670
26671
26672
26673
26674
26675
26676
26677
26678
26679
26680
26681
26682
26683
26684
26685
26686
26687
26688
26689
26690
26691
26692
26693
26694
26695
26696
26697
26698
26699
26700
26701
26702
26703
26704
26705
26706
26707
26708
26709
26710
26711
26712
26713
26714
26715
26716
26717
26718
26719
26720
26721
26722
26723
26724
26725
26726
26727
26728
26729
26730
26731
26732
26733
26734
26735
26736
26737
26738
26739
26740
26741
26742
26743
26744
26745
26746
26747
26748
26749
26750
26751
26752
26753
26754
26755
26756
26757
26758
26759
26760
26761
26762
26763
26764
26765
26766
26767
26768
26769
26770
26771
26772
26773
26774
26775
26776
26777
26778
26779
26780
26781
26782
26783
26784
26785
26786
26787
26788
26789
26790
26791
26792
26793
26794
26795
26796
26797
26798
26799
26800
26801
26802
26803
26804
26805
26806
26807
26808
26809
26810
26811
26812
26813
26814
26815
26816
26817
26818
26819
26820
26821
26822
26823
26824
26825
26826
26827
26828
26829
26830
26831
26832
26833
26834
26835
26836
26837
26838
26839
26840
26841
26842
26843
26844
26845
26846
26847
26848
26849
26850
26851
26852
26853
26854
26855
26856
26857
26858
26859
26860
26861
26862
26863
26864
26865
26866
26867
26868
26869
26870
26871
26872
26873
26874
26875
26876
26877
26878
26879
26880
26881
26882
26883
26884
26885
26886
26887
26888
26889
26890
26891
26892
26893
26894
26895
26896
26897
26898
26899
26900
26901
26902
26903
26904
26905
26906
26907
26908
26909
26910
26911
26912
26913
26914
26915
26916
26917
26918
26919
26920
26921
26922
26923
26924
26925
26926
26927
26928
26929
26930
26931
26932
26933
26934
26935
26936
26937
26938
26939
26940
26941
26942
26943
26944
26945
26946
26947
26948
26949
26950
26951
26952
26953
26954
26955
26956
26957
26958
26959
26960
26961
26962
26963
26964
26965
26966
26967
26968
26969
26970
26971
26972
26973
26974
26975
26976
26977
26978
26979
26980
26981
26982
26983
26984
26985
26986
26987
26988
26989
26990
26991
26992
26993
26994
26995
26996
26997
26998
26999
27000
27001
27002
27003
27004
27005
27006
27007
27008
27009
27010
27011
27012
27013
27014
27015
27016
27017
27018
27019
27020
27021
27022
27023
27024
27025
27026
27027
27028
27029
27030
27031
27032
27033
27034
27035
27036
27037
27038
27039
27040
27041
27042
27043
27044
27045
27046
27047
27048
27049
27050
27051
27052
27053
27054
27055
27056
27057
27058
27059
27060
27061
27062
27063
27064
27065
27066
27067
27068
27069
27070
27071
27072
27073
27074
27075
27076
27077
27078
27079
27080
27081
27082
27083
27084
27085
27086
27087
27088
27089
27090
27091
27092
27093
27094
27095
27096
27097
27098
27099
27100
27101
27102
27103
27104
27105
27106
27107
27108
27109
27110
27111
27112
27113
27114
27115
27116
27117
27118
27119
27120
27121
27122
27123
27124
27125
27126
27127
27128
27129
27130
27131
27132
27133
27134
27135
27136
27137
27138
27139
27140
27141
27142
27143
27144
27145
27146
27147
27148
27149
27150
27151
27152
27153
27154
27155
27156
27157
27158
27159
27160
27161
27162
27163
27164
27165
27166
27167
27168
27169
27170
27171
27172
27173
27174
27175
27176
27177
27178
27179
27180
27181
27182
27183
27184
27185
27186
27187
27188
27189
27190
27191
27192
27193
27194
27195
27196
27197
27198
27199
27200
27201
27202
27203
27204
27205
27206
27207
27208
27209
27210
27211
27212
27213
27214
27215
27216
27217
27218
27219
27220
27221
27222
27223
27224
27225
27226
27227
27228
27229
27230
27231
27232
27233
27234
27235
27236
27237
27238
27239
27240
27241
27242
27243
27244
27245
27246
27247
27248
27249
27250
27251
27252
27253
27254
27255
27256
27257
27258
27259
27260
27261
27262
27263
27264
27265
27266
27267
27268
27269
27270
27271
27272
27273
27274
27275
27276
27277
27278
27279
27280
27281
27282
27283
27284
27285
27286
27287
27288
27289
27290
27291
27292
27293
27294
27295
27296
27297
27298
27299
27300
27301
27302
27303
27304
27305
27306
27307
27308
27309
27310
27311
27312
27313
27314
27315
27316
27317
27318
27319
27320
27321
27322
27323
27324
27325
27326
27327
27328
27329
27330
27331
27332
27333
27334
27335
27336
27337
27338
27339
27340
27341
27342
27343
27344
27345
27346
27347
27348
27349
27350
27351
27352
27353
27354
27355
27356
27357
27358
27359
27360
27361
27362
27363
27364
27365
27366
27367
27368
27369
27370
27371
27372
27373
27374
27375
27376
27377
27378
27379
27380
27381
27382
27383
27384
27385
27386
27387
27388
27389
27390
27391
27392
27393
27394
27395
27396
27397
27398
27399
27400
27401
27402
27403
27404
27405
27406
27407
27408
27409
27410
27411
27412
27413
27414
27415
27416
27417
27418
27419
27420
27421
27422
27423
27424
27425
27426
27427
27428
27429
27430
27431
27432
27433
27434
27435
27436
27437
27438
27439
27440
27441
27442
27443
27444
27445
27446
27447
27448
27449
27450
27451
27452
27453
27454
27455
27456
27457
27458
27459
27460
27461
27462
27463
27464
27465
27466
27467
27468
27469
27470
27471
27472
27473
27474
27475
27476
27477
27478
27479
27480
27481
27482
27483
27484
27485
27486
27487
27488
27489
27490
27491
27492
27493
27494
27495
27496
27497
27498
27499
27500
27501
27502
27503
27504
27505
27506
27507
27508
27509
27510
27511
27512
27513
27514
27515
27516
27517
27518
27519
27520
27521
27522
27523
27524
27525
27526
27527
27528
27529
27530
27531
27532
27533
27534
27535
27536
27537
27538
27539
27540
27541
27542
27543
27544
27545
27546
27547
27548
27549
27550
27551
27552
27553
27554
27555
27556
27557
27558
27559
27560
27561
27562
27563
27564
27565
27566
27567
27568
27569
27570
27571
27572
27573
27574
27575
27576
27577
27578
27579
27580
27581
27582
27583
27584
27585
27586
27587
27588
27589
27590
27591
27592
27593
27594
27595
27596
27597
27598
27599
27600
27601
27602
27603
27604
27605
27606
27607
27608
27609
27610
27611
27612
27613
27614
27615
27616
27617
27618
27619
27620
27621
27622
27623
27624
27625
27626
27627
27628
27629
27630
27631
27632
27633
27634
27635
27636
27637
27638
27639
27640
27641
27642
27643
27644
27645
27646
27647
27648
27649
27650
27651
27652
27653
27654
27655
27656
27657
27658
27659
27660
27661
27662
27663
27664
27665
27666
27667
27668
27669
27670
27671
27672
27673
27674
27675
27676
27677
27678
27679
27680
27681
27682
27683
27684
27685
27686
27687
27688
27689
27690
27691
27692
27693
27694
27695
27696
27697
27698
27699
27700
27701
27702
27703
27704
27705
27706
27707
27708
27709
27710
27711
27712
27713
27714
27715
27716
27717
27718
27719
27720
27721
27722
27723
27724
27725
27726
27727
27728
27729
27730
27731
27732
27733
27734
27735
27736
27737
27738
27739
27740
27741
27742
27743
27744
27745
27746
27747
27748
27749
27750
27751
27752
27753
27754
27755
27756
27757
27758
27759
27760
27761
27762
27763
27764
27765
27766
27767
27768
27769
27770
27771
27772
27773
27774
27775
27776
27777
27778
27779
27780
27781
27782
27783
27784
27785
27786
27787
27788
27789
27790
27791
27792
27793
27794
27795
27796
27797
27798
27799
27800
27801
27802
27803
27804
27805
27806
27807
27808
27809
27810
27811
27812
27813
27814
27815
27816
27817
27818
27819
27820
27821
27822
27823
27824
27825
27826
27827
27828
27829
27830
27831
27832
27833
27834
27835
27836
27837
27838
27839
27840
27841
27842
27843
27844
27845
27846
27847
27848
27849
27850
27851
27852
27853
27854
27855
27856
27857
27858
27859
27860
27861
27862
27863
27864
27865
27866
27867
27868
27869
27870
27871
27872
27873
27874
27875
27876
27877
27878
27879
27880
27881
27882
27883
27884
27885
27886
27887
27888
27889
27890
27891
27892
27893
27894
27895
27896
27897
27898
27899
27900
27901
27902
27903
27904
27905
27906
27907
27908
27909
27910
27911
27912
27913
27914
27915
27916
27917
27918
27919
27920
27921
27922
27923
27924
27925
27926
27927
27928
27929
27930
27931
27932
27933
27934
27935
27936
27937
27938
27939
27940
27941
27942
27943
27944
27945
27946
27947
27948
27949
27950
27951
27952
27953
27954
27955
27956
27957
27958
27959
27960
27961
27962
27963
27964
27965
27966
27967
27968
27969
27970
27971
27972
27973
27974
27975
27976
27977
27978
27979
27980
27981
27982
27983
27984
27985
27986
27987
27988
27989
27990
27991
27992
27993
27994
27995
27996
27997
27998
27999
28000
28001
28002
28003
28004
28005
28006
28007
28008
28009
28010
28011
28012
28013
28014
28015
28016
28017
28018
28019
28020
28021
28022
28023
28024
28025
28026
28027
28028
28029
28030
28031
28032
28033
28034
28035
28036
28037
28038
28039
28040
28041
28042
28043
28044
28045
28046
28047
28048
28049
28050
28051
28052
28053
28054
28055
28056
28057
28058
28059
28060
28061
28062
28063
28064
28065
28066
28067
28068
28069
28070
28071
28072
28073
28074
28075
28076
28077
28078
28079
28080
28081
28082
28083
28084
28085
28086
28087
28088
28089
28090
28091
28092
28093
28094
28095
28096
28097
28098
28099
28100
28101
28102
28103
28104
28105
28106
28107
28108
28109
28110
28111
28112
28113
28114
28115
28116
28117
28118
28119
28120
28121
28122
28123
28124
28125
28126
28127
28128
28129
28130
28131
28132
28133
28134
28135
28136
28137
28138
28139
28140
28141
28142
28143
28144
28145
28146
28147
28148
28149
28150
28151
28152
28153
28154
28155
28156
28157
28158
28159
28160
28161
28162
28163
28164
28165
28166
28167
28168
28169
28170
28171
28172
28173
28174
28175
28176
28177
28178
28179
28180
28181
28182
28183
28184
28185
28186
28187
28188
28189
28190
28191
28192
28193
28194
28195
28196
28197
28198
28199
28200
28201
28202
28203
28204
28205
28206
28207
28208
28209
28210
28211
28212
28213
28214
28215
28216
28217
28218
28219
28220
28221
28222
28223
28224
28225
28226
28227
28228
28229
28230
28231
28232
28233
28234
28235
28236
28237
28238
28239
28240
28241
28242
28243
28244
28245
28246
28247
28248
28249
28250
28251
28252
28253
28254
28255
28256
28257
28258
28259
28260
28261
28262
28263
28264
28265
28266
28267
28268
28269
28270
28271
28272
28273
28274
28275
28276
28277
28278
28279
28280
28281
28282
28283
28284
28285
28286
28287
28288
28289
28290
28291
28292
28293
28294
28295
28296
28297
28298
28299
28300
28301
28302
28303
28304
28305
28306
28307
28308
28309
28310
28311
28312
28313
28314
28315
28316
28317
28318
28319
28320
28321
28322
28323
28324
28325
28326
28327
28328
28329
28330
28331
28332
28333
28334
28335
28336
28337
28338
28339
28340
28341
28342
28343
28344
28345
28346
28347
28348
28349
28350
28351
28352
28353
28354
28355
28356
28357
28358
28359
28360
28361
28362
28363
28364
28365
28366
28367
28368
28369
28370
28371
28372
28373
28374
28375
28376
28377
28378
28379
28380
28381
28382
28383
28384
28385
28386
28387
28388
28389
28390
28391
28392
28393
28394
28395
28396
28397
28398
28399
28400
28401
28402
28403
28404
28405
28406
28407
28408
28409
28410
28411
28412
28413
28414
28415
28416
28417
28418
28419
28420
28421
28422
28423
28424
28425
28426
28427
28428
28429
28430
28431
28432
28433
28434
28435
28436
28437
28438
28439
28440
28441
28442
28443
28444
28445
28446
28447
28448
28449
28450
28451
28452
28453
28454
28455
28456
28457
28458
28459
28460
28461
28462
28463
28464
28465
28466
28467
28468
28469
28470
28471
28472
28473
28474
28475
28476
28477
28478
28479
28480
28481
28482
28483
28484
28485
28486
28487
28488
28489
28490
28491
28492
28493
28494
28495
28496
28497
28498
28499
28500
28501
28502
28503
28504
28505
28506
28507
28508
28509
28510
28511
28512
28513
28514
28515
28516
28517
28518
28519
28520
28521
28522
28523
28524
28525
28526
28527
28528
28529
28530
28531
28532
28533
28534
28535
28536
28537
28538
28539
28540
28541
28542
28543
28544
28545
28546
28547
28548
28549
28550
28551
28552
28553
28554
28555
28556
28557
28558
28559
28560
28561
28562
28563
28564
28565
28566
28567
28568
28569
28570
28571
28572
28573
28574
28575
28576
28577
28578
28579
28580
28581
28582
28583
28584
28585
28586
28587
28588
28589
28590
28591
28592
28593
28594
28595
28596
28597
28598
28599
28600
28601
28602
28603
28604
28605
28606
28607
28608
28609
28610
28611
28612
28613
28614
28615
28616
28617
28618
28619
28620
28621
28622
28623
28624
28625
28626
28627
28628
28629
28630
28631
28632
28633
28634
28635
28636
28637
28638
28639
28640
28641
28642
28643
28644
28645
28646
28647
28648
28649
28650
28651
28652
28653
28654
28655
28656
28657
28658
28659
28660
28661
28662
28663
28664
28665
28666
28667
28668
28669
28670
28671
28672
28673
28674
28675
28676
28677
28678
28679
28680
28681
28682
28683
28684
28685
28686
28687
28688
28689
28690
28691
28692
28693
28694
28695
28696
28697
28698
28699
28700
28701
28702
28703
28704
28705
28706
28707
28708
28709
28710
28711
28712
28713
28714
28715
28716
28717
28718
28719
28720
28721
28722
28723
28724
28725
28726
28727
28728
28729
28730
28731
28732
28733
28734
28735
28736
28737
28738
28739
28740
28741
28742
28743
28744
28745
28746
28747
28748
28749
28750
28751
28752
28753
28754
28755
28756
28757
28758
28759
28760
28761
28762
28763
28764
28765
28766
28767
28768
28769
28770
28771
28772
28773
28774
28775
28776
28777
28778
28779
28780
28781
28782
28783
28784
28785
28786
28787
28788
28789
28790
28791
28792
28793
28794
28795
28796
28797
28798
28799
28800
28801
28802
28803
28804
28805
28806
28807
28808
28809
28810
28811
28812
28813
28814
28815
28816
28817
28818
28819
28820
28821
28822
28823
28824
28825
28826
28827
28828
28829
28830
28831
28832
28833
28834
28835
28836
28837
28838
28839
28840
28841
28842
28843
28844
28845
28846
28847
28848
28849
28850
28851
28852
28853
28854
28855
28856
28857
28858
28859
28860
28861
28862
28863
28864
28865
28866
28867
28868
28869
28870
28871
28872
28873
28874
28875
28876
28877
28878
28879
28880
28881
28882
28883
28884
28885
28886
28887
28888
28889
28890
28891
28892
28893
28894
28895
28896
28897
28898
28899
28900
28901
28902
28903
28904
28905
28906
28907
28908
28909
28910
28911
28912
28913
28914
28915
28916
28917
28918
28919
28920
28921
28922
28923
28924
28925
28926
28927
28928
28929
28930
28931
28932
28933
28934
28935
28936
28937
28938
28939
28940
28941
28942
28943
28944
28945
28946
28947
28948
28949
28950
28951
28952
28953
28954
28955
28956
28957
28958
28959
28960
28961
28962
28963
28964
28965
28966
28967
28968
28969
28970
28971
28972
28973
28974
28975
28976
28977
28978
28979
28980
28981
28982
28983
28984
28985
28986
28987
28988
28989
28990
28991
28992
28993
28994
28995
28996
28997
28998
28999
29000
29001
29002
29003
29004
29005
29006
29007
29008
29009
29010
29011
29012
29013
29014
29015
29016
29017
29018
29019
29020
29021
29022
29023
29024
29025
29026
29027
29028
29029
29030
29031
29032
29033
29034
29035
29036
29037
29038
29039
29040
29041
29042
29043
29044
29045
29046
29047
29048
29049
29050
29051
29052
29053
29054
29055
29056
29057
29058
29059
29060
29061
29062
29063
29064
29065
29066
29067
29068
29069
29070
29071
29072
29073
29074
29075
29076
29077
29078
29079
29080
29081
29082
29083
29084
29085
29086
29087
29088
29089
29090
29091
29092
29093
29094
29095
29096
29097
29098
29099
29100
29101
29102
29103
29104
29105
29106
29107
29108
29109
29110
29111
29112
29113
29114
29115
29116
29117
29118
29119
29120
29121
29122
29123
29124
29125
29126
29127
29128
29129
29130
29131
29132
29133
29134
29135
29136
29137
29138
29139
29140
29141
29142
29143
29144
29145
29146
29147
29148
29149
29150
29151
29152
29153
29154
29155
29156
29157
29158
29159
29160
29161
29162
29163
29164
29165
29166
29167
29168
29169
29170
29171
29172
29173
29174
29175
29176
29177
29178
29179
29180
29181
29182
29183
29184
29185
29186
29187
29188
29189
29190
29191
29192
29193
29194
29195
29196
29197
29198
29199
29200
29201
29202
29203
29204
29205
29206
29207
29208
29209
29210
29211
29212
29213
29214
29215
29216
29217
29218
29219
29220
29221
29222
29223
29224
29225
29226
29227
29228
29229
29230
29231
29232
29233
29234
29235
29236
29237
29238
29239
29240
29241
29242
29243
29244
29245
29246
29247
29248
29249
29250
29251
29252
29253
29254
29255
29256
29257
29258
29259
29260
29261
29262
29263
29264
29265
29266
29267
29268
29269
29270
29271
29272
29273
29274
29275
29276
29277
29278
29279
29280
29281
29282
29283
29284
29285
29286
29287
29288
29289
29290
29291
29292
29293
29294
29295
29296
29297
29298
29299
29300
29301
29302
29303
29304
29305
29306
29307
29308
29309
29310
29311
29312
29313
29314
29315
29316
29317
29318
29319
29320
29321
29322
29323
29324
29325
29326
29327
29328
29329
29330
29331
29332
29333
29334
29335
29336
29337
29338
29339
29340
29341
29342
29343
29344
29345
29346
29347
29348
29349
29350
29351
29352
29353
29354
29355
29356
29357
29358
29359
29360
29361
29362
29363
29364
29365
29366
29367
29368
29369
29370
29371
29372
29373
29374
29375
29376
29377
29378
29379
29380
29381
29382
29383
29384
29385
29386
29387
29388
29389
29390
29391
29392
29393
29394
29395
29396
29397
29398
29399
29400
29401
29402
29403
29404
29405
29406
29407
29408
29409
29410
29411
29412
29413
29414
29415
29416
29417
29418
29419
29420
29421
29422
29423
29424
29425
29426
29427
29428
29429
29430
29431
29432
29433
29434
29435
29436
29437
29438
29439
29440
29441
29442
29443
29444
29445
29446
29447
29448
29449
29450
29451
29452
29453
29454
29455
29456
29457
29458
29459
29460
29461
29462
29463
29464
29465
29466
29467
29468
29469
29470
29471
29472
29473
29474
29475
29476
29477
29478
29479
29480
29481
29482
29483
29484
29485
29486
29487
29488
29489
29490
29491
29492
29493
29494
29495
29496
29497
29498
29499
29500
29501
29502
29503
29504
29505
29506
29507
29508
29509
29510
29511
29512
29513
29514
29515
29516
29517
29518
29519
29520
29521
29522
29523
29524
29525
29526
29527
29528
29529
29530
29531
29532
29533
29534
29535
29536
29537
29538
29539
29540
29541
29542
29543
29544
29545
29546
29547
29548
29549
29550
29551
29552
29553
29554
29555
29556
29557
29558
29559
29560
29561
29562
29563
29564
29565
29566
29567
29568
29569
29570
29571
29572
29573
29574
29575
29576
29577
29578
29579
29580
29581
29582
29583
29584
29585
29586
29587
29588
29589
29590
29591
29592
29593
29594
29595
29596
29597
29598
29599
29600
29601
29602
29603
29604
29605
29606
29607
29608
29609
29610
29611
29612
29613
29614
29615
29616
29617
29618
29619
29620
29621
29622
29623
29624
29625
29626
29627
29628
29629
29630
29631
29632
29633
29634
29635
29636
29637
29638
29639
29640
29641
29642
29643
29644
29645
29646
29647
29648
29649
29650
29651
29652
29653
29654
29655
29656
29657
29658
29659
29660
29661
29662
29663
29664
29665
29666
29667
29668
29669
29670
29671
29672
29673
29674
29675
29676
29677
29678
29679
29680
29681
29682
29683
29684
29685
29686
29687
29688
29689
29690
29691
29692
29693
29694
29695
29696
29697
29698
29699
29700
29701
29702
29703
29704
29705
29706
29707
29708
29709
29710
29711
29712
29713
29714
29715
29716
29717
29718
29719
29720
29721
29722
29723
29724
29725
29726
29727
29728
29729
29730
29731
29732
29733
29734
29735
29736
29737
29738
29739
29740
29741
29742
29743
29744
29745
29746
29747
29748
29749
29750
29751
29752
29753
29754
29755
29756
29757
29758
29759
29760
29761
29762
29763
29764
29765
29766
29767
29768
29769
29770
29771
29772
29773
29774
29775
29776
29777
29778
29779
29780
29781
29782
29783
29784
29785
29786
29787
29788
29789
29790
29791
29792
29793
29794
29795
29796
29797
29798
29799
29800
29801
29802
29803
29804
29805
29806
29807
29808
29809
29810
29811
29812
29813
29814
29815
29816
29817
29818
29819
29820
29821
29822
29823
29824
29825
29826
29827
29828
29829
29830
29831
29832
29833
29834
29835
29836
29837
29838
29839
29840
29841
29842
29843
29844
29845
29846
29847
29848
29849
29850
29851
29852
29853
29854
29855
29856
29857
29858
29859
29860
29861
29862
29863
29864
29865
29866
29867
29868
29869
29870
29871
29872
29873
29874
29875
29876
29877
29878
29879
29880
29881
29882
29883
29884
29885
29886
29887
29888
29889
29890
29891
29892
29893
29894
29895
29896
29897
29898
29899
29900
29901
29902
29903
29904
29905
29906
29907
29908
29909
29910
29911
29912
29913
29914
29915
29916
29917
29918
29919
29920
29921
29922
29923
29924
29925
29926
29927
29928
29929
29930
29931
29932
29933
29934
29935
29936
29937
29938
29939
29940
29941
29942
29943
29944
29945
29946
29947
29948
29949
29950
29951
29952
29953
29954
29955
29956
29957
29958
29959
29960
29961
29962
29963
29964
29965
29966
29967
29968
29969
29970
29971
29972
29973
29974
29975
29976
29977
29978
29979
29980
29981
29982
29983
29984
29985
29986
29987
29988
29989
29990
29991
29992
29993
29994
29995
29996
29997
29998
29999
30000
30001
30002
30003
30004
30005
30006
30007
30008
30009
30010
30011
30012
30013
30014
30015
30016
30017
30018
30019
30020
30021
30022
30023
30024
30025
30026
30027
30028
30029
30030
30031
30032
30033
30034
30035
30036
30037
30038
30039
30040
30041
30042
30043
30044
30045
30046
30047
30048
30049
30050
30051
30052
30053
30054
30055
30056
30057
30058
30059
30060
30061
30062
30063
30064
30065
30066
30067
30068
30069
30070
30071
30072
30073
30074
30075
30076
30077
30078
30079
30080
30081
30082
30083
30084
30085
30086
30087
30088
30089
30090
30091
30092
30093
30094
30095
30096
30097
30098
30099
30100
30101
30102
30103
30104
30105
30106
30107
30108
30109
30110
30111
30112
30113
30114
30115
30116
30117
30118
30119
30120
30121
30122
30123
30124
30125
30126
30127
30128
30129
30130
30131
30132
30133
30134
30135
30136
30137
30138
30139
30140
30141
30142
30143
30144
30145
30146
30147
30148
30149
30150
30151
30152
30153
30154
30155
30156
30157
30158
30159
30160
30161
30162
30163
30164
30165
30166
30167
30168
30169
30170
30171
30172
30173
30174
30175
30176
30177
30178
30179
30180
30181
30182
30183
30184
30185
30186
30187
30188
30189
30190
30191
30192
30193
30194
30195
30196
30197
30198
30199
30200
30201
30202
30203
30204
30205
30206
30207
30208
30209
30210
30211
30212
30213
30214
30215
30216
30217
30218
30219
30220
30221
30222
30223
30224
30225
30226
30227
30228
30229
30230
30231
30232
30233
30234
30235
30236
30237
30238
30239
30240
30241
30242
30243
30244
30245
30246
30247
30248
30249
30250
30251
30252
30253
30254
30255
30256
30257
30258
30259
30260
30261
30262
30263
30264
30265
30266
30267
30268
30269
30270
30271
30272
30273
30274
30275
30276
30277
30278
30279
30280
30281
30282
30283
30284
30285
30286
30287
30288
30289
30290
30291
30292
30293
30294
30295
30296
30297
30298
30299
30300
30301
30302
30303
30304
30305
30306
30307
30308
30309
30310
30311
30312
30313
30314
30315
30316
30317
30318
30319
30320
30321
30322
30323
30324
30325
30326
30327
30328
30329
30330
30331
30332
30333
30334
30335
30336
30337
30338
30339
30340
30341
30342
30343
30344
30345
30346
30347
30348
30349
30350
30351
30352
30353
30354
30355
30356
30357
30358
30359
30360
30361
30362
30363
30364
30365
30366
30367
30368
30369
30370
30371
30372
30373
30374
30375
30376
30377
30378
30379
30380
30381
30382
30383
30384
30385
30386
30387
30388
30389
30390
30391
30392
30393
30394
30395
30396
30397
30398
30399
30400
30401
30402
30403
30404
30405
30406
30407
30408
30409
30410
30411
30412
30413
30414
30415
30416
30417
30418
30419
30420
30421
30422
30423
30424
30425
30426
30427
30428
30429
30430
30431
30432
30433
30434
30435
30436
30437
30438
30439
30440
30441
30442
30443
30444
30445
30446
30447
30448
30449
30450
30451
30452
30453
30454
30455
30456
30457
30458
30459
30460
30461
30462
30463
30464
30465
30466
30467
30468
30469
30470
30471
30472
30473
30474
30475
30476
30477
30478
30479
30480
30481
30482
30483
30484
30485
30486
30487
30488
30489
30490
30491
30492
30493
30494
30495
30496
30497
30498
30499
30500
30501
30502
30503
30504
30505
30506
30507
30508
30509
30510
30511
30512
30513
30514
30515
30516
30517
30518
30519
30520
30521
30522
30523
30524
30525
30526
30527
30528
30529
30530
30531
30532
30533
30534
30535
30536
30537
30538
30539
30540
30541
30542
30543
30544
30545
30546
30547
30548
30549
30550
30551
30552
30553
30554
30555
30556
30557
30558
30559
30560
30561
30562
30563
30564
30565
30566
30567
30568
30569
30570
30571
30572
30573
30574
30575
30576
30577
30578
30579
30580
30581
30582
30583
30584
30585
30586
30587
30588
30589
30590
30591
30592
30593
30594
30595
30596
30597
30598
30599
30600
30601
30602
30603
30604
30605
30606
30607
30608
30609
30610
30611
30612
30613
30614
30615
30616
30617
30618
30619
30620
30621
30622
30623
30624
30625
30626
30627
30628
30629
30630
30631
30632
30633
30634
30635
30636
30637
30638
30639
30640
30641
30642
30643
30644
30645
30646
30647
30648
30649
30650
30651
30652
30653
30654
30655
30656
30657
30658
30659
30660
30661
30662
30663
30664
30665
30666
30667
30668
30669
30670
30671
30672
30673
30674
30675
30676
30677
30678
30679
30680
30681
30682
30683
30684
30685
30686
30687
30688
30689
30690
30691
30692
30693
30694
30695
30696
30697
30698
30699
30700
30701
30702
30703
30704
30705
30706
30707
30708
30709
30710
30711
30712
30713
30714
30715
30716
30717
30718
30719
30720
30721
30722
30723
30724
30725
30726
30727
30728
30729
30730
30731
30732
30733
30734
30735
30736
30737
30738
30739
30740
30741
30742
30743
30744
30745
30746
30747
30748
30749
30750
30751
30752
30753
30754
30755
30756
30757
30758
30759
30760
30761
30762
30763
30764
30765
30766
30767
30768
30769
30770
30771
30772
30773
30774
30775
30776
30777
30778
30779
30780
30781
30782
30783
30784
30785
30786
30787
30788
30789
30790
30791
30792
30793
30794
30795
30796
30797
30798
30799
30800
30801
30802
30803
30804
30805
30806
30807
30808
30809
30810
30811
30812
30813
30814
30815
30816
30817
30818
30819
30820
30821
30822
30823
30824
30825
30826
30827
30828
30829
30830
30831
30832
30833
30834
30835
30836
30837
30838
30839
30840
30841
30842
30843
30844
30845
30846
30847
30848
30849
30850
30851
30852
30853
30854
30855
30856
30857
30858
30859
30860
30861
30862
30863
30864
30865
30866
30867
30868
30869
30870
30871
30872
30873
30874
30875
30876
30877
30878
30879
30880
30881
30882
30883
30884
30885
30886
30887
30888
30889
30890
30891
30892
30893
30894
30895
30896
30897
30898
30899
30900
30901
30902
30903
30904
30905
30906
30907
30908
30909
30910
30911
30912
30913
30914
30915
30916
30917
30918
30919
30920
30921
30922
30923
30924
30925
30926
30927
30928
30929
30930
30931
30932
30933
30934
30935
30936
30937
30938
30939
30940
30941
30942
30943
30944
30945
30946
30947
30948
30949
30950
30951
30952
30953
30954
30955
30956
30957
30958
30959
30960
30961
30962
30963
30964
30965
30966
30967
30968
30969
30970
30971
30972
30973
30974
30975
30976
30977
30978
30979
30980
30981
30982
30983
30984
30985
30986
30987
30988
30989
30990
30991
30992
30993
30994
30995
30996
30997
30998
30999
31000
31001
31002
31003
31004
31005
31006
31007
31008
31009
31010
31011
31012
31013
31014
31015
31016
31017
31018
31019
31020
31021
31022
31023
31024
31025
31026
31027
31028
31029
31030
31031
31032
31033
31034
31035
31036
31037
31038
31039
31040
31041
31042
31043
31044
31045
31046
31047
31048
31049
31050
31051
31052
31053
31054
31055
31056
31057
31058
31059
31060
31061
31062
31063
31064
31065
31066
31067
31068
31069
31070
31071
31072
31073
31074
31075
31076
31077
31078
31079
31080
31081
31082
31083
31084
31085
31086
31087
31088
31089
31090
31091
31092
31093
31094
31095
31096
31097
31098
31099
31100
31101
31102
31103
31104
31105
31106
31107
31108
31109
31110
31111
31112
31113
31114
31115
31116
31117
31118
31119
31120
31121
31122
31123
31124
31125
31126
31127
31128
31129
31130
31131
31132
31133
31134
31135
31136
31137
31138
31139
31140
31141
31142
31143
31144
31145
31146
31147
31148
31149
31150
31151
31152
31153
31154
31155
31156
31157
31158
31159
31160
31161
31162
31163
31164
31165
31166
31167
31168
31169
31170
31171
31172
31173
31174
31175
31176
31177
31178
31179
31180
31181
31182
31183
31184
31185
31186
31187
31188
31189
31190
31191
31192
31193
31194
31195
31196
31197
31198
31199
31200
31201
31202
31203
31204
31205
31206
31207
31208
31209
31210
31211
31212
31213
31214
31215
31216
31217
31218
31219
31220
31221
31222
31223
31224
31225
31226
31227
31228
31229
31230
31231
31232
31233
31234
31235
31236
31237
31238
31239
31240
31241
31242
31243
31244
31245
31246
31247
31248
31249
31250
31251
31252
31253
31254
31255
31256
31257
31258
31259
31260
31261
31262
31263
31264
31265
31266
31267
31268
31269
31270
31271
31272
31273
31274
31275
31276
31277
31278
31279
31280
31281
31282
31283
31284
31285
31286
31287
31288
31289
31290
31291
31292
31293
31294
31295
31296
31297
31298
31299
31300
31301
31302
31303
31304
31305
31306
31307
31308
31309
31310
31311
31312
31313
31314
31315
31316
31317
31318
31319
31320
31321
31322
31323
31324
31325
31326
31327
31328
31329
31330
31331
31332
31333
31334
31335
31336
31337
31338
31339
31340
31341
31342
31343
31344
31345
31346
31347
31348
31349
31350
31351
31352
31353
31354
31355
31356
31357
31358
31359
31360
31361
31362
31363
31364
31365
31366
31367
31368
31369
31370
31371
31372
31373
31374
31375
31376
31377
31378
31379
31380
31381
31382
31383
31384
31385
31386
31387
31388
31389
31390
31391
31392
31393
31394
31395
31396
31397
31398
31399
31400
31401
31402
31403
31404
31405
31406
31407
31408
31409
31410
31411
31412
31413
31414
31415
31416
31417
31418
31419
31420
31421
31422
31423
31424
31425
31426
31427
31428
31429
31430
31431
31432
31433
31434
31435
31436
31437
31438
31439
31440
31441
31442
31443
31444
31445
31446
31447
31448
31449
31450
31451
31452
31453
31454
31455
31456
31457
31458
31459
31460
31461
31462
31463
31464
31465
31466
31467
31468
31469
31470
31471
31472
31473
31474
31475
31476
31477
31478
31479
31480
31481
31482
31483
31484
31485
31486
31487
31488
31489
31490
31491
31492
31493
31494
31495
31496
31497
31498
31499
31500
31501
31502
31503
31504
31505
31506
31507
31508
31509
31510
31511
31512
31513
31514
31515
31516
31517
31518
31519
31520
31521
31522
31523
31524
31525
31526
31527
31528
31529
31530
31531
31532
31533
31534
31535
31536
31537
31538
31539
31540
31541
31542
31543
31544
31545
31546
31547
31548
31549
31550
31551
31552
31553
31554
31555
31556
31557
31558
31559
31560
31561
31562
31563
31564
31565
31566
31567
31568
31569
31570
31571
31572
31573
31574
31575
31576
31577
31578
31579
31580
31581
31582
31583
31584
31585
31586
31587
31588
31589
31590
31591
31592
31593
31594
31595
31596
31597
31598
31599
31600
31601
31602
31603
31604
31605
31606
31607
31608
31609
31610
31611
31612
31613
31614
31615
31616
31617
31618
31619
31620
31621
31622
31623
31624
31625
31626
31627
31628
31629
31630
31631
31632
31633
31634
31635
31636
31637
31638
31639
31640
31641
31642
31643
31644
31645
31646
31647
31648
31649
31650
31651
31652
31653
31654
31655
31656
31657
31658
31659
31660
31661
31662
31663
31664
31665
31666
31667
31668
31669
31670
31671
31672
31673
31674
31675
31676
31677
31678
31679
31680
31681
31682
31683
31684
31685
31686
31687
31688
31689
31690
31691
31692
31693
31694
31695
31696
31697
31698
31699
31700
31701
31702
31703
31704
31705
31706
31707
31708
31709
31710
31711
31712
31713
31714
31715
31716
31717
31718
31719
31720
31721
31722
31723
31724
31725
31726
31727
31728
31729
31730
31731
31732
31733
31734
31735
31736
31737
31738
31739
31740
31741
31742
31743
31744
31745
31746
31747
31748
31749
31750
31751
31752
31753
31754
31755
31756
31757
31758
31759
31760
31761
31762
31763
31764
31765
31766
31767
31768
31769
31770
31771
31772
31773
31774
31775
31776
31777
31778
31779
31780
31781
31782
31783
31784
31785
31786
31787
31788
31789
31790
31791
31792
31793
31794
31795
31796
31797
31798
31799
31800
31801
31802
31803
31804
31805
31806
31807
31808
31809
31810
31811
31812
31813
31814
31815
31816
31817
31818
31819
31820
31821
31822
31823
31824
31825
31826
31827
31828
31829
31830
31831
31832
31833
31834
31835
31836
31837
31838
31839
31840
31841
31842
31843
31844
31845
31846
31847
31848
31849
31850
31851
31852
31853
31854
31855
31856
31857
31858
31859
31860
31861
31862
31863
31864
31865
31866
31867
31868
31869
31870
31871
31872
31873
31874
31875
31876
31877
31878
31879
31880
31881
31882
31883
31884
31885
31886
31887
31888
31889
31890
31891
31892
31893
31894
31895
31896
31897
31898
31899
31900
31901
31902
31903
31904
31905
31906
31907
31908
31909
31910
31911
31912
31913
31914
31915
31916
31917
31918
31919
31920
31921
31922
31923
31924
31925
31926
31927
31928
31929
31930
31931
31932
31933
31934
31935
31936
31937
31938
31939
31940
31941
31942
31943
31944
31945
31946
31947
31948
31949
31950
31951
31952
31953
31954
31955
31956
31957
31958
31959
31960
31961
31962
31963
31964
31965
31966
31967
31968
31969
31970
31971
31972
31973
31974
31975
31976
31977
31978
31979
31980
31981
31982
31983
31984
31985
31986
31987
31988
31989
31990
31991
31992
31993
31994
31995
31996
31997
31998
31999
32000
32001
32002
32003
32004
32005
32006
32007
32008
32009
32010
32011
32012
32013
32014
32015
32016
32017
32018
32019
32020
32021
32022
32023
32024
32025
32026
32027
32028
32029
32030
32031
32032
32033
32034
32035
32036
32037
32038
32039
32040
32041
32042
32043
32044
32045
32046
32047
32048
32049
32050
32051
32052
32053
32054
32055
32056
32057
32058
32059
32060
32061
32062
32063
32064
32065
32066
32067
32068
32069
32070
32071
32072
32073
32074
32075
32076
32077
32078
32079
32080
32081
32082
32083
32084
32085
32086
32087
32088
32089
32090
32091
32092
32093
32094
32095
32096
32097
32098
32099
32100
32101
32102
32103
32104
32105
32106
32107
32108
32109
32110
32111
32112
32113
32114
32115
32116
32117
32118
32119
32120
32121
32122
32123
32124
32125
32126
32127
32128
32129
32130
32131
32132
32133
32134
32135
32136
32137
32138
32139
32140
32141
32142
32143
32144
32145
32146
32147
32148
32149
32150
32151
32152
32153
32154
32155
32156
32157
32158
32159
32160
32161
32162
32163
32164
32165
32166
32167
32168
32169
32170
32171
32172
32173
32174
32175
32176
32177
32178
32179
32180
32181
32182
32183
32184
32185
32186
32187
32188
32189
32190
32191
32192
32193
32194
32195
32196
32197
32198
32199
32200
32201
32202
32203
32204
32205
32206
32207
32208
32209
32210
32211
32212
32213
32214
32215
32216
32217
32218
32219
32220
32221
32222
32223
32224
32225
32226
32227
32228
32229
32230
32231
32232
32233
32234
32235
32236
32237
32238
32239
32240
32241
32242
32243
32244
32245
32246
32247
32248
32249
32250
32251
32252
32253
32254
32255
32256
32257
32258
32259
32260
32261
32262
32263
32264
32265
32266
32267
32268
32269
32270
32271
32272
32273
32274
32275
32276
32277
32278
32279
32280
32281
32282
32283
32284
32285
32286
32287
32288
32289
32290
32291
32292
32293
32294
32295
32296
32297
32298
32299
32300
32301
32302
32303
32304
32305
32306
32307
32308
32309
32310
32311
32312
32313
32314
32315
32316
32317
32318
32319
32320
32321
32322
32323
32324
32325
32326
32327
32328
32329
32330
32331
32332
32333
32334
32335
32336
32337
32338
32339
32340
32341
32342
32343
32344
32345
32346
32347
32348
32349
32350
32351
32352
32353
32354
32355
32356
32357
32358
32359
32360
32361
32362
32363
32364
32365
32366
32367
32368
32369
32370
32371
32372
32373
32374
32375
32376
32377
32378
32379
32380
32381
32382
32383
32384
32385
32386
32387
32388
32389
32390
32391
32392
32393
32394
32395
32396
32397
32398
32399
32400
32401
32402
32403
32404
32405
32406
32407
32408
32409
32410
32411
32412
32413
32414
32415
32416
32417
32418
32419
32420
32421
32422
32423
32424
32425
32426
32427
32428
32429
32430
32431
32432
32433
32434
32435
32436
32437
32438
32439
32440
32441
32442
32443
32444
32445
32446
32447
32448
32449
32450
32451
32452
32453
32454
32455
32456
32457
32458
32459
32460
32461
32462
32463
32464
32465
32466
32467
32468
32469
32470
32471
32472
32473
32474
32475
32476
32477
32478
32479
32480
32481
32482
32483
32484
32485
32486
32487
32488
32489
32490
32491
32492
32493
32494
32495
32496
32497
32498
32499
32500
32501
32502
32503
32504
32505
32506
32507
32508
32509
32510
32511
32512
32513
32514
32515
32516
32517
32518
32519
32520
32521
32522
32523
32524
32525
32526
32527
32528
32529
32530
32531
32532
32533
32534
32535
32536
32537
32538
32539
32540
32541
32542
32543
32544
32545
32546
32547
32548
32549
32550
32551
32552
32553
32554
32555
32556
32557
32558
32559
32560
32561
32562
32563
32564
32565
32566
32567
32568
32569
32570
32571
32572
32573
32574
32575
32576
32577
32578
32579
32580
32581
32582
32583
32584
32585
32586
32587
32588
32589
32590
32591
32592
32593
32594
32595
32596
32597
32598
32599
32600
32601
32602
32603
32604
32605
32606
32607
32608
32609
32610
32611
32612
32613
32614
32615
32616
32617
32618
32619
32620
32621
32622
32623
32624
32625
32626
32627
32628
32629
32630
32631
32632
32633
32634
32635
32636
32637
32638
32639
32640
32641
32642
32643
32644
32645
32646
32647
32648
32649
32650
32651
32652
32653
32654
32655
32656
32657
32658
32659
32660
32661
32662
32663
32664
32665
32666
32667
32668
32669
32670
32671
32672
32673
32674
32675
32676
32677
32678
32679
32680
32681
32682
32683
32684
32685
32686
32687
32688
32689
32690
32691
32692
32693
32694
32695
32696
32697
32698
32699
32700
32701
32702
32703
32704
32705
32706
32707
32708
32709
32710
32711
32712
32713
32714
32715
32716
32717
32718
32719
32720
32721
32722
32723
32724
32725
32726
32727
32728
32729
32730
32731
32732
32733
32734
32735
32736
32737
32738
32739
32740
32741
32742
32743
32744
32745
32746
32747
32748
32749
32750
32751
32752
32753
32754
32755
32756
32757
32758
32759
32760
32761
32762
32763
32764
32765
32766
32767
32768
32769
32770
32771
32772
32773
32774
32775
32776
32777
32778
32779
32780
32781
32782
32783
32784
32785
32786
32787
32788
32789
32790
32791
32792
32793
32794
32795
32796
32797
32798
32799
32800
32801
32802
32803
32804
32805
32806
32807
32808
32809
32810
32811
32812
32813
32814
32815
32816
32817
32818
32819
32820
32821
32822
32823
32824
32825
32826
32827
32828
32829
32830
32831
32832
32833
32834
32835
32836
32837
32838
32839
32840
32841
32842
32843
32844
32845
32846
32847
32848
32849
32850
32851
32852
32853
32854
32855
32856
32857
32858
32859
32860
32861
32862
32863
32864
32865
32866
32867
32868
32869
32870
32871
32872
32873
32874
32875
32876
32877
32878
32879
32880
32881
32882
32883
32884
32885
32886
32887
32888
32889
32890
32891
32892
32893
32894
32895
32896
32897
32898
32899
32900
32901
32902
32903
32904
32905
32906
32907
32908
32909
32910
32911
32912
32913
32914
32915
32916
32917
32918
32919
32920
32921
32922
32923
32924
32925
32926
32927
32928
32929
32930
32931
32932
32933
32934
32935
32936
32937
32938
32939
32940
32941
32942
32943
32944
32945
32946
32947
32948
32949
32950
32951
32952
32953
32954
32955
32956
32957
32958
32959
32960
32961
32962
32963
32964
32965
32966
32967
32968
32969
32970
32971
32972
32973
32974
32975
32976
32977
32978
32979
32980
32981
32982
32983
32984
32985
32986
32987
32988
32989
32990
32991
32992
32993
32994
32995
32996
32997
32998
32999
33000
33001
33002
33003
33004
33005
33006
33007
33008
33009
33010
33011
33012
33013
33014
33015
33016
33017
33018
33019
33020
33021
33022
33023
33024
33025
33026
33027
33028
33029
33030
33031
33032
33033
33034
33035
33036
33037
33038
33039
33040
33041
33042
33043
33044
33045
33046
33047
33048
33049
33050
33051
33052
33053
33054
33055
33056
33057
33058
33059
33060
33061
33062
33063
33064
33065
33066
33067
33068
33069
33070
33071
33072
33073
33074
33075
33076
33077
33078
33079
33080
33081
33082
33083
33084
33085
33086
33087
33088
33089
33090
33091
33092
33093
33094
33095
33096
33097
33098
33099
33100
33101
33102
33103
33104
33105
33106
33107
33108
33109
33110
33111
33112
33113
33114
33115
33116
33117
33118
33119
33120
33121
33122
33123
33124
33125
33126
33127
33128
33129
33130
33131
33132
33133
33134
33135
33136
33137
33138
33139
33140
33141
33142
33143
33144
33145
33146
33147
33148
33149
33150
33151
33152
33153
33154
33155
33156
33157
33158
33159
33160
33161
33162
33163
33164
33165
33166
33167
33168
33169
33170
33171
33172
33173
33174
33175
33176
33177
33178
33179
33180
33181
33182
33183
33184
33185
33186
33187
33188
33189
33190
33191
33192
33193
33194
33195
33196
33197
33198
33199
33200
33201
33202
33203
33204
33205
33206
33207
33208
33209
33210
33211
33212
33213
33214
33215
33216
33217
33218
33219
33220
33221
33222
33223
33224
33225
33226
33227
33228
33229
33230
33231
33232
33233
33234
33235
33236
33237
33238
33239
33240
33241
33242
33243
33244
33245
33246
33247
33248
33249
33250
33251
33252
33253
33254
33255
33256
33257
33258
33259
33260
33261
33262
33263
33264
33265
33266
33267
33268
33269
33270
33271
33272
33273
33274
33275
33276
33277
33278
33279
33280
33281
33282
33283
33284
33285
33286
33287
33288
33289
33290
33291
33292
33293
33294
33295
33296
33297
33298
33299
33300
33301
33302
33303
33304
33305
33306
33307
33308
33309
33310
33311
33312
33313
33314
33315
33316
33317
33318
33319
33320
33321
33322
33323
33324
33325
33326
33327
33328
33329
33330
33331
33332
33333
33334
33335
33336
33337
33338
33339
33340
33341
33342
33343
33344
33345
33346
33347
33348
33349
33350
33351
33352
33353
33354
33355
33356
33357
33358
33359
33360
33361
33362
33363
33364
33365
33366
33367
33368
33369
33370
33371
33372
33373
33374
33375
33376
33377
33378
33379
33380
33381
33382
33383
33384
33385
33386
33387
33388
33389
33390
33391
33392
33393
33394
33395
33396
33397
33398
33399
33400
33401
33402
33403
33404
33405
33406
33407
33408
33409
33410
33411
33412
33413
33414
33415
33416
33417
33418
33419
33420
33421
33422
33423
33424
33425
33426
33427
33428
33429
33430
33431
33432
33433
33434
33435
33436
33437
33438
33439
33440
33441
33442
33443
33444
33445
33446
33447
33448
33449
33450
33451
33452
33453
33454
33455
33456
33457
33458
33459
33460
33461
33462
33463
33464
33465
33466
33467
33468
33469
33470
33471
33472
33473
33474
33475
33476
33477
33478
33479
33480
33481
33482
33483
33484
33485
33486
33487
33488
33489
33490
33491
33492
33493
33494
33495
33496
33497
33498
33499
33500
33501
33502
33503
33504
33505
33506
33507
33508
33509
33510
33511
33512
33513
33514
33515
33516
33517
33518
33519
33520
33521
33522
33523
33524
33525
33526
33527
33528
33529
33530
33531
33532
33533
33534
33535
33536
33537
33538
33539
33540
33541
33542
33543
33544
33545
33546
33547
33548
33549
33550
33551
33552
33553
33554
33555
33556
33557
33558
33559
33560
33561
33562
33563
33564
33565
33566
33567
33568
33569
33570
33571
33572
33573
33574
33575
33576
33577
33578
33579
33580
33581
33582
33583
33584
33585
33586
33587
33588
33589
33590
33591
33592
33593
33594
33595
33596
33597
33598
33599
33600
33601
33602
33603
33604
33605
33606
33607
33608
33609
33610
33611
33612
33613
33614
33615
33616
33617
33618
33619
33620
33621
33622
33623
33624
33625
33626
33627
33628
33629
33630
33631
33632
33633
33634
33635
33636
33637
33638
33639
33640
33641
33642
33643
33644
33645
33646
33647
33648
33649
33650
33651
33652
33653
33654
33655
33656
33657
33658
33659
33660
33661
33662
33663
33664
33665
33666
33667
33668
33669
33670
33671
33672
33673
33674
33675
33676
33677
33678
33679
33680
33681
33682
33683
33684
33685
33686
33687
33688
33689
33690
33691
33692
33693
33694
33695
33696
33697
33698
33699
33700
33701
33702
33703
33704
33705
33706
33707
33708
33709
33710
33711
33712
33713
33714
33715
33716
33717
33718
33719
33720
33721
33722
33723
33724
33725
33726
33727
33728
33729
33730
33731
33732
33733
33734
33735
33736
33737
33738
33739
33740
33741
33742
33743
33744
33745
33746
33747
33748
33749
33750
33751
33752
33753
33754
33755
33756
33757
33758
33759
33760
33761
33762
33763
33764
33765
33766
33767
33768
33769
33770
33771
33772
33773
33774
33775
33776
33777
33778
33779
33780
33781
33782
33783
33784
33785
33786
33787
33788
33789
33790
33791
33792
33793
33794
33795
33796
33797
33798
33799
33800
33801
33802
33803
33804
33805
33806
33807
33808
33809
33810
33811
33812
33813
33814
33815
33816
33817
33818
33819
33820
33821
33822
33823
33824
33825
33826
33827
33828
33829
33830
33831
33832
33833
33834
33835
33836
33837
33838
33839
33840
33841
33842
33843
33844
33845
33846
33847
33848
33849
33850
33851
33852
33853
33854
33855
33856
33857
33858
33859
33860
33861
33862
33863
33864
33865
33866
33867
33868
33869
33870
33871
33872
33873
33874
33875
33876
33877
33878
33879
33880
33881
33882
33883
33884
33885
33886
33887
33888
33889
33890
33891
33892
33893
33894
33895
33896
33897
33898
33899
33900
33901
33902
33903
33904
33905
33906
33907
33908
33909
33910
33911
33912
33913
33914
33915
33916
33917
33918
33919
33920
33921
33922
33923
33924
33925
33926
33927
33928
33929
33930
33931
33932
33933
33934
33935
33936
33937
33938
33939
33940
33941
33942
33943
33944
33945
33946
33947
33948
33949
33950
33951
33952
33953
33954
33955
33956
33957
33958
33959
33960
33961
33962
33963
33964
33965
33966
33967
33968
33969
33970
33971
33972
33973
33974
33975
33976
33977
33978
33979
33980
33981
33982
33983
33984
33985
33986
33987
33988
33989
33990
33991
33992
33993
33994
33995
33996
33997
33998
33999
34000
34001
34002
34003
34004
34005
34006
34007
34008
34009
34010
34011
34012
34013
34014
34015
34016
34017
34018
34019
34020
34021
34022
34023
34024
34025
34026
34027
34028
34029
34030
34031
34032
34033
34034
34035
34036
34037
34038
34039
34040
34041
34042
34043
34044
34045
34046
34047
34048
34049
34050
34051
34052
34053
34054
34055
34056
34057
34058
34059
34060
34061
34062
34063
34064
34065
34066
34067
34068
34069
34070
34071
34072
34073
34074
34075
34076
34077
34078
34079
34080
34081
34082
34083
34084
34085
34086
34087
34088
34089
34090
34091
34092
34093
34094
34095
34096
34097
34098
34099
34100
34101
34102
34103
34104
34105
34106
34107
34108
34109
34110
34111
34112
34113
34114
34115
34116
34117
34118
34119
34120
34121
34122
34123
34124
34125
34126
34127
34128
34129
34130
34131
34132
34133
34134
34135
34136
34137
34138
34139
34140
34141
34142
34143
34144
34145
34146
34147
34148
34149
34150
34151
34152
34153
34154
34155
34156
34157
34158
34159
34160
34161
34162
34163
34164
34165
34166
34167
34168
34169
34170
34171
34172
34173
34174
34175
34176
34177
34178
34179
34180
34181
34182
34183
34184
34185
34186
34187
34188
34189
34190
34191
34192
34193
34194
34195
34196
34197
34198
34199
34200
34201
34202
34203
34204
34205
34206
34207
34208
34209
34210
34211
34212
34213
34214
34215
34216
34217
34218
34219
34220
34221
34222
34223
34224
34225
34226
34227
34228
34229
34230
34231
34232
34233
34234
34235
34236
34237
34238
34239
34240
34241
34242
34243
34244
34245
34246
34247
34248
34249
34250
34251
34252
34253
34254
34255
34256
34257
34258
34259
34260
34261
34262
34263
34264
34265
34266
34267
34268
34269
34270
34271
34272
34273
34274
34275
34276
34277
34278
34279
34280
34281
34282
34283
34284
34285
34286
34287
34288
34289
34290
34291
34292
34293
34294
34295
34296
34297
34298
34299
34300
34301
34302
34303
34304
34305
34306
34307
34308
34309
34310
34311
34312
34313
34314
34315
34316
34317
34318
34319
34320
34321
34322
34323
34324
34325
34326
34327
34328
34329
34330
34331
34332
34333
34334
34335
34336
34337
34338
34339
34340
34341
34342
34343
34344
34345
34346
34347
34348
34349
34350
34351
34352
34353
34354
34355
34356
34357
34358
34359
34360
34361
34362
34363
34364
34365
34366
34367
34368
34369
34370
34371
34372
34373
34374
34375
34376
34377
34378
34379
34380
34381
34382
34383
34384
34385
34386
34387
34388
34389
34390
34391
34392
34393
34394
34395
34396
34397
34398
34399
34400
34401
34402
34403
34404
34405
34406
34407
34408
34409
34410
34411
34412
34413
34414
34415
34416
34417
34418
34419
34420
34421
34422
34423
34424
34425
34426
34427
34428
34429
34430
34431
34432
34433
34434
34435
34436
34437
34438
34439
34440
34441
34442
34443
34444
34445
34446
34447
34448
34449
34450
34451
34452
34453
34454
34455
34456
34457
34458
34459
34460
34461
34462
34463
34464
34465
34466
34467
34468
34469
34470
34471
34472
34473
34474
34475
34476
34477
34478
34479
34480
34481
34482
34483
34484
34485
34486
34487
34488
34489
34490
34491
34492
34493
34494
34495
34496
34497
34498
34499
34500
34501
34502
34503
34504
34505
34506
34507
34508
34509
34510
34511
34512
34513
34514
34515
34516
34517
34518
34519
34520
34521
34522
34523
34524
34525
34526
34527
34528
34529
34530
34531
34532
34533
34534
34535
34536
34537
34538
34539
34540
34541
34542
34543
34544
34545
34546
34547
34548
34549
34550
34551
34552
34553
34554
34555
34556
34557
34558
34559
34560
34561
34562
34563
34564
34565
34566
34567
34568
34569
34570
34571
34572
34573
34574
34575
34576
34577
34578
34579
34580
34581
34582
34583
34584
34585
34586
34587
34588
34589
34590
34591
34592
34593
34594
34595
34596
34597
34598
34599
34600
34601
34602
34603
34604
34605
34606
34607
34608
34609
34610
34611
34612
34613
34614
34615
34616
34617
34618
34619
34620
34621
34622
34623
34624
34625
34626
34627
34628
34629
34630
34631
34632
34633
34634
34635
34636
34637
34638
34639
34640
34641
34642
34643
34644
34645
34646
34647
34648
34649
34650
34651
34652
34653
34654
34655
34656
34657
34658
34659
34660
34661
34662
34663
34664
34665
34666
34667
34668
34669
34670
34671
34672
34673
34674
34675
34676
34677
34678
34679
34680
34681
34682
34683
34684
34685
34686
34687
34688
34689
34690
34691
34692
34693
34694
34695
34696
34697
34698
34699
34700
34701
34702
34703
34704
34705
34706
34707
34708
34709
34710
34711
34712
34713
34714
34715
34716
34717
34718
34719
34720
34721
34722
34723
34724
34725
34726
34727
34728
34729
34730
34731
34732
34733
34734
34735
34736
34737
34738
34739
34740
34741
34742
34743
34744
34745
34746
34747
34748
34749
34750
34751
34752
34753
34754
34755
34756
34757
34758
34759
34760
34761
34762
34763
34764
34765
34766
34767
34768
34769
34770
34771
34772
34773
34774
34775
34776
34777
34778
34779
34780
34781
34782
34783
34784
34785
34786
34787
34788
34789
34790
34791
34792
34793
34794
34795
34796
34797
34798
34799
34800
34801
34802
34803
34804
34805
34806
34807
34808
34809
34810
34811
34812
34813
34814
34815
34816
34817
34818
34819
34820
34821
34822
34823
34824
34825
34826
34827
34828
34829
34830
34831
34832
34833
34834
34835
34836
34837
34838
34839
34840
34841
34842
34843
34844
34845
34846
34847
34848
34849
34850
34851
34852
34853
34854
34855
34856
34857
34858
34859
34860
34861
34862
34863
34864
34865
34866
34867
34868
34869
34870
34871
34872
34873
34874
34875
34876
34877
34878
34879
34880
34881
34882
34883
34884
34885
34886
34887
34888
34889
34890
34891
34892
34893
34894
34895
34896
34897
34898
34899
34900
34901
34902
34903
34904
34905
34906
34907
34908
34909
34910
34911
34912
34913
34914
34915
34916
34917
34918
34919
34920
34921
34922
34923
34924
34925
34926
34927
34928
34929
34930
34931
34932
34933
34934
34935
34936
34937
34938
34939
34940
34941
34942
34943
34944
34945
34946
34947
34948
34949
34950
34951
34952
34953
34954
34955
34956
34957
34958
34959
34960
34961
34962
34963
34964
34965
34966
34967
34968
34969
34970
34971
34972
34973
34974
34975
34976
34977
34978
34979
34980
34981
34982
34983
34984
34985
34986
34987
34988
34989
34990
34991
34992
34993
34994
34995
34996
34997
34998
34999
35000
35001
35002
35003
35004
35005
35006
35007
35008
35009
35010
35011
35012
35013
35014
35015
35016
35017
35018
35019
35020
35021
35022
35023
35024
35025
35026
35027
35028
35029
35030
35031
35032
35033
35034
35035
35036
35037
35038
35039
35040
35041
35042
35043
35044
35045
35046
35047
35048
35049
35050
35051
35052
35053
35054
35055
35056
35057
35058
35059
35060
35061
35062
35063
35064
35065
35066
35067
35068
35069
35070
35071
35072
35073
35074
35075
35076
35077
35078
35079
35080
35081
35082
35083
35084
35085
35086
35087
35088
35089
35090
35091
35092
35093
35094
35095
35096
35097
35098
35099
35100
35101
35102
35103
35104
35105
35106
35107
35108
35109
35110
35111
35112
35113
35114
35115
35116
35117
35118
35119
35120
35121
35122
35123
35124
35125
35126
35127
35128
35129
35130
35131
35132
35133
35134
35135
35136
35137
35138
35139
35140
35141
35142
35143
35144
35145
35146
35147
35148
35149
35150
35151
35152
35153
35154
35155
35156
35157
35158
35159
35160
35161
35162
35163
35164
35165
35166
35167
35168
35169
35170
35171
35172
35173
35174
35175
35176
35177
35178
35179
35180
35181
35182
35183
35184
35185
35186
35187
35188
35189
35190
35191
35192
35193
35194
35195
35196
35197
35198
35199
35200
35201
35202
35203
35204
35205
35206
35207
35208
35209
35210
35211
35212
35213
35214
35215
35216
35217
35218
35219
35220
35221
35222
35223
35224
35225
35226
35227
35228
35229
35230
35231
35232
35233
35234
35235
35236
35237
35238
35239
35240
35241
35242
35243
35244
35245
35246
35247
35248
35249
35250
35251
35252
35253
35254
35255
35256
35257
35258
35259
35260
35261
35262
35263
35264
35265
35266
35267
35268
35269
35270
35271
35272
35273
35274
35275
35276
35277
35278
35279
35280
35281
35282
35283
35284
35285
35286
35287
35288
35289
35290
35291
35292
35293
35294
35295
35296
35297
35298
35299
35300
35301
35302
35303
35304
35305
35306
35307
35308
35309
35310
35311
35312
35313
35314
35315
35316
35317
35318
35319
35320
35321
35322
35323
35324
35325
35326
35327
35328
35329
35330
35331
35332
35333
35334
35335
35336
35337
35338
35339
35340
35341
35342
35343
35344
35345
35346
35347
35348
35349
35350
35351
35352
35353
35354
35355
35356
35357
35358
35359
35360
35361
35362
35363
35364
35365
35366
35367
35368
35369
35370
35371
35372
35373
35374
35375
35376
35377
35378
35379
35380
35381
35382
35383
35384
35385
35386
35387
35388
35389
35390
35391
35392
35393
35394
35395
35396
35397
35398
35399
35400
35401
35402
35403
35404
35405
35406
35407
35408
35409
35410
35411
35412
35413
35414
35415
35416
35417
35418
35419
35420
35421
35422
35423
35424
35425
35426
35427
35428
35429
35430
35431
35432
35433
35434
35435
35436
35437
35438
35439
35440
35441
35442
35443
35444
35445
35446
35447
35448
35449
35450
35451
35452
|
% $Id: mp.w 2103 2016-11-25 13:03:37Z luigi $
%
% This file is part of MetaPost;
% the MetaPost program is in the public domain.
% See the <Show version...> code in mpost.w for more info.
% Here is TeX material that gets inserted after \input webmac
\def\hang{\hangindent 3em\noindent\ignorespaces}
\def\textindent#1{\hangindent2.5em\noindent\hbox to2.5em{\hss#1 }\ignorespaces}
\def\ps{PostScript}
\def\psqrt#1{\sqrt{\mathstrut#1}}
\def\k{_{k+1}}
\def\pct!{{\char`\%}} % percent sign in ordinary text
\font\tenlogo=logo10 % font used for the METAFONT logo
\font\logos=logosl10
\def\MF{{\tenlogo META}\-{\tenlogo FONT}}
\def\MP{{\tenlogo META}\-{\tenlogo POST}}
\def\<#1>{$\langle#1\rangle$}
\def\section{\mathhexbox278}
\let\swap=\leftrightarrow
\def\round{\mathop{\rm round}\nolimits}
\mathchardef\vbv="026A % synonym for `\|'
\def\vb{\relax\ifmmode\vbv\else$\vbv$\fi}
\def\(#1){} % this is used to make section names sort themselves better
\def\9#1{} % this is used for sort keys in the index via @@:sort key}{entry@@>
\def\title{MetaPost}
\pdfoutput=1
\pageno=3
@* Introduction.
This is \MP\ by John Hobby, a graphics-language processor based on D. E. Knuth's \MF.
Much of the original Pascal version of this program was copied with
permission from MF.web Version 1.9. It interprets a language very
similar to D.E. Knuth's METAFONT, but with changes designed to make it
more suitable for PostScript output.
The main purpose of the following program is to explain the algorithms of \MP\
as clearly as possible. However, the program has been written so that it
can be tuned to run efficiently in a wide variety of operating environments
by making comparatively few changes. Such flexibility is possible because
the documentation that follows is written in the \.{WEB} language, which is
at a higher level than C.
A large piece of software like \MP\ has inherent complexity that cannot
be reduced below a certain level of difficulty, although each individual
part is fairly simple by itself. The \.{WEB} language is intended to make
the algorithms as readable as possible, by reflecting the way the
individual program pieces fit together and by providing the
cross-references that connect different parts. Detailed comments about
what is going on, and about why things were done in certain ways, have
been liberally sprinkled throughout the program. These comments explain
features of the implementation, but they rarely attempt to explain the
\MP\ language itself, since the reader is supposed to be familiar with
{\sl The {\logos METAFONT\/}book} as well as the manual
@.WEB@>
@:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
{\sl A User's Manual for MetaPost}, Computing Science Technical Report 162,
AT\AM T Bell Laboratories.
@ The present implementation is a preliminary version, but the possibilities
for new features are limited by the desire to remain as nearly compatible
with \MF\ as possible.
On the other hand, the \.{WEB} description can be extended without changing
the core of the program, and it has been designed so that such
extensions are not extremely difficult to make.
The |banner| string defined here should be changed whenever \MP\
undergoes any modifications, so that it will be clear which version of
\MP\ might be the guilty party when a problem arises.
@^extensions to \MP@>
@^system dependencies@>
@d default_banner "This is MetaPost, Version 1.9991" /* printed when \MP\ starts */
@d true 1
@d false 0
@<Metapost version header@>=
#define metapost_version "1.9991"
@ The external library header for \MP\ is |mplib.h|. It contains a
few typedefs and the header defintions for the externally used
fuctions.
The most important of the typedefs is the definition of the structure
|MP_options|, that acts as a small, configurable front-end to the fairly
large |MP_instance| structure.
@(mplib.h@>=
#ifndef MPLIB_H
#define MPLIB_H 1
#include <stdlib.h>
#ifndef HAVE_BOOLEAN
typedef int boolean;
#endif
@<Metapost version header@>
typedef struct MP_instance *MP;
@<Exported types@>
typedef struct MP_options {
@<Option variables@>
} MP_options;
@<Exported function headers@>
@<MPlib header stuff@>
#endif
@ The internal header file is much longer: it not only lists the complete
|MP_instance|, but also a lot of functions that have to be available to
the \ps\ backend, that is defined in a separate \.{WEB} file.
The variables from |MP_options| are included inside the |MP_instance|
wholesale.
@(mpmp.h@>=
#ifndef MPMP_H
#define MPMP_H 1
#include "avl.h"
#include "mplib.h"
#include <setjmp.h>
typedef struct psout_data_struct *psout_data;
typedef struct svgout_data_struct *svgout_data;
typedef struct pngout_data_struct *pngout_data;
#ifndef HAVE_BOOLEAN
typedef int boolean;
#endif
#ifndef INTEGER_TYPE
typedef int integer;
#endif
@<Declare helpers@>;
@<Enumeration types@>;
@<Types in the outer block@>;
@<Constants in the outer block@>;
typedef struct MP_instance {
@<Option variables@>
@<Global variables@>
} MP_instance;
@<Internal library declarations@>
@<MPlib internal header stuff@>
#endif
@ @c
/*#define DEBUGENVELOPE */
#ifdef DEBUGENVELOPE
static int DEBUGENVELOPECOUNTER=0;
#define dbg_str(A) printf("\n--[==[%03d DEBUGENVELOPE ]==] %s", DEBUGENVELOPECOUNTER++, #A)
#define dbg_n(A) printf("\n--[==[%03d DEBUGENVELOPE ]==] ['%s']=%s, ", DEBUGENVELOPECOUNTER++, #A, number_tostring(A))
#define dbg_in(A) printf("\n--[==[%03d DEBUGENVELOPE ]==] ['%s']=%d, ", DEBUGENVELOPECOUNTER++, #A, (int)(A))
#define dbg_dn(A) printf("\n--[==[%03d DEBUGENVELOPE ]==] ['%s']=%.100f, ",DEBUGENVELOPECOUNTER++, #A, (double)(A))
#define dbg_key(A) printf("\n--[==[%03d DEBUGENVELOPE ]==] ['%s']= ", DEBUGENVELOPECOUNTER++, #A)
#define dbg_key_nval(K,V) printf("\n--[==[%03d DEBUGENVELOPE ]==] ['%s']=%s", DEBUGENVELOPECOUNTER++, #K,number_tostring(V))
#define dbg_key_ival(K,V) printf("\n--[==[%03d DEBUGENVELOPE ]==] ['%s']=%d", DEBUGENVELOPECOUNTER++, #K,(int)(V))
#define dbg_key_dval(K,V) printf("\n--[==[%03d DEBUGENVELOPE ]==] ['%s']=%.100f", DEBUGENVELOPECOUNTER++, #K,(double)(V))
#define dbg_comment(A) printf("\n--[==[%03d DEBUGENVELOPE ]==] --[==[%s]==]", DEBUGENVELOPECOUNTER++, #A)
#define dbg_sp printf("\n--[==[%03d DEBUGENVELOPE ]==] ", DEBUGENVELOPECOUNTER++)
#define dbg_open_t printf("\n--[==[%03d DEBUGENVELOPE ]==] {", DEBUGENVELOPECOUNTER++)
#define dbg_close_t printf("\n--[==[%03d DEBUGENVELOPE ]==] }", DEBUGENVELOPECOUNTER++)
#define dbg_comma printf("\n--[==[%03d DEBUGENVELOPE ]==] ,", DEBUGENVELOPECOUNTER++)
#define dbg_nl printf("\n--[==[%03d DEBUGENVELOPE ]==] \n", DEBUGENVELOPECOUNTER++)
#define dbg_CUBIC dbg_n(p->x_coord); dbg_n(p->y_coord); \
dbg_n(p->right_x); dbg_n(p->right_y); \
dbg_n(q->left_x); dbg_n(q->left_y); \
dbg_n(q->x_coord); dbg_n(q->y_coord)
#endif
#define KPATHSEA_DEBUG_H 1
#include <w2c/config.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <assert.h>
#include <math.h>
#ifdef HAVE_UNISTD_H
# include <unistd.h> /* for access */
#endif
#include <time.h> /* for struct tm \& co */
#include <zlib.h> /* for |ZLIB_VERSION|, zlibVersion() */
#include <png.h> /* for |PNG_LIBPNG_VER_STRING|, |png_libpng_ver| */
#include <pixman.h> /* for |PIXMAN_VERSION_STRING|, |pixman_version_string()| */
#include <cairo.h> /* for |CAIRO_VERSION_STRING|, |cairo_version_string()| */
#include <gmp.h> /* for |gmp_version| */
#include <mpfr.h> /* for |MPFR_VERSION_STRING|, |mpfr_get_version()| */
#include "mplib.h"
#include "mplibps.h" /* external header */
#include "mplibsvg.h" /* external header */
#include "mplibpng.h" /* external header */
#include "mpmp.h" /* internal header */
#include "mppsout.h" /* internal header */
#include "mpsvgout.h" /* internal header */
#include "mppngout.h" /* internal header */
#include "mpmath.h" /* internal header */
#include "mpmathdouble.h" /* internal header */
#include "mpmathdecimal.h" /* internal header */
#include "mpmathbinary.h" /* internal header */
#include "mpstrings.h" /* internal header */
/* BEGIN PATCH */
mp_number dx_ap; /* approximation of dx */
mp_number dy_ap; /* approximation of dy */
mp_number dxin_ap; /* approximation of dxin */
mp_number dyin_ap; /* approximation of dyin */
mp_number ueps_ap; /* epsilon for above approximations */
boolean is_dxdy, is_dxindyin;
/* END PATCH */
extern font_number mp_read_font_info (MP mp, char *fname); /* tfmin.w */
@h @<Declarations@>;
@<Basic printing procedures@>;
@<Error handling procedures@>
@ Some debugging support for development. The trick with the variadic macros
probably only works in gcc, as this preprocessor feature was not formalized
until the c99 standard (and that is too new for us). Lets' hope that at least
most compilers understand the non-debug version.
@^system dependencies@>
@<MPlib internal header stuff@>=
/*#define DEBUG 2*/
#if DEBUG
#define debug_number(A) printf("%d: %s=%.32f (%d)\n", __LINE__, #A, number_to_double(A), number_to_scaled(A))
#else
#define debug_number(A)
#endif
#if DEBUG>1
void do_debug_printf(MP mp, const char *prefix, const char *fmt, ...);
# define debug_printf(a1,a2,a3) do_debug_printf(mp, "", a1,a2,a3)
# define FUNCTION_TRACE1(a1) do_debug_printf(mp, "FTRACE: ", a1)
# define FUNCTION_TRACE2(a1,a2) do_debug_printf(mp, "FTRACE: ", a1,a2)
# define FUNCTION_TRACE3(a1,a2,a3) do_debug_printf(mp, "FTRACE: ", a1,a2,a3)
# define FUNCTION_TRACE3X(a1,a2,a3) (void)mp
# define FUNCTION_TRACE4(a1,a2,a3,a4) do_debug_printf(mp, "FTRACE: ", a1,a2,a3,a4)
#else
# define debug_printf(a1,a2,a3)
# define FUNCTION_TRACE1(a1) (void)mp
# define FUNCTION_TRACE2(a1,a2) (void)mp
# define FUNCTION_TRACE3(a1,a2,a3) (void)mp
# define FUNCTION_TRACE3X(a1,a2,a3) (void)mp
# define FUNCTION_TRACE4(a1,a2,a3,a4) (void)mp
#endif
@ This function occasionally crashes (if something is written after the
log file is already closed), but that is not so important while debugging.
@c
#if DEBUG
void do_debug_printf(MP mp, const char *prefix, const char *fmt, ...) ;
void do_debug_printf(MP mp, const char *prefix, const char *fmt, ...) {
va_list ap;
#if 0
va_start (ap, fmt);
if (mp->log_file && !ferror((FILE *)mp->log_file)) {
fputs(prefix, mp->log_file);
vfprintf(mp->log_file, fmt, ap);
}
va_end(ap);
#endif
va_start (ap, fmt);
#if 0
if (mp->term_out && !ferror((FILE *)mp->term_out)) {
#else
if (false) {
#endif
fputs(prefix, mp->term_out);
vfprintf(mp->term_out, fmt, ap);
} else {
fputs(prefix, stdout);
vfprintf(stdout, fmt, ap);
}
va_end(ap);
}
#endif
@ Here are the functions that set up the \MP\ instance.
@<Declarations@>=
MP_options *mp_options (void);
MP mp_initialize (MP_options * opt);
@ @c
MP_options *mp_options (void) {
MP_options *opt;
size_t l = sizeof (MP_options);
opt = malloc (l);
if (opt != NULL) {
memset (opt, 0, l);
}
return opt;
}
@ @<Internal library declarations@>=
@<Declare subroutines for parsing file names@>
@ The whole instance structure is initialized with zeroes,
this greatly reduces the number of statements needed in
the |Allocate or initialize variables| block.
@d set_callback_option(A) do { mp->A = mp_##A;
if (opt->A!=NULL) mp->A = opt->A;
} while (0)
@c
static MP mp_do_new (jmp_buf * buf) {
MP mp = malloc (sizeof (MP_instance));
if (mp == NULL) {
xfree (buf);
return NULL;
}
memset (mp, 0, sizeof (MP_instance));
mp->jump_buf = buf;
return mp;
}
@ @c
static void mp_free (MP mp) {
int k; /* loop variable */
@<Dealloc variables@>;
if (mp->noninteractive) {
@<Finish non-interactive use@>;
}
xfree (mp->jump_buf);
@<Free table entries@>;
free_math();
xfree (mp);
}
@ @c
static void mp_do_initialize (MP mp) {
@<Local variables for initialization@>;
@<Set initial values of key variables@>;
}
@ For the retargetable math library, we need to have a pointer, at least.
@<Global variables@>=
void *math;
@ @<Exported types@>=
typedef enum {
mp_nan_type = 0,
mp_scaled_type,
mp_fraction_type,
mp_angle_type,
mp_double_type,
mp_binary_type,
mp_decimal_type
} mp_number_type;
typedef union {
void *num;
double dval;
int val;
} mp_number_store;
typedef struct mp_number_data {
mp_number_store data;
mp_number_type type;
} mp_number_data;
typedef struct mp_number_data mp_number;
#define is_number(A) ((A).type != mp_nan_type)
typedef void (*convert_func) (mp_number *r);
typedef void (*m_log_func) (MP mp, mp_number *r, mp_number a);
typedef void (*m_exp_func) (MP mp, mp_number *r, mp_number a);
typedef void (*m_unif_rand_func) (MP mp, mp_number *ret, mp_number x_orig);
typedef void (*m_norm_rand_func) (MP mp, mp_number *ret);
typedef void (*pyth_add_func) (MP mp, mp_number *r, mp_number a, mp_number b);
typedef void (*pyth_sub_func) (MP mp, mp_number *r, mp_number a, mp_number b);
typedef void (*n_arg_func) (MP mp, mp_number *r, mp_number a, mp_number b);
typedef void (*velocity_func) (MP mp, mp_number *r, mp_number a, mp_number b, mp_number c, mp_number d, mp_number e);
typedef void (*ab_vs_cd_func) (MP mp, mp_number *r, mp_number a, mp_number b, mp_number c, mp_number d);
typedef void (*crossing_point_func) (MP mp, mp_number *r, mp_number a, mp_number b, mp_number c);
typedef void (*number_from_int_func) (mp_number *A, int B);
typedef void (*number_from_boolean_func) (mp_number *A, int B);
typedef void (*number_from_scaled_func) (mp_number *A, int B);
typedef void (*number_from_double_func) (mp_number *A, double B);
typedef void (*number_from_addition_func) (mp_number *A, mp_number B, mp_number C);
typedef void (*number_from_substraction_func) (mp_number *A, mp_number B, mp_number C);
typedef void (*number_from_div_func) (mp_number *A, mp_number B, mp_number C);
typedef void (*number_from_mul_func) (mp_number *A, mp_number B, mp_number C);
typedef void (*number_from_int_div_func) (mp_number *A, mp_number B, int C);
typedef void (*number_from_int_mul_func) (mp_number *A, mp_number B, int C);
typedef void (*number_from_oftheway_func) (MP mp, mp_number *A, mp_number t, mp_number B, mp_number C);
typedef void (*number_negate_func) (mp_number *A);
typedef void (*number_add_func) (mp_number *A, mp_number B);
typedef void (*number_substract_func) (mp_number *A, mp_number B);
typedef void (*number_modulo_func) (mp_number *A, mp_number B);
typedef void (*number_half_func) (mp_number *A);
typedef void (*number_halfp_func) (mp_number *A);
typedef void (*number_double_func) (mp_number *A);
typedef void (*number_abs_func) (mp_number *A);
typedef void (*number_clone_func) (mp_number *A, mp_number B);
typedef void (*number_swap_func) (mp_number *A, mp_number *B);
typedef void (*number_add_scaled_func) (mp_number *A, int b);
typedef void (*number_multiply_int_func) (mp_number *A, int b);
typedef void (*number_divide_int_func) (mp_number *A, int b);
typedef int (*number_to_int_func) (mp_number A);
typedef int (*number_to_boolean_func) (mp_number A);
typedef int (*number_to_scaled_func) (mp_number A);
typedef int (*number_round_func) (mp_number A);
typedef void (*number_floor_func) (mp_number *A);
typedef double (*number_to_double_func) (mp_number A);
typedef int (*number_odd_func) (mp_number A);
typedef int (*number_equal_func) (mp_number A, mp_number B);
typedef int (*number_less_func) (mp_number A, mp_number B);
typedef int (*number_greater_func) (mp_number A, mp_number B);
typedef int (*number_nonequalabs_func) (mp_number A, mp_number B);
typedef void (*make_scaled_func) (MP mp, mp_number *ret, mp_number A, mp_number B);
typedef void (*make_fraction_func) (MP mp, mp_number *ret, mp_number A, mp_number B);
typedef void (*take_fraction_func) (MP mp, mp_number *ret, mp_number A, mp_number B);
typedef void (*take_scaled_func) (MP mp, mp_number *ret, mp_number A, mp_number B);
typedef void (*sin_cos_func) (MP mp, mp_number A, mp_number *S, mp_number *C);
typedef void (*slow_add_func) (MP mp, mp_number *A, mp_number S, mp_number C);
typedef void (*sqrt_func) (MP mp, mp_number *ret, mp_number A);
typedef void (*init_randoms_func) (MP mp, int seed);
typedef void (*new_number_func) (MP mp, mp_number *A, mp_number_type t);
typedef void (*free_number_func) (MP mp, mp_number *n);
typedef void (*fraction_to_round_scaled_func) (mp_number *n);
typedef void (*print_func) (MP mp, mp_number A);
typedef char * (*tostring_func) (MP mp, mp_number A);
typedef void (*scan_func) (MP mp, int A);
typedef void (*mp_free_func) (MP mp);
typedef void (*set_precision_func) (MP mp);
typedef struct math_data {
mp_number precision_default;
mp_number precision_max;
mp_number precision_min;
mp_number epsilon_t;
mp_number inf_t;
mp_number one_third_inf_t;
mp_number zero_t;
mp_number unity_t;
mp_number two_t;
mp_number three_t;
mp_number half_unit_t;
mp_number three_quarter_unit_t;
mp_number fraction_one_t;
mp_number fraction_half_t;
mp_number fraction_three_t;
mp_number fraction_four_t;
mp_number one_eighty_deg_t;
mp_number three_sixty_deg_t;
mp_number one_k;
mp_number sqrt_8_e_k;
mp_number twelve_ln_2_k;
mp_number coef_bound_k;
mp_number coef_bound_minus_1;
mp_number twelvebits_3;
mp_number arc_tol_k;
mp_number twentysixbits_sqrt2_t;
mp_number twentyeightbits_d_t;
mp_number twentysevenbits_sqrt2_d_t;
mp_number fraction_threshold_t;
mp_number half_fraction_threshold_t;
mp_number scaled_threshold_t;
mp_number half_scaled_threshold_t;
mp_number near_zero_angle_t;
mp_number p_over_v_threshold_t;
mp_number equation_threshold_t;
mp_number tfm_warn_threshold_t;
mp_number warning_limit_t;
new_number_func allocate;
free_number_func free;
number_from_int_func from_int;
number_from_boolean_func from_boolean;
number_from_scaled_func from_scaled;
number_from_double_func from_double;
number_from_addition_func from_addition;
number_from_substraction_func from_substraction;
number_from_div_func from_div;
number_from_mul_func from_mul;
number_from_int_div_func from_int_div;
number_from_int_mul_func from_int_mul;
number_from_oftheway_func from_oftheway;
number_negate_func negate;
number_add_func add;
number_substract_func substract;
number_half_func half;
number_modulo_func modulo;
number_halfp_func halfp;
number_double_func do_double;
number_abs_func abs;
number_clone_func clone;
number_swap_func swap;
number_add_scaled_func add_scaled;
number_multiply_int_func multiply_int;
number_divide_int_func divide_int;
number_to_int_func to_int;
number_to_boolean_func to_boolean;
number_to_scaled_func to_scaled;
number_to_double_func to_double;
number_odd_func odd;
number_equal_func equal;
number_less_func less;
number_greater_func greater;
number_nonequalabs_func nonequalabs;
number_round_func round_unscaled;
number_floor_func floor_scaled;
make_scaled_func make_scaled;
make_fraction_func make_fraction;
take_fraction_func take_fraction;
take_scaled_func take_scaled;
velocity_func velocity;
ab_vs_cd_func ab_vs_cd;
crossing_point_func crossing_point;
n_arg_func n_arg;
m_log_func m_log;
m_exp_func m_exp;
m_unif_rand_func m_unif_rand;
m_norm_rand_func m_norm_rand;
pyth_add_func pyth_add;
pyth_sub_func pyth_sub;
fraction_to_round_scaled_func fraction_to_round_scaled;
convert_func fraction_to_scaled;
convert_func scaled_to_fraction;
convert_func scaled_to_angle;
convert_func angle_to_scaled;
init_randoms_func init_randoms;
sin_cos_func sin_cos;
sqrt_func sqrt;
slow_add_func slow_add;
print_func print;
tostring_func tostring;
scan_func scan_numeric;
scan_func scan_fractional;
mp_free_func free_math;
set_precision_func set_precision;
} math_data;
@ This procedure gets things started properly.
@c
MP mp_initialize (MP_options * opt) {
MP mp;
jmp_buf *buf = malloc (sizeof (jmp_buf));
if (buf == NULL || setjmp (*buf) != 0)
return NULL;
mp = mp_do_new (buf);
if (mp == NULL)
return NULL;
mp->userdata = opt->userdata;
mp->noninteractive = opt->noninteractive;
mp->extensions = opt->extensions;
set_callback_option (find_file);
set_callback_option (open_file);
set_callback_option (read_ascii_file);
set_callback_option (read_binary_file);
set_callback_option (close_file);
set_callback_option (eof_file);
set_callback_option (flush_file);
set_callback_option (write_ascii_file);
set_callback_option (write_binary_file);
set_callback_option (shipout_backend);
set_callback_option (run_script);
set_callback_option (make_text);
if (opt->banner && *(opt->banner)) {
mp->banner = xstrdup (opt->banner);
} else {
mp->banner = xstrdup (default_banner);
}
if (opt->command_line && *(opt->command_line))
mp->command_line = xstrdup (opt->command_line);
if (mp->noninteractive) {
@<Prepare function pointers for non-interactive use@>;
}
/* open the terminal for output */
t_open_out();
#if DEBUG
setvbuf(stdout, (char *) NULL, _IONBF, 0);
setvbuf(mp->term_out, (char *) NULL, _IONBF, 0);
#endif
if (opt->math_mode == mp_math_scaled_mode) {
mp->math = mp_initialize_scaled_math(mp);
} else if (opt->math_mode == mp_math_decimal_mode) {
mp->math = mp_initialize_decimal_math(mp);
} else if (opt->math_mode == mp_math_binary_mode) {
mp->math = mp_initialize_binary_math(mp);
} else {
mp->math = mp_initialize_double_math(mp);
}
@<Find and load preload file, if required@>;
@<Allocate or initialize variables@>;
mp_reallocate_paths (mp, 1000);
mp_reallocate_fonts (mp, 8);
mp->history = mp_fatal_error_stop; /* in case we quit during initialization */
@<Check the ``constant'' values...@>;
if (mp->bad > 0) {
char ss[256];
mp_snprintf (ss, 256, "Ouch---my internal constants have been clobbered!\n"
"---case %i", (int) mp->bad);
mp_fputs ((char *) ss, mp->err_out);
@.Ouch...clobbered@>;
return mp;
}
mp_do_initialize (mp); /* erase preloaded mem */
mp_init_tab (mp); /* initialize the tables */
if (opt->math_mode == mp_math_scaled_mode) {
set_internal_string (mp_number_system, mp_intern (mp, "scaled"));
} else if (opt->math_mode == mp_math_decimal_mode) {
set_internal_string (mp_number_system, mp_intern (mp, "decimal"));
} else if (opt->math_mode == mp_math_binary_mode) {
set_internal_string (mp_number_system, mp_intern (mp, "binary"));
} else {
set_internal_string (mp_number_system, mp_intern (mp, "double"));
}
mp_init_prim (mp); /* call |primitive| for each primitive */
mp_fix_date_and_time (mp);
if (!mp->noninteractive) {
@<Initialize the output routines@>;
@<Get the first line of input and prepare to start@>;
@<Initializations after first line is read@>;
@<Fix up |mp->internal[mp_job_name]|@>;
} else {
mp->history = mp_spotless;
}
set_precision();
return mp;
}
@ @<Initializations after first line is read@>=
mp_open_log_file (mp);
mp_set_job_id (mp);
mp_init_map_file (mp, mp->troff_mode);
mp->history = mp_spotless; /* ready to go! */
if (mp->troff_mode) {
number_clone (internal_value (mp_gtroffmode), unity_t);
number_clone (internal_value (mp_prologues), unity_t);
}
if (mp->start_sym != NULL) { /* insert the `\&{everyjob}' symbol */
set_cur_sym (mp->start_sym);
mp_back_input (mp);
}
@ @<Exported function headers@>=
extern MP_options *mp_options (void);
extern MP mp_initialize (MP_options * opt);
extern int mp_status (MP mp);
extern void *mp_userdata (MP mp);
@ @c
int mp_status (MP mp) {
return mp->history;
}
@ @c
void *mp_userdata (MP mp) {
return mp->userdata;
}
@ The overall \MP\ program begins with the heading just shown, after which
comes a bunch of procedure declarations and function declarations.
Finally we will get to the main program, which begins with the
comment `|start_here|'. If you want to skip down to the
main program now, you can look up `|start_here|' in the index.
But the author suggests that the best way to understand this program
is to follow pretty much the order of \MP's components as they appear in the
\.{WEB} description you are now reading, since the present ordering is
intended to combine the advantages of the ``bottom up'' and ``top down''
approaches to the problem of understanding a somewhat complicated system.
@ Some of the code below is intended to be used only when diagnosing the
strange behavior that sometimes occurs when \MP\ is being installed or
when system wizards are fooling around with \MP\ without quite knowing
what they are doing. Such code will not normally be compiled; it is
delimited by the preprocessor test `|#ifdef DEBUG .. #endif|'.
@ The following parameters can be changed at compile time to extend or
reduce \MP's capacity.
@^system dependencies@>
@<Constants...@>=
#define bistack_size 1500 /* size of stack for bisection algorithms;
should probably be left at this value */
@ Like the preceding parameters, the following quantities can be changed
to extend or reduce \MP's capacity.
@ @<Glob...@>=
int pool_size; /* maximum number of characters in strings, including all
error messages and help texts, and the names of all identifiers */
int max_in_open; /* maximum number of input files and error insertions that
can be going on simultaneously */
int param_size; /* maximum number of simultaneous macro parameters */
@ @<Option variables@>=
int error_line; /* width of context lines on terminal error messages */
int half_error_line; /* width of first lines of contexts in terminal
error messages; should be between 30 and |error_line-15| */
int halt_on_error; /* do we quit at the first error? */
int max_print_line; /* width of longest text lines output; should be at least 60 */
void *userdata; /* this allows the calling application to setup local */
char *banner; /* the banner that is printed to the screen and log */
int ini_version;
@ @<Dealloc variables@>=
xfree (mp->banner);
@
@d set_lower_limited_value(a,b,c) do { a=c; if (b>c) a=b; } while (0)
@<Allocate or ...@>=
mp->param_size = 4;
mp->max_in_open = 0;
mp->pool_size = 10000;
set_lower_limited_value (mp->error_line, opt->error_line, 79);
set_lower_limited_value (mp->half_error_line, opt->half_error_line, 50);
if (mp->half_error_line > mp->error_line - 15)
mp->half_error_line = mp->error_line - 15;
mp->max_print_line = 100;
set_lower_limited_value (mp->max_print_line, opt->max_print_line, 79);
mp->halt_on_error = (opt->halt_on_error ? true : false);
mp->ini_version = (opt->ini_version ? true : false);
@ In case somebody has inadvertently made bad settings of the ``constants,''
\MP\ checks them using a global variable called |bad|.
This is the second of many sections of \MP\ where global variables are
defined.
@<Glob...@>=
integer bad; /* is some ``constant'' wrong? */
@ Later on we will say `|if ( int_packets+17*int_increment>bistack_size )mp->bad=19;|',
or something similar.
In case you are wondering about the non-consequtive values of |bad|: most
of the things that used to be WEB constants are now runtime variables
with checking at assignment time.
@<Check the ``constant'' values for consistency@>=
mp->bad = 0;
@ Here are some macros for common programming idioms.
@d incr(A) (A)=(A)+1 /* increase a variable by unity */
@d decr(A) (A)=(A)-1 /* decrease a variable by unity */
@d negate(A) (A)=-(A) /* change the sign of a variable */
@d double(A) (A)=(A)+(A)
@d odd(A) (abs(A)%2==1)
@* The character set.
In order to make \MP\ readily portable to a wide variety of
computers, all of its input text is converted to an internal eight-bit
code that includes standard ASCII, the ``American Standard Code for
Information Interchange.'' This conversion is done immediately when each
character is read in. Conversely, characters are converted from ASCII to
the user's external representation just before they are output to a
text file.
@^ASCII code@>
Such an internal code is relevant to users of \MP\ only with respect to
the \&{char} and \&{ASCII} operations, and the comparison of strings.
@ Characters of text that have been converted to \MP's internal form
are said to be of type |ASCII_code|, which is a subrange of the integers.
@<Types...@>=
typedef unsigned char ASCII_code; /* eight-bit numbers */
@ The present specification of \MP\ has been written under the assumption
that the character set contains at least the letters and symbols associated
with ASCII codes 040 through 0176; all of these characters are now
available on most computer terminals.
@<Types...@>=
typedef unsigned char text_char; /* the data type of characters in text files */
@ @<Local variables for init...@>=
integer i;
@ The \MP\ processor converts between ASCII code and
the user's external character set by means of arrays |xord| and |xchr|
that are analogous to Pascal's |ord| and |chr| functions.
@<MPlib internal header stuff@>=
#define xchr(A) mp->xchr[(A)]
#define xord(A) mp->xord[(A)]
@ @<Glob...@>=
ASCII_code xord[256]; /* specifies conversion of input characters */
text_char xchr[256]; /* specifies conversion of output characters */
@ The core system assumes all 8-bit is acceptable. If it is not,
a change file has to alter the below section.
@^system dependencies@>
Additionally, people with extended character sets can
assign codes arbitrarily, giving an |xchr| equivalent to whatever
characters the users of \MP\ are allowed to have in their input files.
Appropriate changes to \MP's |char_class| table should then be made.
(Unlike \TeX, each installation of \MP\ has a fixed assignment of category
codes, called the |char_class|.) Such changes make portability of programs
more difficult, so they should be introduced cautiously if at all.
@^character set dependencies@>
@^system dependencies@>
@<Set initial ...@>=
for (i = 0; i <= 0377; i++) {
xchr (i) = (text_char) i;
}
@ The following system-independent code makes the |xord| array contain a
suitable inverse to the information in |xchr|. Note that if |xchr[i]=xchr[j]|
where |i<j<0177|, the value of |xord[xchr[i]]| will turn out to be
|j| or more; hence, standard ASCII code numbers will be used instead of
codes below 040 in case there is a coincidence.
@<Set initial ...@>=
for (i = 0; i <= 255; i++) {
xord (xchr (i)) = 0177;
}
for (i = 0200; i <= 0377; i++) {
xord (xchr (i)) = (ASCII_code) i;
}
for (i = 0; i <= 0176; i++) {
xord (xchr (i)) = (ASCII_code) i;
}
@* Input and output.
The bane of portability is the fact that different operating systems treat
input and output quite differently, perhaps because computer scientists
have not given sufficient attention to this problem. People have felt somehow
that input and output are not part of ``real'' programming. Well, it is true
that some kinds of programming are more fun than others. With existing
input/output conventions being so diverse and so messy, the only sources of
joy in such parts of the code are the rare occasions when one can find a
way to make the program a little less bad than it might have been. We have
two choices, either to attack I/O now and get it over with, or to postpone
I/O until near the end. Neither prospect is very attractive, so let's
get it over with.
The basic operations we need to do are (1)~inputting and outputting of
text, to or from a file or the user's terminal; (2)~inputting and
outputting of eight-bit bytes, to or from a file; (3)~instructing the
operating system to initiate (``open'') or to terminate (``close'') input or
output from a specified file; (4)~testing whether the end of an input
file has been reached; (5)~display of bits on the user's screen.
The bit-display operation will be discussed in a later section; we shall
deal here only with more traditional kinds of I/O.
@ Finding files happens in a slightly roundabout fashion: the \MP\
instance object contains a field that holds a function pointer that finds a
file, and returns its name, or NULL. For this, it receives three
parameters: the non-qualified name |fname|, the intended |fopen|
operation type |fmode|, and the type of the file |ftype|.
The file types that are passed on in |ftype| can be used to
differentiate file searches if a library like kpathsea is used,
the fopen mode is passed along for the same reason.
@<Types...@>=
typedef unsigned char eight_bits; /* unsigned one-byte quantity */
@ @<Exported types@>=
enum mp_filetype {
mp_filetype_terminal = 0, /* the terminal */
mp_filetype_error, /* the terminal */
mp_filetype_program, /* \MP\ language input */
mp_filetype_log, /* the log file */
mp_filetype_postscript, /* the postscript output */
mp_filetype_bitmap, /* the bitmap output file */
mp_filetype_memfile, /* memory dumps, obsolete */
mp_filetype_metrics, /* TeX font metric files */
mp_filetype_fontmap, /* PostScript font mapping files */
mp_filetype_font, /* PostScript type1 font programs */
mp_filetype_encoding, /* PostScript font encoding files */
mp_filetype_text /* first text file for readfrom and writeto primitives */
};
typedef char *(*mp_file_finder) (MP, const char *, const char *, int);
typedef char *(*mp_script_runner) (MP, const char *);
typedef char *(*mp_text_maker) (MP, const char *, int mode);
typedef void *(*mp_file_opener) (MP, const char *, const char *, int);
typedef char *(*mp_file_reader) (MP, void *, size_t *);
typedef void (*mp_binfile_reader) (MP, void *, void **, size_t *);
typedef void (*mp_file_closer) (MP, void *);
typedef int (*mp_file_eoftest) (MP, void *);
typedef void (*mp_file_flush) (MP, void *);
typedef void (*mp_file_writer) (MP, void *, const char *);
typedef void (*mp_binfile_writer) (MP, void *, void *, size_t);
@ @<Option variables@>=
mp_file_finder find_file;
mp_file_opener open_file;
mp_script_runner run_script;
mp_text_maker make_text;
mp_file_reader read_ascii_file;
mp_binfile_reader read_binary_file;
mp_file_closer close_file;
mp_file_eoftest eof_file;
mp_file_flush flush_file;
mp_file_writer write_ascii_file;
mp_binfile_writer write_binary_file;
@ The default function for finding files is |mp_find_file|. It is
pretty stupid: it will only find files in the current directory.
@c
static char *mp_find_file (MP mp, const char *fname, const char *fmode,
int ftype) {
(void) mp;
if (fmode[0] != 'r' || (!access (fname, R_OK)) || ftype) {
return mp_strdup (fname);
}
return NULL;
}
@ @c
static char *mp_run_script (MP mp, const char *str) {
(void) mp;
return mp_strdup (str);
}
@ @c
static char *mp_make_text (MP mp, const char *str, int mode) {
(void) mp;
return mp_strdup (str);
}
@ Because |mp_find_file| is used so early, it has to be in the helpers
section.
@<Declarations@>=
static char *mp_find_file (MP mp, const char *fname, const char *fmode,
int ftype);
static void *mp_open_file (MP mp, const char *fname, const char *fmode,
int ftype);
static char *mp_read_ascii_file (MP mp, void *f, size_t * size);
static void mp_read_binary_file (MP mp, void *f, void **d, size_t * size);
static void mp_close_file (MP mp, void *f);
static int mp_eof_file (MP mp, void *f);
static void mp_flush_file (MP mp, void *f);
static void mp_write_ascii_file (MP mp, void *f, const char *s);
static void mp_write_binary_file (MP mp, void *f, void *s, size_t t);
static char *mp_run_script (MP mp, const char *str);
static char *mp_make_text (MP mp, const char *str, int mode);
@ The function to open files can now be very short.
@c
void *mp_open_file (MP mp, const char *fname, const char *fmode, int ftype) {
char realmode[3];
(void) mp;
realmode[0] = *fmode;
realmode[1] = 'b';
realmode[2] = 0;
if (ftype == mp_filetype_terminal) {
return (fmode[0] == 'r' ? stdin : stdout);
} else if (ftype == mp_filetype_error) {
return stderr;
} else if (fname != NULL && (fmode[0] != 'r' || (!access (fname, R_OK)))) {
return (void *) fopen (fname, realmode);
}
return NULL;
}
@ (Almost) all file names pass through |name_of_file|.
@<Glob...@>=
char *name_of_file; /* the name of a system file */
@ If this parameter is true, the terminal and log will report the found
file names for input files instead of the requested ones.
It is off by default because it creates an extra filename lookup.
@<Option variables@>=
int print_found_names; /* configuration parameter */
@ @<Allocate or initialize ...@>=
mp->print_found_names = (opt->print_found_names > 0 ? true : false);
@ The |file_line_error_style| parameter makes \MP\ use a more
standard compiler error message format instead of the Knuthian
exclamation mark. It needs the actual version of the current input
file name, that will be saved by |open_in| in the |long_name|.
TODO: currently these long strings cause memory leaks, because they cannot
be safely freed as they may appear in the |input_stack| multiple times.
In fact, the current implementation is just a quick hack in response
to a bug report for metapost 1.205.
@d long_name mp->cur_input.long_name_field /* long name of the current file */
@<Option variables@>=
int file_line_error_style; /* configuration parameter */
@ @<Allocate or initialize ...@>=
mp->file_line_error_style = (opt->file_line_error_style > 0 ? true : false);
@ \MP's file-opening procedures return |false| if no file identified by
|name_of_file| could be opened.
The |do_open_file| function takes care of the |print_found_names| parameter.
@c
static boolean mp_do_open_file (MP mp, void **f, int ftype, const char *mode) {
if (mp->print_found_names || mp->file_line_error_style) {
char *s = (mp->find_file)(mp,mp->name_of_file,mode,ftype);
if (s!=NULL) {
*f = (mp->open_file)(mp,mp->name_of_file,mode, ftype);
if (mp->print_found_names) {
xfree(mp->name_of_file);
mp->name_of_file = xstrdup(s);
}
if ((*mode == 'r') && (ftype == mp_filetype_program)) {
long_name = xstrdup(s);
}
xfree(s);
} else {
*f = NULL;
}
} else {
*f = (mp->open_file)(mp,mp->name_of_file,mode, ftype);
}
return (*f ? true : false);
}
@#
static boolean mp_open_in (MP mp, void **f, int ftype) {
/* open a file for input */
return mp_do_open_file (mp, f, ftype, "r");
}
@#
static boolean mp_open_out (MP mp, void **f, int ftype) {
/* open a file for output */
return mp_do_open_file (mp, f, ftype, "w");
}
@ @c
static char *mp_read_ascii_file (MP mp, void *ff, size_t * size) {
int c;
size_t len = 0, lim = 128;
char *s = NULL;
FILE *f = (FILE *) ff;
*size = 0;
(void) mp; /* for -Wunused */
if (f == NULL)
return NULL;
c = fgetc (f);
if (c == EOF)
return NULL;
s = malloc (lim);
if (s == NULL)
return NULL;
while (c != EOF && c != '\n' && c != '\r') {
if ((len + 1) == lim) {
s = realloc (s, (lim + (lim >> 2)));
if (s == NULL)
return NULL;
lim += (lim >> 2);
}
s[len++] = (char) c;
c = fgetc (f);
}
if (c == '\r') {
c = fgetc (f);
if (c != EOF && c != '\n')
ungetc (c, f);
}
s[len] = 0;
*size = len;
return s;
}
@ @c
void mp_write_ascii_file (MP mp, void *f, const char *s) {
(void) mp;
if (f != NULL) {
fputs (s, (FILE *) f);
}
}
@ @c
void mp_read_binary_file (MP mp, void *f, void **data, size_t * size) {
size_t len = 0;
(void) mp;
if (f != NULL)
len = fread (*data, 1, *size, (FILE *) f);
*size = len;
}
@ @c
void mp_write_binary_file (MP mp, void *f, void *s, size_t size) {
(void) mp;
if (f != NULL)
(void) fwrite (s, size, 1, (FILE *) f);
}
@ @c
void mp_close_file (MP mp, void *f) {
(void) mp;
if (f != NULL)
fclose ((FILE *) f);
}
@ @c
int mp_eof_file (MP mp, void *f) {
(void) mp;
if (f != NULL)
return feof ((FILE *) f);
else
return 1;
}
@ @c
void mp_flush_file (MP mp, void *f) {
(void) mp;
if (f != NULL)
fflush ((FILE *) f);
}
@ Input from text files is read one line at a time, using a routine called
|input_ln|. This function is defined in terms of global variables called
|buffer|, |first|, and |last| that will be described in detail later; for
now, it suffices for us to know that |buffer| is an array of |ASCII_code|
values, and that |first| and |last| are indices into this array
representing the beginning and ending of a line of text.
@<Glob...@>=
size_t buf_size; /* maximum number of characters simultaneously present in
current lines of open files */
ASCII_code *buffer; /* lines of characters being read */
size_t first; /* the first unused position in |buffer| */
size_t last; /* end of the line just input to |buffer| */
size_t max_buf_stack; /* largest index used in |buffer| */
@ @<Allocate or initialize ...@>=
mp->buf_size = 200;
mp->buffer = xmalloc ((mp->buf_size + 1), sizeof (ASCII_code));
@ @<Dealloc variables@>=
xfree (mp->buffer);
@ @c
static void mp_reallocate_buffer (MP mp, size_t l) {
ASCII_code *buffer;
if (l > max_halfword) {
mp_confusion (mp, "buffer size"); /* can't happen (I hope) */
}
buffer = xmalloc ((l + 1), sizeof (ASCII_code));
(void) memcpy (buffer, mp->buffer, (mp->buf_size + 1));
xfree (mp->buffer);
mp->buffer = buffer;
mp->buf_size = l;
}
@ The |input_ln| function brings the next line of input from the specified
field into available positions of the buffer array and returns the value
|true|, unless the file has already been entirely read, in which case it
returns |false| and sets |last:=first|. In general, the |ASCII_code|
numbers that represent the next line of the file are input into
|buffer[first]|, |buffer[first+1]|, \dots, |buffer[last-1]|; and the
global variable |last| is set equal to |first| plus the length of the
line. Trailing blanks are removed from the line; thus, either |last=first|
(in which case the line was entirely blank) or |buffer[last-1]<>" "|.
@^inner loop@>
The variable |max_buf_stack|, which is used to keep track of how large
the |buf_size| parameter must be to accommodate the present job, is
also kept up to date by |input_ln|.
@c
static boolean mp_input_ln (MP mp, void *f) {
/* inputs the next line or returns |false| */
char *s;
size_t size = 0;
mp->last = mp->first; /* cf.\ Matthew 19\thinspace:\thinspace30 */
s = (mp->read_ascii_file) (mp, f, &size);
if (s == NULL)
return false;
if (size > 0) {
mp->last = mp->first + size;
if (mp->last >= mp->max_buf_stack) {
mp->max_buf_stack = mp->last + 1;
while (mp->max_buf_stack > mp->buf_size) {
mp_reallocate_buffer (mp, (mp->buf_size + (mp->buf_size >> 2)));
}
}
(void) memcpy ((mp->buffer + mp->first), s, size);
}
free (s);
return true;
}
@ The user's terminal acts essentially like other files of text, except
that it is used both for input and for output. When the terminal is
considered an input file, the file variable is called |term_in|, and when it
is considered an output file the file variable is |term_out|.
@^system dependencies@>
@<Glob...@>=
void *term_in; /* the terminal as an input file */
void *term_out; /* the terminal as an output file */
void *err_out; /* the terminal as an output file */
@ Here is how to open the terminal files. In the default configuration,
nothing happens except that the command line (if there is one) is copied
to the input buffer. The variable |command_line| will be filled by the
|main| procedure.
@d t_open_out() do {/* open the terminal for text output */
mp->term_out = (mp->open_file)(mp,"terminal", "w", mp_filetype_terminal);
mp->err_out = (mp->open_file)(mp,"error", "w", mp_filetype_error);
} while (0)
@d t_open_in() do { /* open the terminal for text input */
mp->term_in = (mp->open_file)(mp,"terminal", "r", mp_filetype_terminal);
if (mp->command_line!=NULL) {
mp->last = strlen(mp->command_line);
(void)memcpy((void *)mp->buffer,(void *)mp->command_line,mp->last);
xfree(mp->command_line);
} else {
mp->last = 0;
}
} while (0)
@<Option variables@>=
char *command_line;
@ Sometimes it is necessary to synchronize the input/output mixture that
happens on the user's terminal, and three system-dependent
procedures are used for this
purpose. The first of these, |update_terminal|, is called when we want
to make sure that everything we have output to the terminal so far has
actually left the computer's internal buffers and been sent.
The second, |clear_terminal|, is called when we wish to cancel any
input that the user may have typed ahead (since we are about to
issue an unexpected error message). The third, |wake_up_terminal|,
is supposed to revive the terminal if the user has disabled it by
some instruction to the operating system. The following macros show how
these operations can be specified:
@^system dependencies@>
@<MPlib internal header stuff@>=
#define update_terminal() (mp->flush_file)(mp,mp->term_out) /* empty the terminal output buffer */
#define clear_terminal() /* clear the terminal input buffer */
#define wake_up_terminal() (mp->flush_file)(mp,mp->term_out)
/* cancel the user's cancellation of output */
@ We need a special routine to read the first line of \MP\ input from
the user's terminal. This line is different because it is read before we
have opened the transcript file; there is sort of a ``chicken and
egg'' problem here. If the user types `\.{input cmr10}' on the first
line, or if some macro invoked by that line does such an \.{input},
the transcript file will be named `\.{cmr10.log}'; but if no \.{input}
commands are performed during the first line of terminal input, the transcript
file will acquire its default name `\.{mpout.log}'. (The transcript file
will not contain error messages generated by the first line before the
first \.{input} command.)
The first line is even more special. It's nice to let the user start
running a \MP\ job by typing a command line like `\.{MP cmr10}'; in
such a case, \MP\ will operate as if the first line of input were
`\.{cmr10}', i.e., the first line will consist of the remainder of the
command line, after the part that invoked \MP.
@ Different systems have different ways to get started. But regardless of
what conventions are adopted, the routine that initializes the terminal
should satisfy the following specifications:
\yskip\textindent{1)}It should open file |term_in| for input from the
terminal. (The file |term_out| will already be open for output to the
terminal.)
\textindent{2)}If the user has given a command line, this line should be
considered the first line of terminal input. Otherwise the
user should be prompted with `\.{**}', and the first line of input
should be whatever is typed in response.
\textindent{3)}The first line of input, which might or might not be a
command line, should appear in locations |first| to |last-1| of the
|buffer| array.
\textindent{4)}The global variable |loc| should be set so that the
character to be read next by \MP\ is in |buffer[loc]|. This
character should not be blank, and we should have |loc<last|.
\yskip\noindent(It may be necessary to prompt the user several times
before a non-blank line comes in. The prompt is `\.{**}' instead of the
later `\.*' because the meaning is slightly different: `\.{input}' need
not be typed immediately after~`\.{**}'.)
@d loc mp->cur_input.loc_field /* location of first unread character in |buffer| */
@c
boolean mp_init_terminal (MP mp) { /* gets the terminal input started */
t_open_in();
if (mp->last != 0) {
loc = 0;
mp->first = 0;
return true;
}
while (1) {
if (!mp->noninteractive) {
wake_up_terminal();
mp_fputs ("**", mp->term_out);
@.**@>;
update_terminal();
}
if (!mp_input_ln (mp, mp->term_in)) { /* this shouldn't happen */
mp_fputs ("\n! End of file on the terminal... why?", mp->term_out);
@.End of file on the terminal@>;
return false;
}
loc = (halfword) mp->first;
while ((loc < (int) mp->last) && (mp->buffer[loc] == ' '))
incr (loc);
if (loc < (int) mp->last) {
return true; /* return unless the line was all blank */
}
if (!mp->noninteractive) {
mp_fputs ("Please type the name of your input file.\n", mp->term_out);
}
}
}
@ @<Declarations@>=
static boolean mp_init_terminal (MP mp);
@* Globals for strings.
@ Symbolic token names and diagnostic messages are variable-length strings
of eight-bit characters. Many strings \MP\ uses are simply literals
in the compiled source, like the error messages and the names of the
internal parameters. Other strings are used or defined from the \MP\ input
language, and these have to be interned.
\MP\ uses strings more extensively than \MF\ does, but the necessary
operations can still be handled with a fairly simple data structure.
The avl tree |strings| contains all of the known string structures.
Each structure contains an |unsigned char| pointer containing the eight-bit
data, a |size_t| that holds the length of that data, and an |int| that
indicates how often this string is referenced (this will be explained below).
Such strings are referred to by structure pointers called |mp_string|.
Besides the avl tree, there is a set of three variables called |cur_string|,
|cur_length| and |cur_string_size| that are used for strings while they are
being built.
@<Exported types...@>=
typedef struct {
unsigned char *str; /* the string value */
size_t len; /* its length */
int refs; /* number of references */
} mp_lstring;
typedef mp_lstring *mp_string; /* for pointers to string values */
@ The string handling functions are in \.{mpstrings.w}, but strings
need a bunch of globals and those are defined here in the main file.
@<Glob...@>=
avl_tree strings; /* string avl tree */
unsigned char *cur_string; /* current string buffer */
size_t cur_length; /* current index in that buffer */
size_t cur_string_size; /* malloced size of |cur_string| */
@ @<Allocate or initialize ...@>=
mp_initialize_strings(mp);
@ @<Dealloc variables@>=
mp_dealloc_strings(mp);
@ The next four variables are for keeping track of string memory usage.
@<Glob...@>=
integer pool_in_use; /* total number of string bytes actually in use */
integer max_pl_used; /* maximum |pool_in_use| so far */
integer strs_in_use; /* total number of strings actually in use */
integer max_strs_used; /* maximum |strs_in_use| so far */
@* On-line and off-line printing.
Messages that are sent to a user's terminal and to the transcript-log file
are produced by several `|print|' procedures. These procedures will
direct their output to a variety of places, based on the setting of
the global variable |selector|, which has the following possible
values:
\yskip
\hang |term_and_log|, the normal setting, prints on the terminal and on the
transcript file.
\hang |log_only|, prints only on the transcript file.
\hang |term_only|, prints only on the terminal.
\hang |no_print|, doesn't print at all. This is used only in rare cases
before the transcript file is open.
\hang |pseudo|, puts output into a cyclic buffer that is used
by the |show_context| routine; when we get to that routine we shall discuss
the reasoning behind this curious mode.
\hang |new_string|, appends the output to the current string in the
string pool.
\hang |>=write_file| prints on one of the files used for the \&{write}
@:write_}{\&{write} primitive@>
command.
\yskip
\noindent The symbolic names `|term_and_log|', etc., have been assigned
numeric codes that satisfy the convenient relations |no_print+1=term_only|,
|no_print+2=log_only|, |term_only+2=log_only+1=term_and_log|. These
relations are not used when |selector| could be |pseudo|, or |new_string|.
We need not check for unprintable characters when |selector<pseudo|.
Three additional global variables, |tally|, |term_offset| and |file_offset|
record the number of characters that have been printed
since they were most recently cleared to zero. We use |tally| to record
the length of (possibly very long) stretches of printing; |term_offset|,
and |file_offset|, on the other hand, keep track of how many
characters have appeared so far on the current line that has been output
to the terminal, the transcript file, or the \ps\ output file, respectively.
@d new_string 0 /* printing is deflected to the string pool */
@d pseudo 2 /* special |selector| setting for |show_context| */
@d no_print 3 /* |selector| setting that makes data disappear */
@d term_only 4 /* printing is destined for the terminal only */
@d log_only 5 /* printing is destined for the transcript file only */
@d term_and_log 6 /* normal |selector| setting */
@d write_file 7 /* first write file selector */
@<Glob...@>=
void *log_file; /* transcript of \MP\ session */
void *output_file; /* the generic font output goes here */
unsigned int selector; /* where to print a message */
integer tally; /* the number of characters recently printed */
unsigned int term_offset;
/* the number of characters on the current terminal line */
unsigned int file_offset;
/* the number of characters on the current file line */
ASCII_code *trick_buf; /* circular buffer for pseudoprinting */
integer trick_count; /* threshold for pseudoprinting, explained later */
integer first_count; /* another variable for pseudoprinting */
@ The first 128 strings will contain 95 standard ASCII characters, and the
other 33 characters will be printed in three-symbol form like `\.{\^\^A}'
unless a system-dependent change is made here. Installations that have
an extended character set, where for example |xchr[032]=@t\.{'^^Z'}@>|,
would like string 032 to be printed as the single character 032 instead
of the three characters 0136, 0136, 0132 (\.{\^\^Z}). On the other hand,
even people with an extended character set will want to represent string
015 by \.{\^\^M}, since 015 is ASCII's ``carriage return'' code; the idea is
to produce visible strings instead of tabs or line-feeds or carriage-returns
or bell-rings or characters that are treated anomalously in text files.
The boolean expression defined here should be |true| unless \MP\ internal
code number~|k| corresponds to a non-troublesome visible symbol in the
local character set.
If character |k| cannot be printed, and |k<0200|, then character |k+0100| or
|k-0100| must be printable; moreover, ASCII codes |[060..071, 0141..0146]|
must be printable.
@^character set dependencies@>
@^system dependencies@>
@<Character |k| cannot be printed@>=
(k < ' ') || (k == 127)
@ @<Allocate or initialize ...@>=
mp->trick_buf = xmalloc ((mp->error_line + 1), sizeof (ASCII_code));
@ @<Dealloc variables@>=
xfree (mp->trick_buf);
@ @<Initialize the output routines@>=
mp->selector = term_only;
mp->tally = 0;
mp->term_offset = 0;
mp->file_offset = 0;
@ Macro abbreviations for output to the terminal and to the log file are
defined here for convenience. Some systems need special conventions
for terminal output, and it is possible to adhere to those conventions
by changing |wterm|, |wterm_ln|, and |wterm_cr| here.
@^system dependencies@>
@<MPlib internal header stuff@>=
#define mp_fputs(b,f) (mp->write_ascii_file)(mp,f,b)
#define wterm(A) mp_fputs((A), mp->term_out)
#define wterm_chr(A) { unsigned char ss[2]; ss[0]=(A); ss[1]='\0'; wterm((char *)ss);}
#define wterm_cr mp_fputs("\n", mp->term_out)
#define wterm_ln(A) { wterm_cr; mp_fputs((A), mp->term_out); }
#define wlog(A) mp_fputs((A), mp->log_file)
#define wlog_chr(A) { unsigned char ss[2]; ss[0]=(A); ss[1]='\0'; wlog((char *)ss);}
#define wlog_cr mp_fputs("\n", mp->log_file)
#define wlog_ln(A) { wlog_cr; mp_fputs((A), mp->log_file); }
@ To end a line of text output, we call |print_ln|. Cases |0..max_write_files|
use an array |wr_file| that will be declared later.
@d mp_print_text(A) mp_print_str(mp,text((A)))
@<Internal library ...@>=
void mp_print (MP mp, const char *s);
void mp_printf (MP mp, const char *ss, ...);
void mp_print_ln (MP mp);
void mp_print_char (MP mp, ASCII_code k);
void mp_print_str (MP mp, mp_string s);
void mp_print_nl (MP mp, const char *s);
void mp_print_two (MP mp, mp_number x, mp_number y);
@ @<Declarations@>=
static void mp_print_visible_char (MP mp, ASCII_code s);
@ @<Basic print...@>=
void mp_print_ln (MP mp) { /* prints an end-of-line */
switch (mp->selector) {
case term_and_log:
wterm_cr;
wlog_cr;
mp->term_offset = 0;
mp->file_offset = 0;
break;
case log_only:
wlog_cr;
mp->file_offset = 0;
break;
case term_only:
wterm_cr;
mp->term_offset = 0;
break;
case no_print:
case pseudo:
case new_string:
break;
default:
mp_fputs ("\n", mp->wr_file[(mp->selector - write_file)]);
}
} /* note that |tally| is not affected */
@ The |print_visible_char| procedure sends one character to the desired
destination, using the |xchr| array to map it into an external character
compatible with |input_ln|. (It assumes that it is always called with
a visible ASCII character.) All printing comes through |print_ln| or
|print_char|, which ultimately calls |print_visible_char|, hence these
routines are the ones that limit lines to at most |max_print_line| characters.
But we must make an exception for the \ps\ output file since it is not safe
to cut up lines arbitrarily in \ps.
@<Basic printing...@>=
static void mp_print_visible_char (MP mp, ASCII_code s) { /* prints a single character */
switch (mp->selector) {
case term_and_log:
wterm_chr (xchr (s));
wlog_chr (xchr (s));
incr (mp->term_offset);
incr (mp->file_offset);
if (mp->term_offset == (unsigned) mp->max_print_line) {
wterm_cr;
mp->term_offset = 0;
};
if (mp->file_offset == (unsigned) mp->max_print_line) {
wlog_cr;
mp->file_offset = 0;
};
break;
case log_only:
wlog_chr (xchr (s));
incr (mp->file_offset);
if (mp->file_offset == (unsigned) mp->max_print_line)
mp_print_ln (mp);
break;
case term_only:
wterm_chr (xchr (s));
incr (mp->term_offset);
if (mp->term_offset == (unsigned) mp->max_print_line)
mp_print_ln (mp);
break;
case no_print:
break;
case pseudo:
if (mp->tally < mp->trick_count)
mp->trick_buf[mp->tally % mp->error_line] = s;
break;
case new_string:
append_char (s);
break;
default:
{
text_char ss[2] = {0,0};
ss[0] = xchr (s);
mp_fputs ((char *) ss, mp->wr_file[(mp->selector - write_file)]);
}
}
incr (mp->tally);
}
@ The |print_char| procedure sends one character to the desired destination.
File names and string expressions might contain |ASCII_code| values that
can't be printed using |print_visible_char|. These characters will be
printed in three- or four-symbol form like `\.{\^\^A}' or `\.{\^\^e4}'.
(This procedure assumes that it is safe to bypass all checks for unprintable
characters when |selector| is in the range |0..max_write_files-1|.
The user might want to write unprintable characters.
@<Basic printing...@>=
void mp_print_char (MP mp, ASCII_code k) { /* prints a single character */
if (mp->selector < pseudo || mp->selector >= write_file) {
mp_print_visible_char (mp, k);
} else if (@<Character |k| cannot be printed@>) {
mp_print (mp, "^^");
if (k < 0100) {
mp_print_visible_char (mp, (ASCII_code) (k + 0100));
} else if (k < 0200) {
mp_print_visible_char (mp, (ASCII_code) (k - 0100));
} else {
int l; /* small index or counter */
l = (k / 16);
mp_print_visible_char (mp, xord (l < 10 ? l + '0' : l - 10 + 'a'));
l = (k % 16);
mp_print_visible_char (mp, xord (l < 10 ? l + '0' : l - 10 + 'a'));
}
} else {
mp_print_visible_char (mp, k);
}
}
@ An entire string is output by calling |print|. Note that if we are outputting
the single standard ASCII character \.c, we could call |print("c")|, since
|"c"=99| is the number of a single-character string, as explained above. But
|print_char("c")| is quicker, so \MP\ goes directly to the |print_char|
routine when it knows that this is safe. (The present implementation
assumes that it is always safe to print a visible ASCII character.)
@^system dependencies@>
@<Basic print...@>=
static void mp_do_print (MP mp, const char *ss, size_t len) { /* prints string |s| */
if (len==0)
return;
if (mp->selector == new_string) {
str_room (len);
memcpy((mp->cur_string+mp->cur_length), ss, len);
mp->cur_length += len;
} else {
size_t j = 0;
while (j < len) {
/* this was |xord((int)ss[j])| but that doesnt work */
mp_print_char (mp, (ASCII_code) ss[j]);
j++;
}
}
}
@
@<Basic print...@>=
void mp_print (MP mp, const char *ss) {
assert (ss != NULL);
mp_do_print (mp, ss, strlen (ss));
}
void mp_printf (MP mp, const char *ss, ...) {
va_list ap;
char pval[256];
assert (ss != NULL);
va_start(ap, ss);
vsnprintf (pval, 256, ss, ap);
mp_do_print (mp, pval, strlen (pval));
va_end(ap);
}
void mp_print_str (MP mp, mp_string s) {
assert (s != NULL);
mp_do_print (mp, (const char *) s->str, s->len);
}
@ Here is the very first thing that \MP\ prints: a headline that identifies
the version number and base name. The |term_offset| variable is temporarily
incorrect, but the discrepancy is not serious since we assume that the banner
and mem identifier together will occupy at most |max_print_line|
character positions.
@<Initialize the output...@>=
wterm (mp->banner);
mp_print_ln (mp);
update_terminal();
@ The procedure |print_nl| is like |print|, but it makes sure that the
string appears at the beginning of a new line.
@<Basic print...@>=
void mp_print_nl (MP mp, const char *s) { /* prints string |s| at beginning of line */
switch (mp->selector) {
case term_and_log:
if ((mp->term_offset > 0) || (mp->file_offset > 0))
mp_print_ln (mp);
break;
case log_only:
if (mp->file_offset > 0)
mp_print_ln (mp);
break;
case term_only:
if (mp->term_offset > 0)
mp_print_ln (mp);
break;
case no_print:
case pseudo:
case new_string:
break;
} /* there are no other cases */
mp_print (mp, s);
}
@ The following procedure, which prints out the decimal representation of a
given integer |n|, assumes that all integers fit nicely into a |int|.
@^system dependencies@>
@<Basic print...@>=
void mp_print_int (MP mp, integer n) { /* prints an integer in decimal form */
char s[12];
mp_snprintf (s, 12, "%d", (int) n);
mp_print (mp, s);
}
void mp_print_pointer (MP mp, void *n) { /* prints an pointer in hexadecimal form */
char s[12];
mp_snprintf (s, 12, "%p", n);
mp_print (mp, s);
}
@ @<Internal library ...@>=
void mp_print_int (MP mp, integer n);
void mp_print_pointer (MP mp, void *n);
@ \MP\ also makes use of a trivial procedure to print two digits. The
following subroutine is usually called with a parameter in the range |0<=n<=99|.
@c
static void mp_print_dd (MP mp, integer n) { /* prints two least significant digits */
n = abs (n) % 100;
mp_print_char (mp, xord ('0' + (n / 10)));
mp_print_char (mp, xord ('0' + (n % 10)));
}
@ @<Declarations@>=
static void mp_print_dd (MP mp, integer n);
@ Here is a procedure that asks the user to type a line of input,
assuming that the |selector| setting is either |term_only| or |term_and_log|.
The input is placed into locations |first| through |last-1| of the
|buffer| array, and echoed on the transcript file if appropriate.
This procedure is never called when |interaction<mp_scroll_mode|.
@d prompt_input(A) do {
if (!mp->noninteractive) {
wake_up_terminal();
mp_print(mp, (A));
}
mp_term_input(mp);
} while (0) /* prints a string and gets a line of input */
@c
void mp_term_input (MP mp) { /* gets a line from the terminal */
size_t k; /* index into |buffer| */
if (mp->noninteractive) {
if (!mp_input_ln (mp, mp->term_in))
longjmp (*(mp->jump_buf), 1); /* chunk finished */
mp->buffer[mp->last] = xord ('%');
} else {
update_terminal(); /* Now the user sees the prompt for sure */
if (!mp_input_ln (mp, mp->term_in)) {
mp_fatal_error (mp, "End of file on the terminal!");
@.End of file on the terminal@>
}
mp->term_offset = 0; /* the user's line ended with \<\rm return> */
decr (mp->selector); /* prepare to echo the input */
if (mp->last != mp->first) {
for (k = mp->first; k < mp->last; k++) {
mp_print_char (mp, mp->buffer[k]);
}
}
mp_print_ln (mp);
mp->buffer[mp->last] = xord ('%');
incr (mp->selector); /* restore previous status */
}
}
@* Reporting errors.
The |print_err| procedure supplies a `\.!' before the official message,
and makes sure that the terminal is awake if a stop is going to occur.
The |error| procedure supplies a `\..' after the official message, then it
shows the location of the error; and if |interaction=error_stop_mode|,
it also enters into a dialog with the user, during which time the help
message may be printed.
@^system dependencies@>
@ The global variable |interaction| has four settings, representing increasing
amounts of user interaction:
@<Exported types@>=
enum mp_interaction_mode {
mp_unspecified_mode = 0, /* extra value for command-line switch */
mp_batch_mode, /* omits all stops and omits terminal output */
mp_nonstop_mode, /* omits all stops */
mp_scroll_mode, /* omits error stops */
mp_error_stop_mode /* stops at every opportunity to interact */
};
@ @<Option variables@>=
int interaction; /* current level of interaction */
int noninteractive; /* do we have a terminal? */
int extensions;
@ Set it here so it can be overwritten by the commandline
@<Allocate or initialize ...@>=
mp->interaction = opt->interaction;
if (mp->interaction == mp_unspecified_mode
|| mp->interaction > mp_error_stop_mode)
mp->interaction = mp_error_stop_mode;
if (mp->interaction < mp_unspecified_mode)
mp->interaction = mp_batch_mode;
@ |print_err| is not merged in |error| because it is also used in |prompt_file_name|,
where |error| is not called at all.
@<Declarations@>=
static void mp_print_err (MP mp, const char *A);
@ @c
static void mp_print_err (MP mp, const char *A) {
if (mp->interaction == mp_error_stop_mode)
wake_up_terminal();
if (mp->file_line_error_style && file_state && !terminal_input) {
mp_print_nl (mp, "");
if (long_name != NULL) {
mp_print (mp, long_name);
} else {
mp_print (mp, mp_str (mp, name));
}
mp_print (mp, ":");
mp_print_int (mp, line);
mp_print (mp, ": ");
} else {
mp_print_nl (mp, "! ");
}
mp_print (mp, A);
@.!\relax@>
}
@ \MP\ is careful not to call |error| when the print |selector| setting
might be unusual. The only possible values of |selector| at the time of
error messages are
\yskip\hang|no_print| (when |interaction=mp_batch_mode|
and |log_file| not yet open);
\hang|term_only| (when |interaction>mp_batch_mode| and |log_file| not yet open);
\hang|log_only| (when |interaction=mp_batch_mode| and |log_file| is open);
\hang|term_and_log| (when |interaction>mp_batch_mode| and |log_file| is open).
@d initialize_print_selector() mp->selector = (mp->interaction == mp_batch_mode ? no_print : term_only);
@ The global variable |history| records the worst level of error that
has been detected. It has four possible values: |spotless|, |warning_issued|,
|error_message_issued|, and |fatal_error_stop|.
Another global variable, |error_count|, is increased by one when an
|error| occurs without an interactive dialog, and it is reset to zero at
the end of every statement. If |error_count| reaches 100, \MP\ decides
that there is no point in continuing further.
@<Exported types@>=
enum mp_history_state {
mp_spotless = 0, /* |history| value when nothing has been amiss yet */
mp_warning_issued, /* |history| value when |begin_diagnostic| has been called */
mp_error_message_issued, /* |history| value when |error| has been called */
mp_fatal_error_stop, /* |history| value when termination was premature */
mp_system_error_stop /* |history| value when termination was due to disaster */
};
@ @<Glob...@>=
int history; /* has the source input been clean so far? */
int error_count; /* the number of scrolled errors since the last statement ended */
@ The value of |history| is initially |fatal_error_stop|, but it will
be changed to |spotless| if \MP\ survives the initialization process.
@ Since errors can be detected almost anywhere in \MP, we want to declare the
error procedures near the beginning of the program. But the error procedures
in turn use some other procedures, which need to be declared |forward|
before we get to |error| itself.
It is possible for |error| to be called recursively if some error arises
when |get_next| is being used to delete a token, and/or if some fatal error
occurs while \MP\ is trying to fix a non-fatal one. But such recursion
@^recursion@>
is never more than two levels deep.
@<Declarations@>=
static void mp_get_next (MP mp);
static void mp_term_input (MP mp);
static void mp_show_context (MP mp);
static void mp_begin_file_reading (MP mp);
static void mp_open_log_file (MP mp);
static void mp_clear_for_error_prompt (MP mp);
@ @<Internal ...@>=
void mp_normalize_selector (MP mp);
@ @<Glob...@>=
boolean use_err_help; /* should the |err_help| string be shown? */
mp_string err_help; /* a string set up by \&{errhelp} */
@ @<Allocate or ...@>=
mp->use_err_help = false;
@ The |jump_out| procedure just cuts across all active procedure levels and
goes to |end_of_MP|. This is the only nonlocal |goto| statement in the
whole program. It is used when there is no recovery from a particular error.
The program uses a |jump_buf| to handle this, this is initialized at three
spots: the start of |mp_new|, the start of |mp_initialize|, and the start
of |mp_run|. Those are the only library enty points.
@^system dependencies@>
@<Glob...@>=
jmp_buf *jump_buf;
@ If the array of internals is still |NULL| when |jump_out| is called, a
crash occured during initialization, and it is not safe to run the normal
cleanup routine.
@<Error hand...@>=
void mp_jump_out (MP mp) {
if (mp->internal != NULL && mp->history < mp_system_error_stop)
mp_close_files_and_terminate (mp);
longjmp (*(mp->jump_buf), 1);
}
@ @<Internal ...@>=
void mp_jump_out (MP mp);
@
@<Error hand...@>=
void mp_warn (MP mp, const char *msg) {
unsigned saved_selector = mp->selector;
mp_normalize_selector (mp);
mp_print_nl (mp, "Warning: ");
mp_print (mp, msg);
mp_print_ln (mp);
mp->selector = saved_selector;
}
@ Here now is the general |error| routine.
The argument |deletions_allowed| is set |false| if the |get_next|
routine is active when |error| is called; this ensures that |get_next|
will never be called recursively.
@^recursion@>
Individual lines of help are recorded in the array |help_line|, which
contains entries in positions |0..(help_ptr-1)|. They should be printed
in reverse order, i.e., with |help_line[0]| appearing last.
@c
void mp_error (MP mp, const char *msg, const char **hlp, boolean deletions_allowed) {
ASCII_code c; /* what the user types */
integer s1, s2; /* used to save global variables when deleting tokens */
mp_sym s3; /* likewise */
int i = 0;
const char *help_line[6]; /* helps for the next |error| */
unsigned int help_ptr; /* the number of help lines present */
const char **cnt = NULL;
mp_print_err(mp, msg);
if (hlp) {
cnt = hlp;
while (*cnt) {
i++; cnt++;
}
cnt = hlp;
}
help_ptr=i;
while (i>0) {
help_line[--i]= *cnt++;
}
if (mp->history < mp_error_message_issued)
mp->history = mp_error_message_issued;
mp_print_char (mp, xord ('.'));
mp_show_context (mp);
if (mp->halt_on_error) {
mp->history = mp_fatal_error_stop;
mp_jump_out (mp);
}
if ((!mp->noninteractive) && (mp->interaction == mp_error_stop_mode)) {
@<Get user's advice and |return|@>;
}
incr (mp->error_count);
if (mp->error_count == 100) {
mp_print_nl (mp, "(That makes 100 errors; please try again.)");
@.That makes 100 errors...@>;
mp->history = mp_fatal_error_stop;
mp_jump_out (mp);
}
@<Put help message on the transcript file@>;
}
@ @<Exported function ...@>=
extern void mp_error (MP mp, const char *msg, const char **hlp, boolean deletions_allowed);
extern void mp_warn (MP mp, const char *msg);
@ @<Get user's advice...@>=
while (true) {
CONTINUE:
mp_clear_for_error_prompt (mp);
prompt_input ("? ");
@.?\relax@>;
if (mp->last == mp->first)
return;
c = mp->buffer[mp->first];
if (c >= 'a')
c = (ASCII_code) (c + 'A' - 'a'); /* convert to uppercase */
@<Interpret code |c| and |return| if done@>;
}
@ It is desirable to provide an `\.E' option here that gives the user
an easy way to return from \MP\ to the system editor, with the offending
line ready to be edited. But such an extension requires some system
wizardry, so the present implementation simply types out the name of the
file that should be
edited and the relevant line number.
@^system dependencies@>
@<Exported types@>=
typedef void (*mp_editor_cmd) (MP, char *, int);
@ @<Option variables@>=
mp_editor_cmd run_editor;
@ @<Allocate or initialize ...@>=
set_callback_option (run_editor);
@ @<Declarations@>=
static void mp_run_editor (MP mp, char *fname, int fline);
@ @c
void mp_run_editor (MP mp, char *fname, int fline) {
char *s = xmalloc (256, 1);
mp_snprintf (s, 256, "You want to edit file %s at line %d\n", fname, fline);
wterm_ln (s);
@.You want to edit file x@>
}
@
@<Interpret code |c| and |return| if done@>=
switch (c) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
if (deletions_allowed) {
@<Delete tokens and |continue|@>;
}
break;
case 'E':
if (mp->file_ptr > 0) {
mp->interaction = mp_scroll_mode;
mp_close_files_and_terminate (mp);
(mp->run_editor) (mp,
mp_str (mp, mp->input_stack[mp->file_ptr].name_field),
mp_true_line (mp));
mp_jump_out (mp);
}
break;
case 'H':
@<Print the help information and |continue|@>;
/* |break;| */
case 'I':
@<Introduce new material from the terminal and |return|@>;
/* |break;| */
case 'Q':
case 'R':
case 'S':
@<Change the interaction level and |return|@>;
/* |break;| */
case 'X':
mp->interaction = mp_scroll_mode;
mp_jump_out (mp);
break;
default:
break;
}
@<Print the menu of available options@>
@ @<Print the menu...@>=
{
mp_print (mp, "Type <return> to proceed, S to scroll future error messages,");
@.Type <return> to proceed...@>;
mp_print_nl (mp, "R to run without stopping, Q to run quietly,");
mp_print_nl (mp, "I to insert something, ");
if (mp->file_ptr > 0)
mp_print (mp, "E to edit your file,");
if (deletions_allowed)
mp_print_nl (mp,
"1 or ... or 9 to ignore the next 1 to 9 tokens of input,");
mp_print_nl (mp, "H for help, X to quit.");
}
@ @<Change the interaction...@>=
{
mp->error_count = 0;
mp_print (mp, "OK, entering ");
switch (c) {
case 'Q':
mp->interaction = mp_batch_mode;
mp_print (mp, "batchmode");
decr (mp->selector);
break;
case 'R':
mp->interaction = mp_nonstop_mode;
mp_print (mp, "nonstopmode");
break;
case 'S':
mp->interaction = mp_scroll_mode;
mp_print (mp, "scrollmode");
break;
} /* there are no other cases */
mp_print (mp, "...");
mp_print_ln (mp);
update_terminal();
return;
}
@ When the following code is executed, |buffer[(first+1)..(last-1)]| may
contain the material inserted by the user; otherwise another prompt will
be given. In order to understand this part of the program fully, you need
to be familiar with \MP's input stacks.
@<Introduce new material...@>=
{
mp_begin_file_reading (mp); /* enter a new syntactic level for terminal input */
if (mp->last > mp->first + 1) {
loc = (halfword) (mp->first + 1);
mp->buffer[mp->first] = xord (' ');
} else {
prompt_input ("insert>");
loc = (halfword) mp->first;
@.insert>@>
}
mp->first = mp->last + 1;
mp->cur_input.limit_field = (halfword) mp->last;
return;
}
@ We allow deletion of up to 99 tokens at a time.
@<Delete tokens...@>=
{
s1 = cur_cmd();
s2 = cur_mod();
s3 = cur_sym();
mp->OK_to_interrupt = false;
if ((mp->last > mp->first + 1) && (mp->buffer[mp->first + 1] >= '0')
&& (mp->buffer[mp->first + 1] <= '9'))
c = xord (c * 10 + mp->buffer[mp->first + 1] - '0' * 11);
else
c = (ASCII_code) (c - '0');
while (c > 0) {
mp_get_next (mp); /* one-level recursive call of |error| is possible */
@<Decrease the string reference count, if the current token is a string@>;
c--;
};
set_cur_cmd (s1);
set_cur_mod (s2);
set_cur_sym (s3);
mp->OK_to_interrupt = true;
help_ptr = 2;
help_line[1] = "I have just deleted some text, as you asked.";
help_line[0] = "You can now delete more, or insert, or whatever.";
mp_show_context (mp);
goto CONTINUE;
}
@ Some wriggling with |help_line| is done here to avoid giving no
information whatsoever, or presenting the same information twice
in a row.
@<Print the help info...@>=
{
if (mp->use_err_help) {
@<Print the string |err_help|, possibly on several lines@>;
mp->use_err_help = false;
} else {
if (help_ptr == 0) {
help_ptr=2;
help_line[1] = "Sorry, I don't know how to help in this situation.";
help_line[0] = "Maybe you should try asking a human?";
}
do {
decr (help_ptr);
mp_print (mp, help_line[help_ptr]);
mp_print_ln (mp);
} while (help_ptr != 0);
};
help_ptr=4;
help_line[3] = "Sorry, I already gave what help I could...";
help_line[2] = "Maybe you should try asking a human?";
help_line[1] = "An error might have occurred before I noticed any problems.";
help_line[0] = "``If all else fails, read the instructions.''";
goto CONTINUE;
}
@ @<Print the string |err_help|, possibly on several lines@>=
{
size_t j = 0;
while (j < mp->err_help->len) {
if (*(mp->err_help->str + j) != '%')
mp_print (mp, (const char *) (mp->err_help->str + j));
else if (j + 1 == mp->err_help->len)
mp_print_ln (mp);
else if (*(mp->err_help->str + j) != '%')
mp_print_ln (mp);
else {
j++;
mp_print_char (mp, xord ('%'));
};
j++;
}
}
@ @<Put help message on the transcript file@>=
if (! mp->noninteractive) {
if (mp->interaction > mp_batch_mode) {
decr (mp->selector); /* avoid terminal output */
}
}
if (mp->use_err_help) {
mp_print_nl (mp, "");
@<Print the string |err_help|, possibly on several lines@>;
} else {
while (help_ptr > 0) {
decr (help_ptr);
mp_print_nl (mp, help_line[help_ptr]);
};
mp_print_ln (mp);
if (! mp->noninteractive) {
if (mp->interaction > mp_batch_mode)
incr (mp->selector); /* re-enable terminal output */
}
mp_print_ln (mp);
}
@ In anomalous cases, the print selector might be in an unknown state;
the following subroutine is called to fix things just enough to keep
running a bit longer.
@c
void mp_normalize_selector (MP mp) {
if (mp->log_opened)
mp->selector = term_and_log;
else
mp->selector = term_only;
if (mp->job_name == NULL)
mp_open_log_file (mp);
if (mp->interaction == mp_batch_mode)
decr (mp->selector);
}
@ The following procedure prints \MP's last words before dying.
@<Error hand...@>=
void mp_fatal_error (MP mp, const char *s) { /* prints |s|, and that's it */
const char *hlp[] = {s, NULL} ;
mp_normalize_selector (mp);
if ( mp->interaction==mp_error_stop_mode )
mp->interaction=mp_scroll_mode; /* no more interaction */
if ( mp->log_opened )
mp_error(mp, "Emergency stop", hlp, true);
mp->history=mp_fatal_error_stop;
mp_jump_out(mp); /* irrecoverable error */
@.Emergency stop@>
}
@ @<Exported function ...@>=
extern void mp_fatal_error (MP mp, const char *s);
@ @<Internal library declarations@>=
void mp_overflow (MP mp, const char *s, integer n);
@ @<Error hand...@>=
void mp_overflow (MP mp, const char *s, integer n) { /* stop due to finiteness */
char msg[256];
const char *hlp[] = {
"If you really absolutely need more capacity,",
"you can ask a wizard to enlarge me.",
NULL };
mp_normalize_selector (mp);
mp_snprintf (msg, 256, "MetaPost capacity exceeded, sorry [%s=%d]", s, (int) n);
@.MetaPost capacity exceeded ...@>;
if ( mp->interaction==mp_error_stop_mode )
mp->interaction=mp_scroll_mode; /* no more interaction */
if ( mp->log_opened )
mp_error(mp, msg, hlp, true);
mp->history=mp_fatal_error_stop;
mp_jump_out(mp); /* irrecoverable error */
}
@ The program might sometime run completely amok, at which point there is
no choice but to stop. If no previous error has been detected, that's bad
news; a message is printed that is really intended for the \MP\
maintenance person instead of the user (unless the user has been
particularly diabolical). The index entries for `this can't happen' may
help to pinpoint the problem.
@^dry rot@>
@<Internal library ...@>=
void mp_confusion (MP mp, const char *s);
@ Consistency check violated; |s| tells where.
@<Error hand...@>=
void mp_confusion (MP mp, const char *s) {
char msg[256];
const char *hlp[] = {
"One of your faux pas seems to have wounded me deeply...",
"in fact, I'm barely conscious. Please fix it and try again.",
NULL };
mp_normalize_selector (mp);
if (mp->history < mp_error_message_issued) {
mp_snprintf (msg, 256, "This can't happen (%s)", s);
@.This can't happen@>;
hlp[0] = "I'm broken. Please show this to someone who can fix can fix";
hlp[1] = NULL;
} else {
mp_snprintf (msg, 256, "I can\'t go on meeting you like this");
@.I can't go on...@>;
}
if ( mp->interaction==mp_error_stop_mode )
mp->interaction=mp_scroll_mode; /* no more interaction */
if ( mp->log_opened )
mp_error(mp, msg, hlp, true);
mp->history=mp_fatal_error_stop;
mp_jump_out(mp); /* irrecoverable error */
}
@ Users occasionally want to interrupt \MP\ while it's running.
If the runtime system allows this, one can implement
a routine that sets the global variable |interrupt| to some nonzero value
when such an interrupt is signaled. Otherwise there is probably at least
a way to make |interrupt| nonzero using the C debugger.
@^system dependencies@>
@^debugging@>
@d check_interrupt { if ( mp->interrupt!=0 )
mp_pause_for_instructions(mp); }
@<Global...@>=
integer interrupt; /* should \MP\ pause for instructions? */
boolean OK_to_interrupt; /* should interrupts be observed? */
integer run_state; /* are we processing input ? */
boolean finished; /* set true by |close_files_and_terminate| */
boolean reading_preload;
@ @<Allocate or ...@>=
mp->OK_to_interrupt = true;
mp->finished = false;
@ When an interrupt has been detected, the program goes into its
highest interaction level and lets the user have the full flexibility of
the |error| routine. \MP\ checks for interrupts only at times when it is
safe to do this.
@c
static void mp_pause_for_instructions (MP mp) {
const char *hlp[] = { "You rang?",
"Try to insert some instructions for me (e.g.,`I show x'),",
"unless you just want to quit by typing `X'.",
NULL } ;
if (mp->OK_to_interrupt) {
mp->interaction = mp_error_stop_mode;
if ((mp->selector == log_only) || (mp->selector == no_print))
incr (mp->selector);
@.Interruption@>;
mp_error (mp, "Interruption", hlp, false);
mp->interrupt = 0;
}
}
@* Arithmetic with scaled numbers.
The principal computations performed by \MP\ are done entirely in terms of
integers less than $2^{31}$ in magnitude; thus, the arithmetic specified in this
program can be carried out in exactly the same way on a wide variety of
computers, including some small ones.
@^small computers@>
But C does not rigidly define the |/| operation in the case of negative
dividends; for example, the result of |(-2*n-1) / 2| is |-(n+1)| on some
computers and |-n| on others (is this true ?). There are two principal
types of arithmetic: ``translation-preserving,'' in which the identity
|(a+q*b)/b=(a/b)+q| is valid; and ``negation-preserving,'' in which
|(-a)/b=-(a/b)|. This leads to two \MP s, which can produce
different results, although the differences should be negligible when the
language is being used properly. The \TeX\ processor has been defined
carefully so that both varieties of arithmetic will produce identical
output, but it would be too inefficient to constrain \MP\ in a similar way.
@d inf_t ((math_data *)mp->math)->inf_t
@ A single computation might use several subroutine calls, and it is
desirable to avoid producing multiple error messages in case of arithmetic
overflow. So the routines below set the global variable |arith_error| to |true|
instead of reporting errors directly to the user.
@^overflow in arithmetic@>
@<Glob...@>=
boolean arith_error; /* has arithmetic overflow occurred recently? */
@ @<Allocate or ...@>=
mp->arith_error = false;
@ At crucial points the program will say |check_arith|, to test if
an arithmetic error has been detected.
@d check_arith() do {
if ( mp->arith_error )
mp_clear_arith(mp);
} while (0)
@c
static void mp_clear_arith (MP mp) {
const char *hlp[] = {
"Uh, oh. A little while ago one of the quantities that I was",
"computing got too large, so I'm afraid your answers will be",
"somewhat askew. You'll probably have to adopt different",
"tactics next time. But I shall try to carry on anyway.",
NULL };
mp_error (mp, "Arithmetic overflow", hlp, true);
@.Arithmetic overflow@>;
mp->arith_error = false;
}
@ The definitions of these are set up by the math initialization.
@d arc_tol_k ((math_data *)mp->math)->arc_tol_k
@d coef_bound_k ((math_data *)mp->math)->coef_bound_k
@d coef_bound_minus_1 ((math_data *)mp->math)->coef_bound_minus_1
@d sqrt_8_e_k ((math_data *)mp->math)->sqrt_8_e_k
@d twelve_ln_2_k ((math_data *)mp->math)->twelve_ln_2_k
@d twelvebits_3 ((math_data *)mp->math)->twelvebits_3
@d one_k ((math_data *)mp->math)->one_k
@d epsilon_t ((math_data *)mp->math)->epsilon_t
@d unity_t ((math_data *)mp->math)->unity_t
@d zero_t ((math_data *)mp->math)->zero_t
@d two_t ((math_data *)mp->math)->two_t
@d three_t ((math_data *)mp->math)->three_t
@d half_unit_t ((math_data *)mp->math)->half_unit_t
@d three_quarter_unit_t ((math_data *)mp->math)->three_quarter_unit_t
@d twentysixbits_sqrt2_t ((math_data *)mp->math)->twentysixbits_sqrt2_t
@d twentyeightbits_d_t ((math_data *)mp->math)->twentyeightbits_d_t
@d twentysevenbits_sqrt2_d_t ((math_data *)mp->math)->twentysevenbits_sqrt2_d_t
@d warning_limit_t ((math_data *)mp->math)->warning_limit_t
@d precision_default ((math_data *)mp->math)->precision_default
@d precision_max ((math_data *)mp->math)->precision_max
@d precision_min ((math_data *)mp->math)->precision_min
@ In fact, the two sorts of scaling discussed above aren't quite
sufficient; \MP\ has yet another, used internally to keep track of angles.
@ We often want to print two scaled quantities in parentheses,
separated by a comma.
@<Basic printing...@>=
void mp_print_two (MP mp, mp_number x, mp_number y) { /* prints `|(x,y)|' */
mp_print_char (mp, xord ('('));
print_number (x);
mp_print_char (mp, xord (','));
print_number (y);
mp_print_char (mp, xord (')'));
}
@
@d fraction_one_t ((math_data *)mp->math)->fraction_one_t
@d fraction_half_t ((math_data *)mp->math)->fraction_half_t
@d fraction_three_t ((math_data *)mp->math)->fraction_three_t
@d fraction_four_t ((math_data *)mp->math)->fraction_four_t
@d one_eighty_deg_t ((math_data *)mp->math)->one_eighty_deg_t
@d three_sixty_deg_t ((math_data *)mp->math)->three_sixty_deg_t
@ @<Local variables for initialization@>=
integer k; /* all-purpose loop index */
@ And now let's complete our collection of numeric utility routines
by considering random number generation.
\MP\ generates pseudo-random numbers with the additive scheme recommended
in Section 3.6 of {\sl The Art of Computer Programming}; however, the
results are random fractions between 0 and |fraction_one-1|, inclusive.
There's an auxiliary array |randoms| that contains 55 pseudo-random
fractions. Using the recurrence $x_n=(x_{n-55}-x_{n-31})\bmod 2^{28}$,
we generate batches of 55 new $x_n$'s at a time by calling |new_randoms|.
The global variable |j_random| tells which element has most recently
been consumed.
The global variable |random_seed| was introduced in version 0.9,
for the sole reason of stressing the fact that the initial value of the
random seed is system-dependant. The initialization code below will initialize
this variable to |(internal[mp_time] div unity)+internal[mp_day]|, but this
is not good enough on modern fast machines that are capable of running
multiple MetaPost processes within the same second.
@^system dependencies@>
@<Glob...@>=
mp_number randoms[55]; /* the last 55 random values generated */
int j_random; /* the number of unused |randoms| */
@ @<Option variables@>=
int random_seed; /* the default random seed */
@ @<Allocate or initialize ...@>=
mp->random_seed = opt->random_seed;
{
int i;
for (i=0;i<55;i++) {
new_fraction (mp->randoms[i]);
}
}
@ @<Dealloc...@>=
{
int i;
for (i=0;i<55;i++) {
free_number (mp->randoms[i]);
}
}
@ @<Internal library ...@>=
void mp_new_randoms (MP mp);
@ @c
void mp_new_randoms (MP mp) {
int k; /* index into |randoms| */
mp_number x; /* accumulator */
new_number (x);
for (k = 0; k <= 23; k++) {
set_number_from_substraction(x, mp->randoms[k], mp->randoms[k + 31]);
if (number_negative(x))
number_add (x, fraction_one_t);
number_clone (mp->randoms[k], x);
}
for (k = 24; k <= 54; k++) {
set_number_from_substraction(x, mp->randoms[k], mp->randoms[k - 24]);
if (number_negative(x))
number_add (x, fraction_one_t);
number_clone (mp->randoms[k], x);
}
free_number (x);
mp->j_random = 54;
}
@ To consume a random fraction, the program below will say `|next_random|'.
Now each number system has its own implementation,
true to the original as much as possibile.
@c
/* Unused.
static void mp\_next\_random (MP mp, mp\_number *ret) {
if ( mp->j\_random==0 )
mp\_new\_randoms(mp);
else
decr(mp->j\_random);
number\_clone (*ret, mp->randoms[mp->j\_random]);
}
*/
@ To produce a uniform random number in the range |0<=u<x| or |0>=u>x|
or |0=u=x|, given a |scaled| value~|x|, we proceed as shown here.
Note that the call of |take_fraction| will produce the values 0 and~|x|
with about half the probability that it will produce any other particular
values between 0 and~|x|, because it rounds its answers.
This is the original one,
that stays as reference:
As said before, now each number system has its own implementation.
@c
/*Unused.
static void mp\_unif\_rand (MP mp, mp\_number *ret, mp\_number x\_orig) {
mp\_number y; // trial value
mp\_number x, abs\_x;
mp\_number u;
new\_fraction (y);
new\_number (x);
new\_number (abs\_x);
new\_number (u);
number\_clone (x, x\_orig);
number\_clone (abs\_x, x);
number\_abs (abs\_x);
mp\_next\_random(mp, \&u);
take\_fraction (y, abs\_x, u);
free\_number (u);
if (number\_equal(y, abs\_x)) {
set\_number\_to\_zero(*ret);
} else if (number\_positive(x)) {
number\_clone (*ret, y);
} else {
number\_clone (*ret, y);
number\_negate (*ret);
}
free\_number (abs\_x);
free\_number (x);
free\_number (y);
}
*/
@ Finally, a normal deviate with mean zero and unit standard deviation
can readily be obtained with the ratio method (Algorithm 3.4.1R in
{\sl The Art of Computer Programming\/}). This is the original one,
that stays as reference:
Now each number system has its own implementation,
true to the original as much as possibile.
@c
/* Unused.
static void mp\_norm\_rand (MP mp, mp\_number *ret) {
mp\_number ab\_vs\_cd;
mp\_number abs\_x;
mp\_number u;
mp\_number r;
mp\_number la, xa;
new\_number (ab\_vs\_cd);
new\_number (la);
new\_number (xa);
new\_number (abs\_x);
new\_number (u);
new\_number (r);
do {
do {
mp\_number v;
new\_number (v);
mp\_next\_random(mp, \&v);
number\_substract (v, fraction\_half\_t);
take\_fraction (xa, sqrt\_8\_e\_k, v);
free\_number (v);
mp\_next\_random(mp, \&u);
number\_clone (abs\_x, xa);
number\_abs (abs\_x);
} while (number\_greaterequal (abs\_x, u));
make\_fraction (r, xa, u);
number\_clone (xa, r);
m\_log (la, u);
set\_number\_from\_substraction(la, twelve\_ln\_2\_k, la);
ab\_vs\_cd (ab\_vs\_cd, one\_k, la, xa, xa);
} while (number\_negative(ab\_vs\_cd));
number\_clone (*ret, xa);
free\_number (ab\_vs\_cd);
free\_number (r);
free\_number (abs\_x);
free\_number (la);
free\_number (xa);
free\_number (u);
}
*/
@* Packed data.
@d max_quarterword 0x3FFF /* largest allowable value in a |quarterword| */
@d max_halfword 0xFFFFFFF /* largest allowable value in a |halfword| */
@ The macros |qi| and |qo| are used for input to and output
from quarterwords. These are legacy macros.
@^system dependencies@>
@d qo(A) (A) /* to read eight bits from a quarterword */
@d qi(A) (quarterword)(A) /* to store eight bits in a quarterword */
@ The reader should study the following definitions closely:
@^system dependencies@>
@<Types...@>=
typedef struct mp_value_node_data *mp_value_node;
typedef struct mp_node_data *mp_node;
typedef struct mp_symbol_entry *mp_sym;
typedef short quarterword; /* 1/4 of a word */
typedef int halfword; /* 1/2 of a word */
typedef struct {
integer scale; /* only for |indep_scale|, used together with |serial| */
integer serial; /* only for |indep_value|, used together with |scale| */
} mp_independent_data;
typedef struct {
mp_independent_data indep;
mp_number n;
mp_string str;
mp_sym sym;
mp_node node;
mp_knot p;
} mp_value_data;
typedef struct {
mp_variable_type type;
mp_value_data data;
} mp_value;
typedef struct {
quarterword b0, b1, b2, b3;
} four_quarters;
typedef union {
integer sc;
four_quarters qqqq;
} font_data;
@ The global variable |math_mode| has four settings, representing the
math value type that will be used in this run.
the typedef for |mp_number| is here because it has to come very early.
@<Exported types@>=
typedef enum {
mp_math_scaled_mode = 0,
mp_math_double_mode = 1,
mp_math_binary_mode = 2,
mp_math_decimal_mode = 3
} mp_math_mode;
@ @<Option variables@>=
int math_mode; /* math mode */
@ @<Allocate or initialize ...@>=
mp->math_mode = opt->math_mode;
@
@d xfree(A) do { mp_xfree(A); A=NULL; } while (0)
@d xrealloc(P,A,B) mp_xrealloc(mp,P,(size_t)A,B)
@d xmalloc(A,B) mp_xmalloc(mp,(size_t)A,B)
@d xstrdup(A) mp_xstrdup(mp,A)
@d XREALLOC(a,b,c) a = xrealloc(a,(b+1),sizeof(c));
@<Declare helpers@>=
extern void mp_xfree (void *x);
extern void *mp_xrealloc (MP mp, void *p, size_t nmem, size_t size);
extern void *mp_xmalloc (MP mp, size_t nmem, size_t size);
extern void mp_do_snprintf (char *str, int size, const char *fmt, ...);
extern void *do_alloc_node(MP mp, size_t size);
@ This is an attempt to spend less time in |malloc()|:
@d max_num_token_nodes 1000
@d max_num_pair_nodes 1000
@d max_num_knot_nodes 1000
@d max_num_value_nodes 1000
@d max_num_symbolic_nodes 1000
@<Global ...@>=
mp_node token_nodes;
int num_token_nodes;
mp_node pair_nodes;
int num_pair_nodes;
mp_knot knot_nodes;
int num_knot_nodes;
mp_node value_nodes;
int num_value_nodes;
mp_node symbolic_nodes;
int num_symbolic_nodes;
@ @<Allocate or initialize ...@>=
mp->token_nodes = NULL;
mp->num_token_nodes = 0;
mp->pair_nodes = NULL;
mp->num_pair_nodes = 0;
mp->knot_nodes = NULL;
mp->num_knot_nodes = 0;
mp->value_nodes = NULL;
mp->num_value_nodes = 0;
mp->symbolic_nodes = NULL;
mp->num_symbolic_nodes = 0;
@ @<Dealloc ...@>=
while (mp->value_nodes) {
mp_node p = mp->value_nodes;
mp->value_nodes = p->link;
mp_free_node(mp,p,value_node_size);
}
while (mp->symbolic_nodes) {
mp_node p = mp->symbolic_nodes;
mp->symbolic_nodes = p->link;
mp_free_node(mp,p,symbolic_node_size);
}
while (mp->pair_nodes) {
mp_node p = mp->pair_nodes;
mp->pair_nodes = p->link;
mp_free_node(mp,p,pair_node_size);
}
while (mp->token_nodes) {
mp_node p = mp->token_nodes;
mp->token_nodes = p->link;
mp_free_node(mp,p,token_node_size);
}
while (mp->knot_nodes) {
mp_knot p = mp->knot_nodes;
mp->knot_nodes = p->next;
mp_free_knot(mp,p);
}
@ This is a nicer way of allocating nodes.
@d malloc_node(A) do_alloc_node(mp,(A))
@
@c
void *do_alloc_node (MP mp, size_t size) {
void *p;
p = xmalloc(1,size);
add_var_used (size);
((mp_node)p)->link = NULL;
((mp_node)p)->has_number = 0;
return p;
}
@ The |max_size_test| guards against overflow, on the assumption that
|size_t| is at least 31bits wide.
@d max_size_test 0x7FFFFFFF
@c
void mp_xfree (void *x) {
if (x != NULL)
free (x);
}
void *mp_xrealloc (MP mp, void *p, size_t nmem, size_t size) {
void *w;
if ((max_size_test / size) < nmem) {
mp_fputs ("Memory size overflow!\n", mp->err_out);
mp->history = mp_fatal_error_stop;
mp_jump_out (mp);
}
w = realloc (p, (nmem * size));
if (w == NULL) {
mp_fputs ("Out of memory!\n", mp->err_out);
mp->history = mp_system_error_stop;
mp_jump_out (mp);
}
return w;
}
void *mp_xmalloc (MP mp, size_t nmem, size_t size) {
void *w;
#if DEBUG
if ((max_size_test / size) < nmem) {
mp_fputs ("Memory size overflow!\n", mp->err_out);
mp->history = mp_fatal_error_stop;
mp_jump_out (mp);
}
#endif
w = malloc (nmem * size);
if (w == NULL) {
mp_fputs ("Out of memory!\n", mp->err_out);
mp->history = mp_system_error_stop;
mp_jump_out (mp);
}
return w;
}
@ @<Internal library declarations@>=
# define mp_snprintf (void)snprintf
@* Dynamic memory allocation.
The \MP\ system does nearly all of its own memory allocation, so that it
can readily be transported into environments that do not have automatic
facilities for strings, garbage collection, etc., and so that it can be in
control of what error messages the user receives.
@d MP_VOID (mp_node)(1) /* |NULL+1|, a |NULL| pointer different from |NULL| */
@d mp_link(A) (A)->link /* the |link| field of a node */
@d set_mp_link(A,B) do {
mp_node d = (B);
/* |printf("set link of %p to %p on line %d\n", (A), d, __LINE__);| */
mp_link((A)) = d;
} while (0)
@d mp_type(A) (A)->type /* identifies what kind of value this is */
@d mp_name_type(A) (A)->name_type /* a clue to the name of this value */
@ @<MPlib internal header stuff@>=
#define NODE_BODY \
mp_variable_type type; \
mp_name_type_type name_type; \
unsigned short has_number; \
struct mp_node_data *link
typedef struct mp_node_data {
NODE_BODY;
mp_value_data data;
} mp_node_data;
typedef struct mp_node_data *mp_symbolic_node;
@ Users who wish to study the memory requirements of particular applications can
can use the special features that keep track of current and maximum memory usage.
\MP\ will report these statistics when |mp_tracing_stats| is positive.
@d add_var_used(a) do {
mp->var_used+=(a);
if (mp->var_used>mp->var_used_max) mp->var_used_max=mp->var_used;
} while (0)
@<Glob...@>=
size_t var_used; /* how much memory is in use */
size_t var_used_max; /* how much memory was in use max */
@ These redirect to function to aid in debugging.
@c
#if DEBUG
#define mp_sym_info(A) get_mp_sym_info(mp,(A))
#define set_mp_sym_info(A,B) do_set_mp_sym_info(mp,(A),(B))
#define mp_sym_sym(A) get_mp_sym_sym(mp,(A))
#define set_mp_sym_sym(A,B) do_set_mp_sym_sym(mp,(A),(mp_sym)(B))
static void do_set_mp_sym_info (MP mp, mp_node p, halfword v) {
FUNCTION_TRACE3 ("do_set_mp_sym_info(%p,%d)\n", p, v);
assert (p->type == mp_symbol_node);
set_indep_value(p, v);
}
static halfword get_mp_sym_info (MP mp, mp_node p) {
FUNCTION_TRACE3 ("%d = get_mp_sym_info(%p)\n", indep_value (p), p);
assert (p->type == mp_symbol_node);
return indep_value(p);
}
static void do_set_mp_sym_sym (MP mp, mp_node p, mp_sym v) {
mp_symbolic_node pp = (mp_symbolic_node) p;
FUNCTION_TRACE3 ("do_set_mp_sym_sym(%p,%p)\n", pp, v);
assert (pp->type == mp_symbol_node);
pp->data.sym = v;
}
static mp_sym get_mp_sym_sym (MP mp, mp_node p) {
mp_symbolic_node pp = (mp_symbolic_node) p;
FUNCTION_TRACE3 ("%p = get_mp_sym_sym(%p)\n", pp->data.sym, pp);
assert (pp->type == mp_symbol_node);
return pp->data.sym;
}
#else
#define mp_sym_info(A) indep_value(A)
#define set_mp_sym_info(A,B) set_indep_value(A, (B))
#define mp_sym_sym(A) (A)->data.sym
#define set_mp_sym_sym(A,B) (A)->data.sym = (mp_sym)(B)
#endif
@ @<Declarations@>=
#if DEBUG
static void do_set_mp_sym_info (MP mp, mp_node A, halfword B);
static halfword get_mp_sym_info (MP mp, mp_node p);
static void do_set_mp_sym_sym (MP mp, mp_node A, mp_sym B);
static mp_sym get_mp_sym_sym (MP mp, mp_node p);
#endif
@ The function |get_symbolic_node| returns a pointer to a new symbolic node whose
|link| field is null.
@^inner loop@>
@d symbolic_node_size sizeof(mp_node_data)
@c
static mp_node mp_get_symbolic_node (MP mp) {
mp_symbolic_node p;
if (mp->symbolic_nodes) {
p = (mp_symbolic_node)mp->symbolic_nodes;
mp->symbolic_nodes = p->link;
mp->num_symbolic_nodes--;
p->link = NULL;
} else {
p = malloc_node (symbolic_node_size);
new_number(p->data.n);
p->has_number = 1;
}
p->type = mp_symbol_node;
p->name_type = mp_normal_sym;
FUNCTION_TRACE2 ("%p = mp_get_symbolic_node()\n", p);
return (mp_node) p;
}
@ Conversely, when some node |p| of size |s| is no longer needed,
the operation |free_node(p,s)| will make its words available, by inserting
|p| as a new empty node just before where |rover| now points.
A symbolic node is recycled by calling |free_symbolic_node|.
@c
void mp_free_node (MP mp, mp_node p, size_t siz) { /* node liberation */
FUNCTION_TRACE3 ("mp_free_node(%p,%d)\n", p, (int)siz);
if (!p) return;
mp->var_used -= siz;
if (mp->math_mode > mp_math_double_mode) {
if (p->has_number >= 1 && is_number(((mp_symbolic_node)p)->data.n)) {
free_number(((mp_symbolic_node)p)->data.n);
}
if (p->has_number == 2 && is_number(((mp_value_node)p)->subscript_)) {
free_number(((mp_value_node)p)->subscript_);
}
/* There was a quite large |switch| here first, but the |mp_dash_node|
case was the only one that did anything ... */
if (mp_type (p) == mp_dash_node_type) {
free_number(((mp_dash_node)p)->start_x);
free_number(((mp_dash_node)p)->stop_x);
free_number(((mp_dash_node)p)->dash_y);
}
}
xfree (p);
}
void mp_free_symbolic_node (MP mp, mp_node p) { /* node liberation */
FUNCTION_TRACE2 ("mp_free_symbolic_node(%p)\n", p);
if (!p) return;
if (mp->num_symbolic_nodes < max_num_symbolic_nodes) {
p->link = mp->symbolic_nodes;
mp->symbolic_nodes = p;
mp->num_symbolic_nodes++;
return;
}
mp->var_used -= symbolic_node_size;
xfree (p);
}
void mp_free_value_node (MP mp, mp_node p) { /* node liberation */
FUNCTION_TRACE2 ("mp_free_value_node(%p)\n", p);
if (!p) return;
if (mp->num_value_nodes < max_num_value_nodes) {
p->link = mp->value_nodes;
mp->value_nodes = p;
mp->num_value_nodes++;
return;
}
mp->var_used -= value_node_size;
assert(p->has_number == 2);
if (mp->math_mode > mp_math_double_mode) {
free_number(((mp_value_node)p)->data.n);
free_number(((mp_value_node)p)->subscript_);
}
xfree (p);
}
@ @<Internal library declarations@>=
void mp_free_node (MP mp, mp_node p, size_t siz);
void mp_free_symbolic_node (MP mp, mp_node p);
void mp_free_value_node (MP mp, mp_node p);
@* Memory layout.
Some nodes are created statically, since static allocation is
more efficient than dynamic allocation when we can get away with it.
@<Glob...@>=
mp_dash_node null_dash;
mp_value_node dep_head;
mp_node inf_val;
mp_node zero_val;
mp_node temp_val;
mp_node end_attr;
mp_node bad_vardef;
mp_node temp_head;
mp_node hold_head;
mp_node spec_head;
@ The following code gets the memory off to a good start.
@<Initialize table entries@>=
mp->spec_head = mp_get_symbolic_node (mp);
mp->last_pending = mp->spec_head;
mp->temp_head = mp_get_symbolic_node (mp);
mp->hold_head = mp_get_symbolic_node (mp);
@ @<Free table entries@>=
mp_free_symbolic_node (mp, mp->spec_head);
mp_free_symbolic_node (mp, mp->temp_head);
mp_free_symbolic_node (mp, mp->hold_head);
@ The procedure |flush_node_list(p)| frees an entire linked list of
nodes that starts at a given position, until coming to a |NULL| pointer.
@^inner loop@>
@c
static void mp_flush_node_list (MP mp, mp_node p) {
mp_node q; /* the node being recycled */
FUNCTION_TRACE2 ("mp_flush_node_list(%p)\n", p);
while (p != NULL) {
q = p;
p = p->link;
if (q->type != mp_symbol_node)
mp_free_token_node (mp, q);
else
mp_free_symbolic_node (mp, q);
}
}
@* The command codes.
Before we can go much further, we need to define symbolic names for the internal
code numbers that represent the various commands obeyed by \MP. These codes
are somewhat arbitrary, but not completely so. For example,
some codes have been made adjacent so that |case| statements in the
program need not consider cases that are widely spaced, or so that |case|
statements can be replaced by |if| statements. A command can begin an
expression if and only if its code lies between |min_primary_command| and
|max_primary_command|, inclusive. The first token of a statement that doesn't
begin with an expression has a command code between |min_command| and
|max_statement_command|, inclusive. Anything less than |min_command| is
eliminated during macro expansions, and anything no more than |max_pre_command|
is eliminated when expanding \TeX\ material. Ranges such as
|min_secondary_command..max_secondary_command| are used when parsing
expressions, but the relative ordering within such a range is generally not
critical.
The ordering of the highest-numbered commands
(|comma<semicolon<end_group<stop|) is crucial for the parsing and
error-recovery methods of this program as is the ordering |if_test<fi_or_else|
for the smallest two commands. The ordering is also important in the ranges
|numeric_token..plus_or_minus| and |left_brace..ampersand|.
At any rate, here is the list, for future reference.
@d mp_max_command_code mp_stop
@d mp_max_pre_command mp_mpx_break
@d mp_min_command (mp_defined_macro+1)
@d mp_max_statement_command mp_type_name
@d mp_min_primary_command mp_type_name
@d mp_min_suffix_token mp_internal_quantity
@d mp_max_suffix_token mp_numeric_token
@d mp_max_primary_command mp_plus_or_minus /* should also be |numeric_token+1| */
@d mp_min_tertiary_command mp_plus_or_minus
@d mp_max_tertiary_command mp_tertiary_binary
@d mp_min_expression_command mp_left_brace
@d mp_max_expression_command mp_equals
@d mp_min_secondary_command mp_and_command
@d mp_max_secondary_command mp_secondary_binary
@d mp_end_of_statement (cur_cmd()>mp_comma)
@<Enumeration types@>=
typedef enum {
mp_start_tex=1, /* begin \TeX\ material (\&{btex}, \&{verbatimtex}) */
mp_etex_marker, /* end \TeX\ material (\&{etex}) */
mp_mpx_break, /* stop reading an \.{MPX} file (\&{mpxbreak}) */
mp_if_test, /* conditional text (\&{if}) */
mp_fi_or_else, /* delimiters for conditionals (\&{elseif}, \&{else}, \&{fi}) */
mp_input, /* input a source file (\&{input}, \&{endinput}) */
mp_iteration, /* iterate (\&{for}, \&{forsuffixes}, \&{forever}, \&{endfor}) */
mp_repeat_loop, /* special command substituted for \&{endfor} */
mp_exit_test, /* premature exit from a loop (\&{exitif}) */
mp_relax, /* do nothing (\.{\char`\\}) */
mp_scan_tokens, /* put a string into the input buffer */
mp_runscript, /* put a script result string into the input buffer */
mp_maketext, /* put a script result string into the input buffer */
mp_expand_after, /* look ahead one token */
mp_defined_macro, /* a macro defined by the user */
mp_save_command, /* save a list of tokens (\&{save}) */
mp_interim_command, /* save an internal quantity (\&{interim}) */
mp_let_command, /* redefine a symbolic token (\&{let}) */
mp_new_internal, /* define a new internal quantity (\&{newinternal}) */
mp_macro_def, /* define a macro (\&{def}, \&{vardef}, etc.) */
mp_ship_out_command, /* output a character (\&{shipout}) */
mp_add_to_command, /* add to edges (\&{addto}) */
mp_bounds_command, /* add bounding path to edges (\&{setbounds}, \&{clip}) */
mp_tfm_command, /* command for font metric info (\&{ligtable}, etc.) */
mp_protection_command, /* set protection flag (\&{outer}, \&{inner}) */
mp_show_command, /* diagnostic output (\&{show}, \&{showvariable}, etc.) */
mp_mode_command, /* set interaction level (\&{batchmode}, etc.) */
mp_random_seed, /* initialize random number generator (\&{randomseed}) */
mp_message_command, /* communicate to user (\&{message}, \&{errmessage}) */
mp_every_job_command, /* designate a starting token (\&{everyjob}) */
mp_delimiters, /* define a pair of delimiters (\&{delimiters}) */
mp_special_command, /* output special info (\&{special})
or font map info (\&{fontmapfile}, \&{fontmapline}) */
mp_write_command, /* write text to a file (\&{write}) */
mp_type_name, /* declare a type (\&{numeric}, \&{pair}, etc.) */
mp_left_delimiter, /* the left delimiter of a matching pair */
mp_begin_group, /* beginning of a group (\&{begingroup}) */
mp_nullary, /* an operator without arguments (e.g., \&{normaldeviate}) */
mp_unary, /* an operator with one argument (e.g., \&{sqrt}) */
mp_str_op, /* convert a suffix to a string (\&{str}) */
mp_cycle, /* close a cyclic path (\&{cycle}) */
mp_primary_binary, /* binary operation taking `\&{of}' (e.g., \&{point}) */
mp_capsule_token, /* a value that has been put into a token list */
mp_string_token, /* a string constant (e.g., |"hello"|) */
mp_internal_quantity, /* internal numeric parameter (e.g., \&{pausing}) */
mp_tag_token, /* a symbolic token without a primitive meaning */
mp_numeric_token, /* a numeric constant (e.g., \.{3.14159}) */
mp_plus_or_minus, /* either `\.+' or `\.-' */
mp_tertiary_secondary_macro, /* a macro defined by \&{secondarydef} */
mp_tertiary_binary, /* an operator at the tertiary level (e.g., `\.{++}') */
mp_left_brace, /* the operator `\.{\char`\{}' */
mp_path_join, /* the operator `\.{..}' */
mp_ampersand, /* the operator `\.\&' */
mp_expression_tertiary_macro, /* a macro defined by \&{tertiarydef} */
mp_expression_binary, /* an operator at the expression level (e.g., `\.<') */
mp_equals, /* the operator `\.=' */
mp_and_command, /* the operator `\&{and}' */
mp_secondary_primary_macro, /* a macro defined by \&{primarydef} */
mp_slash, /* the operator `\./' */
mp_secondary_binary, /* an operator at the binary level (e.g., \&{shifted}) */
mp_param_type, /* type of parameter (\&{primary}, \&{expr}, \&{suffix}, etc.) */
mp_controls, /* specify control points explicitly (\&{controls}) */
mp_tension, /* specify tension between knots (\&{tension}) */
mp_at_least, /* bounded tension value (\&{atleast}) */
mp_curl_command, /* specify curl at an end knot (\&{curl}) */
mp_macro_special, /* special macro operators (\&{quote}, \.{\#\AT!}, etc.) */
mp_right_delimiter, /* the right delimiter of a matching pair */
mp_left_bracket, /* the operator `\.[' */
mp_right_bracket, /* the operator `\.]' */
mp_right_brace, /* the operator `\.{\char`\}}' */
mp_with_option, /* option for filling (\&{withpen}, \&{withweight}, etc.) */
mp_thing_to_add,
/* variant of \&{addto} (\&{contour}, \&{doublepath}, \&{also}) */
mp_of_token, /* the operator `\&{of}' */
mp_to_token, /* the operator `\&{to}' */
mp_step_token, /* the operator `\&{step}' */
mp_until_token, /* the operator `\&{until}' */
mp_within_token, /* the operator `\&{within}' */
mp_lig_kern_token,
/* the operators `\&{kern}' and `\.{=:}' and `\.{=:\char'174}', etc. */
mp_assignment, /* the operator `\.{:=}' */
mp_skip_to, /* the operation `\&{skipto}' */
mp_bchar_label, /* the operator `\.{\char'174\char'174:}' */
mp_double_colon, /* the operator `\.{::}' */
mp_colon, /* the operator `\.:' */
@#
mp_comma, /* the operator `\.,', must be |colon+1| */
mp_semicolon, /* the operator `\.;', must be |comma+1| */
mp_end_group, /* end a group (\&{endgroup}), must be |semicolon+1| */
mp_stop, /* end a job (\&{end}, \&{dump}), must be |end_group+1| */
mp_outer_tag, /* protection code added to command code */
mp_undefined_cs, /* protection code added to command code */
} mp_command_code;
@ Variables and capsules in \MP\ have a variety of ``types,''
distinguished by the code numbers defined here. These numbers are also
not completely arbitrary. Things that get expanded must have types
|>mp_independent|; a type remaining after expansion is numeric if and only if
its code number is at least |numeric_type|; objects containing numeric
parts must have types between |transform_type| and |pair_type|;
all other types must be smaller than |transform_type|; and among the types
that are not unknown or vacuous, the smallest two must be |boolean_type|
and |string_type| in that order.
@d unknown_tag 1 /* this constant is added to certain type codes below */
@d unknown_types mp_unknown_boolean: case mp_unknown_string:
case mp_unknown_pen: case mp_unknown_picture: case mp_unknown_path
@<Enumeration types@>=
typedef enum {
mp_undefined = 0, /* no type has been declared */
mp_vacuous, /* no expression was present */
mp_boolean_type, /* \&{boolean} with a known value */
mp_unknown_boolean,
mp_string_type, /* \&{string} with a known value */
mp_unknown_string,
mp_pen_type, /* \&{pen} with a known value */
mp_unknown_pen,
mp_path_type, /* \&{path} with a known value */
mp_unknown_path,
mp_picture_type, /* \&{picture} with a known value */
mp_unknown_picture,
mp_transform_type, /* \&{transform} variable or capsule */
mp_color_type, /* \&{color} variable or capsule */
mp_cmykcolor_type, /* \&{cmykcolor} variable or capsule */
mp_pair_type, /* \&{pair} variable or capsule */
mp_numeric_type, /* variable that has been declared \&{numeric} but not used */
mp_known, /* \&{numeric} with a known value */
mp_dependent, /* a linear combination with |fraction| coefficients */
mp_proto_dependent, /* a linear combination with |scaled| coefficients */
mp_independent, /* \&{numeric} with unknown value */
mp_token_list, /* variable name or suffix argument or text argument */
mp_structured, /* variable with subscripts and attributes */
mp_unsuffixed_macro, /* variable defined with \&{vardef} but no \.{\AT!\#} */
mp_suffixed_macro, /* variable defined with \&{vardef} and \.{\AT!\#} */
/* here are some generic node types */
mp_symbol_node,
mp_token_node_type,
mp_value_node_type,
mp_attr_node_type,
mp_subscr_node_type,
mp_pair_node_type,
mp_transform_node_type,
mp_color_node_type,
mp_cmykcolor_node_type,
/* it is important that the next 7 items remain in this order, for export */
mp_fill_node_type,
mp_stroked_node_type,
mp_text_node_type,
mp_start_clip_node_type,
mp_start_bounds_node_type,
mp_stop_clip_node_type,
mp_stop_bounds_node_type,
mp_dash_node_type,
mp_dep_node_type,
mp_if_node_type,
mp_edge_header_node_type,
} mp_variable_type;
@ @<Declarations@>=
static void mp_print_type (MP mp, quarterword t);
@ @<Basic printing procedures@>=
static const char *mp_type_string (quarterword t) {
const char *s = NULL;
switch (t) {
case mp_undefined:
s = "undefined";
break;
case mp_vacuous:
s = "vacuous";
break;
case mp_boolean_type:
s = "boolean";
break;
case mp_unknown_boolean:
s = "unknown boolean";
break;
case mp_string_type:
s = "string";
break;
case mp_unknown_string:
s = "unknown string";
break;
case mp_pen_type:
s = "pen";
break;
case mp_unknown_pen:
s = "unknown pen";
break;
case mp_path_type:
s = "path";
break;
case mp_unknown_path:
s = "unknown path";
break;
case mp_picture_type:
s = "picture";
break;
case mp_unknown_picture:
s = "unknown picture";
break;
case mp_transform_type:
s = "transform";
break;
case mp_color_type:
s = "color";
break;
case mp_cmykcolor_type:
s = "cmykcolor";
break;
case mp_pair_type:
s = "pair";
break;
case mp_known:
s = "known numeric";
break;
case mp_dependent:
s = "dependent";
break;
case mp_proto_dependent:
s = "proto-dependent";
break;
case mp_numeric_type:
s = "numeric";
break;
case mp_independent:
s = "independent";
break;
case mp_token_list:
s = "token list";
break;
case mp_structured:
s = "mp_structured";
break;
case mp_unsuffixed_macro:
s = "unsuffixed macro";
break;
case mp_suffixed_macro:
s = "suffixed macro";
break;
case mp_symbol_node:
s = "symbol node";
break;
case mp_token_node_type:
s = "token node";
break;
case mp_value_node_type:
s = "value node";
break;
case mp_attr_node_type:
s = "attribute node";
break;
case mp_subscr_node_type:
s = "subscript node";
break;
case mp_pair_node_type:
s = "pair node";
break;
case mp_transform_node_type:
s = "transform node";
break;
case mp_color_node_type:
s = "color node";
break;
case mp_cmykcolor_node_type:
s = "cmykcolor node";
break;
case mp_fill_node_type:
s = "fill node";
break;
case mp_stroked_node_type:
s = "stroked node";
break;
case mp_text_node_type:
s = "text node";
break;
case mp_start_clip_node_type:
s = "start clip node";
break;
case mp_start_bounds_node_type:
s = "start bounds node";
break;
case mp_stop_clip_node_type:
s = "stop clip node";
break;
case mp_stop_bounds_node_type:
s = "stop bounds node";
break;
case mp_dash_node_type:
s = "dash node";
break;
case mp_dep_node_type:
s = "dependency node";
break;
case mp_if_node_type:
s = "if node";
break;
case mp_edge_header_node_type:
s = "edge header node";
break;
default:
{
char ss[256];
mp_snprintf (ss, 256, "<unknown type %d>", t);
s = strdup(ss);
}
break;
}
return s;
}
void mp_print_type (MP mp, quarterword t) {
if (t >= 0 && t <= mp_edge_header_node_type)
mp_print (mp, mp_type_string (t));
else
mp_print (mp, "unknown");
}
@ Values inside \MP\ are stored in non-symbolic nodes that have a |name_type|
as well as a |type|. The possibilities for |name_type| are defined
here; they will be explained in more detail later.
@<Enumeration types...@>=
typedef enum {
mp_root = 0, /* |name_type| at the top level of a variable */
mp_saved_root, /* same, when the variable has been saved */
mp_structured_root, /* |name_type| where a |mp_structured| branch occurs */
mp_subscr, /* |name_type| in a subscript node */
mp_attr, /* |name_type| in an attribute node */
mp_x_part_sector, /* |name_type| in the \&{xpart} of a node */
mp_y_part_sector, /* |name_type| in the \&{ypart} of a node */
mp_xx_part_sector, /* |name_type| in the \&{xxpart} of a node */
mp_xy_part_sector, /* |name_type| in the \&{xypart} of a node */
mp_yx_part_sector, /* |name_type| in the \&{yxpart} of a node */
mp_yy_part_sector, /* |name_type| in the \&{yypart} of a node */
mp_red_part_sector, /* |name_type| in the \&{redpart} of a node */
mp_green_part_sector, /* |name_type| in the \&{greenpart} of a node */
mp_blue_part_sector, /* |name_type| in the \&{bluepart} of a node */
mp_cyan_part_sector, /* |name_type| in the \&{redpart} of a node */
mp_magenta_part_sector, /* |name_type| in the \&{greenpart} of a node */
mp_yellow_part_sector, /* |name_type| in the \&{bluepart} of a node */
mp_black_part_sector, /* |name_type| in the \&{greenpart} of a node */
mp_grey_part_sector, /* |name_type| in the \&{bluepart} of a node */
mp_capsule, /* |name_type| in stashed-away subexpressions */
mp_token, /* |name_type| in a numeric token or string token */
/* Symbolic nodes also have |name_type|, which is a different enumeration */
mp_normal_sym,
mp_internal_sym, /* for values of internals */
mp_macro_sym, /* for macro names */
mp_expr_sym, /* for macro parameters if type |expr| */
mp_suffix_sym, /* for macro parameters if type |suffix| */
mp_text_sym, /* for macro parameters if type |text| */
@<Operation codes@>
} mp_name_type_type;
@ Primitive operations that produce values have a secondary identification
code in addition to their command code; it's something like genera and species.
For example, `\.*' has the command code |primary_binary|, and its
secondary identification is |times|. The secondary codes start such that
they don't overlap with the type codes; some type codes (e.g., |mp_string_type|)
are used as operators as well as type identifications. The relative values
are not critical, except for |true_code..false_code|, |or_op..and_op|,
and |filled_op..bounded_op|. The restrictions are that
|and_op-false_code=or_op-true_code|, that the ordering of
|x_part...blue_part| must match that of |x_part_sector..mp_blue_part_sector|,
and the ordering of |filled_op..bounded_op| must match that of the code
values they test for.
@d mp_min_of mp_substring_of
@<Operation codes@>=
mp_true_code, /* operation code for \.{true} */
mp_false_code, /* operation code for \.{false} */
mp_null_picture_code, /* operation code for \.{nullpicture} */
mp_null_pen_code, /* operation code for \.{nullpen} */
mp_read_string_op, /* operation code for \.{readstring} */
mp_pen_circle, /* operation code for \.{pencircle} */
mp_normal_deviate, /* operation code for \.{normaldeviate} */
mp_read_from_op, /* operation code for \.{readfrom} */
mp_close_from_op, /* operation code for \.{closefrom} */
mp_odd_op, /* operation code for \.{odd} */
mp_known_op, /* operation code for \.{known} */
mp_unknown_op, /* operation code for \.{unknown} */
mp_not_op, /* operation code for \.{not} */
mp_decimal, /* operation code for \.{decimal} */
mp_reverse, /* operation code for \.{reverse} */
mp_make_path_op, /* operation code for \.{makepath} */
mp_make_pen_op, /* operation code for \.{makepen} */
mp_oct_op, /* operation code for \.{oct} */
mp_hex_op, /* operation code for \.{hex} */
mp_ASCII_op, /* operation code for \.{ASCII} */
mp_char_op, /* operation code for \.{char} */
mp_length_op, /* operation code for \.{length} */
mp_turning_op, /* operation code for \.{turningnumber} */
mp_color_model_part, /* operation code for \.{colormodel} */
mp_x_part, /* operation code for \.{xpart} */
mp_y_part, /* operation code for \.{ypart} */
mp_xx_part, /* operation code for \.{xxpart} */
mp_xy_part, /* operation code for \.{xypart} */
mp_yx_part, /* operation code for \.{yxpart} */
mp_yy_part, /* operation code for \.{yypart} */
mp_red_part, /* operation code for \.{redpart} */
mp_green_part, /* operation code for \.{greenpart} */
mp_blue_part, /* operation code for \.{bluepart} */
mp_cyan_part, /* operation code for \.{cyanpart} */
mp_magenta_part, /* operation code for \.{magentapart} */
mp_yellow_part, /* operation code for \.{yellowpart} */
mp_black_part, /* operation code for \.{blackpart} */
mp_grey_part, /* operation code for \.{greypart} */
mp_font_part, /* operation code for \.{fontpart} */
mp_text_part, /* operation code for \.{textpart} */
mp_path_part, /* operation code for \.{pathpart} */
mp_pen_part, /* operation code for \.{penpart} */
mp_dash_part, /* operation code for \.{dashpart} */
mp_prescript_part, /* operation code for \.{prescriptpart} */
mp_postscript_part, /* operation code for \.{postscriptpart} */
mp_sqrt_op, /* operation code for \.{sqrt} */
mp_m_exp_op, /* operation code for \.{mexp} */
mp_m_log_op, /* operation code for \.{mlog} */
mp_sin_d_op, /* operation code for \.{sind} */
mp_cos_d_op, /* operation code for \.{cosd} */
mp_floor_op, /* operation code for \.{floor} */
mp_uniform_deviate, /* operation code for \.{uniformdeviate} */
mp_char_exists_op, /* operation code for \.{charexists} */
mp_font_size, /* operation code for \.{fontsize} */
mp_ll_corner_op, /* operation code for \.{llcorner} */
mp_lr_corner_op, /* operation code for \.{lrcorner} */
mp_ul_corner_op, /* operation code for \.{ulcorner} */
mp_ur_corner_op, /* operation code for \.{urcorner} */
mp_arc_length, /* operation code for \.{arclength} */
mp_angle_op, /* operation code for \.{angle} */
mp_cycle_op, /* operation code for \.{cycle} */
mp_filled_op, /* operation code for \.{filled} */
mp_stroked_op, /* operation code for \.{stroked} */
mp_textual_op, /* operation code for \.{textual} */
mp_clipped_op, /* operation code for \.{clipped} */
mp_bounded_op, /* operation code for \.{bounded} */
mp_plus, /* operation code for \.+ */
mp_minus, /* operation code for \.- */
mp_times, /* operation code for \.* */
mp_over, /* operation code for \./ */
mp_pythag_add, /* operation code for \.{++} */
mp_pythag_sub, /* operation code for \.{+-+} */
mp_or_op, /* operation code for \.{or} */
mp_and_op, /* operation code for \.{and} */
mp_less_than, /* operation code for \.< */
mp_less_or_equal, /* operation code for \.{<=} */
mp_greater_than, /* operation code for \.> */
mp_greater_or_equal, /* operation code for \.{>=} */
mp_equal_to, /* operation code for \.= */
mp_unequal_to, /* operation code for \.{<>} */
mp_concatenate, /* operation code for \.\& */
mp_rotated_by, /* operation code for \.{rotated} */
mp_slanted_by, /* operation code for \.{slanted} */
mp_scaled_by, /* operation code for \.{scaled} */
mp_shifted_by, /* operation code for \.{shifted} */
mp_transformed_by, /* operation code for \.{transformed} */
mp_x_scaled, /* operation code for \.{xscaled} */
mp_y_scaled, /* operation code for \.{yscaled} */
mp_z_scaled, /* operation code for \.{zscaled} */
mp_in_font, /* operation code for \.{infont} */
mp_intersect, /* operation code for \.{intersectiontimes} */
mp_double_dot, /* operation code for improper \.{..} */
mp_substring_of, /* operation code for \.{substring} */
mp_subpath_of, /* operation code for \.{subpath} */
mp_direction_time_of, /* operation code for \.{directiontime} */
mp_point_of, /* operation code for \.{point} */
mp_precontrol_of, /* operation code for \.{precontrol} */
mp_postcontrol_of, /* operation code for \.{postcontrol} */
mp_pen_offset_of, /* operation code for \.{penoffset} */
mp_arc_time_of, /* operation code for \.{arctime} */
mp_version, /* operation code for \.{mpversion} */
mp_envelope_of, /* operation code for \.{envelope} */
mp_glyph_infont, /* operation code for \.{glyph} */
mp_kern_flag /* operation code for \.{kern} */
@ @c
static void mp_print_op (MP mp, quarterword c) {
if (c <= mp_numeric_type) {
mp_print_type (mp, c);
} else {
switch (c) {
case mp_true_code:
mp_print (mp, "true");
break;
case mp_false_code:
mp_print (mp, "false");
break;
case mp_null_picture_code:
mp_print (mp, "nullpicture");
break;
case mp_null_pen_code:
mp_print (mp, "nullpen");
break;
case mp_read_string_op:
mp_print (mp, "readstring");
break;
case mp_pen_circle:
mp_print (mp, "pencircle");
break;
case mp_normal_deviate:
mp_print (mp, "normaldeviate");
break;
case mp_read_from_op:
mp_print (mp, "readfrom");
break;
case mp_close_from_op:
mp_print (mp, "closefrom");
break;
case mp_odd_op:
mp_print (mp, "odd");
break;
case mp_known_op:
mp_print (mp, "known");
break;
case mp_unknown_op:
mp_print (mp, "unknown");
break;
case mp_not_op:
mp_print (mp, "not");
break;
case mp_decimal:
mp_print (mp, "decimal");
break;
case mp_reverse:
mp_print (mp, "reverse");
break;
case mp_make_path_op:
mp_print (mp, "makepath");
break;
case mp_make_pen_op:
mp_print (mp, "makepen");
break;
case mp_oct_op:
mp_print (mp, "oct");
break;
case mp_hex_op:
mp_print (mp, "hex");
break;
case mp_ASCII_op:
mp_print (mp, "ASCII");
break;
case mp_char_op:
mp_print (mp, "char");
break;
case mp_length_op:
mp_print (mp, "length");
break;
case mp_turning_op:
mp_print (mp, "turningnumber");
break;
case mp_x_part:
mp_print (mp, "xpart");
break;
case mp_y_part:
mp_print (mp, "ypart");
break;
case mp_xx_part:
mp_print (mp, "xxpart");
break;
case mp_xy_part:
mp_print (mp, "xypart");
break;
case mp_yx_part:
mp_print (mp, "yxpart");
break;
case mp_yy_part:
mp_print (mp, "yypart");
break;
case mp_red_part:
mp_print (mp, "redpart");
break;
case mp_green_part:
mp_print (mp, "greenpart");
break;
case mp_blue_part:
mp_print (mp, "bluepart");
break;
case mp_cyan_part:
mp_print (mp, "cyanpart");
break;
case mp_magenta_part:
mp_print (mp, "magentapart");
break;
case mp_yellow_part:
mp_print (mp, "yellowpart");
break;
case mp_black_part:
mp_print (mp, "blackpart");
break;
case mp_grey_part:
mp_print (mp, "greypart");
break;
case mp_color_model_part:
mp_print (mp, "colormodel");
break;
case mp_font_part:
mp_print (mp, "fontpart");
break;
case mp_text_part:
mp_print (mp, "textpart");
break;
case mp_prescript_part:
mp_print (mp, "prescriptpart");
break;
case mp_postscript_part:
mp_print (mp, "postscriptpart");
break;
case mp_path_part:
mp_print (mp, "pathpart");
break;
case mp_pen_part:
mp_print (mp, "penpart");
break;
case mp_dash_part:
mp_print (mp, "dashpart");
break;
case mp_sqrt_op:
mp_print (mp, "sqrt");
break;
case mp_m_exp_op:
mp_print (mp, "mexp");
break;
case mp_m_log_op:
mp_print (mp, "mlog");
break;
case mp_sin_d_op:
mp_print (mp, "sind");
break;
case mp_cos_d_op:
mp_print (mp, "cosd");
break;
case mp_floor_op:
mp_print (mp, "floor");
break;
case mp_uniform_deviate:
mp_print (mp, "uniformdeviate");
break;
case mp_char_exists_op:
mp_print (mp, "charexists");
break;
case mp_font_size:
mp_print (mp, "fontsize");
break;
case mp_ll_corner_op:
mp_print (mp, "llcorner");
break;
case mp_lr_corner_op:
mp_print (mp, "lrcorner");
break;
case mp_ul_corner_op:
mp_print (mp, "ulcorner");
break;
case mp_ur_corner_op:
mp_print (mp, "urcorner");
break;
case mp_arc_length:
mp_print (mp, "arclength");
break;
case mp_angle_op:
mp_print (mp, "angle");
break;
case mp_cycle_op:
mp_print (mp, "cycle");
break;
case mp_filled_op:
mp_print (mp, "filled");
break;
case mp_stroked_op:
mp_print (mp, "stroked");
break;
case mp_textual_op:
mp_print (mp, "textual");
break;
case mp_clipped_op:
mp_print (mp, "clipped");
break;
case mp_bounded_op:
mp_print (mp, "bounded");
break;
case mp_plus:
mp_print_char (mp, xord ('+'));
break;
case mp_minus:
mp_print_char (mp, xord ('-'));
break;
case mp_times:
mp_print_char (mp, xord ('*'));
break;
case mp_over:
mp_print_char (mp, xord ('/'));
break;
case mp_pythag_add:
mp_print (mp, "++");
break;
case mp_pythag_sub:
mp_print (mp, "+-+");
break;
case mp_or_op:
mp_print (mp, "or");
break;
case mp_and_op:
mp_print (mp, "and");
break;
case mp_less_than:
mp_print_char (mp, xord ('<'));
break;
case mp_less_or_equal:
mp_print (mp, "<=");
break;
case mp_greater_than:
mp_print_char (mp, xord ('>'));
break;
case mp_greater_or_equal:
mp_print (mp, ">=");
break;
case mp_equal_to:
mp_print_char (mp, xord ('='));
break;
case mp_unequal_to:
mp_print (mp, "<>");
break;
case mp_concatenate:
mp_print (mp, "&");
break;
case mp_rotated_by:
mp_print (mp, "rotated");
break;
case mp_slanted_by:
mp_print (mp, "slanted");
break;
case mp_scaled_by:
mp_print (mp, "scaled");
break;
case mp_shifted_by:
mp_print (mp, "shifted");
break;
case mp_transformed_by:
mp_print (mp, "transformed");
break;
case mp_x_scaled:
mp_print (mp, "xscaled");
break;
case mp_y_scaled:
mp_print (mp, "yscaled");
break;
case mp_z_scaled:
mp_print (mp, "zscaled");
break;
case mp_in_font:
mp_print (mp, "infont");
break;
case mp_intersect:
mp_print (mp, "intersectiontimes");
break;
case mp_substring_of:
mp_print (mp, "substring");
break;
case mp_subpath_of:
mp_print (mp, "subpath");
break;
case mp_direction_time_of:
mp_print (mp, "directiontime");
break;
case mp_point_of:
mp_print (mp, "point");
break;
case mp_precontrol_of:
mp_print (mp, "precontrol");
break;
case mp_postcontrol_of:
mp_print (mp, "postcontrol");
break;
case mp_pen_offset_of:
mp_print (mp, "penoffset");
break;
case mp_arc_time_of:
mp_print (mp, "arctime");
break;
case mp_version:
mp_print (mp, "mpversion");
break;
case mp_envelope_of:
mp_print (mp, "envelope");
break;
case mp_glyph_infont:
mp_print (mp, "glyph");
break;
default:
mp_print (mp, "..");
break;
}
}
}
@ \MP\ also has a bunch of internal parameters that a user might want to
fuss with. Every such parameter has an identifying code number, defined here.
@<Types...@>=
enum mp_given_internal {
mp_output_template = 1, /* a string set up by \&{outputtemplate} */
mp_output_filename, /* the output file name, accessible as \&{outputfilename} */
mp_output_format, /* the output format set up by \&{outputformat} */
mp_output_format_options, /* the output format options set up by \&{outputformatoptions} */
mp_number_system, /* the number system as set up by \&{numbersystem} */
mp_number_precision, /* the number system precision as set up by \&{numberprecision} */
mp_job_name, /* the perceived jobname, as set up from the options stucture,
the name of the input file, or by \&{jobname} */
mp_tracing_titles, /* show titles online when they appear */
mp_tracing_equations, /* show each variable when it becomes known */
mp_tracing_capsules, /* show capsules too */
mp_tracing_choices, /* show the control points chosen for paths */
mp_tracing_specs, /* show path subdivision prior to filling with polygonal a pen */
mp_tracing_commands, /* show commands and operations before they are performed */
mp_tracing_restores, /* show when a variable or internal is restored */
mp_tracing_macros, /* show macros before they are expanded */
mp_tracing_output, /* show digitized edges as they are output */
mp_tracing_stats, /* show memory usage at end of job */
mp_tracing_lost_chars, /* show characters that aren't \&{infont} */
mp_tracing_online, /* show long diagnostics on terminal and in the log file */
mp_year, /* the current year (e.g., 1984) */
mp_month, /* the current month (e.g., 3 $\equiv$ March) */
mp_day, /* the current day of the month */
mp_time, /* the number of minutes past midnight when this job started */
mp_hour, /* the number of hours past midnight when this job started */
mp_minute, /* the number of minutes in that hour when this job started */
mp_char_code, /* the number of the next character to be output */
mp_char_ext, /* the extension code of the next character to be output */
mp_char_wd, /* the width of the next character to be output */
mp_char_ht, /* the height of the next character to be output */
mp_char_dp, /* the depth of the next character to be output */
mp_char_ic, /* the italic correction of the next character to be output */
mp_design_size, /* the unit of measure used for |mp_char_wd..mp_char_ic|, in points */
mp_pausing, /* positive to display lines on the terminal before they are read */
mp_showstopping, /* positive to stop after each \&{show} command */
mp_fontmaking, /* positive if font metric output is to be produced */
mp_linejoin, /* as in \ps: 0 for mitered, 1 for round, 2 for beveled */
mp_linecap, /* as in \ps: 0 for butt, 1 for round, 2 for square */
mp_miterlimit, /* controls miter length as in \ps */
mp_warning_check, /* controls error message when variable value is large */
mp_boundary_char, /* the right boundary character for ligatures */
mp_prologues, /* positive to output conforming PostScript using built-in fonts */
mp_true_corners, /* positive to make \&{llcorner} etc. ignore \&{setbounds} */
mp_default_color_model, /* the default color model for unspecified items */
mp_restore_clip_color,
mp_procset, /* wether or not create PostScript command shortcuts */
mp_hppp, /* horizontal pixels per point (for png output) */
mp_vppp, /* vertical pixels per point (for png output) */
mp_gtroffmode, /* whether the user specified |-troff| on the command line */
};
typedef struct {
mp_value v;
char *intname;
} mp_internal;
@ @<MPlib internal header stuff@>=
#define internal_value(A) mp->internal[(A)].v.data.n
#define set_internal_from_number(A,B) do { \
number_clone (internal_value ((A)),(B));\
} while (0)
#define internal_string(A) (mp_string)mp->internal[(A)].v.data.str
#define set_internal_string(A,B) mp->internal[(A)].v.data.str=(B)
#define internal_name(A) mp->internal[(A)].intname
#define set_internal_name(A,B) mp->internal[(A)].intname=(B)
#define internal_type(A) (mp_variable_type)mp->internal[(A)].v.type
#define set_internal_type(A,B) mp->internal[(A)].v.type=(B)
#define set_internal_from_cur_exp(A) do { \
if (internal_type ((A)) == mp_string_type) { \
add_str_ref (cur_exp_str ()); \
set_internal_string ((A), cur_exp_str ()); \
} else { \
set_internal_from_number ((A), cur_exp_value_number ()); \
} \
} while (0)
@
@d max_given_internal mp_gtroffmode
@<Glob...@>=
mp_internal *internal; /* the values of internal quantities */
int int_ptr; /* the maximum internal quantity defined so far */
int max_internal; /* current maximum number of internal quantities */
@ @<Option variables@>=
int troff_mode;
@ @<Allocate or initialize ...@>=
mp->max_internal = 2 * max_given_internal;
mp->internal = xmalloc ((mp->max_internal + 1), sizeof (mp_internal));
memset (mp->internal, 0,
(size_t) (mp->max_internal + 1) * sizeof (mp_internal));
{
int i;
for (i = 1; i <= mp->max_internal; i++) {
new_number(mp->internal[i].v.data.n);
}
for (i = 1; i <= max_given_internal; i++) {
set_internal_type (i, mp_known);
}
}
set_internal_type (mp_output_format, mp_string_type);
set_internal_type (mp_output_filename, mp_string_type);
set_internal_type (mp_output_format_options, mp_string_type);
set_internal_type (mp_output_template, mp_string_type);
set_internal_type (mp_number_system, mp_string_type);
set_internal_type (mp_job_name, mp_string_type);
mp->troff_mode = (opt->troff_mode > 0 ? true : false);
@ @<Exported function ...@>=
int mp_troff_mode (MP mp);
@ @c
int mp_troff_mode (MP mp) {
return mp->troff_mode;
}
@ @<Set initial ...@>=
mp->int_ptr = max_given_internal;
@ The symbolic names for internal quantities are put into \MP's hash table
by using a routine called |primitive|, which will be defined later. Let us
enter them now, so that we don't have to list all those names again
anywhere else.
@<Put each of \MP's primitives into the hash table@>=
mp_primitive (mp, "tracingtitles", mp_internal_quantity, mp_tracing_titles);
@:tracingtitles_}{\&{tracingtitles} primitive@>;
mp_primitive (mp, "tracingequations", mp_internal_quantity, mp_tracing_equations);
@:mp_tracing_equations_}{\&{tracingequations} primitive@>;
mp_primitive (mp, "tracingcapsules", mp_internal_quantity, mp_tracing_capsules);
@:mp_tracing_capsules_}{\&{tracingcapsules} primitive@>;
mp_primitive (mp, "tracingchoices", mp_internal_quantity, mp_tracing_choices);
@:mp_tracing_choices_}{\&{tracingchoices} primitive@>;
mp_primitive (mp, "tracingspecs", mp_internal_quantity, mp_tracing_specs);
@:mp_tracing_specs_}{\&{tracingspecs} primitive@>;
mp_primitive (mp, "tracingcommands", mp_internal_quantity, mp_tracing_commands);
@:mp_tracing_commands_}{\&{tracingcommands} primitive@>;
mp_primitive (mp, "tracingrestores", mp_internal_quantity, mp_tracing_restores);
@:mp_tracing_restores_}{\&{tracingrestores} primitive@>;
mp_primitive (mp, "tracingmacros", mp_internal_quantity, mp_tracing_macros);
@:mp_tracing_macros_}{\&{tracingmacros} primitive@>;
mp_primitive (mp, "tracingoutput", mp_internal_quantity, mp_tracing_output);
@:mp_tracing_output_}{\&{tracingoutput} primitive@>;
mp_primitive (mp, "tracingstats", mp_internal_quantity, mp_tracing_stats);
@:mp_tracing_stats_}{\&{tracingstats} primitive@>;
mp_primitive (mp, "tracinglostchars", mp_internal_quantity, mp_tracing_lost_chars);
@:mp_tracing_lost_chars_}{\&{tracinglostchars} primitive@>;
mp_primitive (mp, "tracingonline", mp_internal_quantity, mp_tracing_online);
@:mp_tracing_online_}{\&{tracingonline} primitive@>;
mp_primitive (mp, "year", mp_internal_quantity, mp_year);
@:mp_year_}{\&{year} primitive@>;
mp_primitive (mp, "month", mp_internal_quantity, mp_month);
@:mp_month_}{\&{month} primitive@>;
mp_primitive (mp, "day", mp_internal_quantity, mp_day);
@:mp_day_}{\&{day} primitive@>;
mp_primitive (mp, "time", mp_internal_quantity, mp_time);
@:time_}{\&{time} primitive@>;
mp_primitive (mp, "hour", mp_internal_quantity, mp_hour);
@:hour_}{\&{hour} primitive@>;
mp_primitive (mp, "minute", mp_internal_quantity, mp_minute);
@:minute_}{\&{minute} primitive@>;
mp_primitive (mp, "charcode", mp_internal_quantity, mp_char_code);
@:mp_char_code_}{\&{charcode} primitive@>;
mp_primitive (mp, "charext", mp_internal_quantity, mp_char_ext);
@:mp_char_ext_}{\&{charext} primitive@>;
mp_primitive (mp, "charwd", mp_internal_quantity, mp_char_wd);
@:mp_char_wd_}{\&{charwd} primitive@>;
mp_primitive (mp, "charht", mp_internal_quantity, mp_char_ht);
@:mp_char_ht_}{\&{charht} primitive@>;
mp_primitive (mp, "chardp", mp_internal_quantity, mp_char_dp);
@:mp_char_dp_}{\&{chardp} primitive@>;
mp_primitive (mp, "charic", mp_internal_quantity, mp_char_ic);
@:mp_char_ic_}{\&{charic} primitive@>;
mp_primitive (mp, "designsize", mp_internal_quantity, mp_design_size);
@:mp_design_size_}{\&{designsize} primitive@>;
mp_primitive (mp, "pausing", mp_internal_quantity, mp_pausing);
@:mp_pausing_}{\&{pausing} primitive@>;
mp_primitive (mp, "showstopping", mp_internal_quantity, mp_showstopping);
@:mp_showstopping_}{\&{showstopping} primitive@>;
mp_primitive (mp, "fontmaking", mp_internal_quantity, mp_fontmaking);
@:mp_fontmaking_}{\&{fontmaking} primitive@>;
mp_primitive (mp, "linejoin", mp_internal_quantity, mp_linejoin);
@:mp_linejoin_}{\&{linejoin} primitive@>;
mp_primitive (mp, "linecap", mp_internal_quantity, mp_linecap);
@:mp_linecap_}{\&{linecap} primitive@>;
mp_primitive (mp, "miterlimit", mp_internal_quantity, mp_miterlimit);
@:mp_miterlimit_}{\&{miterlimit} primitive@>;
mp_primitive (mp, "warningcheck", mp_internal_quantity, mp_warning_check);
@:mp_warning_check_}{\&{warningcheck} primitive@>;
mp_primitive (mp, "boundarychar", mp_internal_quantity, mp_boundary_char);
@:mp_boundary_char_}{\&{boundarychar} primitive@>;
mp_primitive (mp, "prologues", mp_internal_quantity, mp_prologues);
@:mp_prologues_}{\&{prologues} primitive@>;
mp_primitive (mp, "truecorners", mp_internal_quantity, mp_true_corners);
@:mp_true_corners_}{\&{truecorners} primitive@>;
mp_primitive (mp, "mpprocset", mp_internal_quantity, mp_procset);
@:mp_procset_}{\&{mpprocset} primitive@>;
mp_primitive (mp, "troffmode", mp_internal_quantity, mp_gtroffmode);
@:troffmode_}{\&{troffmode} primitive@>;
mp_primitive (mp, "defaultcolormodel", mp_internal_quantity,
mp_default_color_model);
@:mp_default_color_model_}{\&{defaultcolormodel} primitive@>;
mp_primitive (mp, "restoreclipcolor", mp_internal_quantity, mp_restore_clip_color);
@:mp_restore_clip_color_}{\&{restoreclipcolor} primitive@>;
mp_primitive (mp, "outputtemplate", mp_internal_quantity, mp_output_template);
@:mp_output_template_}{\&{outputtemplate} primitive@>;
mp_primitive (mp, "outputfilename", mp_internal_quantity, mp_output_filename);
@:mp_output_filename_}{\&{outputfilename} primitive@>;
mp_primitive (mp, "numbersystem", mp_internal_quantity, mp_number_system);
@:mp_number_system_}{\&{numbersystem} primitive@>;
mp_primitive (mp, "numberprecision", mp_internal_quantity, mp_number_precision);
@:mp_number_precision_}{\&{numberprecision} primitive@>;
mp_primitive (mp, "outputformat", mp_internal_quantity, mp_output_format);
@:mp_output_format_}{\&{outputformat} primitive@>;
mp_primitive (mp, "outputformatoptions", mp_internal_quantity, mp_output_format_options);
@:mp_output_format_options_}{\&{outputformatoptions} primitive@>;
mp_primitive (mp, "jobname", mp_internal_quantity, mp_job_name);
@:mp_job_name_}{\&{jobname} primitive@>
mp_primitive (mp, "hppp", mp_internal_quantity, mp_hppp);
@:mp_hppp_}{\&{hppp} primitive@>;
mp_primitive (mp, "vppp", mp_internal_quantity, mp_vppp);
@:mp_vppp_}{\&{vppp} primitive@>;
@ Colors can be specified in four color models. In the special
case of |no_model|, MetaPost does not output any color operator to
the postscript output.
Note: these values are passed directly on to |with_option|. This only
works because the other possible values passed to |with_option| are
8 and 10 respectively (from |with_pen| and |with_picture|).
There is a first state, that is only used for |gs_colormodel|. It flags
the fact that there has not been any kind of color specification by
the user so far in the game.
@<MPlib header stuff@>=
enum mp_color_model {
mp_no_model = 1,
mp_grey_model = 3,
mp_rgb_model = 5,
mp_cmyk_model = 7,
mp_uninitialized_model = 9
};
@ @<Initialize table entries@>=
set_internal_from_number (mp_default_color_model, unity_t);
number_multiply_int (internal_value (mp_default_color_model), mp_rgb_model);
number_clone (internal_value (mp_restore_clip_color), unity_t);
number_clone (internal_value (mp_hppp), unity_t);
number_clone (internal_value (mp_vppp), unity_t);
set_internal_string (mp_output_template, mp_intern (mp, "%j.%c"));
set_internal_string (mp_output_filename, mp_intern (mp, ""));
set_internal_string (mp_output_format, mp_intern (mp, "eps"));
set_internal_string (mp_output_format_options, mp_intern (mp, ""));
set_internal_string (mp_number_system, mp_intern (mp, "scaled"));
set_internal_from_number (mp_number_precision, precision_default);
#if DEBUG
number_clone (internal_value (mp_tracing_titles), three_t);
number_clone (internal_value (mp_tracing_equations), three_t);
number_clone (internal_value (mp_tracing_capsules), three_t);
number_clone (internal_value (mp_tracing_choices), three_t);
number_clone (internal_value (mp_tracing_specs), three_t);
number_clone (internal_value (mp_tracing_commands), three_t);
number_clone (internal_value (mp_tracing_restores), three_t);
number_clone (internal_value (mp_tracing_macros), three_t);
number_clone (internal_value (mp_tracing_output), three_t);
number_clone (internal_value (mp_tracing_stats), three_t);
number_clone (internal_value (mp_tracing_lost_chars), three_t);
number_clone (internal_value (mp_tracing_online), three_t);
#endif
@ Well, we do have to list the names one more time, for use in symbolic
printouts.
@<Initialize table...@>=
set_internal_name (mp_tracing_titles, xstrdup ("tracingtitles"));
set_internal_name (mp_tracing_equations, xstrdup ("tracingequations"));
set_internal_name (mp_tracing_capsules, xstrdup ("tracingcapsules"));
set_internal_name (mp_tracing_choices, xstrdup ("tracingchoices"));
set_internal_name (mp_tracing_specs, xstrdup ("tracingspecs"));
set_internal_name (mp_tracing_commands, xstrdup ("tracingcommands"));
set_internal_name (mp_tracing_restores, xstrdup ("tracingrestores"));
set_internal_name (mp_tracing_macros, xstrdup ("tracingmacros"));
set_internal_name (mp_tracing_output, xstrdup ("tracingoutput"));
set_internal_name (mp_tracing_stats, xstrdup ("tracingstats"));
set_internal_name (mp_tracing_lost_chars, xstrdup ("tracinglostchars"));
set_internal_name (mp_tracing_online, xstrdup ("tracingonline"));
set_internal_name (mp_year, xstrdup ("year"));
set_internal_name (mp_month, xstrdup ("month"));
set_internal_name (mp_day, xstrdup ("day"));
set_internal_name (mp_time, xstrdup ("time"));
set_internal_name (mp_hour, xstrdup ("hour"));
set_internal_name (mp_minute, xstrdup ("minute"));
set_internal_name (mp_char_code, xstrdup ("charcode"));
set_internal_name (mp_char_ext, xstrdup ("charext"));
set_internal_name (mp_char_wd, xstrdup ("charwd"));
set_internal_name (mp_char_ht, xstrdup ("charht"));
set_internal_name (mp_char_dp, xstrdup ("chardp"));
set_internal_name (mp_char_ic, xstrdup ("charic"));
set_internal_name (mp_design_size, xstrdup ("designsize"));
set_internal_name (mp_pausing, xstrdup ("pausing"));
set_internal_name (mp_showstopping, xstrdup ("showstopping"));
set_internal_name (mp_fontmaking, xstrdup ("fontmaking"));
set_internal_name (mp_linejoin, xstrdup ("linejoin"));
set_internal_name (mp_linecap, xstrdup ("linecap"));
set_internal_name (mp_miterlimit, xstrdup ("miterlimit"));
set_internal_name (mp_warning_check, xstrdup ("warningcheck"));
set_internal_name (mp_boundary_char, xstrdup ("boundarychar"));
set_internal_name (mp_prologues, xstrdup ("prologues"));
set_internal_name (mp_true_corners, xstrdup ("truecorners"));
set_internal_name (mp_default_color_model, xstrdup ("defaultcolormodel"));
set_internal_name (mp_procset, xstrdup ("mpprocset"));
set_internal_name (mp_gtroffmode, xstrdup ("troffmode"));
set_internal_name (mp_restore_clip_color, xstrdup ("restoreclipcolor"));
set_internal_name (mp_output_template, xstrdup ("outputtemplate"));
set_internal_name (mp_output_filename, xstrdup ("outputfilename"));
set_internal_name (mp_output_format, xstrdup ("outputformat"));
set_internal_name (mp_output_format_options, xstrdup ("outputformatoptions"));
set_internal_name (mp_job_name, xstrdup ("jobname"));
set_internal_name (mp_number_system, xstrdup ("numbersystem"));
set_internal_name (mp_number_precision, xstrdup ("numberprecision"));
set_internal_name (mp_hppp, xstrdup ("hppp"));
set_internal_name (mp_vppp, xstrdup ("vppp"));
@ The following procedure, which is called just before \MP\ initializes its
input and output, establishes the initial values of the date and time.
@^system dependencies@>
Note that the values are |scaled| integers. Hence \MP\ can no longer
be used after the year 32767.
@c
static void mp_fix_date_and_time (MP mp) {
time_t aclock = time ((time_t *) 0);
struct tm *tmptr = localtime (&aclock);
set_internal_from_number (mp_time, unity_t);
number_multiply_int (internal_value(mp_time), (tmptr->tm_hour * 60 + tmptr->tm_min));
set_internal_from_number (mp_hour, unity_t);
number_multiply_int (internal_value(mp_hour), (tmptr->tm_hour));
set_internal_from_number (mp_minute, unity_t);
number_multiply_int (internal_value(mp_minute), (tmptr->tm_min));
set_internal_from_number (mp_day, unity_t);
number_multiply_int (internal_value(mp_day), (tmptr->tm_mday));
set_internal_from_number (mp_month, unity_t);
number_multiply_int (internal_value(mp_month), (tmptr->tm_mon + 1));
set_internal_from_number (mp_year, unity_t);
number_multiply_int (internal_value(mp_year), (tmptr->tm_year + 1900));
}
@ @<Declarations@>=
static void mp_fix_date_and_time (MP mp);
@ \MP\ is occasionally supposed to print diagnostic information that
goes only into the transcript file, unless |mp_tracing_online| is positive.
Now that we have defined |mp_tracing_online| we can define
two routines that adjust the destination of print commands:
@<Declarations@>=
static void mp_begin_diagnostic (MP mp);
static void mp_end_diagnostic (MP mp, boolean blank_line);
static void mp_print_diagnostic (MP mp, const char *s, const char *t,
boolean nuline);
@ @<Basic printing...@>=
void mp_begin_diagnostic (MP mp) { /* prepare to do some tracing */
mp->old_setting = mp->selector;
if (number_nonpositive(internal_value (mp_tracing_online))
&& (mp->selector == term_and_log)) {
decr (mp->selector);
if (mp->history == mp_spotless)
mp->history = mp_warning_issued;
}
}
@#
void mp_end_diagnostic (MP mp, boolean blank_line) {
/* restore proper conditions after tracing */
mp_print_nl (mp, "");
if (blank_line)
mp_print_ln (mp);
mp->selector = mp->old_setting;
}
@
@<Glob...@>=
unsigned int old_setting;
@ We will occasionally use |begin_diagnostic| in connection with line-number
printing, as follows. (The parameter |s| is typically |"Path"| or
|"Cycle spec"|, etc.)
@<Basic printing...@>=
void mp_print_diagnostic (MP mp, const char *s, const char *t, boolean nuline) {
mp_begin_diagnostic (mp);
if (nuline)
mp_print_nl (mp, s);
else
mp_print (mp, s);
mp_print (mp, " at line ");
mp_print_int (mp, mp_true_line (mp));
mp_print (mp, t);
mp_print_char (mp, xord (':'));
}
@ The 256 |ASCII_code| characters are grouped into classes by means of
the |char_class| table. Individual class numbers have no semantic
or syntactic significance, except in a few instances defined here.
There's also |max_class|, which can be used as a basis for additional
class numbers in nonstandard extensions of \MP.
@d digit_class 0 /* the class number of \.{0123456789} */
@d period_class 1 /* the class number of `\..' */
@d space_class 2 /* the class number of spaces and nonstandard characters */
@d percent_class 3 /* the class number of `\.\%' */
@d string_class 4 /* the class number of `\."' */
@d right_paren_class 8 /* the class number of `\.)' */
@d isolated_classes 5: case 6: case 7: case 8 /* characters that make length-one tokens only */
@d letter_class 9 /* letters and the underline character */
@d mp_left_bracket_class 17 /* `\.[' */
@d mp_right_bracket_class 18 /* `\.]' */
@d invalid_class 20 /* bad character in the input */
@d max_class 20 /* the largest class number */
@<Glob...@>=
#define digit_class 0 /* the class number of \.{0123456789} */
int char_class[256]; /* the class numbers */
@ If changes are made to accommodate non-ASCII character sets, they should
follow the guidelines in Appendix~C of {\sl The {\logos METAFONT\/}book}.
@:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
@^system dependencies@>
@<Set initial ...@>=
for (k = '0'; k <= '9'; k++)
mp->char_class[k] = digit_class;
mp->char_class['.'] = period_class;
mp->char_class[' '] = space_class;
mp->char_class['%'] = percent_class;
mp->char_class['"'] = string_class;
mp->char_class[','] = 5;
mp->char_class[';'] = 6;
mp->char_class['('] = 7;
mp->char_class[')'] = right_paren_class;
for (k = 'A'; k <= 'Z'; k++)
mp->char_class[k] = letter_class;
for (k = 'a'; k <= 'z'; k++)
mp->char_class[k] = letter_class;
mp->char_class['_'] = letter_class;
mp->char_class['<'] = 10;
mp->char_class['='] = 10;
mp->char_class['>'] = 10;
mp->char_class[':'] = 10;
mp->char_class['|'] = 10;
mp->char_class['`'] = 11;
mp->char_class['\''] = 11;
mp->char_class['+'] = 12;
mp->char_class['-'] = 12;
mp->char_class['/'] = 13;
mp->char_class['*'] = 13;
mp->char_class['\\'] = 13;
mp->char_class['!'] = 14;
mp->char_class['?'] = 14;
mp->char_class['#'] = 15;
mp->char_class['&'] = 15;
mp->char_class['@@'] = 15;
mp->char_class['$'] = 15;
mp->char_class['^'] = 16;
mp->char_class['~'] = 16;
mp->char_class['['] = mp_left_bracket_class;
mp->char_class[']'] = mp_right_bracket_class;
mp->char_class['{'] = 19;
mp->char_class['}'] = 19;
for (k = 0; k < ' '; k++)
mp->char_class[k] = invalid_class;
mp->char_class['\t'] = space_class;
mp->char_class['\f'] = space_class;
for (k = 127; k <= 255; k++)
mp->char_class[k] = invalid_class;
@* The hash table.
Symbolic tokens are stored in and retrieved from an AVL tree. This
is not as fast as an actual hash table, but it is easily extensible.
A symbolic token contains a pointer to the |mp_string| that
contains the string representation of the symbol, a |halfword|
that holds the current command value of the token, and an
|mp_value| for the associated equivalent.
@d set_text(A) do {
FUNCTION_TRACE3 ("set_text(%p, %p)\n",(A),(B));
(A)->text=(B) ;
} while (0)
@d set_eq_type(A,B) do {
FUNCTION_TRACE3 ("set_eq_type(%p, %d)\n",(A),(B));
(A)->type=(B) ;
} while (0)
@d set_equiv(A,B) do {
FUNCTION_TRACE3 ("set_equiv(%p, %d)\n",(A),(B));
(A)->v.data.node=NULL ;
(A)->v.data.indep.serial=(B);
} while (0)
@d set_equiv_node(A,B) do {
FUNCTION_TRACE3 ("set_equiv_node(%p, %p)\n",(A),(B));
(A)->v.data.node=(B) ;
(A)->v.data.indep.serial=0;
} while (0)
@d set_equiv_sym(A,B) do {
FUNCTION_TRACE3 ("set_equiv_sym(%p, %p)\n",(A),(B));
(A)->v.data.node=(mp_node)(B);
(A)->v.data.indep.serial=0;
} while (0)
@ @c
#if DEBUG
#define text(A) do_get_text(mp, (A))
#define eq_type(A) do_get_eq_type(mp, (A))
#define equiv(A) do_get_equiv(mp, (A))
#define equiv_node(A) do_get_equiv_node(mp, (A))
#define equiv_sym(A) do_get_equiv_sym(mp, (A))
static mp_string do_get_text (MP mp, mp_sym A) {
FUNCTION_TRACE3 ("%d = do_get_text(%p)\n",A->text,A);
return A->text;
}
static halfword do_get_eq_type (MP mp, mp_sym A) {
FUNCTION_TRACE3 ("%d = do_get_eq_type(%p)\n",A->type,A);
return A->type;
}
static halfword do_get_equiv (MP mp, mp_sym A) {
FUNCTION_TRACE3 ("%d = do_get_equiv(%p)\n",A->v.data.indep.serial,A);
return A->v.data.indep.serial;
}
static mp_node do_get_equiv_node (MP mp, mp_sym A) {
FUNCTION_TRACE3 ("%p = do_get_equiv_node(%p)\n",A->v.data.node,A);
return A->v.data.node;
}
static mp_sym do_get_equiv_sym (MP mp, mp_sym A) {
FUNCTION_TRACE3 ("%p = do_get_equiv_sym(%p)\n",A->v.data.node,A);
return (mp_sym)A->v.data.node;
}
#else
#define text(A) (A)->text
#define eq_type(A) (A)->type
#define equiv(A) (A)->v.data.indep.serial
#define equiv_node(A) (A)->v.data.node
#define equiv_sym(A) (mp_sym)(A)->v.data.node
#endif
@ @<Declarations...@>=
#if DEBUG
static mp_string do_get_text (MP mp, mp_sym A);
static halfword do_get_eq_type (MP mp, mp_sym A);
static halfword do_get_equiv (MP mp, mp_sym A);
static mp_node do_get_equiv_node (MP mp, mp_sym A);
static mp_sym do_get_equiv_sym (MP mp, mp_sym A);
#endif
@ @<Types...@>=
typedef struct mp_symbol_entry {
halfword type;
mp_value v;
mp_string text;
void *parent;
} mp_symbol_entry;
@ @<Glob...@>=
integer st_count; /* total number of known identifiers */
avl_tree symbols; /* avl tree of symbolic tokens */
avl_tree frozen_symbols; /* avl tree of frozen symbolic tokens */
mp_sym frozen_bad_vardef;
mp_sym frozen_colon;
mp_sym frozen_end_def;
mp_sym frozen_end_for;
mp_sym frozen_end_group;
mp_sym frozen_etex;
mp_sym frozen_fi;
mp_sym frozen_inaccessible;
mp_sym frozen_left_bracket;
mp_sym frozen_mpx_break;
mp_sym frozen_repeat_loop;
mp_sym frozen_right_delimiter;
mp_sym frozen_semicolon;
mp_sym frozen_slash;
mp_sym frozen_undefined;
mp_sym frozen_dump;
@ Here are the functions needed for the avl construction.
@<Declarations@>=
static int comp_symbols_entry (void *p, const void *pa, const void *pb);
static void *copy_symbols_entry (const void *p);
static void *delete_symbols_entry (void *p);
@ The avl comparison function is a straightword version of |strcmp|,
except that checks for the string lengths first.
@c
static int comp_symbols_entry (void *p, const void *pa, const void *pb) {
const mp_symbol_entry *a = (const mp_symbol_entry *) pa;
const mp_symbol_entry *b = (const mp_symbol_entry *) pb;
(void) p;
if (a->text->len != b->text->len) {
return (a->text->len > b->text->len ? 1 : -1);
}
return strncmp ((const char *) a->text->str, (const char *) b->text->str,
a->text->len);
}
@ Copying a symbol happens when an item is inserted into an AVL tree.
The |text| and |mp_number| needs to be deep copied, every thing else
can be reassigned.
@c
static void *copy_symbols_entry (const void *p) {
MP mp;
mp_sym ff;
const mp_symbol_entry *fp;
fp = (const mp_symbol_entry *) p;
mp = (MP)fp->parent;
ff = malloc (sizeof (mp_symbol_entry));
if (ff == NULL)
return NULL;
ff->text = copy_strings_entry (fp->text);
if (ff->text == NULL)
return NULL;
ff->v = fp->v;
ff->type = fp->type;
ff->parent = mp;
new_number(ff->v.data.n);
number_clone(ff->v.data.n, fp->v.data.n);
return ff;
}
@ In the current implementation, symbols are not freed until the
end of the run.
@c
static void *delete_symbols_entry (void *p) {
MP mp;
mp_sym ff = (mp_sym) p;
mp = (MP)ff->parent;
free_number(ff->v.data.n);
mp_xfree (ff->text->str);
mp_xfree (ff->text);
mp_xfree (ff);
return NULL;
}
@ @<Allocate or initialize ...@>=
mp->symbols = avl_create (comp_symbols_entry,
copy_symbols_entry,
delete_symbols_entry, malloc, free, NULL);
mp->frozen_symbols = avl_create (comp_symbols_entry,
copy_symbols_entry,
delete_symbols_entry, malloc, free, NULL);
@ @<Dealloc variables@>=
if (mp->symbols != NULL)
avl_destroy (mp->symbols);
if (mp->frozen_symbols != NULL)
avl_destroy (mp->frozen_symbols);
@ Actually creating symbols is done by |id_lookup|, but in order to
do so it needs a way to create a new, empty symbol structure.
@<Declarations@>=
static mp_sym new_symbols_entry (MP mp, unsigned char *nam, size_t len);
@ @c
static mp_sym new_symbols_entry (MP mp, unsigned char *nam, size_t len) {
mp_sym ff;
ff = mp_xmalloc (mp, 1, sizeof (mp_symbol_entry));
memset (ff, 0, sizeof (mp_symbol_entry));
ff->parent = mp;
ff->text = mp_xmalloc (mp, 1, sizeof (mp_lstring));
ff->text->str = nam;
ff->text->len = len;
ff->type = mp_tag_token;
ff->v.type = mp_known;
new_number(ff->v.data.n);
FUNCTION_TRACE4 ("%p = new_symbols_entry(\"%s\",%d)\n", ff, nam, (int)len);
return ff;
}
@ There is one global variable so that |id_lookup| does not always have to
create a new entry just for testing. This is not freed because it creates
a double-free thanks to the |NULL| init.
@<Global ...@>=
mp_sym id_lookup_test;
@ @<Initialize table entries@>=
mp->id_lookup_test = new_symbols_entry (mp, NULL, 0);
@ Certain symbols are ``frozen'' and not redefinable, since they are
used
in error recovery.
@<Initialize table entries@>=
mp->st_count = 0;
mp->frozen_bad_vardef = mp_frozen_primitive (mp, "a bad variable", mp_tag_token, 0);
mp->frozen_right_delimiter = mp_frozen_primitive (mp, ")", mp_right_delimiter, 0);
mp->frozen_inaccessible = mp_frozen_primitive (mp, " INACCESSIBLE", mp_tag_token, 0);
mp->frozen_undefined = mp_frozen_primitive (mp, " UNDEFINED", mp_tag_token, 0);
@ Here is the subroutine that searches the avl tree for an identifier
that matches a given string of length~|l| appearing in |buffer[j..
(j+l-1)]|. If the identifier is not found, it is inserted if
|insert_new| is |true|, and the corresponding symbol will be returned.
There are two variations on the lookup function: one for the normal
symbol table, and one for the table of error recovery symbols.
@d mp_id_lookup(A,B,C,D) mp_do_id_lookup ((A), mp->symbols, (B), (C), (D))
@c
static mp_sym mp_do_id_lookup (MP mp, avl_tree symbols, char *j,
size_t l, boolean insert_new) {
/* search an avl tree */
mp_sym str;
mp->id_lookup_test->text->str = (unsigned char *)j;
mp->id_lookup_test->text->len = l;
str = (mp_sym) avl_find (mp->id_lookup_test, symbols);
if (str == NULL && insert_new) {
unsigned char *nam = (unsigned char *) mp_xstrldup (mp, j, l);
mp_sym s = new_symbols_entry (mp, nam, l);
mp->st_count++;
assert (avl_ins (s, symbols, avl_false) > 0);
str = (mp_sym) avl_find (s, symbols);
delete_symbols_entry (s);
}
return str;
}
static mp_sym mp_frozen_id_lookup (MP mp, char *j, size_t l,
boolean insert_new) {
/* search the error recovery symbol table */
return mp_do_id_lookup (mp, mp->frozen_symbols, j, l, insert_new);
}
/* see mp\_print\_sym (mp\_sym sym) */
@ Get a numeric value from \MP\ is not easy. We have to consider
the macro and the loops, as also the internal type (this is a
first attempt, and more work is needed). If we are inside
a \&{for} loop, then the global |loop_ptr| is not null and the other loops
eventually nested are available by mean of |loop_ptr->link|.
The current numeric value is stored in |old_value|.
@c
double mp_get_numeric_value (MP mp, const char *s, size_t l) {
char *ss = mp_xstrdup(mp,s);
if (ss) {
mp_sym sym = mp_id_lookup(mp,ss,l,false);
if (sym != NULL) {
if (mp->loop_ptr != NULL) {
mp_loop_data *s;
s = mp->loop_ptr;
while (s != NULL && sym != s->var)
s = mp->loop_ptr->link;
if (s != NULL && sym == s->var ){
mp_xfree (ss);
return number_to_double(s->old_value) ;
}
}
if (mp_type(sym) == mp_internal_quantity) {
halfword qq = equiv(sym);
mp_xfree (ss);
if (internal_type (qq) != mp_string_type)
return number_to_double(internal_value(qq));
else
return 0;
}
if (sym->v.data.node != NULL && mp_type(sym->v.data.node) == mp_known) {
mp_xfree (ss);
return number_to_double(sym->v.data.node->data.n) ;
}
}
}
mp_xfree (ss);
return 0 ;
}
int mp_get_boolean_value (MP mp, const char *s, size_t l) {
char *ss = mp_xstrdup(mp,s);
if (ss) {
mp_sym sym = mp_id_lookup(mp,ss,l,false);
if (sym != NULL) {
if (mp_type(sym->v.data.node) == mp_boolean_type) {
if (number_to_boolean (sym->v.data.node->data.n) == mp_true_code) {
mp_xfree(ss);
return 1 ;
}
}
}
}
mp_xfree (ss);
return 0;
}
char *mp_get_string_value (MP mp, const char *s, size_t l) {
char *ss = mp_xstrdup(mp,s);
if (ss) {
mp_sym sym = mp_id_lookup(mp,ss,l,false);
if (sym != NULL) {
if (mp_type(sym->v.data.node) == mp_string_type) {
mp_xfree (ss);
return (char *) sym->v.data.node->data.str->str;
}
}
}
mp_xfree (ss);
return NULL;
}
@ @<Exported function headers@>=
double mp_get_numeric_value(MP mp,const char *s,size_t l);
int mp_get_boolean_value(MP mp,const char *s,size_t l);
char *mp_get_string_value(MP mp,const char *s,size_t l);
@ We need to put \MP's ``primitive'' symbolic tokens into the hash
table, together with their command code (which will be the |eq_type|)
and an operand (which will be the |equiv|). The |primitive| procedure
does this, in a way that no \MP\ user can. The global value |cur_sym|
contains the new |eqtb| pointer after |primitive| has acted.
@c
static void mp_primitive (MP mp, const char *ss, halfword c, halfword o) {
char *s = mp_xstrdup (mp, ss);
set_cur_sym (mp_id_lookup (mp, s, strlen (s), true));
mp_xfree (s);
set_eq_type (cur_sym(), c);
set_equiv (cur_sym(), o);
}
@ Some other symbolic tokens only exist for error recovery.
@c
static mp_sym mp_frozen_primitive (MP mp, const char *ss, halfword c,
halfword o) {
char *s = mp_xstrdup (mp, ss);
mp_sym str = mp_frozen_id_lookup (mp, s, strlen (ss), true);
mp_xfree (s);
str->type = c;
str->v.data.indep.serial = o;
return str;
}
@ This routine returns |true| if the argument is an un-redefinable symbol
because it is one of the error recovery tokens (as explained elsewhere,
|frozen_inaccessible| actuall is redefinable).
@c
static boolean mp_is_frozen (MP mp, mp_sym sym) {
mp_sym temp = mp_frozen_id_lookup (mp, (char *) sym->text->str, sym->text->len, false);
if (temp==mp->frozen_inaccessible)
return false;
return (temp == sym);
}
@ Many of \MP's primitives need no |equiv|, since they are identifiable
by their |eq_type| alone. These primitives are loaded into the hash table
as follows:
@<Put each of \MP's primitives into the hash table@>=
mp_primitive (mp, "..", mp_path_join, 0);
@:.._}{\.{..} primitive@>;
mp_primitive (mp, "[", mp_left_bracket, 0);
mp->frozen_left_bracket = mp_frozen_primitive (mp, "[", mp_left_bracket, 0);
@:[ }{\.{[} primitive@>;
mp_primitive (mp, "]", mp_right_bracket, 0);
@:] }{\.{]} primitive@>;
mp_primitive (mp, "}", mp_right_brace, 0);
@:]]}{\.{\char`\}} primitive@>;
mp_primitive (mp, "{", mp_left_brace, 0);
@:][}{\.{\char`\{} primitive@>;
mp_primitive (mp, ":", mp_colon, 0);
mp->frozen_colon = mp_frozen_primitive (mp, ":", mp_colon, 0);
@:: }{\.{:} primitive@>;
mp_primitive (mp, "::", mp_double_colon, 0);
@::: }{\.{::} primitive@>;
mp_primitive (mp, "||:", mp_bchar_label, 0);
@:::: }{\.{\char'174\char'174:} primitive@>;
mp_primitive (mp, ":=", mp_assignment, 0);
@::=_}{\.{:=} primitive@>;
mp_primitive (mp, ",", mp_comma, 0);
@:, }{\., primitive@>;
mp_primitive (mp, ";", mp_semicolon, 0);
mp->frozen_semicolon = mp_frozen_primitive (mp, ";", mp_semicolon, 0);
@:; }{\.; primitive@>;
mp_primitive (mp, "\\", mp_relax, 0);
@:]]\\}{\.{\char`\\} primitive@>;
mp_primitive (mp, "addto", mp_add_to_command, 0);
@:add_to_}{\&{addto} primitive@>;
mp_primitive (mp, "atleast", mp_at_least, 0);
@:at_least_}{\&{atleast} primitive@>;
mp_primitive (mp, "begingroup", mp_begin_group, 0);
mp->bg_loc = cur_sym();
@:begin_group_}{\&{begingroup} primitive@>;
mp_primitive (mp, "controls", mp_controls, 0);
@:controls_}{\&{controls} primitive@>;
mp_primitive (mp, "curl", mp_curl_command, 0);
@:curl_}{\&{curl} primitive@>;
mp_primitive (mp, "delimiters", mp_delimiters, 0);
@:delimiters_}{\&{delimiters} primitive@>;
mp_primitive (mp, "endgroup", mp_end_group, 0);
mp->eg_loc = cur_sym();
mp->frozen_end_group = mp_frozen_primitive (mp, "endgroup", mp_end_group, 0);
@:endgroup_}{\&{endgroup} primitive@>;
mp_primitive (mp, "everyjob", mp_every_job_command, 0);
@:every_job_}{\&{everyjob} primitive@>;
mp_primitive (mp, "exitif", mp_exit_test, 0);
@:exit_if_}{\&{exitif} primitive@>;
mp_primitive (mp, "expandafter", mp_expand_after, 0);
@:expand_after_}{\&{expandafter} primitive@>;
mp_primitive (mp, "interim", mp_interim_command, 0);
@:interim_}{\&{interim} primitive@>;
mp_primitive (mp, "let", mp_let_command, 0);
@:let_}{\&{let} primitive@>;
mp_primitive (mp, "newinternal", mp_new_internal, 0);
@:new_internal_}{\&{newinternal} primitive@>;
mp_primitive (mp, "of", mp_of_token, 0);
@:of_}{\&{of} primitive@>;
mp_primitive (mp, "randomseed", mp_random_seed, 0);
@:mp_random_seed_}{\&{randomseed} primitive@>;
mp_primitive (mp, "save", mp_save_command, 0);
@:save_}{\&{save} primitive@>;
mp_primitive (mp, "scantokens", mp_scan_tokens, 0);
@:scan_tokens_}{\&{scantokens} primitive@>;
mp_primitive (mp, "runscript", mp_runscript, 0);
@:run_script_}{\&{runscript} primitive@>;
mp_primitive (mp, "maketext", mp_maketext, 0);
@:make_text_}{\&{maketext} primitive@>;
mp_primitive (mp, "shipout", mp_ship_out_command, 0);
@:ship_out_}{\&{shipout} primitive@>;
mp_primitive (mp, "skipto", mp_skip_to, 0);
@:skip_to_}{\&{skipto} primitive@>;
mp_primitive (mp, "special", mp_special_command, 0);
@:special}{\&{special} primitive@>;
mp_primitive (mp, "fontmapfile", mp_special_command, 1);
@:fontmapfile}{\&{fontmapfile} primitive@>;
mp_primitive (mp, "fontmapline", mp_special_command, 2);
@:fontmapline}{\&{fontmapline} primitive@>;
mp_primitive (mp, "step", mp_step_token, 0);
@:step_}{\&{step} primitive@>;
mp_primitive (mp, "str", mp_str_op, 0);
@:str_}{\&{str} primitive@>;
mp_primitive (mp, "tension", mp_tension, 0);
@:tension_}{\&{tension} primitive@>;
mp_primitive (mp, "to", mp_to_token, 0);
@:to_}{\&{to} primitive@>;
mp_primitive (mp, "until", mp_until_token, 0);
@:until_}{\&{until} primitive@>;
mp_primitive (mp, "within", mp_within_token, 0);
@:within_}{\&{within} primitive@>;
mp_primitive (mp, "write", mp_write_command, 0);
@:write_}{\&{write} primitive@>
@ Each primitive has a corresponding inverse, so that it is possible to
display the cryptic numeric contents of |eqtb| in symbolic form.
Every call of |primitive| in this program is therefore accompanied by some
straightforward code that forms part of the |print_cmd_mod| routine
explained below.
@<Cases of |print_cmd_mod| for symbolic printing of primitives@>=
case mp_add_to_command:
mp_print (mp, "addto");
break;
case mp_assignment:
mp_print (mp, ":=");
break;
case mp_at_least:
mp_print (mp, "atleast");
break;
case mp_bchar_label:
mp_print (mp, "||:");
break;
case mp_begin_group:
mp_print (mp, "begingroup");
break;
case mp_colon:
mp_print (mp, ":");
break;
case mp_comma:
mp_print (mp, ",");
break;
case mp_controls:
mp_print (mp, "controls");
break;
case mp_curl_command:
mp_print (mp, "curl");
break;
case mp_delimiters:
mp_print (mp, "delimiters");
break;
case mp_double_colon:
mp_print (mp, "::");
break;
case mp_end_group:
mp_print (mp, "endgroup");
break;
case mp_every_job_command:
mp_print (mp, "everyjob");
break;
case mp_exit_test:
mp_print (mp, "exitif");
break;
case mp_expand_after:
mp_print (mp, "expandafter");
break;
case mp_interim_command:
mp_print (mp, "interim");
break;
case mp_left_brace:
mp_print (mp, "{");
break;
case mp_left_bracket:
mp_print (mp, "[");
break;
case mp_let_command:
mp_print (mp, "let");
break;
case mp_new_internal:
mp_print (mp, "newinternal");
break;
case mp_of_token:
mp_print (mp, "of");
break;
case mp_path_join:
mp_print (mp, "..");
break;
case mp_random_seed:
mp_print (mp, "randomseed");
break;
case mp_relax:
mp_print_char (mp, xord ('\\'));
break;
case mp_right_brace:
mp_print_char (mp, xord ('}'));
break;
case mp_right_bracket:
mp_print_char (mp, xord (']'));
break;
case mp_save_command:
mp_print (mp, "save");
break;
case mp_scan_tokens:
mp_print (mp, "scantokens");
break;
case mp_runscript:
mp_print (mp, "runscript");
break;
case mp_maketext:
mp_print (mp, "maketext");
break;
case mp_semicolon:
mp_print_char (mp, xord (';'));
break;
case mp_ship_out_command:
mp_print (mp, "shipout");
break;
case mp_skip_to:
mp_print (mp, "skipto");
break;
case mp_special_command:
if (m == 2)
mp_print (mp, "fontmapline");
else if (m == 1)
mp_print (mp, "fontmapfile");
else
mp_print (mp, "special");
break;
case mp_step_token:
mp_print (mp, "step");
break;
case mp_str_op:
mp_print (mp, "str");
break;
case mp_tension:
mp_print (mp, "tension");
break;
case mp_to_token:
mp_print (mp, "to");
break;
case mp_until_token:
mp_print (mp, "until");
break;
case mp_within_token:
mp_print (mp, "within");
break;
case mp_write_command:
mp_print (mp, "write");
break;
@ We will deal with the other primitives later, at some point in the program
where their |eq_type| and |equiv| values are more meaningful. For example,
the primitives for macro definitions will be loaded when we consider the
routines that define macros. It is easy to find where each particular
primitive was treated by looking in the index at the end; for example, the
section where |"def"| entered |eqtb| is listed under `\&{def} primitive'.
@* Token lists.
A \MP\ token is either symbolic or numeric or a string, or it denotes a macro
parameter or capsule or an internal; so there are six corresponding ways to
encode it internally:
@^token@>
(1)~A symbolic token for symbol |p| is represented by the pointer |p|,
in the |sym_sym| field of a symbolic node in~|mem|. The |type| field is |symbol_node|;
and it has a |name_type| to differentiate various subtypes of symbolic tokens,
which is usually |normal_sym|, but |macro_sym| for macro names.
(2)~A numeric token whose |scaled| value is~|v| is
represented in a non-symbolic node of~|mem|; the |type| field is |known|,
the |name_type| field is |token|, and the |value| field holds~|v|.
(3)~A string token is also represented in a non-symbolic node; the |type|
field is |mp_string_type|, the |name_type| field is |token|, and the
|value| field holds the corresponding |mp_string|.
(4)~Capsules have |name_type=capsule|, and their |type| and |value| fields
represent arbitrary values, with |type| different from |symbol_node|
(in ways to be explained later).
(5)~Macro parameters appear in |sym_info| fields of symbolic nodes. The |type|
field is |symbol_node|; the $k$th parameter is represented by |k| in |sym_info|;
and |expr_sym| in |name_type|, if it is of type \&{expr}, or |suffix_sym| if it
is of type \&{suffix}, or by |text_sym| if it is of type \&{text}.
(6)~The $k$th internal is also represented by |k| in |sym_info|; the |type| field is
|symbol_node| as for the other symbolic tokens; and |internal_sym| is its |name_type|;
Actual values of the parameters and internals are kept in a separate
stack, as we will see later.
Note that the `\\{type}' field of a node has nothing to do with ``type'' in a
printer's sense. It's curious that the same word is used in such different ways.
@d token_node_size sizeof(mp_node_data) /* the number of words in a large token node */
@d set_value_sym(A,B) do_set_value_sym(mp, (mp_token_node)(A), (B))
@d set_value_number(A,B) do_set_value_number(mp, (mp_token_node)(A), (B))
@d set_value_node(A,B) do_set_value_node(mp, (mp_token_node)(A), (B))
@d set_value_str(A,B) do_set_value_str(mp, (mp_token_node)(A), (B))
@d set_value_knot(A,B) do_set_value_knot(mp, (mp_token_node)A, (B))
@d value_sym_NEW(A) (mp_sym)mp_link(A)
@d set_value_sym_NEW(A,B) set_mp_link(A,(mp_node)B)
@<MPlib internal header stuff@>=
typedef struct mp_node_data *mp_token_node;
@ @c
#if DEBUG
#define value_sym(A) do_get_value_sym(mp,(mp_token_node)(A))
/* |#define value_number(A) do_get_value_number(mp,(mp_token_node)(A))| */
#define value_number(A) ((mp_token_node)(A))->data.n
#define value_node(A) do_get_value_node(mp,(mp_token_node)(A))
#define value_str(A) do_get_value_str(mp,(mp_token_node)(A))
#define value_knot(A) do_get_value_knot(mp,(mp_token_node)(A))
#else
#define value_sym(A) ((mp_token_node)(A))->data.sym
#define value_number(A) ((mp_token_node)(A))->data.n
#define value_node(A) ((mp_token_node)(A))->data.node
#define value_str(A) ((mp_token_node)(A))->data.str
#define value_knot(A) ((mp_token_node)(A))->data.p
#endif
static void do_set_value_sym(MP mp, mp_token_node A, mp_sym B) {
FUNCTION_TRACE3 ("set_value_sym(%p,%p)\n", (A),(B));
A->data.sym=(B);
}
static void do_set_value_number(MP mp, mp_token_node A, mp_number B) {
FUNCTION_TRACE3 ("set_value(%p,%s)\n", (A), number_tostring(B));
A->data.p = NULL;
A->data.str = NULL;
A->data.node = NULL;
number_clone (A->data.n, B);
}
static void do_set_value_str(MP mp, mp_token_node A, mp_string B) {
FUNCTION_TRACE3 ("set_value_str(%p,%p)\n", (A),(B));
assert (A->type != mp_structured);
A->data.p = NULL;
A->data.str = (B);
add_str_ref((B));
A->data.node = NULL;
number_clone (A->data.n, zero_t);
}
static void do_set_value_node(MP mp, mp_token_node A, mp_node B) {
/* store the value in a large token node */
FUNCTION_TRACE3 ("set_value_node(%p,%p)\n", A,B);
assert (A->type != mp_structured);
A->data.p = NULL;
A->data.str = NULL;
A->data.node = B;
number_clone (A->data.n, zero_t);
}
static void do_set_value_knot(MP mp, mp_token_node A, mp_knot B) {
FUNCTION_TRACE3 ("set_value_knot(%p,%p)\n", (A),(B));
assert (A->type != mp_structured);
A->data.p = (B);
A->data.str = NULL;
A->data.node = NULL;
number_clone (A->data.n, zero_t);
}
@ @c
#if DEBUG
static mp_sym do_get_value_sym (MP mp, mp_token_node A) {
/* |A->type| can be structured in this case */
FUNCTION_TRACE3 ("%p = get_value_sym(%p)\n", A->data.sym, A);
return A->data.sym ;
}
static mp_node do_get_value_node (MP mp, mp_token_node A) {
assert (A->type != mp_structured);
FUNCTION_TRACE3 ("%p = get_value_node(%p)\n", A->data.node, A);
return A->data.node ;
}
static mp_string do_get_value_str (MP mp, mp_token_node A) {
assert (A->type != mp_structured);
FUNCTION_TRACE3 ("%p = get_value_str(%p)\n", A->data.str, A);
return A->data.str ;
}
static mp_knot do_get_value_knot (MP mp, mp_token_node A) {
assert (A->type != mp_structured);
FUNCTION_TRACE3 ("%p = get_value_knot(%p)\n", A->data.p, A);
return A->data.p ;
}
static mp_number do_get_value_number (MP mp, mp_token_node A) {
assert (A->type != mp_structured);
FUNCTION_TRACE3 ("%d = get_value_number(%p)\n", A->data.n.type, A);
return A->data.n ;
}
#endif
@ @<Declarations@>=
#if DEBUG
static mp_number do_get_value_number (MP mp, mp_token_node A);
static mp_sym do_get_value_sym (MP mp, mp_token_node A);
static mp_node do_get_value_node (MP mp, mp_token_node A);
static mp_string do_get_value_str (MP mp, mp_token_node A) ;
static mp_knot do_get_value_knot (MP mp, mp_token_node A) ;
#endif
static void do_set_value_sym (MP mp, mp_token_node A, mp_sym B);
static void do_set_value_number (MP mp, mp_token_node A, mp_number B);
static void do_set_value_node (MP mp, mp_token_node A, mp_node B);
static void do_set_value_str (MP mp, mp_token_node A, mp_string B);
static void do_set_value_knot (MP mp, mp_token_node A, mp_knot B);
@
@c
static mp_node mp_get_token_node (MP mp) {
mp_node p;
if (mp->token_nodes) {
p = mp->token_nodes;
mp->token_nodes = p->link;
mp->num_token_nodes--;
p->link = NULL;
} else {
p = malloc_node (token_node_size);
new_number(p->data.n);
p->has_number = 1;
}
p->type = mp_token_node_type;
FUNCTION_TRACE2 ("%p = mp_get_token_node()\n", p);
return (mp_node) p;
}
@ @c
static void mp_free_token_node (MP mp, mp_node p) {
FUNCTION_TRACE2 ("mp_free_token_node(%p)\n", p);
if (!p) return;
if (mp->num_token_nodes < max_num_token_nodes) {
p->link = mp->token_nodes;
mp->token_nodes = p;
mp->num_token_nodes++;
return;
}
mp->var_used -= token_node_size;
if (mp->math_mode > mp_math_double_mode) {
free_number(((mp_value_node)p)->data.n);
}
xfree (p);
}
@ @<Declarations@>=
static void mp_free_token_node (MP mp, mp_node p);
@ A numeric token is created by the following trivial routine.
@c
static mp_node mp_new_num_tok (MP mp, mp_number v) {
mp_node p; /* the new node */
p = mp_get_token_node (mp);
set_value_number (p, v);
p->type = mp_known;
p->name_type = mp_token;
FUNCTION_TRACE3 ("%p = mp_new_num_tok(%p)\n", p, v);
return p;
}
@ A token list is a singly linked list of nodes in |mem|, where
each node contains a token and a link. Here's a subroutine that gets rid
of a token list when it is no longer needed.
@c
static void mp_flush_token_list (MP mp, mp_node p) {
mp_node q; /* the node being recycled */
FUNCTION_TRACE2 ("mp_flush_token_list(%p)\n", p);
while (p != NULL) {
q = p;
p = mp_link (p);
if (mp_type (q) == mp_symbol_node) {
mp_free_symbolic_node (mp, q);
} else {
switch (mp_type (q)) {
case mp_vacuous:
case mp_boolean_type:
case mp_known:
break;
case mp_string_type:
delete_str_ref (value_str (q));
break;
case unknown_types:
case mp_pen_type:
case mp_path_type:
case mp_picture_type:
case mp_pair_type:
case mp_color_type:
case mp_cmykcolor_type:
case mp_transform_type:
case mp_dependent:
case mp_proto_dependent:
case mp_independent:
mp_recycle_value (mp, q);
break;
default:
mp_confusion (mp, "token");
@:this can't happen token}{\quad token@>;
}
mp_free_token_node (mp, q);
}
}
}
@ The procedure |show_token_list|, which prints a symbolic form of
the token list that starts at a given node |p|, illustrates these
conventions. The token list being displayed should not begin with a reference
count.
An additional parameter |q| is also given; this parameter is either NULL
or it points to a node in the token list where a certain magic computation
takes place that will be explained later. (Basically, |q| is non-NULL when
we are printing the two-line context information at the time of an error
message; |q| marks the place corresponding to where the second line
should begin.)
The generation will stop, and `\.{\char`\ ETC.}' will be printed, if the length
of printing exceeds a given limit~|l|; the length of printing upon entry is
assumed to be a given amount called |null_tally|. (Note that
|show_token_list| sometimes uses itself recursively to print
variable names within a capsule.)
@^recursion@>
Unusual entries are printed in the form of all-caps tokens
preceded by a space, e.g., `\.{\char`\ BAD}'.
@<Declarations@>=
static void mp_show_token_list (MP mp, mp_node p, mp_node q, integer l,
integer null_tally);
@ @c
void mp_show_token_list (MP mp, mp_node p, mp_node q, integer l,
integer null_tally) {
quarterword cclass, c; /* the |char_class| of previous and new tokens */
cclass = percent_class;
mp->tally = null_tally;
while ((p != NULL) && (mp->tally < l)) {
if (p == q) {
set_trick_count();
}
/* Display token |p| and set |c| to its class; but |return| if there are problems */
c = letter_class; /* the default */
if (mp_type (p) != mp_symbol_node) {
/* Display non-symbolic token */
if (mp_name_type (p) == mp_token) {
if (mp_type (p) == mp_known) {
/* Display a numeric token */
if (cclass == digit_class)
mp_print_char (mp, xord (' '));
if (number_negative (value_number (p))) {
if (cclass == mp_left_bracket_class)
mp_print_char (mp, xord (' '));
mp_print_char (mp, xord ('['));
print_number (value_number (p));
mp_print_char (mp, xord (']'));
c = mp_right_bracket_class;
} else {
print_number (value_number (p));
c = digit_class;
}
} else if (mp_type (p) != mp_string_type) {
mp_print (mp, " BAD");
} else {
mp_print_char (mp, xord ('"'));
mp_print_str (mp, value_str (p));
mp_print_char (mp, xord ('"'));
c = string_class;
}
} else if ((mp_name_type (p) != mp_capsule) || (mp_type (p) < mp_vacuous)
|| (mp_type (p) > mp_independent)) {
mp_print (mp, " BAD");
} else {
mp_print_capsule (mp, p);
c = right_paren_class;
}
} else {
if (mp_name_type (p) == mp_expr_sym ||
mp_name_type (p) == mp_suffix_sym || mp_name_type (p) == mp_text_sym) {
integer r; /* temporary register */
r = mp_sym_info (p);
if (mp_name_type (p) == mp_expr_sym) {
mp_print (mp, "(EXPR");
} else if (mp_name_type (p) == mp_suffix_sym) {
mp_print (mp, "(SUFFIX");
} else {
mp_print (mp, "(TEXT");
}
mp_print_int (mp, r);
mp_print_char (mp, xord (')'));
c = right_paren_class;
} else {
mp_sym sr = mp_sym_sym (p);
if (sr == collective_subscript) {
/* Display a collective subscript */
if (cclass == mp_left_bracket_class)
mp_print_char (mp, xord (' '));
mp_print (mp, "[]");
c = mp_right_bracket_class;
} else {
mp_string rr = text (sr);
if (rr == NULL || rr->str == NULL) {
mp_print (mp, " NONEXISTENT");
} else {
/* Print string |r| as a symbolic token and set |c| to its class */
c = (quarterword) mp->char_class[(rr->str[0])];
if (c == cclass) {
switch (c) {
case letter_class:
mp_print_char (mp, xord ('.'));
break;
case isolated_classes:
break;
default:
mp_print_char (mp, xord (' '));
break;
}
}
mp_print_str (mp, rr);
}
}
}
}
cclass = c;
p = mp_link (p);
}
if (p != NULL)
mp_print (mp, " ETC.");
return;
}
@ @<Declarations@>=
static void mp_print_capsule (MP mp, mp_node p);
@ @<Declare miscellaneous procedures that were declared |forward|@>=
void mp_print_capsule (MP mp, mp_node p) {
mp_print_char (mp, xord ('('));
mp_print_exp (mp, p, 0);
mp_print_char (mp, xord (')'));
}
@ Macro definitions are kept in \MP's memory in the form of token lists
that have a few extra symbolic nodes at the beginning.
The first node contains a reference count that is used to tell when the
list is no longer needed. To emphasize the fact that a reference count is
present, we shall refer to the |sym_info| field of this special node as the
|ref_count| field.
@^reference counts@>
The next node or nodes after the reference count serve to describe the
formal parameters. They consist of zero or more parameter tokens followed
by a code for the type of macro.
/* reference count preceding a macro definition or picture header */
@d ref_count(A) indep_value(A)
@d set_ref_count(A,B) set_indep_value(A,B)
@d add_mac_ref(A) set_ref_count((A),ref_count((A))+1) /* make a new reference to a macro list */
@d decr_mac_ref(A) set_ref_count((A),ref_count((A))-1) /* remove a reference to a macro list */
@<Types...@>=
typedef enum {
mp_general_macro, /* preface to a macro defined with a parameter list */
mp_primary_macro, /* preface to a macro with a \&{primary} parameter */
mp_secondary_macro, /* preface to a macro with a \&{secondary} parameter */
mp_tertiary_macro, /* preface to a macro with a \&{tertiary} parameter */
mp_expr_macro, /* preface to a macro with an undelimited \&{expr} parameter */
mp_of_macro, /* preface to a macro with undelimited `\&{expr} |x| \&{of}~|y|' parameters */
mp_suffix_macro, /* preface to a macro with an undelimited \&{suffix} parameter */
mp_text_macro, /* preface to a macro with an undelimited \&{text} parameter */
mp_expr_param, /* used by \.{expr} primitive */
mp_suffix_param, /* used by \.{suffix} primitive */
mp_text_param /* used by \.{text} primitive */
} mp_macro_info;
@ @c
static void mp_delete_mac_ref (MP mp, mp_node p) {
/* |p| points to the reference count of a macro list that is
losing one reference */
if (ref_count (p) == 0)
mp_flush_token_list (mp, p);
else
decr_mac_ref (p);
}
@ The following subroutine displays a macro, given a pointer to its
reference count.
@c
static void mp_show_macro (MP mp, mp_node p, mp_node q, integer l) {
mp_node r; /* temporary storage */
p = mp_link (p); /* bypass the reference count */
while (mp_name_type (p) != mp_macro_sym) {
r = mp_link (p);
mp_link (p) = NULL;
mp_show_token_list (mp, p, NULL, l, 0);
mp_link (p) = r;
p = r;
if (l > 0)
l = l - mp->tally;
else
return;
} /* control printing of `\.{ETC.}' */
@.ETC@>;
mp->tally = 0;
switch (mp_sym_info (p)) {
case mp_general_macro:
mp_print (mp, "->");
break;
@.->@>
case mp_primary_macro:
case mp_secondary_macro:
case mp_tertiary_macro:
mp_print_char (mp, xord ('<'));
mp_print_cmd_mod (mp, mp_param_type, mp_sym_info (p));
mp_print (mp, ">->");
break;
case mp_expr_macro:
mp_print (mp, "<expr>->");
break;
case mp_of_macro:
mp_print (mp, "<expr>of<primary>->");
break;
case mp_suffix_macro:
mp_print (mp, "<suffix>->");
break;
case mp_text_macro:
mp_print (mp, "<text>->");
break;
} /* there are no other cases */
mp_show_token_list (mp, mp_link (p), q, l - mp->tally, 0);
}
@* Data structures for variables.
The variables of \MP\ programs can be simple, like `\.x', or they can
combine the structural properties of arrays and records, like `\.{x20a.b}'.
A \MP\ user assigns a type to a variable like \.{x20a.b} by saying, for
example, `\.{boolean} \.{x[]a.b}'. It's time for us to study how such
things are represented inside of the computer.
Each variable value occupies two consecutive words, either in a non-symbolic
node called a value node, or as a non-symbolic subfield of a larger node. One
of those two words is called the |value| field; it is an integer,
containing either a |scaled| numeric value or the representation of some
other type of quantity. (It might also be subdivided into halfwords, in
which case it is referred to by other names instead of |value|.) The other
word is broken into subfields called |type|, |name_type|, and |link|. The
|type| field is a quarterword that specifies the variable's type, and
|name_type| is a quarterword from which \MP\ can reconstruct the
variable's name (sometimes by using the |link| field as well). Thus, only
1.25 words are actually devoted to the value itself; the other
three-quarters of a word are overhead, but they aren't wasted because they
allow \MP\ to deal with sparse arrays and to provide meaningful diagnostics.
In this section we shall be concerned only with the structural aspects of
variables, not their values. Later parts of the program will change the
|type| and |value| fields, but we shall treat those fields as black boxes
whose contents should not be touched.
However, if the |type| field is |mp_structured|, there is no |value| field,
and the second word is broken into two pointer fields called |attr_head|
and |subscr_head|. Those fields point to additional nodes that
contain structural information, as we shall see.
TH Note: DEK and JDH had a nice theoretical split between |value|,
|attr| and |subscr| nodes, as documented above and further
below. However, all three types had a bad habit of transmuting into
each other in practice while pointers to them still lived on
elsewhere, so using three different C structures is simply not
workable. All three are now represented as a single C structure called
|mp_value_node|.
There is a potential union in this structure in the interest of space
saving: |subscript_| and |hashloc_| are mutually exclusive.
Actually, so are |attr_head_| + |subscr_head_| on one side and and
|value_| on the other, but because of all the access macros that are
used in the code base to get at values, those cannot be folded into a
union (yet); this would have required creating a similar union in
|mp_token_node| where it would only serve to confuse things.
Finally, |parent_| only applies in |attr| nodes (the ones that have
|hashloc_|), but creating an extra substructure inside the union just
for that does not save space and the extra complication in the
structure is not worth the minimal extra code clarification.
@d attr_head(A) do_get_attr_head(mp,(mp_value_node)(A))
@d set_attr_head(A,B) do_set_attr_head(mp,(mp_value_node)(A),(mp_node)(B))
@d subscr_head(A) do_get_subscr_head(mp,(mp_value_node)(A))
@d set_subscr_head(A,B) do_set_subscr_head(mp,(mp_value_node)(A),(mp_node)(B))
@<MPlib internal header stuff@>=
typedef struct mp_value_node_data {
NODE_BODY;
mp_value_data data;
mp_number subscript_;
mp_sym hashloc_;
mp_node parent_;
mp_node attr_head_;
mp_node subscr_head_;
} mp_value_node_data;
@ @c
static mp_node do_get_attr_head (MP mp, mp_value_node A) {
assert (A->type == mp_structured);
FUNCTION_TRACE3 ("%p = get_attr_head(%p)\n", A->attr_head_, A);
return A->attr_head_;
}
static mp_node do_get_subscr_head (MP mp, mp_value_node A) {
assert (A->type == mp_structured);
FUNCTION_TRACE3 ("%p = get_subscr_head(%p)\n", A->subscr_head_, A);
return A->subscr_head_;
}
static void do_set_attr_head (MP mp, mp_value_node A, mp_node d) {
FUNCTION_TRACE4 ("set_attr_head(%p,%p) on line %d\n", (A), d, __LINE__);
assert (A->type == mp_structured);
A->attr_head_ = d;
}
static void do_set_subscr_head (MP mp, mp_value_node A, mp_node d) {
FUNCTION_TRACE4 ("set_subscr_head(%p,%p) on line %d\n", (A), d, __LINE__);
assert (A->type == mp_structured);
A->subscr_head_ = d;
}
@ @<Declarations@>=
static mp_node do_get_subscr_head (MP mp, mp_value_node A);
static mp_node do_get_attr_head (MP mp, mp_value_node A);
static void do_set_attr_head (MP mp, mp_value_node A, mp_node d);
static void do_set_subscr_head (MP mp, mp_value_node A, mp_node d);
@ It would have been nicer to make |mp_get_value_node| return
|mp_value_node| variables, but with |eqtb| as it stands that
became messy: lots of typecasts. So, it returns a simple
|mp_node| for now.
@d value_node_size sizeof(struct mp_value_node_data)
@c
static mp_node mp_get_value_node (MP mp) {
mp_value_node p;
if (mp->value_nodes) {
p = (mp_value_node)mp->value_nodes;
mp->value_nodes = p->link;
mp->num_value_nodes--;
p->link = NULL;
} else {
p = malloc_node (value_node_size);
new_number(p->data.n);
new_number(p->subscript_);
p->has_number = 2;
}
mp_type (p) = mp_value_node_type;
FUNCTION_TRACE2 ("%p = mp_get_value_node()\n", p);
return (mp_node)p;
}
#if DEBUG > 1
static void debug_dump_value_node (mp_node x) {
mp_value_node qq = (mp_value_node)x;
fprintf (stdout, "\nnode %p:\n", qq);
fprintf (stdout, " type=%s\n", mp_type_string(qq->type));
fprintf (stdout, " name_type=%d\n", qq->name_type);
fprintf (stdout, " link=%p\n", qq->link);
fprintf (stdout, " data.n=%d\n", qq->data.n.type);
if (is_number(qq->data.n)) {
fprintf (stdout, " data.n.data.val=%d\n", qq->data.n.data.val);
fprintf (stdout, " data.n.data.dval=%f\n", qq->data.n.data.dval);
}
fprintf (stdout, " data.str=%p\n", qq->data.str);
if (qq->data.str != NULL) {
fprintf (stdout, " data.str->len=%d\n", (int)qq->data.str->len);
fprintf (stdout, " data.str->str=%s\n", qq->data.str->str);
}
fprintf (stdout, " data.indep.serial=%d\n data.indep.scale=%d\n", qq->data.indep.serial,
qq->data.indep.scale);
fprintf (stdout, " data.sym=%p\n", qq->data.sym);
fprintf (stdout, " data.p=%p\n", qq->data.p);
fprintf (stdout, " data.node=%p\n", qq->data.node);
fprintf (stdout, " subscript=%d\n", qq->subscript_.type);
if (is_number(qq->subscript_)) {
fprintf (stdout, " subscript_.data.val=%d\n", qq->subscript_.data.val);
fprintf (stdout, " subscript_.data.dval=%f\n", qq->subscript_.data.dval);
}
fprintf (stdout, " hashloc=%p\n", qq->hashloc_);
fprintf (stdout, " parent=%p\n", qq->parent_);
fprintf (stdout, " attr_head=%p\n", qq->attr_head_);
fprintf (stdout, " subscr_head=%p\n\n", qq->subscr_head_);
}
#endif
@ @<Declarations@>=
static mp_node mp_get_value_node (MP mp);
#if DEBUG > 1
static void debug_dump_value_node (mp_node x);
#endif
@ An attribute node is three words long. Two of these words contain |type|
and |value| fields as described above, and the third word contains
additional information: There is an |hashloc| field, which contains the
hash address of the token that names this attribute; and there's also a
|parent| field, which points to the value node of |mp_structured| type at the
next higher level (i.e., at the level to which this attribute is
subsidiary). The |name_type| in an attribute node is `|attr|'. The
|link| field points to the next attribute with the same parent; these are
arranged in increasing order, so that |hashloc(mp_link(p))>hashloc(p)|. The
final attribute node links to the constant |end_attr|, whose |hashloc|
field is greater than any legal hash address. The |attr_head| in the
parent points to a node whose |name_type| is |mp_structured_root|; this
node represents the NULL attribute, i.e., the variable that is relevant
when no attributes are attached to the parent. The |attr_head| node
has the fields of either
a value node, a subscript node, or an attribute node, depending on what
the parent would be if it were not structured; but the subscript and
attribute fields are ignored, so it effectively contains only the data of
a value node. The |link| field in this special node points to an attribute
node whose |hashloc| field is zero; the latter node represents a collective
subscript `\.{[]}' attached to the parent, and its |link| field points to
the first non-special attribute node (or to |end_attr| if there are none).
A subscript node likewise occupies three words, with |type| and |value| fields
plus extra information; its |name_type| is |subscr|. In this case the
third word is called the |subscript| field, which is a |scaled| integer.
The |link| field points to the subscript node with the next larger
subscript, if any; otherwise the |link| points to the attribute node
for collective subscripts at this level. We have seen that the latter node
contains an upward pointer, so that the parent can be deduced.
The |name_type| in a parent-less value node is |root|, and the |link|
is the hash address of the token that names this value.
In other words, variables have a hierarchical structure that includes
enough threads running around so that the program is able to move easily
between siblings, parents, and children. An example should be helpful:
(The reader is advised to draw a picture while reading the following
description, since that will help to firm up the ideas.)
Suppose that `\.x' and `\.{x.a}' and `\.{x[]b}' and `\.{x5}'
and `\.{x20b}' have been mentioned in a user's program, where
\.{x[]b} has been declared to be of \&{boolean} type. Let |h(x)|, |h(a)|,
and |h(b)| be the hash addresses of \.x, \.a, and~\.b. Then
|eq_type(h(x))=name| and |equiv(h(x))=p|, where |p|~is a non-symbolic value
node with |mp_name_type(p)=root| and |mp_link(p)=h(x)|. We have |type(p)=mp_structured|,
|attr_head(p)=q|, and |subscr_head(p)=r|, where |q| points to a value
node and |r| to a subscript node. (Are you still following this? Use
a pencil to draw a diagram.) The lone variable `\.x' is represented by
|type(q)| and |value(q)|; furthermore
|mp_name_type(q)=mp_structured_root| and |mp_link(q)=q1|, where |q1| points
to an attribute node representing `\.{x[]}'. Thus |mp_name_type(q1)=attr|,
|hashloc(q1)=collective_subscript=0|, |parent(q1)=p|,
|type(q1)=mp_structured|, |attr_head(q1)=qq|, and |subscr_head(q1)=qq1|;
|qq| is a three-word ``attribute-as-value'' node with |type(qq)=numeric_type|
(assuming that \.{x5} is numeric, because |qq| represents `\.{x[]}'
with no further attributes), |mp_name_type(qq)=structured_root|,
|hashloc(qq)=0|, |parent(qq)=p|, and
|mp_link(qq)=qq1|. (Now pay attention to the next part.) Node |qq1| is
an attribute node representing `\.{x[][]}', which has never yet
occurred; its |type| field is |undefined|, and its |value| field is
undefined. We have |mp_name_type(qq1)=attr|, |hashloc(qq1)=collective_subscript|,
|parent(qq1)=q1|, and |mp_link(qq1)=qq2|. Since |qq2| represents
`\.{x[]b}', |type(qq2)=mp_unknown_boolean|; also |hashloc(qq2)=h(b)|,
|parent(qq2)=q1|, |mp_name_type(qq2)=attr|, |mp_link(qq2)=end_attr|.
(Maybe colored lines will help untangle your picture.)
Node |r| is a subscript node with |type| and |value|
representing `\.{x5}'; |mp_name_type(r)=subscr|, |subscript(r)=5.0|,
and |mp_link(r)=r1| is another subscript node. To complete the picture,
see if you can guess what |mp_link(r1)| is; give up? It's~|q1|.
Furthermore |subscript(r1)=20.0|, |mp_name_type(r1)=subscr|,
|type(r1)=mp_structured|, |attr_head(r1)=qqq|, |subscr_head(r1)=qqq1|,
and we finish things off with three more nodes
|qqq|, |qqq1|, and |qqq2| hung onto~|r1|. (Perhaps you should start again
with a larger sheet of paper.) The value of variable \.{x20b}
appears in node~|qqq2|, as you can well imagine.
If the example in the previous paragraph doesn't make things crystal
clear, a glance at some of the simpler subroutines below will reveal how
things work out in practice.
The only really unusual thing about these conventions is the use of
collective subscript attributes. The idea is to avoid repeating a lot of
type information when many elements of an array are identical macros
(for which distinct values need not be stored) or when they don't have
all of the possible attributes. Branches of the structure below collective
subscript attributes do not carry actual values except for macro identifiers;
branches of the structure below subscript nodes do not carry significant
information in their collective subscript attributes.
@c
#if DEBUG
#define hashloc(A) do_get_hashloc(mp,(mp_value_node)(A))
#define set_hashloc(A,B) do_set_hashloc (mp,(mp_value_node)A, B)
#define parent(A) do_get_parent(mp, A)
#define set_parent(A,B) do_set_parent (mp,(mp_value_node)A, B)
static mp_sym do_get_hashloc (MP mp, mp_value_node A) {
assert((A)->type == mp_attr_node_type || (A)->name_type == mp_attr);
return (A)->hashloc_;
}
static void do_set_hashloc (MP mp, mp_value_node A, mp_sym B) {
FUNCTION_TRACE4 ("set_hashloc(%p,%p) on line %d\n", (A), (B), __LINE__);
assert((A)->type == mp_attr_node_type || (A)->name_type == mp_attr);
A->hashloc_ = B;
}
static mp_node do_get_parent (MP mp, mp_value_node A) {
assert((A)->type == mp_attr_node_type || (A)->name_type == mp_attr);
return (A)->parent_; /* pointer to |mp_structured| variable */
}
static void do_set_parent (MP mp, mp_value_node A, mp_node d) {
assert((A)->type == mp_attr_node_type || (A)->name_type == mp_attr);
FUNCTION_TRACE4 ("set_parent(%p,%p) on line %d\n", (A), d, __LINE__);
A->parent_ = d;
}
#else
#define hashloc(A) ((mp_value_node)(A))->hashloc_
#define set_hashloc(A,B) ((mp_value_node)(A))->hashloc_ = B
#define parent(A) ((mp_value_node)(A))->parent_
#define set_parent(A,B) ((mp_value_node)(A))->parent_ = B
#endif
@
@d mp_free_attr_node(a,b) do {
assert((b)->type == mp_attr_node_type || (b)->name_type == mp_attr);
mp_free_value_node(a,b);
} while (0)
@c
static mp_value_node mp_get_attr_node (MP mp) {
mp_value_node p = (mp_value_node) mp_get_value_node (mp);
mp_type (p) = mp_attr_node_type;
return p;
}
@ Setting the |hashloc| field of |end_attr| to a value greater than
any legal hash address is done by assigning $-1$ typecasted to
|mp_sym|, hopefully resulting in all bits being set. On systems that
support negative pointer values or where typecasting $-1$ does not
result in all bits in a pointer being set, something else needs to be done.
@^system dependencies@>
@<Initialize table...@>=
mp->end_attr = (mp_node) mp_get_attr_node (mp);
set_hashloc (mp->end_attr, (mp_sym)-1);
set_parent ((mp_value_node) mp->end_attr, NULL);
@ @<Free table...@>=
mp_free_attr_node (mp, mp->end_attr);
@
@d collective_subscript (void *)0 /* code for the attribute `\.{[]}' */
@d subscript(A) ((mp_value_node)(A))->subscript_
@d set_subscript(A,B) do_set_subscript (mp, (mp_value_node)(A), B)
@c
static void do_set_subscript (MP mp, mp_value_node A, mp_number B) {
FUNCTION_TRACE3("set_subscript(%p,%p)\n", (A), (B));
assert((A)->type == mp_subscr_node_type || (A)->name_type == mp_subscr);
number_clone(A->subscript_,B); /* subscript of this variable */
}
@
@c
static mp_value_node mp_get_subscr_node (MP mp) {
mp_value_node p = (mp_value_node) mp_get_value_node (mp);
mp_type (p) = mp_subscr_node_type;
return p;
}
@ Variables of type \&{pair} will have values that point to four-word
nodes containing two numeric values. The first of these values has
|name_type=mp_x_part_sector| and the second has |name_type=mp_y_part_sector|;
the |link| in the first points back to the node whose |value| points
to this four-word node.
@d x_part(A) ((mp_pair_node)(A))->x_part_ /* where the \&{xpart} is found in a pair node */
@d y_part(A) ((mp_pair_node)(A))->y_part_ /* where the \&{ypart} is found in a pair node */
@<MPlib internal header stuff@>=
typedef struct mp_pair_node_data {
NODE_BODY;
mp_node x_part_;
mp_node y_part_;
} mp_pair_node_data;
typedef struct mp_pair_node_data *mp_pair_node;
@
@d pair_node_size sizeof(struct mp_pair_node_data) /* the number of words in a subscript node */
@c
static mp_node mp_get_pair_node (MP mp) {
mp_node p;
if (mp->pair_nodes) {
p = mp->pair_nodes;
mp->pair_nodes = p->link;
mp->num_pair_nodes--;
p->link = NULL;
} else {
p = malloc_node (pair_node_size);
}
mp_type (p) = mp_pair_node_type;
FUNCTION_TRACE2("get_pair_node(): %p\n", p);
return (mp_node) p;
}
@ @<Declarations@>=
void mp_free_pair_node (MP mp, mp_node p);
@ @c
void mp_free_pair_node (MP mp, mp_node p) {
FUNCTION_TRACE2 ("mp_free_pair_node(%p)\n", p);
if (!p) return;
if (mp->num_pair_nodes < max_num_pair_nodes) {
p->link = mp->pair_nodes;
mp->pair_nodes = p;
mp->num_pair_nodes++;
return;
}
mp->var_used -= pair_node_size;
xfree (p);
}
@ If |type(p)=mp_pair_type| or if |value(p)=NULL|, the procedure call |init_pair_node(p)| will
allocate a pair node for~|p|. The individual parts of such nodes are initially of type
|mp_independent|.
@c
static void mp_init_pair_node (MP mp, mp_node p) {
mp_node q; /* the new node */
mp_type (p) = mp_pair_type;
q = mp_get_pair_node (mp);
y_part (q) = mp_get_value_node (mp);
mp_new_indep (mp, y_part (q)); /* sets |type(q)| and |value(q)| */
mp_name_type (y_part (q)) = (quarterword) (mp_y_part_sector);
mp_link (y_part (q)) = p;
x_part (q) = mp_get_value_node (mp);
mp_new_indep (mp, x_part (q)); /* sets |type(q)| and |value(q)| */
mp_name_type (x_part (q)) = (quarterword) (mp_x_part_sector);
mp_link (x_part (q)) = p;
set_value_node (p, q);
}
@
Variables of type \&{transform} are similar, but in this case their
|value| points to a 12-word node containing six values, identified by
|x_part_sector|, |y_part_sector|, |mp_xx_part_sector|, |mp_xy_part_sector|,
|mp_yx_part_sector|, and |mp_yy_part_sector|.
@d tx_part(A) ((mp_transform_node)(A))->tx_part_ /* where the \&{xpart} is found in a transform node */
@d ty_part(A) ((mp_transform_node)(A))->ty_part_ /* where the \&{ypart} is found in a transform node */
@d xx_part(A) ((mp_transform_node)(A))->xx_part_ /* where the \&{xxpart} is found in a transform node */
@d xy_part(A) ((mp_transform_node)(A))->xy_part_ /* where the \&{xypart} is found in a transform node */
@d yx_part(A) ((mp_transform_node)(A))->yx_part_ /* where the \&{yxpart} is found in a transform node */
@d yy_part(A) ((mp_transform_node)(A))->yy_part_ /* where the \&{yypart} is found in a transform node */
@<MPlib internal header stuff@>=
typedef struct mp_transform_node_data {
NODE_BODY;
mp_node tx_part_;
mp_node ty_part_;
mp_node xx_part_;
mp_node yx_part_;
mp_node xy_part_;
mp_node yy_part_;
} mp_transform_node_data;
typedef struct mp_transform_node_data *mp_transform_node;
@
@d transform_node_size sizeof(struct mp_transform_node_data) /* the number of words in a subscript node */
@c
static mp_node mp_get_transform_node (MP mp) {
mp_transform_node p = (mp_transform_node) malloc_node (transform_node_size);
mp_type (p) = mp_transform_node_type;
return (mp_node) p;
}
@ @c
static void mp_init_transform_node (MP mp, mp_node p) {
mp_node q; /* the new node */
mp_type (p) = mp_transform_type;
q = mp_get_transform_node (mp); /* big node */
yy_part (q) = mp_get_value_node (mp);
mp_new_indep (mp, yy_part (q)); /* sets |type(q)| and |value(q)| */
mp_name_type (yy_part (q)) = (quarterword) (mp_yy_part_sector);
mp_link (yy_part (q)) = p;
yx_part (q) = mp_get_value_node (mp);
mp_new_indep (mp, yx_part (q)); /* sets |type(q)| and |value(q)| */
mp_name_type (yx_part (q)) = (quarterword) (mp_yx_part_sector);
mp_link (yx_part (q)) = p;
xy_part (q) = mp_get_value_node (mp);
mp_new_indep (mp, xy_part (q)); /* sets |type(q)| and |value(q)| */
mp_name_type (xy_part (q)) = (quarterword) (mp_xy_part_sector);
mp_link (xy_part (q)) = p;
xx_part (q) = mp_get_value_node (mp);
mp_new_indep (mp, xx_part (q)); /* sets |type(q)| and |value(q)| */
mp_name_type (xx_part (q)) = (quarterword) (mp_xx_part_sector);
mp_link (xx_part (q)) = p;
ty_part (q) = mp_get_value_node (mp);
mp_new_indep (mp, ty_part (q)); /* sets |type(q)| and |value(q)| */
mp_name_type (ty_part (q)) = (quarterword) (mp_y_part_sector);
mp_link (ty_part (q)) = p;
tx_part (q) = mp_get_value_node (mp);
mp_new_indep (mp, tx_part (q)); /* sets |type(q)| and |value(q)| */
mp_name_type (tx_part (q)) = (quarterword) (mp_x_part_sector);
mp_link (tx_part (q)) = p;
set_value_node (p, q);
}
@
Variables of type \&{color} have 3~values in 6~words identified by |mp_red_part_sector|,
|mp_green_part_sector|, and |mp_blue_part_sector|.
@d red_part(A) ((mp_color_node)(A))->red_part_ /* where the \&{redpart} is found in a color node */
@d green_part(A) ((mp_color_node)(A))->green_part_ /* where the \&{greenpart} is found in a color node */
@d blue_part(A) ((mp_color_node)(A))->blue_part_ /* where the \&{bluepart} is found in a color node */
@d grey_part(A) red_part(A) /* where the \&{greypart} is found in a color node */
@<MPlib internal header stuff@>=
typedef struct mp_color_node_data {
NODE_BODY;
mp_node red_part_;
mp_node green_part_;
mp_node blue_part_;
} mp_color_node_data;
typedef struct mp_color_node_data *mp_color_node;
@
@d color_node_size sizeof(struct mp_color_node_data) /* the number of words in a subscript node */
@c
static mp_node mp_get_color_node (MP mp) {
mp_color_node p = (mp_color_node) malloc_node (color_node_size);
mp_type (p) = mp_color_node_type;
p->link = NULL;
return (mp_node) p;
}
@
@c
static void mp_init_color_node (MP mp, mp_node p) {
mp_node q; /* the new node */
mp_type (p) = mp_color_type;
q = mp_get_color_node (mp); /* big node */
blue_part (q) = mp_get_value_node (mp);
mp_new_indep (mp, blue_part (q)); /* sets |type(q)| and |value(q)| */
mp_name_type (blue_part (q)) = (quarterword) (mp_blue_part_sector);
mp_link (blue_part (q)) = p;
green_part (q) = mp_get_value_node (mp);
mp_new_indep (mp, green_part (q)); /* sets |type(q)| and |value(q)| */
mp_name_type (y_part (q)) = (quarterword) (mp_green_part_sector);
mp_link (green_part (q)) = p;
red_part (q) = mp_get_value_node (mp);
mp_new_indep (mp, red_part (q)); /* sets |type(q)| and |value(q)| */
mp_name_type (red_part (q)) = (quarterword) (mp_red_part_sector);
mp_link (red_part (q)) = p;
set_value_node (p, q);
}
@ Finally, variables of type |cmykcolor|.
@d cyan_part(A) ((mp_cmykcolor_node)(A))->cyan_part_ /* where the \&{cyanpart} is found in a color node */
@d magenta_part(A) ((mp_cmykcolor_node)(A))->magenta_part_ /* where the \&{magentapart} is found in a color node */
@d yellow_part(A) ((mp_cmykcolor_node)(A))->yellow_part_ /* where the \&{yellowpart} is found in a color node */
@d black_part(A) ((mp_cmykcolor_node)(A))->black_part_ /* where the \&{blackpart} is found in a color node */
@<MPlib internal header stuff@>=
typedef struct mp_cmykcolor_node_data {
NODE_BODY;
mp_node cyan_part_;
mp_node magenta_part_;
mp_node yellow_part_;
mp_node black_part_;
} mp_cmykcolor_node_data;
typedef struct mp_cmykcolor_node_data *mp_cmykcolor_node;
@
@d cmykcolor_node_size sizeof(struct mp_cmykcolor_node_data) /* the number of words in a subscript node */
@c
static mp_node mp_get_cmykcolor_node (MP mp) {
mp_cmykcolor_node p = (mp_cmykcolor_node) malloc_node (cmykcolor_node_size);
mp_type (p) = mp_cmykcolor_node_type;
p->link = NULL;
return (mp_node) p;
}
@
@c
static void mp_init_cmykcolor_node (MP mp, mp_node p) {
mp_node q; /* the new node */
mp_type (p) = mp_cmykcolor_type;
q = mp_get_cmykcolor_node (mp); /* big node */
black_part (q) = mp_get_value_node (mp);
mp_new_indep (mp, black_part (q)); /* sets |type(q)| and |value(q)| */
mp_name_type (black_part (q)) = (quarterword) (mp_black_part_sector);
mp_link (black_part (q)) = p;
yellow_part (q) = mp_get_value_node (mp);
mp_new_indep (mp, yellow_part (q)); /* sets |type(q)| and |value(q)| */
mp_name_type (yellow_part (q)) = (quarterword) (mp_yellow_part_sector);
mp_link (yellow_part (q)) = p;
magenta_part (q) = mp_get_value_node (mp);
mp_new_indep (mp, magenta_part (q)); /* sets |type(q)| and |value(q)| */
mp_name_type (magenta_part (q)) = (quarterword) (mp_magenta_part_sector);
mp_link (magenta_part (q)) = p;
cyan_part (q) = mp_get_value_node (mp);
mp_new_indep (mp, cyan_part (q)); /* sets |type(q)| and |value(q)| */
mp_name_type (cyan_part (q)) = (quarterword) (mp_cyan_part_sector);
mp_link (cyan_part (q)) = p;
set_value_node (p, q);
}
@ When an entire structured variable is saved, the |root| indication
is temporarily replaced by |saved_root|.
Some variables have no name; they just are used for temporary storage
while expressions are being evaluated. We call them {\sl capsules}.
@ The |id_transform| function creates a capsule for the
identity transformation.
@c
static mp_node mp_id_transform (MP mp) {
mp_node p, q; /* list manipulation registers */
p = mp_get_value_node (mp);
mp_name_type (p) = mp_capsule;
set_value_number (p, zero_t); /* todo: this was |null| */
mp_init_transform_node (mp, p);
q = value_node (p);
mp_type (tx_part (q)) = mp_known;
set_value_number (tx_part (q), zero_t);
mp_type (ty_part (q)) = mp_known;
set_value_number (ty_part (q), zero_t);
mp_type (xy_part (q)) = mp_known;
set_value_number (xy_part (q), zero_t);
mp_type (yx_part (q)) = mp_known;
set_value_number (yx_part (q), zero_t);
mp_type (xx_part (q)) = mp_known;
set_value_number (xx_part (q), unity_t);
mp_type (yy_part (q)) = mp_known;
set_value_number (yy_part (q), unity_t);
return p;
}
@ Tokens are of type |tag_token| when they first appear, but they point
to |NULL| until they are first used as the root of a variable.
The following subroutine establishes the root node on such grand occasions.
@c
static void mp_new_root (MP mp, mp_sym x) {
mp_node p; /* the new node */
p = mp_get_value_node (mp);
mp_type (p) = mp_undefined;
mp_name_type (p) = mp_root;
set_value_sym (p, x);
set_equiv_node (x, p);
}
@ These conventions for variable representation are illustrated by the
|print_variable_name| routine, which displays the full name of a
variable given only a pointer to its value.
@<Declarations@>=
static void mp_print_variable_name (MP mp, mp_node p);
@ @c
void mp_print_variable_name (MP mp, mp_node p) {
mp_node q; /* a token list that will name the variable's suffix */
mp_node r; /* temporary for token list creation */
while (mp_name_type (p) >= mp_x_part_sector) {
switch (mp_name_type (p)) {
case mp_x_part_sector: mp_print (mp, "xpart "); break;
case mp_y_part_sector: mp_print (mp, "ypart "); break;
case mp_xx_part_sector: mp_print (mp, "xxpart "); break;
case mp_xy_part_sector: mp_print (mp, "xypart "); break;
case mp_yx_part_sector: mp_print (mp, "yxpart "); break;
case mp_yy_part_sector: mp_print (mp, "yypart "); break;
case mp_red_part_sector: mp_print (mp, "redpart "); break;
case mp_green_part_sector: mp_print (mp, "greenpart "); break;
case mp_blue_part_sector: mp_print (mp, "bluepart "); break;
case mp_cyan_part_sector: mp_print (mp, "cyanpart "); break;
case mp_magenta_part_sector:mp_print (mp, "magentapart ");break;
case mp_yellow_part_sector: mp_print (mp, "yellowpart "); break;
case mp_black_part_sector: mp_print (mp, "blackpart "); break;
case mp_grey_part_sector: mp_print (mp, "greypart "); break;
case mp_capsule: mp_printf (mp, "%%CAPSULE%p",p); return; break;
/* this is to please the compiler: the remaining cases are operation codes */
default: break;
}
p = mp_link (p);
}
q = NULL;
while (mp_name_type (p) > mp_saved_root) {
/* Ascend one level, pushing a token onto list |q|
and replacing |p| by its parent */
if (mp_name_type (p) == mp_subscr) {
r = mp_new_num_tok (mp, subscript (p));
do {
p = mp_link (p);
} while (mp_name_type (p) != mp_attr);
} else if (mp_name_type (p) == mp_structured_root) {
p = mp_link (p);
goto FOUND;
} else {
if (mp_name_type (p) != mp_attr)
mp_confusion (mp, "var");
r = mp_get_symbolic_node (mp);
set_mp_sym_sym (r, hashloc (p)); /* the hash address */
}
set_mp_link (r, q);
q = r;
FOUND:
p = parent ((mp_value_node) p);
}
/* now |link(p)| is the hash address of |p|, and
|name_type(p)| is either |root| or |saved_root|.
Have to prepend a token to |q| for |show_token_list|. */
r = mp_get_symbolic_node (mp);
set_mp_sym_sym (r, value_sym (p));
mp_link (r) = q;
if (mp_name_type (p) == mp_saved_root)
mp_print (mp, "(SAVED)");
mp_show_token_list (mp, r, NULL, max_integer, mp->tally);
mp_flush_token_list (mp, r);
}
@ The |interesting| function returns |true| if a given variable is not
in a capsule, or if the user wants to trace capsules.
@c
static boolean mp_interesting (MP mp, mp_node p) {
mp_name_type_type t; /* a |name_type| */
if (number_positive(internal_value (mp_tracing_capsules))) {
return true;
} else {
t = mp_name_type (p);
if (t >= mp_x_part_sector && t != mp_capsule) {
mp_node tt = value_node(mp_link(p));
switch (t) {
case mp_x_part_sector:
t = mp_name_type (x_part (tt));
break;
case mp_y_part_sector:
t = mp_name_type (y_part (tt));
break;
case mp_xx_part_sector:
t = mp_name_type (xx_part (tt));
break;
case mp_xy_part_sector:
t = mp_name_type (xy_part (tt));
break;
case mp_yx_part_sector:
t = mp_name_type (yx_part (tt));
break;
case mp_yy_part_sector:
t = mp_name_type (yy_part (tt));
break;
case mp_red_part_sector:
t = mp_name_type (red_part (tt));
break;
case mp_green_part_sector:
t = mp_name_type (green_part (tt));
break;
case mp_blue_part_sector:
t = mp_name_type (blue_part (tt));
break;
case mp_cyan_part_sector:
t = mp_name_type (cyan_part (tt));
break;
case mp_magenta_part_sector:
t = mp_name_type (magenta_part (tt));
break;
case mp_yellow_part_sector:
t = mp_name_type (yellow_part (tt));
break;
case mp_black_part_sector:
t = mp_name_type (black_part (tt));
break;
case mp_grey_part_sector:
t = mp_name_type (grey_part (tt));
break;
default:
break;
}
}
}
return (t != mp_capsule);
}
@ Now here is a subroutine that converts an unstructured type into an
equivalent structured type, by inserting a |mp_structured| node that is
capable of growing. This operation is done only when |mp_name_type(p)=root|,
|subscr|, or |attr|.
The procedure returns a pointer to the new node that has taken node~|p|'s
place in the structure. Node~|p| itself does not move, nor are its
|value| or |type| fields changed in any way.
@c
static mp_node mp_new_structure (MP mp, mp_node p) {
mp_node q, r = NULL; /* list manipulation registers */
mp_sym qq = NULL;
switch (mp_name_type (p)) {
case mp_root:
{
qq = value_sym (p);
r = mp_get_value_node (mp);
set_equiv_node (qq, r);
}
break;
case mp_subscr:
/* Link a new subscript node |r| in place of node |p| */
{
mp_node q_new;
q = p;
do {
q = mp_link (q);
} while (mp_name_type (q) != mp_attr);
q = parent ((mp_value_node) q);
r = mp->temp_head;
set_mp_link (r, subscr_head (q));
do {
q_new = r;
r = mp_link (r);
} while (r != p);
r = (mp_node) mp_get_subscr_node (mp);
if (q_new == mp->temp_head) {
set_subscr_head (q, r);
} else {
set_mp_link (q_new, r);
}
set_subscript (r, subscript (p));
}
break;
case mp_attr:
/* Link a new attribute node |r| in place of node |p| */
/* If the attribute is |collective_subscript|, there are two pointers to
node~|p|, so we must change both of them. */
{
mp_value_node rr;
q = parent ((mp_value_node) p);
r = attr_head (q);
do {
q = r;
r = mp_link (r);
} while (r != p);
rr = mp_get_attr_node (mp);
r = (mp_node) rr;
set_mp_link (q, (mp_node) rr);
set_hashloc (rr, hashloc (p));
set_parent (rr, parent ((mp_value_node) p));
if (hashloc (p) == collective_subscript) {
q = mp->temp_head;
set_mp_link (q, subscr_head (parent ((mp_value_node) p)));
while (mp_link (q) != p)
q = mp_link (q);
if (q == mp->temp_head)
set_subscr_head (parent ((mp_value_node) p), (mp_node) rr);
else
set_mp_link (q, (mp_node) rr);
}
}
break;
default:
mp_confusion (mp, "struct");
break;
}
set_mp_link (r, mp_link (p));
set_value_sym (r, value_sym (p));
mp_type (r) = mp_structured;
mp_name_type (r) = mp_name_type (p);
set_attr_head (r, p);
mp_name_type (p) = mp_structured_root;
{
mp_value_node qqr = mp_get_attr_node (mp);
set_mp_link (p, (mp_node) qqr);
set_subscr_head (r, (mp_node) qqr);
set_parent (qqr, r);
mp_type (qqr) = mp_undefined;
mp_name_type (qqr) = mp_attr;
set_mp_link (qqr, mp->end_attr);
set_hashloc (qqr, collective_subscript);
}
return r;
}
@ The |find_variable| routine is given a pointer~|t| to a nonempty token
list of suffixes; it returns a pointer to the corresponding non-symbolic
value. For example, if |t| points to token \.x followed by a numeric
token containing the value~7, |find_variable| finds where the value of
\.{x7} is stored in memory. This may seem a simple task, and it
usually is, except when \.{x7} has never been referenced before.
Indeed, \.x may never have even been subscripted before; complexities
arise with respect to updating the collective subscript information.
If a macro type is detected anywhere along path~|t|, or if the first
item on |t| isn't a |tag_token|, the value |NULL| is returned.
Otherwise |p| will be a non-NULL pointer to a node such that
|undefined<type(p)<mp_structured|.
@c
static mp_node mp_find_variable (MP mp, mp_node t) {
mp_node p, q, r, s; /* nodes in the ``value'' line */
mp_sym p_sym;
mp_node pp, qq, rr, ss; /* nodes in the ``collective'' line */
@^inner loop@>;
p_sym = mp_sym_sym (t);
t = mp_link (t);
if ((eq_type (p_sym) % mp_outer_tag) != mp_tag_token)
return NULL;
if (equiv_node (p_sym) == NULL)
mp_new_root (mp, p_sym);
p = equiv_node (p_sym);
pp = p;
while (t != NULL) {
/* Make sure that both nodes |p| and |pp| are of |mp_structured| type */
/* Although |pp| and |p| begin together, they diverge when a subscript occurs;
|pp|~stays in the collective line while |p|~goes through actual subscript
values. */
if (mp_type (pp) != mp_structured) {
if (mp_type (pp) > mp_structured)
return NULL;
ss = mp_new_structure (mp, pp);
if (p == pp)
p = ss;
pp = ss;
} /* now |type(pp)=mp_structured| */
if (mp_type (p) != mp_structured) { /* it cannot be |>mp_structured| */
p = mp_new_structure (mp, p); /* now |type(p)=mp_structured| */
}
if (mp_type (t) != mp_symbol_node) {
/* Descend one level for the subscript |value(t)| */
/* We want this part of the program to be reasonably fast, in case there are
lots of subscripts at the same level of the data structure. Therefore
we store an ``infinite'' value in the word that appears at the end of the
subscript list, even though that word isn't part of a subscript node. */
mp_number nn, save_subscript; /* temporary storage */
new_number (nn);
new_number (save_subscript);
number_clone (nn, value_number (t));
pp = mp_link (attr_head (pp)); /* now |hashloc(pp)=collective_subscript| */
q = mp_link (attr_head (p));
number_clone (save_subscript, subscript (q));
set_number_to_inf(subscript (q));
s = mp->temp_head;
set_mp_link (s, subscr_head (p));
do {
r = s;
s = mp_link (s);
} while (number_greater (nn, subscript (s)));
if (number_equal(nn, subscript (s))) {
p = s;
} else {
mp_value_node p1 = mp_get_subscr_node (mp);
if (r == mp->temp_head)
set_subscr_head (p, (mp_node) p1);
else
set_mp_link (r, (mp_node) p1);
set_mp_link (p1, s);
number_clone (subscript (p1), nn);
mp_name_type (p1) = mp_subscr;
mp_type (p1) = mp_undefined;
p = (mp_node) p1;
}
number_clone (subscript (q), save_subscript);
free_number (save_subscript);
free_number (nn);
} else {
/* Descend one level for the attribute |mp_sym_info(t)| */
mp_sym nn1 = mp_sym_sym (t);
ss = attr_head (pp);
do {
rr = ss;
ss = mp_link (ss);
} while (nn1 > hashloc (ss));
if (nn1 < hashloc (ss)) {
qq = (mp_node) mp_get_attr_node (mp);
set_mp_link (rr, qq);
set_mp_link (qq, ss);
set_hashloc (qq, nn1);
mp_name_type (qq) = mp_attr;
mp_type (qq) = mp_undefined;
set_parent ((mp_value_node) qq, pp);
ss = qq;
}
if (p == pp) {
p = ss;
pp = ss;
} else {
pp = ss;
s = attr_head (p);
do {
r = s;
s = mp_link (s);
} while (nn1 > hashloc (s));
if (nn1 == hashloc (s)) {
p = s;
} else {
q = (mp_node) mp_get_attr_node (mp);
set_mp_link (r, q);
set_mp_link (q, s);
set_hashloc (q, nn1);
mp_name_type (q) = mp_attr;
mp_type (q) = mp_undefined;
set_parent ((mp_value_node) q, p);
p = q;
}
}
}
t = mp_link (t);
}
if (mp_type (pp) >= mp_structured) {
if (mp_type (pp) == mp_structured)
pp = attr_head (pp);
else
return NULL;
}
if (mp_type (p) == mp_structured)
p = attr_head (p);
if (mp_type (p) == mp_undefined) {
if (mp_type (pp) == mp_undefined) {
mp_type (pp) = mp_numeric_type;
set_value_number (pp, zero_t);
}
mp_type (p) = mp_type (pp);
set_value_number (p, zero_t);
}
return p;
}
@ Variables lose their former values when they appear in a type declaration,
or when they are defined to be macros or \&{let} equal to something else.
A subroutine will be defined later that recycles the storage associated
with any particular |type| or |value|; our goal now is to study a higher
level process called |flush_variable|, which selectively frees parts of a
variable structure.
This routine has some complexity because of examples such as
`\hbox{\tt numeric x[]a[]b}'
which recycles all variables of the form \.{x[i]a[j]b} (and no others), while
`\hbox{\tt vardef x[]a[]=...}'
discards all variables of the form \.{x[i]a[j]} followed by an arbitrary
suffix, except for the collective node \.{x[]a[]} itself. The obvious way
to handle such examples is to use recursion; so that's what we~do.
@^recursion@>
Parameter |p| points to the root information of the variable;
parameter |t| points to a list of symbolic nodes that represent
suffixes, with |info=collective_subscript| for subscripts.
@<Declarations@>=
void mp_flush_cur_exp (MP mp, mp_value v);
@ @c
static void mp_flush_variable (MP mp, mp_node p, mp_node t,
boolean discard_suffixes) {
mp_node q, r = NULL; /* list manipulation */
mp_sym n; /* attribute to match */
while (t != NULL) {
if (mp_type (p) != mp_structured) {
return;
}
n = mp_sym_sym (t);
t = mp_link (t);
if (n == collective_subscript) {
q = subscr_head (p);
while (mp_name_type (q) == mp_subscr) {
mp_flush_variable (mp, q, t, discard_suffixes);
if (t == NULL) {
if (mp_type (q) == mp_structured) {
r = q;
} else {
if (r==NULL)
set_subscr_head (p, mp_link (q));
else
set_mp_link (r, mp_link (q));
mp_free_value_node (mp, q);
}
} else {
r = q;
}
q = (r==NULL ? subscr_head (p) : mp_link (r));
}
}
p = attr_head (p);
do {
p = mp_link (p);
} while (hashloc (p) < n);
if (hashloc (p) != n) {
return;
}
}
if (discard_suffixes) {
mp_flush_below_variable (mp, p);
} else {
if (mp_type (p) == mp_structured) {
p = attr_head (p);
}
mp_recycle_value (mp, p);
}
}
@ The next procedure is simpler; it wipes out everything but |p| itself,
which becomes undefined.
@<Declarations@>=
static void mp_flush_below_variable (MP mp, mp_node p);
@ @c
void mp_flush_below_variable (MP mp, mp_node p) {
mp_node q, r; /* list manipulation registers */
FUNCTION_TRACE2 ("mp_flush_below_variable(%p)\n", p);
if (mp_type (p) != mp_structured) {
mp_recycle_value (mp, p); /* this sets |type(p)=undefined| */
} else {
q = subscr_head (p);
while (mp_name_type (q) == mp_subscr) {
mp_flush_below_variable (mp, q);
r = q;
q = mp_link (q);
mp_free_value_node (mp, r);
}
r = attr_head (p);
q = mp_link (r);
mp_recycle_value (mp, r);
mp_free_value_node (mp, r);
do {
mp_flush_below_variable (mp, q);
r = q;
q = mp_link (q);
mp_free_value_node (mp, r);
} while (q != mp->end_attr);
mp_type (p) = mp_undefined;
}
}
@ Just before assigning a new value to a variable, we will recycle the
old value and make the old value undefined. The |und_type| routine
determines what type of undefined value should be given, based on
the current type before recycling.
@c
static quarterword mp_und_type (MP mp, mp_node p) {
(void) mp;
switch (mp_type (p)) {
case mp_vacuous:
return mp_undefined;
case mp_boolean_type:
case mp_unknown_boolean:
return mp_unknown_boolean;
case mp_string_type:
case mp_unknown_string:
return mp_unknown_string;
case mp_pen_type:
case mp_unknown_pen:
return mp_unknown_pen;
case mp_path_type:
case mp_unknown_path:
return mp_unknown_path;
case mp_picture_type:
case mp_unknown_picture:
return mp_unknown_picture;
case mp_transform_type:
case mp_color_type:
case mp_cmykcolor_type:
case mp_pair_type:
case mp_numeric_type:
return mp_type (p);
case mp_known:
case mp_dependent:
case mp_proto_dependent:
case mp_independent:
return mp_numeric_type;
default: /* there are no other valid cases, but please the compiler */
return 0;
}
return 0;
}
@ The |clear_symbol| routine is used when we want to redefine the equivalent
of a symbolic token. It must remove any variable structure or macro
definition that is currently attached to that symbol. If the |saving|
parameter is true, a subsidiary structure is saved instead of destroyed.
@c
static void mp_clear_symbol (MP mp, mp_sym p, boolean saving) {
mp_node q; /* |equiv(p)| */
FUNCTION_TRACE3 ("mp_clear_symbol(%p,%d)\n", p, saving);
q = equiv_node (p);
switch (eq_type (p) % mp_outer_tag) {
case mp_defined_macro:
case mp_secondary_primary_macro:
case mp_tertiary_secondary_macro:
case mp_expression_tertiary_macro:
if (!saving)
mp_delete_mac_ref (mp, q);
break;
case mp_tag_token:
if (q != NULL) {
if (saving) {
mp_name_type (q) = mp_saved_root;
} else {
mp_flush_below_variable (mp, q);
mp_free_value_node (mp, q);
}
}
break;
default:
break;
}
set_equiv (p, mp->frozen_undefined->v.data.indep.serial);
set_eq_type (p, mp->frozen_undefined->type);
}
@* Saving and restoring equivalents.
The nested structure given by \&{begingroup} and \&{endgroup}
allows |eqtb| entries to be saved and restored, so that temporary changes
can be made without difficulty. When the user requests a current value to
be saved, \MP\ puts that value into its ``save stack.'' An appearance of
\&{endgroup} ultimately causes the old values to be removed from the save
stack and put back in their former places.
The save stack is a linked list containing three kinds of entries,
distinguished by their |type| fields. If |p| points to a saved item,
then
\smallskip\hang
|p->type=0| stands for a group boundary; each \&{begingroup} contributes
such an item to the save stack and each \&{endgroup} cuts back the stack
until the most recent such entry has been removed.
\smallskip\hang
|p->type=mp_normal_sym| means that |p->value| holds the former
contents of |eqtb[q]| (saved in the |knot| field of the value, which
is otherwise unused for variables). Such save stack entries are generated by \&{save}
commands.
\smallskip\hang
|p->type=mp_internal_sym| means that |p->value| is a |mp_internal|
to be restored to internal parameter number~|q| (saved in the |serial| field of the value, which
is otherwise unused for internals). Such entries are generated by \&{interim} commands.
\smallskip\noindent
The global variable |save_ptr| points to the top item on the save stack.
@<Types...@>=
typedef struct mp_save_data {
quarterword type;
mp_internal value;
struct mp_save_data *link;
} mp_save_data;
@ @<Glob...@>=
mp_save_data *save_ptr; /* the most recently saved item */
@ @<Set init...@>=
mp->save_ptr = NULL;
@ Saving a boundary item
@c
static void mp_save_boundary (MP mp) {
mp_save_data *p; /* temporary register */
FUNCTION_TRACE1 ("mp_save_boundary ()\n");
p = xmalloc (1, sizeof (mp_save_data));
p->type = 0;
p->link = mp->save_ptr;
mp->save_ptr = p;
}
@ The |save_variable| routine is given a hash address |q|; it salts this
address in the save stack, together with its current equivalent,
then makes token~|q| behave as though it were brand new.
Nothing is stacked when |save_ptr=NULL|, however; there's no way to remove
things from the stack when the program is not inside a group, so there's
no point in wasting the space.
@c
static void mp_save_variable (MP mp, mp_sym q) {
mp_save_data *p; /* temporary register */
FUNCTION_TRACE2 ("mp_save_variable (%p)\n", q);
if (mp->save_ptr != NULL) {
p = xmalloc (1, sizeof (mp_save_data));
p->type = mp_normal_sym;
p->link = mp->save_ptr;
p->value.v.data.indep.scale = eq_type (q);
p->value.v.data.indep.serial = equiv(q);
p->value.v.data.node = equiv_node(q);
p->value.v.data.p = (mp_knot)q;
mp->save_ptr = p;
}
mp_clear_symbol (mp, q, (mp->save_ptr != NULL));
}
static void mp_unsave_variable (MP mp) {
mp_sym q = (mp_sym)mp->save_ptr->value.v.data.p;
if (number_positive(internal_value (mp_tracing_restores))) {
mp_begin_diagnostic (mp);
mp_print_nl (mp, "{restoring ");
mp_print_text (q);
mp_print_char (mp, xord ('}'));
mp_end_diagnostic (mp, false);
}
mp_clear_symbol (mp, q, false);
set_eq_type(q, mp->save_ptr->value.v.data.indep.scale);
set_equiv (q,mp->save_ptr->value.v.data.indep.serial);
q->v.data.node = mp->save_ptr->value.v.data.node;
if (eq_type (q) % mp_outer_tag == mp_tag_token) {
mp_node pp = q->v.data.node;
if (pp != NULL)
mp_name_type (pp) = mp_root;
}
}
@ Similarly, |save_internal| is given the location |q| of an internal
quantity like |mp_tracing_pens|. It creates a save stack entry of the
third kind.
@c
static void mp_save_internal (MP mp, halfword q) {
mp_save_data *p; /* new item for the save stack */
FUNCTION_TRACE2 ("mp_save_internal (%d)\n", q);
if (mp->save_ptr != NULL) {
p = xmalloc (1, sizeof (mp_save_data));
p->type = mp_internal_sym;
p->link = mp->save_ptr;
p->value = mp->internal[q];
p->value.v.data.indep.serial = q;
new_number(p->value.v.data.n);
number_clone(p->value.v.data.n, mp->internal[q].v.data.n);
mp->save_ptr = p;
}
}
static void mp_unsave_internal (MP mp) {
halfword q = mp->save_ptr->value.v.data.indep.serial;
mp_internal saved = mp->save_ptr->value;
if (number_positive(internal_value (mp_tracing_restores))) {
mp_begin_diagnostic (mp);
mp_print_nl (mp, "{restoring ");
mp_print (mp, internal_name (q));
mp_print_char (mp, xord ('='));
if (internal_type (q) == mp_known) {
print_number (saved.v.data.n);
} else if (internal_type (q) == mp_string_type) {
char *s = mp_str (mp, saved.v.data.str);
mp_print (mp, s);
} else {
mp_confusion (mp, "internal_restore");
}
mp_print_char (mp, xord ('}'));
mp_end_diagnostic (mp, false);
}
free_number (mp->internal[q].v.data.n);
mp->internal[q] = saved;
}
@ At the end of a group, the |unsave| routine restores all of the saved
equivalents in reverse order. This routine will be called only when there
is at least one boundary item on the save stack.
@c
static void mp_unsave (MP mp) {
mp_save_data *p; /* saved item */
FUNCTION_TRACE1 ("mp_unsave ()\n");
while (mp->save_ptr->type != 0) {
if (mp->save_ptr->type == mp_internal_sym) {
mp_unsave_internal(mp);
} else {
mp_unsave_variable(mp);
}
p = mp->save_ptr->link;
xfree (mp->save_ptr);
mp->save_ptr = p;
}
p = mp->save_ptr->link;
xfree (mp->save_ptr);
mp->save_ptr = p;
}
@* Data structures for paths.
When a \MP\ user specifies a path, \MP\ will create a list of knots
and control points for the associated cubic spline curves. If the
knots are $z_0$, $z_1$, \dots, $z_n$, there are control points
$z_k^+$ and $z_{k+1}^-$ such that the cubic splines between knots
$z_k$ and $z_{k+1}$ are defined by B\'ezier's formula
@:Bezier}{B\'ezier, Pierre Etienne@>
$$\eqalign{z(t)&=B(z_k,z_k^+,z_{k+1}^-,z_{k+1};t)\cr
&=(1-t)^3z_k+3(1-t)^2tz_k^++3(1-t)t^2z_{k+1}^-+t^3z_{k+1}\cr}$$
for |0<=t<=1|.
There is a 8-word node for each knot $z_k$, containing one word of
control information and six words for the |x| and |y| coordinates of
$z_k^-$ and $z_k$ and~$z_k^+$. The control information appears in the
|mp_left_type| and |mp_right_type| fields, which each occupy a quarter of
the first word in the node; they specify properties of the curve as it
enters and leaves the knot. There's also a halfword |link| field,
which points to the following knot, and a final supplementary word (of
which only a quarter is used).
If the path is a closed contour, knots 0 and |n| are identical;
i.e., the |link| in knot |n-1| points to knot~0. But if the path
is not closed, the |mp_left_type| of knot~0 and the |mp_right_type| of knot~|n|
are equal to |endpoint|. In the latter case the |link| in knot~|n| points
to knot~0, and the control points $z_0^-$ and $z_n^+$ are not used.
@d mp_next_knot(A) (A)->next /* the next knot in this list */
@d mp_left_type(A) (A)->data.types.left_type /* characterizes the path entering this knot */
@d mp_right_type(A) (A)->data.types.right_type /* characterizes the path leaving this knot */
@d mp_prev_knot(A) (A)->data.prev /* the previous knot in this list (only for pens) */
@d mp_knot_info(A) (A)->data.info /* temporary info, used during splitting */
@<Exported types...@>=
typedef struct mp_knot_data *mp_knot;
typedef struct mp_knot_data {
mp_number x_coord; /* the |x| coordinate of this knot */
mp_number y_coord; /* the |y| coordinate of this knot */
mp_number left_x; /* the |x| coordinate of previous control point */
mp_number left_y; /* the |y| coordinate of previous control point */
mp_number right_x; /* the |x| coordinate of next control point */
mp_number right_y; /* the |y| coordinate of next control point */
mp_knot next;
union {
struct {
unsigned short left_type;
unsigned short right_type;
} types;
mp_knot prev;
signed int info;
} data;
unsigned char originator;
} mp_knot_data;
@
@d mp_gr_next_knot(A) (A)->next /* the next knot in this list */
@<Exported types...@>=
typedef struct mp_gr_knot_data *mp_gr_knot;
typedef struct mp_gr_knot_data {
double x_coord;
double y_coord;
double left_x;
double left_y;
double right_x;
double right_y;
mp_gr_knot next;
union {
struct {
unsigned short left_type;
unsigned short right_type;
} types;
mp_gr_knot prev;
signed int info;
} data;
unsigned char originator;
} mp_gr_knot_data;
@ @<MPlib header stuff@>=
enum mp_knot_type {
mp_endpoint = 0, /* |mp_left_type| at path beginning and |mp_right_type| at path end */
mp_explicit, /* |mp_left_type| or |mp_right_type| when control points are known */
mp_given, /* |mp_left_type| or |mp_right_type| when a direction is given */
mp_curl, /* |mp_left_type| or |mp_right_type| when a curl is desired */
mp_open, /* |mp_left_type| or |mp_right_type| when \MP\ should choose the direction */
mp_end_cycle
};
@ Before the B\'ezier control points have been calculated, the memory
space they will ultimately occupy is taken up by information that can be
used to compute them. There are four cases:
\yskip
\textindent{$\bullet$} If |mp_right_type=mp_open|, the curve should leave
the knot in the same direction it entered; \MP\ will figure out a
suitable direction.
\yskip
\textindent{$\bullet$} If |mp_right_type=mp_curl|, the curve should leave the
knot in a direction depending on the angle at which it enters the next
knot and on the curl parameter stored in |right_curl|.
\yskip
\textindent{$\bullet$} If |mp_right_type=mp_given|, the curve should leave the
knot in a nonzero direction stored as an |angle| in |right_given|.
\yskip
\textindent{$\bullet$} If |mp_right_type=mp_explicit|, the B\'ezier control
point for leaving this knot has already been computed; it is in the
|mp_right_x| and |mp_right_y| fields.
\yskip\noindent
The rules for |mp_left_type| are similar, but they refer to the curve entering
the knot, and to \\{left} fields instead of \\{right} fields.
Non-|explicit| control points will be chosen based on ``tension'' parameters
in the |left_tension| and |right_tension| fields. The
`\&{atleast}' option is represented by negative tension values.
@:at_least_}{\&{atleast} primitive@>
For example, the \MP\ path specification
$$\.{z0..z1..tension atleast 1..\{curl 2\}z2..z3\{-1,-2\}..tension
3 and 4..p},$$
where \.p is the path `\.{z4..controls z45 and z54..z5}', will be represented
by the six knots
\def\lodash{\hbox to 1.1em{\thinspace\hrulefill\thinspace}}
$$\vbox{\halign{#\hfil&&\qquad#\hfil\cr
|mp_left_type|&\\{left} info&|x_coord,y_coord|&|mp_right_type|&\\{right} info\cr
\noalign{\yskip}
|endpoint|&\lodash$,\,$\lodash&$x_0,y_0$&|curl|&$1.0,1.0$\cr
|open|&\lodash$,1.0$&$x_1,y_1$&|open|&\lodash$,-1.0$\cr
|curl|&$2.0,-1.0$&$x_2,y_2$&|curl|&$2.0,1.0$\cr
|given|&$d,1.0$&$x_3,y_3$&|given|&$d,3.0$\cr
|open|&\lodash$,4.0$&$x_4,y_4$&|explicit|&$x_{45},y_{45}$\cr
|explicit|&$x_{54},y_{54}$&$x_5,y_5$&|endpoint|&\lodash$,\,$\lodash\cr}}$$
Here |d| is the |angle| obtained by calling |n_arg(-unity,-two)|.
Of course, this example is more complicated than anything a normal user
would ever write.
These types must satisfy certain restrictions because of the form of \MP's
path syntax:
(i)~|open| type never appears in the same node together with |endpoint|,
|given|, or |curl|.
(ii)~The |mp_right_type| of a node is |explicit| if and only if the
|mp_left_type| of the following node is |explicit|.
(iii)~|endpoint| types occur only at the ends, as mentioned above.
@d left_curl left_x /* curl information when entering this knot */
@d left_given left_x /* given direction when entering this knot */
@d left_tension left_y /* tension information when entering this knot */
@d right_curl right_x /* curl information when leaving this knot */
@d right_given right_x /* given direction when leaving this knot */
@d right_tension right_y /* tension information when leaving this knot */
@ Knots can be user-supplied, or they can be created by program code,
like the |split_cubic| function, or |copy_path|. The distinction is
needed for the cleanup routine that runs after |split_cubic|, because
it should only delete knots it has previously inserted, and never
anything that was user-supplied. In order to be able to differentiate
one knot from another, we will set |originator(p):=mp_metapost_user| when
it appeared in the actual metapost program, and
|originator(p):=mp_program_code| in all other cases.
@d mp_originator(A) (A)->originator /* the creator of this knot */
@<Exported types@>=
enum mp_knot_originator {
mp_program_code = 0, /* not created by a user */
mp_metapost_user /* created by a user */
};
@ Here is a routine that prints a given knot list
in symbolic form. It illustrates the conventions discussed above,
and checks for anomalies that might arise while \MP\ is being debugged.
@<Declarations@>=
static void mp_pr_path (MP mp, mp_knot h);
@ @c
void mp_pr_path (MP mp, mp_knot h) {
mp_knot p, q; /* for list traversal */
p = h;
do {
q = mp_next_knot (p);
if ((p == NULL) || (q == NULL)) {
mp_print_nl (mp, "???");
return; /* this won't happen */
@.???@>
}
@<Print information for adjacent knots |p| and |q|@>;
DONE1:
p = q;
if (p && ((p != h) || (mp_left_type (h) != mp_endpoint))) {
@<Print two dots, followed by |given| or |curl| if present@>;
}
} while (p != h);
if (mp_left_type (h) != mp_endpoint)
mp_print (mp, "cycle");
}
@ @<Print information for adjacent knots...@>=
mp_print_two (mp, p->x_coord, p->y_coord);
switch (mp_right_type (p)) {
case mp_endpoint:
if (mp_left_type (p) == mp_open)
mp_print (mp, "{open?}"); /* can't happen */
@.open?@>;
if ((mp_left_type (q) != mp_endpoint) || (q != h))
q = NULL; /* force an error */
goto DONE1;
break;
case mp_explicit:
@<Print control points between |p| and |q|, then |goto done1|@>;
break;
case mp_open:
@<Print information for a curve that begins |open|@>;
break;
case mp_curl:
case mp_given:
@<Print information for a curve that begins |curl| or |given|@>;
break;
default:
mp_print (mp, "???"); /* can't happen */
@.???@>;
break;
}
if (mp_left_type (q) <= mp_explicit) {
mp_print (mp, "..control?"); /* can't happen */
@.control?@>
} else if ((!number_equal(p->right_tension, unity_t)) || (!number_equal(q->left_tension, unity_t))) {
@<Print tension between |p| and |q|@>;
}
@ Since |n_sin_cos| produces |fraction| results, which we will print as if they
were |scaled|, the magnitude of a |given| direction vector will be~4096.
@<Print two dots...@>=
{
mp_number n_sin, n_cos;
new_fraction (n_sin);
new_fraction (n_cos);
mp_print_nl (mp, " ..");
if (mp_left_type (p) == mp_given) {
n_sin_cos (p->left_given, n_cos, n_sin);
mp_print_char (mp, xord ('{'));
print_number (n_cos);
mp_print_char (mp, xord (','));
print_number (n_sin);
mp_print_char (mp, xord ('}'));
} else if (mp_left_type (p) == mp_curl) {
mp_print (mp, "{curl ");
print_number (p->left_curl);
mp_print_char (mp, xord ('}'));
}
free_number (n_sin);
free_number (n_cos);
}
@ @<Print tension between |p| and |q|@>=
{
mp_number v1;
new_number (v1);
mp_print (mp, "..tension ");
if (number_negative(p->right_tension))
mp_print (mp, "atleast");
number_clone (v1, p->right_tension);
number_abs (v1);
print_number (v1);
if (!number_equal(p->right_tension, q->left_tension)) {
mp_print (mp, " and ");
if (number_negative(q->left_tension))
mp_print (mp, "atleast");
number_clone (v1, p->left_tension);
number_abs (v1);
print_number (v1);
}
free_number (v1);
}
@ @<Print control points between |p| and |q|, then |goto done1|@>=
{
mp_print (mp, "..controls ");
mp_print_two (mp, p->right_x, p->right_y);
mp_print (mp, " and ");
if (mp_left_type (q) != mp_explicit) {
mp_print (mp, "??"); /* can't happen */
@.??@>
} else {
mp_print_two (mp, q->left_x, q->left_y);
}
goto DONE1;
}
@ @<Print information for a curve that begins |open|@>=
if ((mp_left_type (p) != mp_explicit) && (mp_left_type (p) != mp_open)) {
mp_print (mp, "{open?}"); /* can't happen */
@.open?@>
}
@ A curl of 1 is shown explicitly, so that the user sees clearly that
\MP's default curl is present.
@<Print information for a curve that begins |curl|...@>=
{
if (mp_left_type (p) == mp_open)
mp_print (mp, "??"); /* can't happen */
@.??@>;
if (mp_right_type (p) == mp_curl) {
mp_print (mp, "{curl ");
print_number (p->right_curl);
} else {
mp_number n_sin, n_cos;
new_fraction (n_sin);
new_fraction (n_cos);
n_sin_cos (p->right_given, n_cos, n_sin);
mp_print_char (mp, xord ('{'));
print_number (n_cos);
mp_print_char (mp, xord (','));
print_number (n_sin);
free_number (n_sin);
free_number (n_cos);
}
mp_print_char (mp, xord ('}'));
}
@ It is convenient to have another version of |pr_path| that prints the path
as a diagnostic message.
@<Declarations@>=
static void mp_print_path (MP mp, mp_knot h, const char *s, boolean nuline);
@ @c
void mp_print_path (MP mp, mp_knot h, const char *s, boolean nuline) {
mp_print_diagnostic (mp, "Path", s, nuline);
mp_print_ln (mp);
@.Path at line...@>;
mp_pr_path (mp, h);
mp_end_diagnostic (mp, true);
}
@ @<Declarations@>=
static mp_knot mp_new_knot (MP mp);
@ @c
static mp_knot mp_new_knot (MP mp) {
mp_knot q;
if (mp->knot_nodes) {
q = mp->knot_nodes;
mp->knot_nodes = q->next;
mp->num_knot_nodes--;
} else {
q = mp_xmalloc (mp, 1, sizeof (struct mp_knot_data));
}
memset(q,0,sizeof (struct mp_knot_data));
new_number(q->x_coord);
new_number(q->y_coord);
new_number(q->left_x);
new_number(q->left_y);
new_number(q->right_x);
new_number(q->right_y);
return q;
}
@ @<Declarations@>=
static mp_gr_knot mp_gr_new_knot (MP mp);
@ @c
static mp_gr_knot mp_gr_new_knot (MP mp) {
mp_gr_knot q = mp_xmalloc (mp, 1, sizeof (struct mp_gr_knot_data));
return q;
}
@ If we want to duplicate a knot node, we can say |copy_knot|:
@c
static mp_knot mp_copy_knot (MP mp, mp_knot p) {
mp_knot q;
if (mp->knot_nodes) {
q = mp->knot_nodes;
mp->knot_nodes = q->next;
mp->num_knot_nodes--;
} else {
q = mp_xmalloc (mp, 1, sizeof (struct mp_knot_data));
}
memcpy (q, p, sizeof (struct mp_knot_data));
if (mp->math_mode > mp_math_double_mode) {
new_number(q->x_coord);
new_number(q->y_coord);
new_number(q->left_x);
new_number(q->left_y);
new_number(q->right_x);
new_number(q->right_y);
number_clone(q->x_coord, p->x_coord);
number_clone(q->y_coord, p->y_coord);
number_clone(q->left_x, p->left_x);
number_clone(q->left_y, p->left_y);
number_clone(q->right_x, p->right_x);
number_clone(q->right_y, p->right_y);
}
mp_next_knot (q) = NULL;
return q;
}
@ If we want to export a knot node, we can say |export_knot|:
@c
static mp_gr_knot mp_export_knot (MP mp, mp_knot p) {
mp_gr_knot q; /* the copy */
q = mp_gr_new_knot (mp);
q->x_coord = number_to_double(p->x_coord);
q->y_coord = number_to_double(p->y_coord);
q->left_x = number_to_double(p->left_x);
q->left_y = number_to_double(p->left_y);
q->right_x = number_to_double(p->right_x);
q->right_y = number_to_double(p->right_y);
q->data.types.left_type = mp_left_type(p);
q->data.types.right_type = mp_left_type(p);
q->data.info = mp_knot_info(p);
mp_gr_next_knot (q) = NULL;
return q;
}
@ The |copy_path| routine makes a clone of a given path.
@c
static mp_knot mp_copy_path (MP mp, mp_knot p) {
mp_knot q, pp, qq; /* for list manipulation */
if (p == NULL)
return NULL;
q = mp_copy_knot (mp, p);
qq = q;
pp = mp_next_knot (p);
while (pp != p) {
mp_next_knot (qq) = mp_copy_knot (mp, pp);
qq = mp_next_knot (qq);
pp = mp_next_knot (pp);
}
mp_next_knot (qq) = q;
return q;
}
@ The |export_path| routine makes a clone of a given path
and converts the |value|s therein to |double|s.
@c
static mp_gr_knot mp_export_path (MP mp, mp_knot p) {
mp_knot pp; /* for list manipulation */
mp_gr_knot q, qq;
if (p == NULL)
return NULL;
q = mp_export_knot (mp, p);
qq = q;
pp = mp_next_knot (p);
while (pp != p) {
mp_gr_next_knot (qq) = mp_export_knot (mp, pp);
qq = mp_gr_next_knot (qq);
pp = mp_next_knot (pp);
}
mp_gr_next_knot (qq) = q;
return q;
}
@ If we want to import a knot node, we can say |import_knot|:
@c
static mp_knot mp_import_knot (MP mp, mp_gr_knot p) {
mp_knot q; /* the copy */
q = mp_new_knot (mp);
set_number_from_double(q->x_coord, p->x_coord);
set_number_from_double(q->y_coord, p->y_coord);
set_number_from_double(q->left_x, p->left_x);
set_number_from_double(q->left_y, p->left_y);
set_number_from_double(q->right_x, p->right_x);
set_number_from_double(q->right_y, p->right_y);
mp_left_type(q) = p->data.types.left_type;
mp_left_type(q) = p->data.types.right_type;
mp_knot_info(q) = p->data.info;
mp_next_knot (q) = NULL;
return q;
}
@ The |import_path| routine makes a clone of a given path
and converts the |value|s therein to |scaled|s.
@c
static mp_knot mp_import_path (MP mp, mp_gr_knot p) {
mp_gr_knot pp; /* for list manipulation */
mp_knot q, qq;
if (p == NULL)
return NULL;
q = mp_import_knot (mp, p);
qq = q;
pp = mp_gr_next_knot (p);
while (pp != p) {
mp_next_knot (qq) = mp_import_knot (mp, pp);
qq = mp_next_knot (qq);
pp = mp_gr_next_knot (pp);
}
mp_next_knot (qq) = q;
return q;
}
@ Just before |ship_out|, knot lists are exported for printing.
@ The |export_knot_list| routine therefore also makes a clone
of a given path.
@c
static mp_gr_knot mp_export_knot_list (MP mp, mp_knot p) {
mp_gr_knot q; /* the exported copy */
if (p == NULL)
return NULL;
q = mp_export_path (mp, p);
return q;
}
static mp_knot mp_import_knot_list (MP mp, mp_gr_knot q) {
mp_knot p; /* the imported copy */
if (q == NULL)
return NULL;
p = mp_import_path (mp, q);
return p;
}
@ Similarly, there's a way to copy the {\sl reverse\/} of a path. This procedure
returns a pointer to the first node of the copy, if the path is a cycle,
but to the final node of a non-cyclic copy. The global
variable |path_tail| will point to the final node of the original path;
this trick makes it easier to implement `\&{doublepath}'.
All node types are assumed to be |endpoint| or |explicit| only.
@c
static mp_knot mp_htap_ypoc (MP mp, mp_knot p) {
mp_knot q, pp, qq, rr; /* for list manipulation */
q = mp_new_knot (mp); /* this will correspond to |p| */
qq = q;
pp = p;
while (1) {
mp_right_type (qq) = mp_left_type (pp);
mp_left_type (qq) = mp_right_type (pp);
number_clone (qq->x_coord, pp->x_coord);
number_clone (qq->y_coord, pp->y_coord);
number_clone (qq->right_x, pp->left_x);
number_clone (qq->right_y, pp->left_y);
number_clone (qq->left_x, pp->right_x);
number_clone (qq->left_y, pp->right_y);
mp_originator (qq) = mp_originator (pp);
if (mp_next_knot (pp) == p) {
mp_next_knot (q) = qq;
mp->path_tail = pp;
return q;
}
rr = mp_new_knot (mp);
mp_next_knot (rr) = qq;
qq = rr;
pp = mp_next_knot (pp);
}
}
@ @<Glob...@>=
mp_knot path_tail; /* the node that links to the beginning of a path */
@ When a cyclic list of knot nodes is no longer needed, it can be recycled by
calling the following subroutine.
@<Declarations@>=
static void mp_toss_knot_list (MP mp, mp_knot p);
static void mp_toss_knot (MP mp, mp_knot p);
static void mp_free_knot (MP mp, mp_knot p);
@ @c
void mp_free_knot (MP mp, mp_knot q) {
free_number (q->x_coord);
free_number (q->y_coord);
free_number (q->left_x);
free_number (q->left_y);
free_number (q->right_x);
free_number (q->right_y);
mp_xfree (q);
}
void mp_toss_knot (MP mp, mp_knot q) {
if (mp->num_knot_nodes < max_num_knot_nodes) {
q->next = mp->knot_nodes;
mp->knot_nodes = q;
mp->num_knot_nodes++;
return;
}
if (mp->math_mode > mp_math_double_mode) {
mp_free_knot(mp,q);
} else {
mp_xfree (q);
}
}
void mp_toss_knot_list (MP mp, mp_knot p) {
mp_knot q; /* the node being freed */
mp_knot r; /* the next node */
if (p == NULL)
return;
q = p;
if (mp->math_mode > mp_math_double_mode) {
do {
r = mp_next_knot (q);
mp_toss_knot(mp, q);
q = r;
} while (q != p);
} else {
do {
r = mp_next_knot (q);
if (mp->num_knot_nodes < max_num_knot_nodes) {
q->next = mp->knot_nodes;
mp->knot_nodes = q;
mp->num_knot_nodes++;
} else {
mp_xfree (q);
}
q = r;
} while (q != p);
}
}
@* Choosing control points.
Now we must actually delve into one of \MP's more difficult routines,
the |make_choices| procedure that chooses angles and control points for
the splines of a curve when the user has not specified them explicitly.
The parameter to |make_choices| points to a list of knots and
path information, as described above.
A path decomposes into independent segments at ``breakpoint'' knots,
which are knots whose left and right angles are both prespecified in
some way (i.e., their |mp_left_type| and |mp_right_type| aren't both open).
@c
void mp_make_choices (MP mp, mp_knot knots) {
mp_knot h; /* the first breakpoint */
mp_knot p, q; /* consecutive breakpoints being processed */
@<Other local variables for |make_choices|@>;
FUNCTION_TRACE1 ("make_choices()\n");
check_arith(); /* make sure that |arith_error=false| */
if (number_positive(internal_value (mp_tracing_choices)))
mp_print_path (mp, knots, ", before choices", true);
@<If consecutive knots are equal, join them explicitly@>;
@<Find the first breakpoint, |h|, on the path;
insert an artificial breakpoint if the path is an unbroken cycle@>;
p = h;
do {
@<Fill in the control points between |p| and the next breakpoint,
then advance |p| to that breakpoint@>;
} while (p != h);
if (number_positive(internal_value (mp_tracing_choices)))
mp_print_path (mp, knots, ", after choices", true);
if (mp->arith_error) {
@<Report an unexpected problem during the choice-making@>;
}
}
@ @<Internal ...@>=
void mp_make_choices (MP mp, mp_knot knots);
@ @<Report an unexpected problem during the choice...@>=
{
const char *hlp[] = {
"The path that I just computed is out of range.",
"So it will probably look funny. Proceed, for a laugh.",
NULL };
mp_back_error (mp, "Some number got too big", hlp, true);
@.Some number got too big@>;
mp_get_x_next (mp);
mp->arith_error = false;
}
@ Two knots in a row with the same coordinates will always be joined
by an explicit ``curve'' whose control points are identical with the
knots.
@<If consecutive knots are equal, join them explicitly@>=
p = knots;
do {
q = mp_next_knot (p);
if (number_equal (p->x_coord, q->x_coord) &&
number_equal (p->y_coord, q->y_coord) &&
mp_right_type (p) > mp_explicit) {
mp_right_type (p) = mp_explicit;
if (mp_left_type (p) == mp_open) {
mp_left_type (p) = mp_curl;
set_number_to_unity(p->left_curl);
}
mp_left_type (q) = mp_explicit;
if (mp_right_type (q) == mp_open) {
mp_right_type (q) = mp_curl;
set_number_to_unity(q->right_curl);
}
number_clone (p->right_x, p->x_coord);
number_clone (q->left_x, p->x_coord);
number_clone (p->right_y, p->y_coord);
number_clone (q->left_y, p->y_coord);
}
p = q;
} while (p != knots)
@ If there are no breakpoints, it is necessary to compute the direction
angles around an entire cycle. In this case the |mp_left_type| of the first
node is temporarily changed to |end_cycle|.
@<Find the first breakpoint, |h|, on the path...@>=
h = knots;
while (1) {
if (mp_left_type (h) != mp_open)
break;
if (mp_right_type (h) != mp_open)
break;
h = mp_next_knot (h);
if (h == knots) {
mp_left_type (h) = mp_end_cycle;
break;
}
}
@ If |mp_right_type(p)<given| and |q=mp_link(p)|, we must have
|mp_right_type(p)=mp_left_type(q)=mp_explicit| or |endpoint|.
@<Fill in the control points between |p| and the next breakpoint...@>=
q = mp_next_knot (p);
if (mp_right_type (p) >= mp_given) {
while ((mp_left_type (q) == mp_open) && (mp_right_type (q) == mp_open)) {
q = mp_next_knot (q);
}
@<Fill in the control information between consecutive breakpoints |p| and |q|@>;
} else if (mp_right_type (p) == mp_endpoint) {
@<Give reasonable values for the unused control points between |p| and~|q|@>;
}
p = q
@ This step makes it possible to transform an explicitly computed path without
checking the |mp_left_type| and |mp_right_type| fields.
@<Give reasonable values for the unused control points between |p| and~|q|@>=
{
number_clone (p->right_x, p->x_coord);
number_clone (p->right_y, p->y_coord);
number_clone (q->left_x, q->x_coord);
number_clone (q->left_y, q->y_coord);
}
@ Before we can go further into the way choices are made, we need to
consider the underlying theory. The basic ideas implemented in |make_choices|
are due to John Hobby, who introduced the notion of ``mock curvature''
@^Hobby, John Douglas@>
at a knot. Angles are chosen so that they preserve mock curvature when
a knot is passed, and this has been found to produce excellent results.
It is convenient to introduce some notations that simplify the necessary
formulas. Let $d_{k,k+1}=\vert z\k-z_k\vert$ be the (nonzero) distance
between knots |k| and |k+1|; and let
$${z\k-z_k\over z_k-z_{k-1}}={d_{k,k+1}\over d_{k-1,k}}e^{i\psi_k}$$
so that a polygonal line from $z_{k-1}$ to $z_k$ to $z\k$ turns left
through an angle of~$\psi_k$. We assume that $\vert\psi_k\vert\L180^\circ$.
The control points for the spline from $z_k$ to $z\k$ will be denoted by
$$\eqalign{z_k^+&=z_k+
\textstyle{1\over3}\rho_k e^{i\theta_k}(z\k-z_k),\cr
z\k^-&=z\k-
\textstyle{1\over3}\sigma\k e^{-i\phi\k}(z\k-z_k),\cr}$$
where $\rho_k$ and $\sigma\k$ are nonnegative ``velocity ratios'' at the
beginning and end of the curve, while $\theta_k$ and $\phi\k$ are the
corresponding ``offset angles.'' These angles satisfy the condition
$$\theta_k+\phi_k+\psi_k=0,\eqno(*)$$
whenever the curve leaves an intermediate knot~|k| in the direction that
it enters.
@ Let $\alpha_k$ and $\beta\k$ be the reciprocals of the ``tension'' of
the curve at its beginning and ending points. This means that
$\rho_k=\alpha_k f(\theta_k,\phi\k)$ and $\sigma\k=\beta\k f(\phi\k,\theta_k)$,
where $f(\theta,\phi)$ is \MP's standard velocity function defined in
the |velocity| subroutine. The cubic spline $B(z_k^{\phantom+},z_k^+,
z\k^-,z\k^{\phantom+};t)$
has curvature
@^curvature@>
$${2\sigma\k\sin(\theta_k+\phi\k)-6\sin\theta_k\over\rho_k^2d_{k,k+1}}
\qquad{\rm and}\qquad
{2\rho_k\sin(\theta_k+\phi\k)-6\sin\phi\k\over\sigma\k^2d_{k,k+1}}$$
at |t=0| and |t=1|, respectively. The mock curvature is the linear
@^mock curvature@>
approximation to this true curvature that arises in the limit for
small $\theta_k$ and~$\phi\k$, if second-order terms are discarded.
The standard velocity function satisfies
$$f(\theta,\phi)=1+O(\theta^2+\theta\phi+\phi^2);$$
hence the mock curvatures are respectively
$${2\beta\k(\theta_k+\phi\k)-6\theta_k\over\alpha_k^2d_{k,k+1}}
\qquad{\rm and}\qquad
{2\alpha_k(\theta_k+\phi\k)-6\phi\k\over\beta\k^2d_{k,k+1}}.\eqno(**)$$
@ The turning angles $\psi_k$ are given, and equation $(*)$ above
determines $\phi_k$ when $\theta_k$ is known, so the task of
angle selection is essentially to choose appropriate values for each
$\theta_k$. When equation~$(*)$ is used to eliminate $\phi$~variables
from $(**)$, we obtain a system of linear equations of the form
$$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta\k=-B_k\psi_k-D_k\psi\k,$$
where
$$A_k={\alpha_{k-1}\over\beta_k^2d_{k-1,k}},
\qquad B_k={3-\alpha_{k-1}\over\beta_k^2d_{k-1,k}},
\qquad C_k={3-\beta\k\over\alpha_k^2d_{k,k+1}},
\qquad D_k={\beta\k\over\alpha_k^2d_{k,k+1}}.$$
The tensions are always $3\over4$ or more, hence each $\alpha$ and~$\beta$
will be at most $4\over3$. It follows that $B_k\G{5\over4}A_k$ and
$C_k\G{5\over4}D_k$; hence the equations are diagonally dominant;
hence they have a unique solution. Moreover, in most cases the tensions
are equal to~1, so that $B_k=2A_k$ and $C_k=2D_k$. This makes the
solution numerically stable, and there is an exponential damping
effect: The data at knot $k\pm j$ affects the angle at knot~$k$ by
a factor of~$O(2^{-j})$.
@ However, we still must consider the angles at the starting and ending
knots of a non-cyclic path. These angles might be given explicitly, or
they might be specified implicitly in terms of an amount of ``curl.''
Let's assume that angles need to be determined for a non-cyclic path
starting at $z_0$ and ending at~$z_n$. Then equations of the form
$$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta_{k+1}=R_k$$
have been given for $0<k<n$, and it will be convenient to introduce
equations of the same form for $k=0$ and $k=n$, where
$$A_0=B_0=C_n=D_n=0.$$
If $\theta_0$ is supposed to have a given value $E_0$, we simply
define $C_0=1$, $D_0=0$, and $R_0=E_0$. Otherwise a curl
parameter, $\gamma_0$, has been specified at~$z_0$; this means
that the mock curvature at $z_0$ should be $\gamma_0$ times the
mock curvature at $z_1$; i.e.,
$${2\beta_1(\theta_0+\phi_1)-6\theta_0\over\alpha_0^2d_{01}}
=\gamma_0{2\alpha_0(\theta_0+\phi_1)-6\phi_1\over\beta_1^2d_{01}}.$$
This equation simplifies to
$$(\alpha_0\chi_0+3-\beta_1)\theta_0+
\bigl((3-\alpha_0)\chi_0+\beta_1\bigr)\theta_1=
-\bigl((3-\alpha_0)\chi_0+\beta_1\bigr)\psi_1,$$
where $\chi_0=\alpha_0^2\gamma_0/\beta_1^2$; so we can set $C_0=
\chi_0\alpha_0+3-\beta_1$, $D_0=(3-\alpha_0)\chi_0+\beta_1$, $R_0=-D_0\psi_1$.
It can be shown that $C_0>0$ and $C_0B_1-A_1D_0>0$ when $\gamma_0\G0$,
hence the linear equations remain nonsingular.
Similar considerations apply at the right end, when the final angle $\phi_n$
may or may not need to be determined. It is convenient to let $\psi_n=0$,
hence $\theta_n=-\phi_n$. We either have an explicit equation $\theta_n=E_n$,
or we have
$$\bigl((3-\beta_n)\chi_n+\alpha_{n-1}\bigr)\theta_{n-1}+
(\beta_n\chi_n+3-\alpha_{n-1})\theta_n=0,\qquad
\chi_n={\beta_n^2\gamma_n\over\alpha_{n-1}^2}.$$
When |make_choices| chooses angles, it must compute the coefficients of
these linear equations, then solve the equations. To compute the coefficients,
it is necessary to compute arctangents of the given turning angles~$\psi_k$.
When the equations are solved, the chosen directions $\theta_k$ are put
back into the form of control points by essentially computing sines and
cosines.
@ OK, we are ready to make the hard choices of |make_choices|.
Most of the work is relegated to an auxiliary procedure
called |solve_choices|, which has been introduced to keep
|make_choices| from being extremely long.
@<Fill in the control information between...@>=
@<Calculate the turning angles $\psi_k$ and the distances $d_{k,k+1}$;
set $n$ to the length of the path@>;
@<Remove |open| types at the breakpoints@>;
mp_solve_choices (mp, p, q, n)
@ It's convenient to precompute quantities that will be needed several
times later. The values of |delta_x[k]| and |delta_y[k]| will be the
coordinates of $z\k-z_k$, and the magnitude of this vector will be
|delta[k]=@t$d_{k,k+1}$@>|. The path angle $\psi_k$ between $z_k-z_{k-1}$
and $z\k-z_k$ will be stored in |psi[k]|.
@<Glob...@>=
int path_size; /* maximum number of knots between breakpoints of a path */
mp_number *delta_x;
mp_number *delta_y;
mp_number *delta; /* knot differences */
mp_number *psi; /* turning angles */
@ @<Dealloc variables@>=
{
int k;
for (k = 0; k<mp->path_size; k++) {
free_number (mp->delta_x[k]);
free_number (mp->delta_y[k]);
free_number (mp->delta[k]);
free_number (mp->psi[k]);
}
xfree (mp->delta_x);
xfree (mp->delta_y);
xfree (mp->delta);
xfree (mp->psi);
}
@ @<Other local variables for |make_choices|@>=
int k, n; /* current and final knot numbers */
mp_knot s, t; /* registers for list traversal */
@ @<Calculate the turning angles...@>=
{
mp_number sine, cosine; /* trig functions of various angles */
new_fraction (sine);
new_fraction (cosine);
RESTART:
k = 0;
s = p;
n = mp->path_size;
do {
t = mp_next_knot (s);
set_number_from_substraction(mp->delta_x[k], t->x_coord, s->x_coord);
set_number_from_substraction(mp->delta_y[k], t->y_coord, s->y_coord);
pyth_add (mp->delta[k], mp->delta_x[k], mp->delta_y[k]);
if (k > 0) {
mp_number arg1, arg2, r1, r2;
new_number (arg1);
new_number (arg2);
new_fraction (r1);
new_fraction (r2);
make_fraction (r1, mp->delta_y[k - 1], mp->delta[k - 1]);
number_clone (sine, r1);
make_fraction (r2, mp->delta_x[k - 1], mp->delta[k - 1]);
number_clone (cosine, r2);
take_fraction (r1, mp->delta_x[k], cosine);
take_fraction (r2, mp->delta_y[k], sine);
set_number_from_addition (arg1, r1, r2);
take_fraction (r1, mp->delta_y[k], cosine);
take_fraction (r2, mp->delta_x[k], sine);
set_number_from_substraction (arg2, r1, r2);
n_arg (mp->psi[k], arg1, arg2 );
free_number (r1);
free_number (r2);
free_number (arg1);
free_number (arg2);
}
incr (k);
s = t;
if (k == mp->path_size) {
mp_reallocate_paths (mp, mp->path_size + (mp->path_size / 4));
goto RESTART; /* retry, loop size has changed */
}
if (s == q)
n = k;
} while (!((k >= n) && (mp_left_type (s) != mp_end_cycle)));
if (k == n)
set_number_to_zero(mp->psi[k]);
else
number_clone(mp->psi[k], mp->psi[1]);
free_number (sine);
free_number (cosine);
}
@ When we get to this point of the code, |mp_right_type(p)| is either
|given| or |curl| or |open|. If it is |open|, we must have
|mp_left_type(p)=mp_end_cycle| or |mp_left_type(p)=mp_explicit|. In the latter
case, the |open| type is converted to |given|; however, if the
velocity coming into this knot is zero, the |open| type is
converted to a |curl|, since we don't know the incoming direction.
Similarly, |mp_left_type(q)| is either |given| or |curl| or |open| or
|mp_end_cycle|. The |open| possibility is reduced either to |given| or to |curl|.
@<Remove |open| types at the breakpoints@>=
{
mp_number delx, dely; /* directions where |open| meets |explicit| */
new_number(delx);
new_number(dely);
if (mp_left_type (q) == mp_open) {
set_number_from_substraction(delx, q->right_x, q->x_coord);
set_number_from_substraction(dely, q->right_y, q->y_coord);
if (number_zero(delx) && number_zero(dely)) {
mp_left_type (q) = mp_curl;
set_number_to_unity(q->left_curl);
} else {
mp_left_type (q) = mp_given;
n_arg (q->left_given, delx, dely);
}
}
if ((mp_right_type (p) == mp_open) && (mp_left_type (p) == mp_explicit)) {
set_number_from_substraction(delx, p->x_coord, p->left_x);
set_number_from_substraction(dely, p->y_coord, p->left_y);
if (number_zero(delx) && number_zero(dely)) {
mp_right_type (p) = mp_curl;
set_number_to_unity(p->right_curl);
} else {
mp_right_type (p) = mp_given;
n_arg (p->right_given, delx, dely);
}
}
free_number (delx);
free_number (dely);
}
@ Linear equations need to be solved whenever |n>1|; and also when |n=1|
and exactly one of the breakpoints involves a curl. The simplest case occurs
when |n=1| and there is a curl at both breakpoints; then we simply draw
a straight line.
But before coding up the simple cases, we might as well face the general case,
since we must deal with it sooner or later, and since the general case
is likely to give some insight into the way simple cases can be handled best.
When there is no cycle, the linear equations to be solved form a tridiagonal
system, and we can apply the standard technique of Gaussian elimination
to convert that system to a sequence of equations of the form
$$\theta_0+u_0\theta_1=v_0,\quad
\theta_1+u_1\theta_2=v_1,\quad\ldots,\quad
\theta_{n-1}+u_{n-1}\theta_n=v_{n-1},\quad
\theta_n=v_n.$$
It is possible to do this diagonalization while generating the equations.
Once $\theta_n$ is known, it is easy to determine $\theta_{n-1}$, \dots,
$\theta_1$, $\theta_0$; thus, the equations will be solved.
The procedure is slightly more complex when there is a cycle, but the
basic idea will be nearly the same. In the cyclic case the right-hand
sides will be $v_k+w_k\theta_0$ instead of simply $v_k$, and we will start
the process off with $u_0=v_0=0$, $w_0=1$. The final equation will be not
$\theta_n=v_n$ but $\theta_n+u_n\theta_1=v_n+w_n\theta_0$; an appropriate
ending routine will take account of the fact that $\theta_n=\theta_0$ and
eliminate the $w$'s from the system, after which the solution can be
obtained as before.
When $u_k$, $v_k$, and $w_k$ are being computed, the three pointer
variables |r|, |s|,~|t| will point respectively to knots |k-1|, |k|,
and~|k+1|. The $u$'s and $w$'s are scaled by $2^{28}$, i.e., they are
of type |fraction|; the $\theta$'s and $v$'s are of type |angle|.
@<Glob...@>=
mp_number *theta; /* values of $\theta_k$ */
mp_number *uu; /* values of $u_k$ */
mp_number *vv; /* values of $v_k$ */
mp_number *ww; /* values of $w_k$ */
@ @<Dealloc variables@>=
{
int k;
for (k = 0; k<mp->path_size; k++) {
free_number (mp->theta[k]);
free_number (mp->uu[k]);
free_number (mp->vv[k]);
free_number (mp->ww[k]);
}
xfree (mp->theta);
xfree (mp->uu);
xfree (mp->vv);
xfree (mp->ww);
}
@ @<Declarations@>=
static void mp_reallocate_paths (MP mp, int l);
@ @c
void mp_reallocate_paths (MP mp, int l) {
int k;
XREALLOC (mp->delta_x, l, mp_number);
XREALLOC (mp->delta_y, l, mp_number);
XREALLOC (mp->delta, l, mp_number);
XREALLOC (mp->psi, l, mp_number);
XREALLOC (mp->theta, l, mp_number);
XREALLOC (mp->uu, l, mp_number);
XREALLOC (mp->vv, l, mp_number);
XREALLOC (mp->ww, l, mp_number);
for (k = mp->path_size; k<l; k++) {
new_number (mp->delta_x[k]);
new_number (mp->delta_y[k]);
new_number (mp->delta[k]);
new_angle (mp->psi[k]);
new_angle (mp->theta[k]);
new_fraction (mp->uu[k]);
new_angle (mp->vv[k]);
new_fraction (mp->ww[k]);
}
mp->path_size = l;
}
@ Our immediate problem is to get the ball rolling by setting up the
first equation or by realizing that no equations are needed, and to fit
this initialization into a framework suitable for the overall computation.
@<Declarations@>=
static void mp_solve_choices (MP mp, mp_knot p, mp_knot q, halfword n);
@ @c
void mp_solve_choices (MP mp, mp_knot p, mp_knot q, halfword n) {
int k; /* current knot number */
mp_knot r, s, t; /* registers for list traversal */
mp_number ff;
new_fraction (ff);
FUNCTION_TRACE2 ("solve_choices(%d)\n", n);
k = 0;
s = p;
r = 0;
while (1) {
t = mp_next_knot (s);
if (k == 0) {
@<Get the linear equations started; or |return|
with the control points in place, if linear equations
needn't be solved@>
} else {
switch (mp_left_type (s)) {
case mp_end_cycle:
case mp_open:
@<Set up equation to match mock curvatures
at $z_k$; then |goto found| with $\theta_n$
adjusted to equal $\theta_0$, if a cycle has ended@>;
break;
case mp_curl:
@<Set up equation for a curl at $\theta_n$
and |goto found|@>;
break;
case mp_given:
@<Calculate the given value of $\theta_n$
and |goto found|@>;
break;
} /* there are no other cases */
}
r = s;
s = t;
incr (k);
}
FOUND:
@<Finish choosing angles and assigning control points@>;
free_number (ff);
}
@ On the first time through the loop, we have |k=0| and |r| is not yet
defined. The first linear equation, if any, will have $A_0=B_0=0$.
@<Get the linear equations started...@>=
switch (mp_right_type (s)) {
case mp_given:
if (mp_left_type (t) == mp_given) {
@<Reduce to simple case of two givens and |return|@>
} else {
@<Set up the equation for a given value of $\theta_0$@>;
}
break;
case mp_curl:
if (mp_left_type (t) == mp_curl) {
@<Reduce to simple case of straight line and |return|@>
} else {
@<Set up the equation for a curl at $\theta_0$@>;
}
break;
case mp_open:
set_number_to_zero(mp->uu[0]);
set_number_to_zero(mp->vv[0]);
number_clone(mp->ww[0], fraction_one_t);
/* this begins a cycle */
break;
} /* there are no other cases */
@ The general equation that specifies equality of mock curvature at $z_k$ is
$$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta\k=-B_k\psi_k-D_k\psi\k,$$
as derived above. We want to combine this with the already-derived equation
$\theta_{k-1}+u_{k-1}\theta_k=v_{k-1}+w_{k-1}\theta_0$ in order to obtain
a new equation
$\theta_k+u_k\theta\k=v_k+w_k\theta_0$. This can be done by dividing the
equation
$$(B_k-u_{k-1}A_k+C_k)\theta_k+D_k\theta\k=-B_k\psi_k-D_k\psi\k-A_kv_{k-1}
-A_kw_{k-1}\theta_0$$
by $B_k-u_{k-1}A_k+C_k$. The trick is to do this carefully with
fixed-point arithmetic, avoiding the chance of overflow while retaining
suitable precision.
The calculations will be performed in several registers that
provide temporary storage for intermediate quantities.
@ @<Set up equation to match mock curvatures...@>=
{
mp_number aa, bb, cc, acc; /* temporary registers */
mp_number dd, ee; /* likewise, but |scaled| */
new_fraction (aa);
new_fraction (bb);
new_fraction (cc);
new_fraction (acc);
new_number (dd);
new_number (ee);
@<Calculate the values $\\{aa}=A_k/B_k$, $\\{bb}=D_k/C_k$,
$\\{dd}=(3-\alpha_{k-1})d_{k,k+1}$, $\\{ee}=(3-\beta\k)d_{k-1,k}$,
and $\\{cc}=(B_k-u_{k-1}A_k)/B_k$@>;
@<Calculate the ratio $\\{ff}=C_k/(C_k+B_k-u_{k-1}A_k)$@>;
take_fraction (mp->uu[k], ff, bb);
@<Calculate the values of $v_k$ and $w_k$@>;
if (mp_left_type (s) == mp_end_cycle) {
@<Adjust $\theta_n$ to equal $\theta_0$ and |goto found|@>;
}
free_number(aa);
free_number(bb);
free_number(cc);
free_number(acc);
free_number(dd);
free_number(ee);
}
@ Since tension values are never less than 3/4, the values |aa| and
|bb| computed here are never more than 4/5.
@<Calculate the values $\\{aa}=...@>=
{
mp_number absval;
new_number (absval);
number_clone (absval, r->right_tension);
number_abs (absval);
if (number_equal (absval, unity_t)) {
number_clone (aa, fraction_half_t);
number_clone (dd, mp->delta[k]);
number_double (dd);
} else {
mp_number arg1, arg2, ret;
new_number (arg2);
new_number (arg1);
number_clone (arg2, r->right_tension);
number_abs (arg2);
number_multiply_int (arg2, 3);
number_substract (arg2, unity_t);
make_fraction (aa, unity_t, arg2);
number_clone (arg2, r->right_tension);
number_abs (arg2);
new_fraction (ret);
make_fraction (ret, unity_t, arg2);
set_number_from_substraction (arg1, fraction_three_t, ret);
take_fraction (arg2, mp->delta[k], arg1);
number_clone (dd, arg2);
free_number (ret);
free_number (arg1);
free_number (arg2);
}
number_clone (absval, t->left_tension);
number_abs (absval);
if (number_equal (absval, unity_t)) {
number_clone (bb, fraction_half_t);
number_clone (ee, mp->delta[k - 1]);
number_double (ee);
} else {
mp_number arg1, arg2, ret;
new_number (arg1);
new_number (arg2);
number_clone (arg2, t->left_tension);
number_abs (arg2);
number_multiply_int (arg2, 3);
number_substract (arg2, unity_t);
make_fraction (bb, unity_t, arg2);
number_clone (arg2, t->left_tension);
number_abs (arg2);
new_fraction(ret);
make_fraction (ret, unity_t, arg2);
set_number_from_substraction (arg1,fraction_three_t, ret);
take_fraction (ee, mp->delta[k - 1], arg1);
free_number (ret);
free_number (arg1);
free_number (arg2);
}
free_number (absval);
}
{
mp_number r1;
new_number (r1);
take_fraction (r1, mp->uu[k - 1], aa);
set_number_from_substraction (cc, fraction_one_t, r1);
free_number (r1);
}
@ The ratio to be calculated in this step can be written in the form
$$\beta_k^2\cdot\\{ee}\over\beta_k^2\cdot\\{ee}+\alpha_k^2\cdot
\\{cc}\cdot\\{dd},$$
because of the quantities just calculated. The values of |dd| and |ee|
will not be needed after this step has been performed.
@<Calculate the ratio $\\{ff}=C_k/(C_k+B_k-u_{k-1}A_k)$@>=
{
mp_number rt, lt;
mp_number arg2;
new_number (arg2);
number_clone (arg2, dd);
take_fraction (dd, arg2, cc);
new_number (lt);
new_number (rt);
number_clone (lt, s->left_tension);
number_abs (lt);
number_clone (rt, s->right_tension);
number_abs (rt);
if (!number_equal(lt, rt)) { /* $\beta_k^{-1}\ne\alpha_k^{-1}$ */
mp_number r1;
new_number (r1);
if (number_less(lt, rt)) {
make_fraction (r1, lt, rt); /* $\alpha_k^2/\beta_k^2$ */
take_fraction (ff, r1, r1);
number_clone (r1, dd);
take_fraction (dd, r1, ff);
} else {
make_fraction (r1, rt, lt); /* $\beta_k^2/\alpha_k^2$ */
take_fraction (ff, r1, r1);
number_clone (r1, ee);
take_fraction (ee, r1, ff);
}
free_number (r1);
}
free_number (rt);
free_number (lt);
set_number_from_addition (arg2, dd, ee);
make_fraction (ff, ee, arg2);
free_number (arg2);
}
@ The value of $u_{k-1}$ will be |<=1| except when $k=1$ and the previous
equation was specified by a curl. In that case we must use a special
method of computation to prevent overflow.
Fortunately, the calculations turn out to be even simpler in this ``hard''
case. The curl equation makes $w_0=0$ and $v_0=-u_0\psi_1$, hence
$-B_1\psi_1-A_1v_0=-(B_1-u_0A_1)\psi_1=-\\{cc}\cdot B_1\psi_1$.
@<Calculate the values of $v_k$ and $w_k$@>=
take_fraction (acc, mp->psi[k + 1], mp->uu[k]);
number_negate (acc);
if (mp_right_type (r) == mp_curl) {
mp_number r1, arg2;
new_fraction (r1);
new_number (arg2);
set_number_from_substraction (arg2, fraction_one_t, ff);
take_fraction (r1, mp->psi[1], arg2);
set_number_to_zero(mp->ww[k]);
set_number_from_substraction(mp->vv[k], acc, r1);
free_number (r1);
free_number (arg2);
} else {
mp_number arg1, r1;
new_fraction (r1);
new_number (arg1);
set_number_from_substraction (arg1, fraction_one_t, ff);
make_fraction (ff, arg1, cc); /* this is $B_k/(C_k+B_k-u_{k-1}A_k)<5$ */
free_number (arg1);
take_fraction (r1, mp->psi[k], ff);
number_substract (acc, r1);
number_clone (r1, ff);
take_fraction (ff, r1, aa); /* this is $A_k/(C_k+B_k-u_{k-1}A_k)$ */
take_fraction (r1, mp->vv[k - 1], ff);
set_number_from_substraction(mp->vv[k], acc, r1 );
if (number_zero(mp->ww[k - 1])) {
set_number_to_zero(mp->ww[k]);
} else {
take_fraction (mp->ww[k], mp->ww[k - 1], ff);
number_negate(mp->ww[k]);
}
free_number (r1);
}
@ When a complete cycle has been traversed, we have $\theta_k+u_k\theta\k=
v_k+w_k\theta_0$, for |1<=k<=n|. We would like to determine the value of
$\theta_n$ and reduce the system to the form $\theta_k+u_k\theta\k=v_k$
for |0<=k<n|, so that the cyclic case can be finished up just as if there
were no cycle.
The idea in the following code is to observe that
$$\eqalign{\theta_n&=v_n+w_n\theta_0-u_n\theta_1=\cdots\cr
&=v_n+w_n\theta_0-u_n\bigl(v_1+w_1\theta_0-u_1(v_2+\cdots
-u_{n-2}(v_{n-1}+w_{n-1}\theta_0-u_{n-1}\theta_0))\bigr),\cr}$$
so we can solve for $\theta_n=\theta_0$.
@<Adjust $\theta_n$ to equal $\theta_0$ and |goto found|@>=
{
mp_number arg2, r1;
new_number (arg2);
new_number (r1);
set_number_to_zero (aa);
number_clone (bb, fraction_one_t); /* we have |k=n| */
do {
decr (k);
if (k == 0)
k = n;
take_fraction (r1, aa, mp->uu[k]);
set_number_from_substraction (aa, mp->vv[k], r1);
take_fraction (r1, bb, mp->uu[k]);
set_number_from_substraction (bb, mp->ww[k], r1);
} while (k != n); /* now $\theta_n=\\{aa}+\\{bb}\cdot\theta_n$ */
set_number_from_substraction (arg2, fraction_one_t, bb);
make_fraction (r1, aa, arg2);
number_clone (aa, r1);
number_clone(mp->theta[n], aa);
number_clone(mp->vv[0], aa);
for (k = 1; k < n; k++) {
take_fraction (r1, aa, mp->ww[k]);
number_add(mp->vv[k], r1);
}
free_number(arg2);
free_number(r1);
free_number(aa);
free_number(bb);
free_number(cc);
free_number(acc);
free_number(dd);
free_number(ee);
goto FOUND;
}
@ @c
void mp_reduce_angle (MP mp, mp_number *a) {
mp_number abs_a;
FUNCTION_TRACE2 ("reduce_angle(%f)\n", number_to_double(*a));
new_number(abs_a);
number_clone(abs_a, *a);
number_abs(abs_a);
if ( number_greater(abs_a, one_eighty_deg_t)) {
if (number_positive(*a)) {
number_substract(*a, three_sixty_deg_t);
} else {
number_add(*a, three_sixty_deg_t);
}
}
free_number(abs_a);
}
@ @<Declarations@>=
void mp_reduce_angle (MP mp, mp_number *a);
@ @<Calculate the given value of $\theta_n$...@>=
{
mp_number narg;
new_angle (narg);
n_arg (narg, mp->delta_x[n - 1], mp->delta_y[n - 1]);
set_number_from_substraction(mp->theta[n], s->left_given, narg);
free_number (narg);
mp_reduce_angle (mp, &mp->theta[n]);
goto FOUND;
}
@ @<Set up the equation for a given value of $\theta_0$@>=
{
mp_number narg;
new_angle (narg);
n_arg (narg, mp->delta_x[0], mp->delta_y[0]);
set_number_from_substraction(mp->vv[0], s->right_given, narg);
free_number (narg);
mp_reduce_angle (mp, &mp->vv[0]);
set_number_to_zero(mp->uu[0]);
set_number_to_zero(mp->ww[0]);
}
@ @<Set up the equation for a curl at $\theta_0$@>=
{
mp_number lt, rt, cc; /* tension values */
new_number (lt);
new_number (rt);
new_number (cc);
number_clone (cc, s->right_curl);
number_clone (lt, t->left_tension);
number_abs(lt);
number_clone (rt, s->right_tension);
number_abs(rt);
if (number_unity(rt) && number_unity(lt)) {
mp_number arg1, arg2;
new_number (arg1);
new_number (arg2);
number_clone (arg1, cc);
number_double (arg1);
number_add (arg1, unity_t);
number_clone (arg2, cc);
number_add (arg2, two_t);
make_fraction (mp->uu[0], arg1, arg2);
free_number (arg1);
free_number (arg2);
} else {
mp_curl_ratio (mp, &mp->uu[0], cc, rt, lt);
}
take_fraction (mp->vv[0], mp->psi[1], mp->uu[0]);
number_negate(mp->vv[0]);
set_number_to_zero(mp->ww[0]);
free_number (rt);
free_number (lt);
free_number (cc);
}
@ @<Set up equation for a curl at $\theta_n$...@>=
{
mp_number lt, rt, cc; /* tension values */
new_number (lt);
new_number (rt);
new_number (cc);
number_clone (cc, s->left_curl);
number_clone (lt, s->left_tension);
number_abs(lt);
number_clone (rt, r->right_tension);
number_abs(rt);
if (number_unity(rt) && number_unity(lt)) {
mp_number arg1, arg2;
new_number (arg1);
new_number (arg2);
number_clone (arg1, cc);
number_double (arg1);
number_add (arg1, unity_t);
number_clone (arg2, cc);
number_add (arg2, two_t);
make_fraction (ff, arg1, arg2);
free_number (arg1);
free_number (arg2);
} else {
mp_curl_ratio (mp, &ff, cc, lt, rt);
}
{
mp_number arg1, arg2, r1;
new_fraction (r1);
new_fraction (arg1);
new_number (arg2);
take_fraction (arg1, mp->vv[n - 1], ff);
take_fraction (r1, ff, mp->uu[n - 1]);
set_number_from_substraction (arg2, fraction_one_t, r1);
make_fraction (mp->theta[n], arg1, arg2);
number_negate(mp->theta[n]);
free_number (r1);
free_number (arg1);
free_number (arg2);
}
free_number (rt);
free_number (lt);
free_number (cc);
goto FOUND;
}
@ The |curl_ratio| subroutine has three arguments, which our previous notation
encourages us to call $\gamma$, $\alpha^{-1}$, and $\beta^{-1}$. It is
a somewhat tedious program to calculate
$${(3-\alpha)\alpha^2\gamma+\beta^3\over
\alpha^3\gamma+(3-\beta)\beta^2},$$
with the result reduced to 4 if it exceeds 4. (This reduction of curl
is necessary only if the curl and tension are both large.)
The values of $\alpha$ and $\beta$ will be at most~4/3.
@<Declarations@>=
static void mp_curl_ratio (MP mp, mp_number *ret, mp_number gamma, mp_number a_tension,
mp_number b_tension);
@ @c
void mp_curl_ratio (MP mp, mp_number *ret, mp_number gamma_orig, mp_number a_tension, mp_number b_tension) {
mp_number alpha, beta, gamma, num, denom, ff; /* registers */
mp_number arg1;
new_number (arg1);
new_fraction (alpha);
new_fraction (beta);
new_fraction (gamma);
new_fraction (ff);
new_fraction (denom);
new_fraction (num);
make_fraction (alpha, unity_t, a_tension);
make_fraction (beta, unity_t, b_tension);
number_clone (gamma, gamma_orig);
if (number_lessequal(alpha, beta)) {
make_fraction (ff, alpha, beta);
number_clone (arg1, ff);
take_fraction (ff, arg1, arg1);
number_clone (arg1, gamma);
take_fraction (gamma, arg1, ff);
convert_fraction_to_scaled (beta);
take_fraction (denom, gamma, alpha);
number_add (denom, three_t);
} else {
make_fraction (ff, beta, alpha);
number_clone (arg1, ff);
take_fraction (ff, arg1, arg1);
take_fraction (arg1, beta, ff);
convert_fraction_to_scaled (arg1);
number_clone (beta, arg1);
take_fraction (denom, gamma, alpha);
set_number_from_div (arg1, ff, twelvebits_3);
number_add (denom, arg1);
}
number_substract (denom, beta);
set_number_from_substraction (arg1, fraction_three_t, alpha);
take_fraction (num, gamma, arg1);
number_add (num, beta);
number_clone (arg1, denom);
number_double (arg1);
number_double (arg1); /* arg1 = 4*denom */
if (number_greaterequal(num, arg1)) {
number_clone(*ret, fraction_four_t);
} else {
make_fraction (*ret, num, denom);
}
free_number (alpha);
free_number (beta);
free_number (gamma);
free_number (num);
free_number (denom);
free_number (ff);
free_number (arg1);
}
@ We're in the home stretch now.
@<Finish choosing angles and assigning control points@>=
{
mp_number r1;
new_number (r1);
for (k = n - 1; k >= 0; k--) {
take_fraction (r1, mp->theta[k + 1], mp->uu[k]);
set_number_from_substraction(mp->theta[k], mp->vv[k], r1);
}
free_number (r1);
}
s = p;
k = 0;
{
mp_number arg;
new_number (arg);
do {
t = mp_next_knot (s);
n_sin_cos (mp->theta[k], mp->ct, mp->st);
number_clone (arg, mp->psi[k + 1]);
number_negate (arg);
number_substract (arg, mp->theta[k + 1]);
n_sin_cos (arg, mp->cf, mp->sf);
mp_set_controls (mp, s, t, k);
incr (k);
s = t;
} while (k != n);
free_number (arg);
}
@ The |set_controls| routine actually puts the control points into
a pair of consecutive nodes |p| and~|q|. Global variables are used to
record the values of $\sin\theta$, $\cos\theta$, $\sin\phi$, and
$\cos\phi$ needed in this calculation.
@<Glob...@>=
mp_number st;
mp_number ct;
mp_number sf;
mp_number cf; /* sines and cosines */
@ @<Initialize table...@>=
new_fraction (mp->st);
new_fraction (mp->ct);
new_fraction (mp->sf);
new_fraction (mp->cf);
@ @<Dealloc ...@>=
free_number (mp->st);
free_number (mp->ct);
free_number (mp->sf);
free_number (mp->cf);
@ @<Declarations@>=
static void mp_set_controls (MP mp, mp_knot p, mp_knot q, integer k);
@ @c
void mp_set_controls (MP mp, mp_knot p, mp_knot q, integer k) {
mp_number rr, ss; /* velocities, divided by thrice the tension */
mp_number lt, rt; /* tensions */
mp_number sine; /* $\sin(\theta+\phi)$ */
mp_number tmp;
mp_number r1, r2;
new_number(tmp);
new_number (lt);
new_number (rt);
new_number (r1);
new_number (r2);
number_clone(lt, q->left_tension);
number_abs(lt);
number_clone(rt, p->right_tension);
number_abs(rt);
new_fraction (sine);
new_fraction (rr);
new_fraction (ss);
velocity (rr, mp->st, mp->ct, mp->sf, mp->cf, rt);
velocity (ss, mp->sf, mp->cf, mp->st, mp->ct, lt);
if (number_negative(p->right_tension) || number_negative(q->left_tension)) {
@<Decrease the velocities,
if necessary, to stay inside the bounding triangle@>;
}
take_fraction (r1, mp->delta_x [k], mp->ct);
take_fraction (r2, mp->delta_y [k], mp->st);
number_substract (r1, r2);
take_fraction (tmp, r1, rr);
set_number_from_addition (p->right_x, p->x_coord, tmp);
take_fraction (r1, mp->delta_y[k], mp->ct);
take_fraction (r2, mp->delta_x[k], mp->st);
number_add (r1, r2);
take_fraction (tmp, r1, rr);
set_number_from_addition (p->right_y, p->y_coord, tmp);
take_fraction (r1, mp->delta_x[k], mp->cf);
take_fraction (r2, mp->delta_y[k], mp->sf);
number_add (r1, r2);
take_fraction (tmp, r1, ss);
set_number_from_substraction (q->left_x, q->x_coord, tmp);
take_fraction (r1, mp->delta_y[k], mp->cf);
take_fraction (r2, mp->delta_x[k], mp->sf);
number_substract (r1, r2);
take_fraction (tmp, r1, ss);
set_number_from_substraction(q->left_y, q->y_coord, tmp);
mp_right_type (p) = mp_explicit;
mp_left_type (q) = mp_explicit;
free_number (tmp);
free_number (r1);
free_number (r2);
free_number (lt);
free_number (rt);
free_number (rr);
free_number (ss);
free_number (sine);
}
@ The boundedness conditions $\\{rr}\L\sin\phi\,/\sin(\theta+\phi)$ and
$\\{ss}\L\sin\theta\,/\sin(\theta+\phi)$ are to be enforced if $\sin\theta$,
$\sin\phi$, and $\sin(\theta+\phi)$ all have the same sign. Otherwise
there is no ``bounding triangle.''
@<Decrease the velocities, if necessary...@>=
if ((number_nonnegative(mp->st) && number_nonnegative(mp->sf)) || (number_nonpositive(mp->st) && number_nonpositive(mp->sf))) {
mp_number r1, r2, arg1;
mp_number ab_vs_cd;
new_number (ab_vs_cd);
new_fraction (r1);
new_fraction (r2);
new_number (arg1);
number_clone (arg1, mp->st);
number_abs (arg1);
take_fraction (r1, arg1, mp->cf);
number_clone (arg1, mp->sf);
number_abs (arg1);
take_fraction (r2, arg1, mp->ct);
set_number_from_addition (sine, r1, r2);
if (number_positive(sine)) {
set_number_from_addition (arg1, fraction_one_t, unity_t); /* safety factor */
number_clone (r1, sine);
take_fraction (sine, r1, arg1);
if (number_negative(p->right_tension)) {
number_clone (arg1, mp->sf);
number_abs (arg1);
ab_vs_cd (ab_vs_cd, arg1, fraction_one_t, rr, sine);
if (number_negative(ab_vs_cd)) {
number_clone (arg1, mp->sf);
number_abs (arg1);
make_fraction (rr, arg1, sine);
}
}
if (number_negative(q->left_tension)) {
number_clone (arg1, mp->st);
number_abs (arg1);
ab_vs_cd (ab_vs_cd, arg1, fraction_one_t, ss, sine);
if (number_negative(ab_vs_cd)) {
number_clone (arg1, mp->st);
number_abs (arg1);
make_fraction (ss, arg1, sine);
}
}
}
free_number (arg1);
free_number (r1);
free_number (r2);
free_number (ab_vs_cd);
}
@ Only the simple cases remain to be handled.
@<Reduce to simple case of two givens and |return|@>=
{
mp_number arg1;
mp_number narg;
new_angle (narg);
n_arg (narg, mp->delta_x[0], mp->delta_y[0]);
new_number (arg1);
set_number_from_substraction (arg1, p->right_given, narg);
n_sin_cos (arg1, mp->ct, mp->st);
set_number_from_substraction (arg1, q->left_given, narg);
n_sin_cos (arg1, mp->cf, mp->sf);
number_negate (mp->sf);
mp_set_controls (mp, p, q, 0);
free_number (narg);
free_number (arg1);
free_number (ff);
return;
}
@ @<Reduce to simple case of straight line and |return|@>=
{
mp_number lt, rt; /* tension values */
mp_right_type (p) = mp_explicit;
mp_left_type (q) = mp_explicit;
new_number (lt);
new_number (rt);
number_clone (lt, q->left_tension);
number_abs(lt);
number_clone (rt, p->right_tension);
number_abs(rt);
if (number_unity(rt)) {
mp_number arg2;
new_number (arg2);
if (number_nonnegative(mp->delta_x[0])) {
set_number_from_addition (arg2, mp->delta_x[0], epsilon_t);
} else {
set_number_from_substraction (arg2, mp->delta_x[0], epsilon_t);
}
number_int_div (arg2, 3);
set_number_from_addition (p->right_x, p->x_coord, arg2);
if (number_nonnegative(mp->delta_y[0])) {
set_number_from_addition (arg2, mp->delta_y[0], epsilon_t);
} else {
set_number_from_substraction (arg2, mp->delta_y[0], epsilon_t);
}
number_int_div (arg2, 3);
set_number_from_addition (p->right_y, p->y_coord, arg2);
free_number (arg2);
} else {
mp_number arg2, r1;
new_fraction (r1);
new_number (arg2);
number_clone (arg2, rt);
number_multiply_int (arg2, 3);
make_fraction (ff, unity_t, arg2); /* $\alpha/3$ */
free_number (arg2);
take_fraction (r1, mp->delta_x[0], ff);
set_number_from_addition (p->right_x, p->x_coord, r1);
take_fraction (r1, mp->delta_y[0], ff);
set_number_from_addition (p->right_y, p->y_coord, r1);
}
if (number_unity(lt)) {
mp_number arg2;
new_number (arg2);
if (number_nonnegative(mp->delta_x[0])) {
set_number_from_addition (arg2, mp->delta_x[0], epsilon_t);
} else {
set_number_from_substraction (arg2, mp->delta_x[0], epsilon_t);
}
number_int_div (arg2, 3);
set_number_from_substraction (q->left_x, q->x_coord, arg2);
if (number_nonnegative(mp->delta_y[0])) {
set_number_from_addition (arg2, mp->delta_y[0], epsilon_t);
} else {
set_number_from_substraction (arg2, mp->delta_y[0], epsilon_t);
}
number_int_div (arg2, 3);
set_number_from_substraction (q->left_y, q->y_coord, arg2);
free_number (arg2);
} else {
mp_number arg2, r1;
new_fraction (r1);
new_number (arg2);
number_clone (arg2, lt);
number_multiply_int (arg2, 3);
make_fraction (ff, unity_t, arg2); /* $\beta/3$ */
free_number (arg2);
take_fraction (r1, mp->delta_x[0], ff);
set_number_from_substraction(q->left_x, q->x_coord, r1);
take_fraction (r1, mp->delta_y[0], ff);
set_number_from_substraction(q->left_y, q->y_coord, r1);
free_number (r1);
}
free_number (ff);
free_number (lt);
free_number (rt);
return;
}
@ Various subroutines that are useful for the new (1.770) exported
api for solving path choices
@c
#define TOO_LARGE(a) (fabs((a))>4096.0)
#define PI 3.1415926535897932384626433832795028841971
static int out_of_range(MP mp, double a)
{
mp_number t;
new_number (t);
set_number_from_double(t,fabs(a));
if (number_greaterequal(t,inf_t)) {
free_number (t);
return 1;
}
free_number (t);
return 0;
}
static int mp_link_knotpair (MP mp, mp_knot p, mp_knot q);
static int mp_link_knotpair (MP mp, mp_knot p, mp_knot q)
{
if (p==NULL ||q==NULL) return 0;
p->next = q;
set_number_from_double(p->right_tension, 1.0);
if (mp_right_type(p)==mp_endpoint) {
mp_right_type(p) = mp_open;
}
set_number_from_double(q->left_tension, 1.0);
if (mp_left_type(q) == mp_endpoint) {
mp_left_type(q) = mp_open;
}
return 1;
}
int mp_close_path_cycle (MP mp, mp_knot p, mp_knot q)
{
return mp_link_knotpair(mp,p,q);
}
int mp_close_path (MP mp, mp_knot q, mp_knot first)
{
if (q==NULL || first==NULL) return 0;
q->next = first;
mp_right_type(q) = mp_endpoint;
set_number_from_double(q->right_tension, 1.0);
mp_left_type(first) = mp_endpoint;
set_number_from_double(first->left_tension, 1.0);
return 1;
}
mp_knot mp_create_knot (MP mp)
{
mp_knot q = mp_new_knot(mp);
mp_left_type(q) = mp_endpoint;
mp_right_type(q) = mp_endpoint;
return q;
}
int mp_set_knot (MP mp, mp_knot p, double x, double y)
{
if (out_of_range(mp, x)) return 0;
if (out_of_range(mp, y)) return 0;
if (p==NULL) return 0;
set_number_from_double(p->x_coord, x);
set_number_from_double(p->y_coord, y);
return 1;
}
mp_knot mp_append_knot (MP mp, mp_knot p, double x, double y)
{
mp_knot q = mp_create_knot(mp);
if (q==NULL) return NULL;
if (!mp_set_knot(mp, q, x, y)) {
free(q);
return NULL;
}
if (p == NULL) return q;
if (!mp_link_knotpair(mp, p,q)) {
free(q);
return NULL;
}
return q;
}
int mp_set_knot_curl (MP mp, mp_knot q, double value) {
if (q==NULL) return 0;
if (TOO_LARGE(value)) return 0;
mp_right_type(q)=mp_curl;
set_number_from_double(q->right_curl, value);
if (mp_left_type(q)==mp_open) {
mp_left_type(q)=mp_curl;
set_number_from_double(q->left_curl, value);
}
return 1;
}
int mp_set_knot_left_curl (MP mp, mp_knot q, double value) {
if (q==NULL) return 0;
if (TOO_LARGE(value)) return 0;
mp_left_type(q)=mp_curl;
set_number_from_double(q->left_curl, value);
if (mp_right_type(q)==mp_open) {
mp_right_type(q)=mp_curl;
set_number_from_double(q->right_curl, value);
}
return 1;
}
int mp_set_knot_right_curl (MP mp, mp_knot q, double value) {
if (q==NULL) return 0;
if (TOO_LARGE(value)) return 0;
mp_right_type(q)=mp_curl;
set_number_from_double(q->right_curl, value);
if (mp_left_type(q)==mp_open) {
mp_left_type(q)=mp_curl;
set_number_from_double(q->left_curl, value);
}
return 1;
}
int mp_set_knotpair_curls (MP mp, mp_knot p, mp_knot q, double t1, double t2) {
if (p==NULL || q==NULL) return 0;
if (mp_set_knot_curl(mp, p, t1))
return mp_set_knot_curl(mp, q, t2);
return 0;
}
int mp_set_knotpair_tensions (MP mp, mp_knot p, mp_knot q, double t1, double t2) {
if (p==NULL || q==NULL) return 0;
if (TOO_LARGE(t1)) return 0;
if (TOO_LARGE(t2)) return 0;
if ((fabs(t1)<0.75)) return 0;
if ((fabs(t2)<0.75)) return 0;
set_number_from_double(p->right_tension, t1);
set_number_from_double(q->left_tension, t2);
return 1;
}
int mp_set_knot_left_tension (MP mp, mp_knot p, double t1) {
if (p==NULL) return 0;
if (TOO_LARGE(t1)) return 0;
if ((fabs(t1)<0.75)) return 0;
set_number_from_double(p->left_tension, t1);
return 1;
}
int mp_set_knot_right_tension (MP mp, mp_knot p, double t1) {
if (p==NULL) return 0;
if (TOO_LARGE(t1)) return 0;
if ((fabs(t1)<0.75)) return 0;
set_number_from_double(p->right_tension, t1);
return 1;
}
int mp_set_knotpair_controls (MP mp, mp_knot p, mp_knot q, double x1, double y1, double x2, double y2) {
if (p==NULL || q==NULL) return 0;
if (out_of_range(mp, x1)) return 0;
if (out_of_range(mp, y1)) return 0;
if (out_of_range(mp, x2)) return 0;
if (out_of_range(mp, y2)) return 0;
mp_right_type(p)=mp_explicit;
set_number_from_double(p->right_x, x1);
set_number_from_double(p->right_y, y1);
mp_left_type(q)=mp_explicit;
set_number_from_double(q->left_x, x2);
set_number_from_double(q->left_y, y2);
return 1;
}
int mp_set_knot_left_control (MP mp, mp_knot p, double x1, double y1) {
if (p==NULL) return 0;
if (out_of_range(mp, x1)) return 0;
if (out_of_range(mp, y1)) return 0;
mp_left_type(p)=mp_explicit;
set_number_from_double(p->left_x, x1);
set_number_from_double(p->left_y, y1);
return 1;
}
int mp_set_knot_right_control (MP mp, mp_knot p, double x1, double y1) {
if (p==NULL) return 0;
if (out_of_range(mp, x1)) return 0;
if (out_of_range(mp, y1)) return 0;
mp_right_type(p)=mp_explicit;
set_number_from_double(p->right_x, x1);
set_number_from_double(p->right_y, y1);
return 1;
}
int mp_set_knot_direction (MP mp, mp_knot q, double x, double y) {
double value = 0;
if (q==NULL) return 0;
if (TOO_LARGE(x)) return 0;
if (TOO_LARGE(y)) return 0;
if (!(x==0 && y == 0))
value = atan2 (y, x) * (180.0 / PI) * 16.0;
mp_right_type(q)=mp_given;
set_number_from_double(q->right_curl, value);
if (mp_left_type(q)==mp_open) {
mp_left_type(q)=mp_given;
set_number_from_double(q->left_curl, value);
}
return 1;
}
int mp_set_knotpair_directions (MP mp, mp_knot p, mp_knot q, double x1, double y1, double x2, double y2) {
if (p==NULL || q==NULL) return 0;
if (mp_set_knot_direction(mp,p, x1, y1))
return mp_set_knot_direction(mp,q, x2, y2);
return 0;
}
@
@c
static int path_needs_fixing (mp_knot source);
static int path_needs_fixing (mp_knot source) {
mp_knot sourcehead = source;
do {
source = source->next;
} while (source && source != sourcehead);
if (!source) {
return 1;
}
return 0;
}
int mp_solve_path (MP mp, mp_knot first)
{
int saved_arith_error = mp->arith_error;
jmp_buf *saved_jump_buf = mp->jump_buf;
int retval = 1;
if (first==NULL) return 0;
if (path_needs_fixing(first)) return 0;
mp->jump_buf = malloc(sizeof(jmp_buf));
if (mp->jump_buf == NULL || setjmp(*(mp->jump_buf)) != 0) {
return 0;
}
mp->arith_error = 0;
mp_make_choices(mp, first);
if (mp->arith_error)
retval = 0;
mp->arith_error = saved_arith_error;
free(mp->jump_buf);
mp->jump_buf = saved_jump_buf;
return retval;
}
void mp_free_path (MP mp, mp_knot p) {
mp_toss_knot_list(mp, p);
}
@ @<Exported function headers@>=
int mp_close_path_cycle (MP mp, mp_knot p, mp_knot q);
int mp_close_path (MP mp, mp_knot q, mp_knot first);
mp_knot mp_create_knot (MP mp);
int mp_set_knot (MP mp, mp_knot p, double x, double y);
mp_knot mp_append_knot (MP mp, mp_knot p, double x, double y);
int mp_set_knot_curl (MP mp, mp_knot q, double value);
int mp_set_knot_left_curl (MP mp, mp_knot q, double value);
int mp_set_knot_right_curl (MP mp, mp_knot q, double value);
int mp_set_knotpair_curls (MP mp, mp_knot p, mp_knot q, double t1, double t2) ;
int mp_set_knotpair_tensions (MP mp, mp_knot p, mp_knot q, double t1, double t2) ;
int mp_set_knot_left_tension (MP mp, mp_knot p, double t1);
int mp_set_knot_right_tension (MP mp, mp_knot p, double t1);
int mp_set_knot_left_control (MP mp, mp_knot p, double t1, double t2);
int mp_set_knot_right_control (MP mp, mp_knot p, double t1, double t2);
int mp_set_knotpair_controls (MP mp, mp_knot p, mp_knot q, double x1, double y1, double x2, double y2) ;
int mp_set_knot_direction (MP mp, mp_knot q, double x, double y) ;
int mp_set_knotpair_directions (MP mp, mp_knot p, mp_knot q, double x1, double y1, double x2, double y2) ;
int mp_solve_path (MP mp, mp_knot first);
void mp_free_path (MP mp, mp_knot p);
@ Simple accessors for |mp_knot|.
@c
mp_number mp_knot_x_coord(MP mp, mp_knot p) { return p->x_coord; }
mp_number mp_knot_y_coord(MP mp, mp_knot p) { return p->y_coord; }
mp_number mp_knot_left_x (MP mp, mp_knot p) { return p->left_x; }
mp_number mp_knot_left_y (MP mp, mp_knot p) { return p->left_y; }
mp_number mp_knot_right_x(MP mp, mp_knot p) { return p->right_x; }
mp_number mp_knot_right_y(MP mp, mp_knot p) { return p->right_y; }
int mp_knot_right_type(MP mp, mp_knot p) { return mp_right_type(p);}
int mp_knot_left_type (MP mp, mp_knot p) { return mp_left_type(p);}
mp_knot mp_knot_next (MP mp, mp_knot p) { return p->next; }
double mp_number_as_double(MP mp, mp_number n) {
return number_to_double(n);
}
@ @<Exported function headers@>=
#define mp_knot_left_curl mp_knot_left_x
#define mp_knot_left_given mp_knot_left_x
#define mp_knot_left_tension mp_knot_left_y
#define mp_knot_right_curl mp_knot_right_x
#define mp_knot_right_given mp_knot_right_x
#define mp_knot_right_tension mp_knot_right_y
mp_number mp_knot_x_coord(MP mp, mp_knot p);
mp_number mp_knot_y_coord(MP mp, mp_knot p);
mp_number mp_knot_left_x(MP mp, mp_knot p);
mp_number mp_knot_left_y(MP mp, mp_knot p);
mp_number mp_knot_right_x(MP mp, mp_knot p);
mp_number mp_knot_right_y(MP mp, mp_knot p);
int mp_knot_right_type(MP mp, mp_knot p);
int mp_knot_left_type(MP mp, mp_knot p);
mp_knot mp_knot_next(MP mp, mp_knot p);
double mp_number_as_double(MP mp, mp_number n);
@* Measuring paths.
\MP's \&{llcorner}, \&{lrcorner}, \&{ulcorner}, and \&{urcorner} operators
allow the user to measure the bounding box of anything that can go into a
picture. It's easy to get rough bounds on the $x$ and $y$ extent of a path
by just finding the bounding box of the knots and the control points. We
need a more accurate version of the bounding box, but we can still use the
easy estimate to save time by focusing on the interesting parts of the path.
@ Computing an accurate bounding box involves a theme that will come up again
and again. Given a Bernshte{\u\i}n polynomial
@^Bernshte{\u\i}n, Serge{\u\i} Natanovich@>
$$B(z_0,z_1,\ldots,z_n;t)=\sum_k{n\choose k}t^k(1-t)^{n-k}z_k,$$
we can conveniently bisect its range as follows:
\smallskip
\textindent{1)} Let $z_k^{(0)}=z_k$, for |0<=k<=n|.
\smallskip
\textindent{2)} Let $z_k^{(j+1)}={1\over2}(z_k^{(j)}+z\k^{(j)})$, for
|0<=k<n-j|, for |0<=j<n|.
\smallskip\noindent
Then
$$B(z_0,z_1,\ldots,z_n;t)=B(z_0^{(0)},z_0^{(1)},\ldots,z_0^{(n)};2t)
=B(z_0^{(n)},z_1^{(n-1)},\ldots,z_n^{(0)};2t-1).$$
This formula gives us the coefficients of polynomials to use over the ranges
$0\L t\L{1\over2}$ and ${1\over2}\L t\L1$.
@ Here is a routine that computes the $x$ or $y$ coordinate of the point on
a cubic corresponding to the |fraction| value~|t|.
@c
static void mp_eval_cubic (MP mp, mp_number *r, mp_knot p, mp_knot q, quarterword c,
mp_number t) {
mp_number x1, x2, x3; /* intermediate values */
new_number(x1);
new_number(x2);
new_number(x3);
if (c == mp_x_code) {
set_number_from_of_the_way(x1, t, p->x_coord, p->right_x);
set_number_from_of_the_way(x2, t, p->right_x, q->left_x);
set_number_from_of_the_way(x3, t, q->left_x, q->x_coord);
} else {
set_number_from_of_the_way(x1, t, p->y_coord, p->right_y);
set_number_from_of_the_way(x2, t, p->right_y, q->left_y);
set_number_from_of_the_way(x3, t, q->left_y, q->y_coord);
}
set_number_from_of_the_way(x1, t, x1, x2);
set_number_from_of_the_way(x2, t, x2, x3);
set_number_from_of_the_way(*r, t, x1, x2);
free_number (x1);
free_number (x2);
free_number (x3);
}
@ The actual bounding box information is stored in global variables.
Since it is convenient to address the $x$ and $y$ information
separately, we define arrays indexed by |x_code..y_code| and use
macros to give them more convenient names.
@<Types...@>=
enum mp_bb_code {
mp_x_code = 0, /* index for |minx| and |maxx| */
mp_y_code /* index for |miny| and |maxy| */
};
@
@d mp_minx mp->bbmin[mp_x_code]
@d mp_maxx mp->bbmax[mp_x_code]
@d mp_miny mp->bbmin[mp_y_code]
@d mp_maxy mp->bbmax[mp_y_code]
@<Glob...@>=
mp_number bbmin[mp_y_code + 1];
mp_number bbmax[mp_y_code + 1];
/* the result of procedures that compute bounding box information */
@ @<Initialize table ...@>=
{
int i;
for (i=0;i<=mp_y_code;i++) {
new_number(mp->bbmin[i]);
new_number(mp->bbmax[i]);
}
}
@ @<Dealloc...@>=
{
int i;
for (i=0;i<=mp_y_code;i++) {
free_number(mp->bbmin[i]);
free_number(mp->bbmax[i]);
}
}
@ Now we're ready for the key part of the bounding box computation.
The |bound_cubic| procedure updates |bbmin[c]| and |bbmax[c]| based on
$$B(\hbox{|knot_coord(p)|}, \hbox{|right_coord(p)|},
\hbox{|left_coord(q)|}, \hbox{|knot_coord(q)|};t)
$$
for $0<t\le1$. In other words, the procedure adjusts the bounds to
accommodate |knot_coord(q)| and any extremes over the range $0<t<1$.
The |c| parameter is |x_code| or |y_code|.
@c
static void mp_bound_cubic (MP mp, mp_knot p, mp_knot q, quarterword c) {
boolean wavy; /* whether we need to look for extremes */
mp_number del1, del2, del3, del, dmax; /* proportional to the control
points of a quadratic derived from a cubic */
mp_number t, tt; /* where a quadratic crosses zero */
mp_number x; /* a value that |bbmin[c]| and |bbmax[c]| must accommodate */
new_number (x);
new_fraction (t);
new_fraction (tt);
if (c == mp_x_code) {
number_clone(x, q->x_coord);
} else {
number_clone(x, q->y_coord);
}
new_number(del1);
new_number(del2);
new_number(del3);
new_number(del);
new_number(dmax);
@<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
@<Check the control points against the bounding box and set |wavy:=true|
if any of them lie outside@>;
if (wavy) {
if (c == mp_x_code) {
set_number_from_substraction(del1, p->right_x, p->x_coord);
set_number_from_substraction(del2, q->left_x, p->right_x);
set_number_from_substraction(del3, q->x_coord, q->left_x);
} else {
set_number_from_substraction(del1, p->right_y, p->y_coord);
set_number_from_substraction(del2, q->left_y, p->right_y);
set_number_from_substraction(del3, q->y_coord, q->left_y);
}
@<Scale up |del1|, |del2|, and |del3| for greater accuracy;
also set |del| to the first nonzero element of |(del1,del2,del3)|@>;
if (number_negative(del)) {
number_negate (del1);
number_negate (del2);
number_negate (del3);
}
crossing_point (t, del1, del2, del3);
if (number_less(t, fraction_one_t)) {
@<Test the extremes of the cubic against the bounding box@>;
}
}
free_number (del3);
free_number (del2);
free_number (del1);
free_number (del);
free_number (dmax);
free_number (x);
free_number (t);
free_number (tt);
}
@ @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>=
if (number_less(x, mp->bbmin[c]))
number_clone(mp->bbmin[c], x);
if (number_greater(x, mp->bbmax[c]))
number_clone(mp->bbmax[c], x)
@ @<Check the control points against the bounding box and set...@>=
wavy = true;
if (c == mp_x_code) {
if (number_lessequal(mp->bbmin[c], p->right_x))
if (number_lessequal (p->right_x, mp->bbmax[c]))
if (number_lessequal(mp->bbmin[c], q->left_x))
if (number_lessequal (q->left_x, mp->bbmax[c]))
wavy = false;
} else {
if (number_lessequal(mp->bbmin[c], p->right_y))
if (number_lessequal (p->right_y, mp->bbmax[c]))
if (number_lessequal(mp->bbmin[c], q->left_y))
if (number_lessequal (q->left_y, mp->bbmax[c]))
wavy = false;
}
@ If |del1=del2=del3=0|, it's impossible to obey the title of this
section. We just set |del=0| in that case.
@<Scale up |del1|, |del2|, and |del3| for greater accuracy...@>=
if (number_nonzero(del1)) {
number_clone (del, del1);
} else if (number_nonzero(del2)) {
number_clone (del, del2);
} else {
number_clone (del, del3);
}
if (number_nonzero(del)) {
mp_number absval1;
new_number(absval1);
number_clone (dmax, del1);
number_abs (dmax);
number_clone (absval1, del2);
number_abs(absval1);
if (number_greater(absval1, dmax)) {
number_clone(dmax, absval1);
}
number_clone (absval1, del3);
number_abs(absval1);
if (number_greater(absval1, dmax)) {
number_clone(dmax, absval1);
}
while (number_less(dmax, fraction_half_t)) {
number_double(dmax);
number_double(del1);
number_double(del2);
number_double(del3);
}
free_number (absval1);
}
@ Since |crossing_point| has tried to choose |t| so that
$B(|del1|,|del2|,|del3|;\tau)$ crosses zero at $\tau=|t|$ with negative
slope, the value of |del2| computed below should not be positive.
But rounding error could make it slightly positive in which case we
must cut it to zero to avoid confusion.
@<Test the extremes of the cubic against the bounding box@>=
{
mp_eval_cubic (mp, &x, p, q, c, t);
@<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
set_number_from_of_the_way(del2, t, del2, del3);
/* now |0,del2,del3| represent the derivative on the remaining interval */
if (number_positive(del2))
set_number_to_zero(del2);
{
mp_number arg2, arg3;
new_number(arg2);
new_number(arg3);
number_clone(arg2, del2);
number_negate(arg2);
number_clone(arg3, del3);
number_negate(arg3);
crossing_point (tt, zero_t, arg2, arg3);
free_number (arg2);
free_number (arg3);
}
if (number_less(tt, fraction_one_t)) {
@<Test the second extreme against the bounding box@>;
}
}
@ @<Test the second extreme against the bounding box@>=
{
mp_number arg;
new_number (arg);
set_number_from_of_the_way (arg, t, tt, fraction_one_t);
mp_eval_cubic (mp, &x, p, q, c, arg);
free_number (arg);
@<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
}
@ Finding the bounding box of a path is basically a matter of applying
|bound_cubic| twice for each pair of adjacent knots.
@c
static void mp_path_bbox (MP mp, mp_knot h) {
mp_knot p, q; /* a pair of adjacent knots */
number_clone(mp_minx, h->x_coord);
number_clone(mp_miny, h->y_coord);
number_clone (mp_maxx, mp_minx);
number_clone (mp_maxy, mp_miny);
p = h;
do {
if (mp_right_type (p) == mp_endpoint)
return;
q = mp_next_knot (p);
mp_bound_cubic (mp, p, q, mp_x_code);
mp_bound_cubic (mp, p, q, mp_y_code);
p = q;
} while (p != h);
}
@ Another important way to measure a path is to find its arc length. This
is best done by using the general bisection algorithm to subdivide the path
until obtaining ``well behaved'' subpaths whose arc lengths can be approximated
by simple means.
Since the arc length is the integral with respect to time of the magnitude of
the velocity, it is natural to use Simpson's rule for the approximation.
@^Simpson's rule@>
If $\dot B(t)$ is the spline velocity, Simpson's rule gives
$$ \vb\dot B(0)\vb + 4\vb\dot B({1\over2})\vb + \vb\dot B(1)\vb \over 6 $$
for the arc length of a path of length~1. For a cubic spline
$B(z_0,z_1,z_2,z_3;t)$, the time derivative $\dot B(t)$ is
$3B(dz_0,dz_1,dz_2;t)$, where $dz_i=z_{i+1}-z_i$. Hence the arc length
approximation is
$$ {\vb dz_0\vb \over 2} + 2\vb dz_{02}\vb + {\vb dz_2\vb \over 2}, $$
where
$$ dz_{02}={1\over2}\left({dz_0+dz_1\over 2}+{dz_1+dz_2\over 2}\right)$$
is the result of the bisection algorithm.
@ The remaining problem is how to decide when a subpath is ``well behaved.''
This could be done via the theoretical error bound for Simpson's rule,
@^Simpson's rule@>
but this is impractical because it requires an estimate of the fourth
derivative of the quantity being integrated. It is much easier to just perform
a bisection step and see how much the arc length estimate changes. Since the
error for Simpson's rule is proportional to the fourth power of the sample
spacing, the remaining error is typically about $1\over16$ of the amount of
the change. We say ``typically'' because the error has a pseudo-random behavior
that could cause the two estimates to agree when each contain large errors.
To protect against disasters such as undetected cusps, the bisection process
should always continue until all the $dz_i$ vectors belong to a single
$90^\circ$ sector. This ensures that no point on the spline can have velocity
less than 70\% of the minimum of $\vb dz_0\vb$, $\vb dz_1\vb$ and $\vb dz_2\vb$.
If such a spline happens to produce an erroneous arc length estimate that
is little changed by bisection, the amount of the error is likely to be fairly
small. We will try to arrange things so that freak accidents of this type do
not destroy the inverse relationship between the \&{arclength} and
\&{arctime} operations.
@:arclength_}{\&{arclength} primitive@>
@:arctime_}{\&{arctime} primitive@>
@ The \&{arclength} and \&{arctime} operations are both based on a recursive
@^recursion@>
function that finds the arc length of a cubic spline given $dz_0$, $dz_1$,
$dz_2$. This |arc_test| routine also takes an arc length goal |a_goal| and
returns the time when the arc length reaches |a_goal| if there is such a time.
Thus the return value is either an arc length less than |a_goal| or, if the
arc length would be at least |a_goal|, it returns a time value decreased by
|two|. This allows the caller to use the sign of the result to distinguish
between arc lengths and time values. On certain types of overflow, it is
possible for |a_goal| and the result of |arc_test| both to be |EL_GORDO|.
Otherwise, the result is always less than |a_goal|.
Rather than halving the control point coordinates on each recursive call to
|arc_test|, it is better to keep them proportional to velocity on the original
curve and halve the results instead. This means that recursive calls can
potentially use larger error tolerances in their arc length estimates. How
much larger depends on to what extent the errors behave as though they are
independent of each other. To save computing time, we use optimistic assumptions
and increase the tolerance by a factor of about $\sqrt2$ for each recursive
call.
In addition to the tolerance parameter, |arc_test| should also have parameters
for ${1\over3}\vb\dot B(0)\vb$, ${2\over3}\vb\dot B({1\over2})\vb$, and
${1\over3}\vb\dot B(1)\vb$. These quantities are relatively expensive to compute
and they are needed in different instances of |arc_test|.
@c
static void mp_arc_test (MP mp, mp_number *ret, mp_number dx0, mp_number dy0, mp_number dx1,
mp_number dy1, mp_number dx2, mp_number dy2, mp_number v0,
mp_number v02, mp_number v2, mp_number a_goal, mp_number tol_orig) {
boolean simple; /* are the control points confined to a $90^\circ$ sector? */
mp_number dx01, dy01, dx12, dy12, dx02, dy02; /* bisection results */
mp_number v002, v022; /* twice the velocity magnitudes at $t={1\over4}$ and $t={3\over4}$ */
mp_number arc; /* best arc length estimate before recursion */
mp_number arc1; /* arc length estimate for the first half */
mp_number simply;
mp_number tol;
new_number (arc );
new_number (arc1);
new_number (dx01);
new_number (dy01);
new_number (dx12);
new_number (dy12);
new_number (dx02);
new_number (dy02);
new_number (v002);
new_number (v022);
new_number (simply);
new_number (tol);
number_clone(tol, tol_orig);
@<Bisect the B\'ezier quadratic given by |dx0|, |dy0|, |dx1|, |dy1|,
|dx2|, |dy2|@>;
@<Initialize |v002|, |v022|, and the arc length estimate |arc|; if it overflows
set |arc_test| and |return|@>;
@<Test if the control points are confined to one quadrant or rotating them
$45^\circ$ would put them in one quadrant. Then set |simple| appropriately@>;
set_number_from_addition(simply, v0, v2);
number_halfp (simply);
number_negate (simply);
number_add (simply, arc);
number_substract (simply, v02);
number_abs (simply);
if (simple && number_lessequal(simply, tol)) {
if (number_less(arc, a_goal)){
number_clone(*ret, arc);
} else {
@<Estimate when the arc length reaches |a_goal| and set |arc_test| to
that time minus |two|@>;
}
} else {
@<Use one or two recursive calls to compute the |arc_test| function@>;
}
DONE:
free_number (arc);
free_number (arc1);
free_number (dx01);
free_number (dy01);
free_number (dx12);
free_number (dy12);
free_number (dx02);
free_number (dy02);
free_number (v002);
free_number (v022);
free_number (simply);
free_number (tol);
}
@ The |tol| value should by multiplied by $\sqrt 2$ before making recursive
calls, but $1.5$ is an adequate approximation. It is best to avoid using
|make_fraction| in this inner loop.
@^inner loop@>
@<Use one or two recursive calls to compute the |arc_test| function@>=
{
mp_number a_new, a_aux; /* the sum of these gives the |a_goal| */
mp_number a, b; /* results of recursive calls */
mp_number half_v02; /* |halfp(v02)|, a recursion argument */
new_number(a_new);
new_number(a_aux);
new_number(half_v02);
@<Set |a_new| and |a_aux| so their sum is |2*a_goal| and |a_new| is as
large as possible@>;
{
mp_number halfp_tol;
new_number(halfp_tol);
number_clone (halfp_tol, tol);
number_halfp (halfp_tol);
number_add(tol, halfp_tol);
free_number (halfp_tol);
}
number_clone(half_v02, v02);
number_halfp(half_v02);
new_number (a);
mp_arc_test (mp, &a, dx0, dy0, dx01, dy01, dx02, dy02,
v0, v002, half_v02, a_new, tol);
if (number_negative(a)) {
set_number_to_unity(*ret);
number_double(*ret); /* two */
number_substract(*ret, a); /* two - a */
number_halfp(*ret);
number_negate(*ret); /* -halfp(two - a) */
} else {
@<Update |a_new| to reduce |a_new+a_aux| by |a|@>;
new_number (b);
mp_arc_test (mp, &b, dx02, dy02, dx12, dy12, dx2, dy2,
half_v02, v022, v2, a_new, tol);
if (number_negative(b)) {
mp_number tmp ;
new_number (tmp);
number_clone(tmp, b);
number_negate(tmp);
number_halfp(tmp);
number_negate(tmp);
number_clone(*ret, tmp);
set_number_to_unity(tmp);
number_halfp(tmp);
number_substract(*ret, tmp); /* (-(halfp(-b)) - 1/2) */
free_number (tmp);
} else {
set_number_from_substraction(*ret, b, a);
number_half(*ret);
set_number_from_addition(*ret, a, *ret); /* (a + half(b - a)) */
}
free_number (b);
}
free_number (half_v02);
free_number (a_aux);
free_number (a_new);
free_number (a);
goto DONE;
}
@ @<Set |a_new| and |a_aux| so their sum is |2*a_goal| and |a_new| is...@>=
set_number_to_inf(a_aux);
number_substract(a_aux, a_goal);
if (number_greater(a_goal, a_aux)) {
set_number_from_substraction(a_aux, a_goal, a_aux);
set_number_to_inf(a_new);
} else {
set_number_from_addition(a_new, a_goal, a_goal);
set_number_to_zero(a_aux);
}
@ There is no need to maintain |a_aux| at this point so we use it as a temporary
to force the additions and subtractions to be done in an order that avoids
overflow.
@<Update |a_new| to reduce |a_new+a_aux| by |a|@>=
if (number_greater(a, a_aux)) {
number_substract(a_aux, a);
number_add(a_new, a_aux);
}
@ This code assumes all {\it dx} and {\it dy} variables have magnitude less than
|fraction_four|. To simplify the rest of the |arc_test| routine, we strengthen
this assumption by requiring the norm of each $({\it dx},{\it dy})$ pair to obey
this bound. Note that recursive calls will maintain this invariant.
@<Bisect the B\'ezier quadratic given by |dx0|, |dy0|, |dx1|, |dy1|,...@>=
set_number_from_addition(dx01, dx0, dx1);
number_half(dx01);
set_number_from_addition(dx12, dx1, dx2);
number_half(dx12);
set_number_from_addition(dx02, dx01, dx12);
number_half(dx02);
set_number_from_addition(dy01, dy0, dy1);
number_half(dy01);
set_number_from_addition(dy12, dy1, dy2);
number_half(dy12);
set_number_from_addition(dy02, dy01, dy12);
number_half(dy02);
@ We should be careful to keep |arc<EL_GORDO| so that calling |arc_test| with
|a_goal=EL_GORDO| is guaranteed to yield the arc length.
@<Initialize |v002|, |v022|, and the arc length estimate |arc|;...@>=
{
mp_number tmp, arg1, arg2 ;
new_number (tmp);
new_number (arg1);
new_number (arg2);
set_number_from_addition(arg1, dx0, dx02);
number_half(arg1);
number_add(arg1, dx01);
set_number_from_addition(arg2, dy0, dy02);
number_half(arg2);
number_add(arg2, dy01);
pyth_add (v002, arg1, arg2);
set_number_from_addition(arg1, dx02, dx2);
number_half(arg1);
number_add(arg1, dx12);
set_number_from_addition(arg2, dy02, dy2);
number_half(arg2);
number_add(arg2, dy12);
pyth_add (v022, arg1, arg2);
free_number(arg1);
free_number(arg2);
number_clone (tmp, v02);
number_add_scaled (tmp, 2);
number_halfp (tmp);
set_number_from_addition(arc1, v0, tmp);
number_halfp (arc1);
number_substract (arc1, v002);
number_half (arc1);
set_number_from_addition(arc1, v002, arc1);
set_number_from_addition(arc, v2, tmp);
number_halfp (arc);
number_substract (arc, v022);
number_half (arc);
set_number_from_addition(arc, v022, arc);
/* reuse |tmp| for the next |if| test: */
set_number_to_inf(tmp);
number_substract(tmp,arc1);
if (number_less(arc, tmp)) {
free_number (tmp);
number_add(arc, arc1);
} else {
free_number (tmp);
mp->arith_error = true;
if (number_infinite(a_goal)) {
set_number_to_inf(*ret);
} else {
set_number_to_unity(*ret);
number_double(*ret);
number_negate(*ret); /* -two */
}
goto DONE;
}
}
@ @<Test if the control points are confined to one quadrant or rotating...@>=
simple = ((number_nonnegative(dx0) && number_nonnegative(dx1) && number_nonnegative(dx2)) ||
(number_nonpositive(dx0) && number_nonpositive(dx1) && number_nonpositive(dx2)));
if (simple) {
simple = (number_nonnegative(dy0) && number_nonnegative(dy1) && number_nonnegative(dy2)) ||
(number_nonpositive(dy0) && number_nonpositive(dy1) && number_nonpositive(dy2));
}
if (!simple) {
simple = (number_greaterequal(dx0, dy0) && number_greaterequal(dx1, dy1) && number_greaterequal(dx2, dy2)) ||
(number_lessequal(dx0, dy0) && number_lessequal(dx1, dy1) && number_lessequal(dx2, dy2));
if (simple) {
mp_number neg_dx0, neg_dx1, neg_dx2;
new_number(neg_dx0);
new_number(neg_dx1);
new_number(neg_dx2);
number_clone(neg_dx0, dx0);
number_clone(neg_dx1, dx1);
number_clone(neg_dx2, dx2);
number_negate(neg_dx0);
number_negate(neg_dx1);
number_negate(neg_dx2);
simple =
(number_greaterequal(neg_dx0, dy0) && number_greaterequal(neg_dx1, dy1) && number_greaterequal(neg_dx2, dy2)) ||
(number_lessequal(neg_dx0, dy0) && number_lessequal(neg_dx1, dy1) && number_lessequal(neg_dx2, dy2));
free_number (neg_dx0);
free_number (neg_dx1);
free_number (neg_dx2);
}
}
@ Since Simpson's rule is based on approximating the integrand by a parabola,
@^Simpson's rule@>
it is appropriate to use the same approximation to decide when the integral
reaches the intermediate value |a_goal|. At this point
$$\eqalign{
{\vb\dot B(0)\vb\over 3} &= \hbox{|v0|}, \qquad
{\vb\dot B({1\over4})\vb\over 3} = {\hbox{|v002|}\over 2}, \qquad
{\vb\dot B({1\over2})\vb\over 3} = {\hbox{|v02|}\over 2}, \cr
{\vb\dot B({3\over4})\vb\over 3} &= {\hbox{|v022|}\over 2}, \qquad
{\vb\dot B(1)\vb\over 3} = \hbox{|v2|} \cr
}
$$
and
$$ {\vb\dot B(t)\vb\over 3} \approx
\cases{B\left(\hbox{|v0|},
\hbox{|v002|}-{1\over 2}\hbox{|v0|}-{1\over 4}\hbox{|v02|},
{1\over 2}\hbox{|v02|}; 2t \right)&
if $t\le{1\over 2}$\cr
B\left({1\over 2}\hbox{|v02|},
\hbox{|v022|}-{1\over 4}\hbox{|v02|}-{1\over 2}\hbox{|v2|},
\hbox{|v2|}; 2t-1 \right)&
if $t\ge{1\over 2}$.\cr}
\eqno (*)
$$
We can integrate $\vb\dot B(t)\vb$ by using
$$\int 3B(a,b,c;\tau)\,dt =
{B(0,a,a+b,a+b+c;\tau) + {\rm constant} \over {d\tau\over dt}}.
$$
This construction allows us to find the time when the arc length reaches
|a_goal| by solving a cubic equation of the form
$$ B(0,a,a+b,a+b+c;\tau) = x, $$
where $\tau$ is $2t$ or $2t+1$, $x$ is |a_goal| or |a_goal-arc1|, and $a$, $b$,
and $c$ are the Bernshte{\u\i}n coefficients from $(*)$ divided by
@^Bernshte{\u\i}n, Serge{\u\i} Natanovich@>
$d\tau\over dt$. We shall define a function |solve_rising_cubic| that finds
$\tau$ given $a$, $b$, $c$, and $x$.
@<Estimate when the arc length reaches |a_goal| and set |arc_test| to...@>=
{
mp_number tmp;
mp_number tmp2;
mp_number tmp3;
mp_number tmp4;
mp_number tmp5;
new_number (tmp);
new_number (tmp2);
new_number (tmp3);
new_number (tmp4);
new_number (tmp5);
number_clone(tmp, v02);
number_add_scaled(tmp, 2);
number_half(tmp);
number_half(tmp); /* (v02+2) / 4 */
if (number_lessequal(a_goal, arc1)) {
number_clone(tmp2, v0);
number_halfp(tmp2);
set_number_from_substraction(tmp3, arc1, tmp2);
number_substract(tmp3, tmp);
mp_solve_rising_cubic (mp, &tmp5, tmp2, tmp3, tmp, a_goal);
number_halfp (tmp5);
set_number_to_unity(tmp3);
number_substract(tmp5, tmp3);
number_substract(tmp5, tmp3);
number_clone(*ret, tmp5);
} else {
number_clone(tmp2, v2);
number_halfp(tmp2);
set_number_from_substraction(tmp3, arc, arc1);
number_substract(tmp3, tmp);
number_substract(tmp3, tmp2);
set_number_from_substraction(tmp4, a_goal, arc1);
mp_solve_rising_cubic (mp, &tmp5, tmp, tmp3, tmp2, tmp4);
number_halfp(tmp5);
set_number_to_unity(tmp2);
set_number_to_unity(tmp3);
number_half(tmp2);
number_substract(tmp2, tmp3);
number_substract(tmp2, tmp3);
set_number_from_addition(*ret, tmp2, tmp5);
}
free_number (tmp);
free_number (tmp2);
free_number (tmp3);
free_number (tmp4);
free_number (tmp5);
goto DONE;
}
@ Here is the |solve_rising_cubic| routine that finds the time~$t$ when
$$ B(0, a, a+b, a+b+c; t) = x. $$
This routine is based on |crossing_point| but is simplified by the
assumptions that $B(a,b,c;t)\ge0$ for $0\le t\le1$ and that |0<=x<=a+b+c|.
If rounding error causes this condition to be violated slightly, we just ignore
it and proceed with binary search. This finds a time when the function value
reaches |x| and the slope is positive.
@<Declarations@>=
static void mp_solve_rising_cubic (MP mp, mp_number *ret, mp_number a, mp_number b, mp_number c, mp_number x);
@ @c
void mp_solve_rising_cubic (MP mp, mp_number *ret, mp_number a_orig, mp_number b_orig, mp_number c_orig, mp_number x_orig) {
mp_number abc;
mp_number a, b, c, x; /* local versions of arguments */
mp_number ab, bc, ac; /* bisection results */
mp_number t; /* $2^k+q$ where unscaled answer is in $[q2^{-k},(q+1)2^{-k})$ */
mp_number xx; /* temporary for updating |x| */
mp_number neg_x; /* temporary for an |if| */
if (number_negative(a_orig) || number_negative(c_orig))
mp_confusion (mp, "rising?");
@:this can't happen rising?}{\quad rising?@>;
new_number (t);
new_number (abc);
new_number (a);
new_number (b);
new_number (c);
new_number (x);
number_clone(a, a_orig);
number_clone(b, b_orig);
number_clone(c, c_orig);
number_clone(x, x_orig);
new_number (ab);
new_number (bc);
new_number (ac);
new_number (xx);
new_number (neg_x);
set_number_from_addition(abc, a, b);
number_add(abc, c);
if (number_nonpositive(x)) {
set_number_to_zero(*ret);
} else if (number_greaterequal(x, abc)) {
set_number_to_unity(*ret);
} else {
number_clone (t, epsilon_t);
@<Rescale if necessary to make sure |a|, |b|, and |c| are all less than
|EL_GORDO div 3|@>;
do {
number_add (t, t);
@<Subdivide the B\'ezier quadratic defined by |a|, |b|, |c|@>;
number_clone(xx,x);
number_substract(xx, a);
number_substract(xx, ab);
number_substract(xx, ac);
number_clone(neg_x, x);
number_negate(neg_x);
if (number_less(xx, neg_x)) {
number_double(x);
number_clone(b, ab);
number_clone(c, ac);
} else {
number_add(x, xx);
number_clone(a, ac);
number_clone(b, bc);
number_add (t, epsilon_t);
}
} while (number_less (t, unity_t));
set_number_from_substraction(*ret, t, unity_t);
}
free_number (abc);
free_number (t);
free_number (a);
free_number (b);
free_number (c);
free_number (ab);
free_number (bc);
free_number (ac);
free_number (xx);
free_number (x);
free_number (neg_x);
}
@ @<Subdivide the B\'ezier quadratic defined by |a|, |b|, |c|@>=
set_number_from_addition(ab, a, b);
number_half(ab);
set_number_from_addition(bc, b, c);
number_half(bc);
set_number_from_addition(ac, ab, bc);
number_half(ac);
@ The upper bound on |a|, |b|, and |c|:
@d one_third_inf_t ((math_data *)mp->math)->one_third_inf_t
@<Rescale if necessary to make sure |a|, |b|, and |c| are all less than...@>=
while (number_greater(a, one_third_inf_t) ||
number_greater(b, one_third_inf_t) ||
number_greater(c, one_third_inf_t)) {
number_halfp(a);
number_half(b);
number_halfp(c);
number_halfp(x);
}
@ It is convenient to have a simpler interface to |arc_test| that requires no
unnecessary arguments and ensures that each $({\it dx},{\it dy})$ pair has
length less than |fraction_four|.
@c
static void mp_do_arc_test (MP mp, mp_number *ret, mp_number dx0, mp_number dy0, mp_number dx1,
mp_number dy1, mp_number dx2, mp_number dy2, mp_number a_goal) {
mp_number v0, v1, v2; /* length of each $({\it dx},{\it dy})$ pair */
mp_number v02; /* twice the norm of the quadratic at $t={1\over2}$ */
new_number (v0);
new_number (v1);
new_number (v2);
pyth_add (v0, dx0, dy0);
pyth_add (v1, dx1, dy1);
pyth_add (v2, dx2, dy2);
if ((number_greaterequal(v0, fraction_four_t)) ||
(number_greaterequal(v1, fraction_four_t)) ||
(number_greaterequal(v2, fraction_four_t))) {
mp->arith_error = true;
if (number_infinite(a_goal)) {
set_number_to_inf(*ret);
} else {
set_number_to_unity(*ret);
number_double(*ret);
number_negate(*ret);
}
} else {
mp_number arg1, arg2;
new_number (v02);
new_number (arg1);
new_number (arg2);
set_number_from_addition(arg1, dx0, dx2);
number_half(arg1);
number_add(arg1, dx1);
set_number_from_addition(arg2, dy0, dy2);
number_half(arg2);
number_add(arg2, dy1);
pyth_add (v02, arg1, arg2);
free_number(arg1);
free_number(arg2);
mp_arc_test (mp, ret, dx0, dy0, dx1, dy1, dx2, dy2, v0, v02, v2, a_goal, arc_tol_k);
free_number (v02);
}
free_number (v0);
free_number (v1);
free_number (v2);
}
@ Now it is easy to find the arc length of an entire path.
@c
static void mp_get_arc_length (MP mp, mp_number *ret, mp_knot h) {
mp_knot p, q; /* for traversing the path */
mp_number a; /* current arc length */
mp_number a_tot; /* total arc length */
mp_number arg1, arg2, arg3, arg4, arg5, arg6;
mp_number arcgoal;
p = h;
new_number (a_tot);
new_number (arg1);
new_number (arg2);
new_number (arg3);
new_number (arg4);
new_number (arg5);
new_number (arg6);
new_number (a);
new_number(arcgoal);
set_number_to_inf(arcgoal);
while (mp_right_type (p) != mp_endpoint) {
q = mp_next_knot (p);
set_number_from_substraction(arg1, p->right_x, p->x_coord);
set_number_from_substraction(arg2, p->right_y, p->y_coord);
set_number_from_substraction(arg3, q->left_x, p->right_x);
set_number_from_substraction(arg4, q->left_y, p->right_y);
set_number_from_substraction(arg5, q->x_coord, q->left_x);
set_number_from_substraction(arg6, q->y_coord, q->left_y);
mp_do_arc_test (mp, &a, arg1, arg2, arg3, arg4, arg5, arg6, arcgoal);
slow_add (a_tot, a, a_tot);
if (q == h)
break;
else
p = q;
}
free_number (arcgoal);
free_number (a);
free_number (arg1);
free_number (arg2);
free_number (arg3);
free_number (arg4);
free_number (arg5);
free_number (arg6);
check_arith();
number_clone (*ret, a_tot);
free_number (a_tot);
}
@ The inverse operation of finding the time on a path~|h| when the arc length
reaches some value |arc0| can also be accomplished via |do_arc_test|. Some care
is required to handle very large times or negative times on cyclic paths. For
non-cyclic paths, |arc0| values that are negative or too large cause
|get_arc_time| to return 0 or the length of path~|h|.
If |arc0| is greater than the arc length of a cyclic path~|h|, the result is a
time value greater than the length of the path. Since it could be much greater,
we must be prepared to compute the arc length of path~|h| and divide this into
|arc0| to find how many multiples of the length of path~|h| to add.
@c
static void mp_get_arc_time (MP mp, mp_number *ret, mp_knot h, mp_number arc0_orig) {
mp_knot p, q; /* for traversing the path */
mp_number t_tot; /* accumulator for the result */
mp_number t; /* the result of |do_arc_test| */
mp_number arc, arc0; /* portion of |arc0| not used up so far */
mp_number arg1, arg2, arg3, arg4, arg5, arg6; /* |do_arc_test| arguments */
if (number_negative(arc0_orig)) {
@<Deal with a negative |arc0_orig| value and |return|@>;
}
new_number (t_tot);
new_number (arc0);
number_clone(arc0, arc0_orig);
if (number_infinite(arc0)) {
number_add_scaled (arc0, -1);
}
new_number (arc);
number_clone(arc, arc0);
p = h;
new_number (arg1);
new_number (arg2);
new_number (arg3);
new_number (arg4);
new_number (arg5);
new_number (arg6);
new_number (t);
while ((mp_right_type (p) != mp_endpoint) && number_positive(arc)) {
q = mp_next_knot (p);
set_number_from_substraction(arg1, p->right_x, p->x_coord);
set_number_from_substraction(arg2, p->right_y, p->y_coord);
set_number_from_substraction(arg3, q->left_x, p->right_x);
set_number_from_substraction(arg4, q->left_y, p->right_y);
set_number_from_substraction(arg5, q->x_coord, q->left_x);
set_number_from_substraction(arg6, q->y_coord, q->left_y);
mp_do_arc_test (mp, &t, arg1, arg2, arg3, arg4, arg5, arg6, arc);
@<Update |arc| and |t_tot| after |do_arc_test| has just returned |t|@>;
if (q == h) {
@<Update |t_tot| and |arc| to avoid going around the cyclic
path too many times but set |arith_error:=true| and |goto done| on
overflow@>;
}
p = q;
}
check_arith();
number_clone (*ret, t_tot);
RETURN:
free_number (t_tot);
free_number (t);
free_number (arc);
free_number (arc0);
free_number (arg1);
free_number (arg2);
free_number (arg3);
free_number (arg4);
free_number (arg5);
free_number (arg6);
}
@ @<Update |arc| and |t_tot| after |do_arc_test| has just returned |t|@>=
if (number_negative(t)) {
number_add (t_tot, t);
number_add (t_tot, two_t);
set_number_to_zero(arc);
} else {
number_add (t_tot, unity_t);
number_substract(arc, t);
}
@ @<Deal with a negative |arc0_orig| value and |return|@>=
{
if (mp_left_type (h) == mp_endpoint) {
set_number_to_zero (*ret);
} else {
mp_number neg_arc0;
p = mp_htap_ypoc (mp, h);
new_number(neg_arc0);
number_clone(neg_arc0, arc0_orig);
number_negate(neg_arc0);
mp_get_arc_time (mp, ret, p, neg_arc0);
number_negate(*ret);
mp_toss_knot_list (mp, p);
free_number (neg_arc0);
}
check_arith();
return;
}
@ @<Update |t_tot| and |arc| to avoid going around the cyclic...@>=
if (number_positive(arc)) {
mp_number n, n1, d1, v1;
new_number (n);
new_number (n1);
new_number (d1);
new_number (v1);
set_number_from_substraction (d1, arc0, arc); /* d1 = arc0 - arc */
set_number_from_div (n1, arc, d1); /* n1 = (arc / d1) */
number_clone (n, n1);
set_number_from_mul (n1, n1, d1); /* n1 = (n1 * d1) */
number_substract (arc, n1); /* arc = arc - n1 */
number_clone (d1, inf_t); /* reuse d1 */
number_clone (v1, n); /* v1 = n */
number_add (v1, epsilon_t); /* v1 = n1+1 */
set_number_from_div (d1, d1, v1); /* |d1 = EL_GORDO / v1| */
if (number_greater (t_tot, d1)) {
mp->arith_error = true;
check_arith();
set_number_to_inf(*ret);
free_number (n);
free_number (n1);
free_number (d1);
free_number (v1);
goto RETURN;
}
set_number_from_mul (t_tot, t_tot, v1);
free_number (n);
free_number (n1);
free_number (d1);
free_number (v1);
}
@* Data structures for pens.
A Pen in \MP\ can be either elliptical or polygonal. Elliptical pens result
in \ps\ \&{stroke} commands, while anything drawn with a polygonal pen is
@:stroke}{\&{stroke} command@>
converted into an area fill as described in the next part of this program.
The mathematics behind this process is based on simple aspects of the theory
of tracings developed by Leo Guibas, Lyle Ramshaw, and Jorge Stolfi
[``A kinematic framework for computational geometry,'' Proc.\ IEEE Symp.\
Foundations of Computer Science {\bf 24} (1983), 100--111].
Polygonal pens are created from paths via \MP's \&{makepen} primitive.
@:makepen_}{\&{makepen} primitive@>
This path representation is almost sufficient for our purposes except that
a pen path should always be a convex polygon with the vertices in
counter-clockwise order.
Since we will need to scan pen polygons both forward and backward, a pen
should be represented as a doubly linked ring of knot nodes. There is
room for the extra back pointer because we do not need the
|mp_left_type| or |mp_right_type| fields. In fact, we don't need the |left_x|,
|left_y|, |right_x|, or |right_y| fields either but we leave these alone
so that certain procedures can operate on both pens and paths. In particular,
pens can be copied using |copy_path| and recycled using |toss_knot_list|.
@ The |make_pen| procedure turns a path into a pen by initializing
the |prev_knot| pointers and making sure the knots form a convex polygon.
Thus each cubic in the given path becomes a straight line and the control
points are ignored. If the path is not cyclic, the ends are connected by a
straight line.
@d copy_pen(A) mp_make_pen(mp, mp_copy_path(mp, (A)),false)
@c
static mp_knot mp_make_pen (MP mp, mp_knot h, boolean need_hull) {
mp_knot p, q; /* two consecutive knots */
q = h;
do {
p = q;
q = mp_next_knot (q);
mp_prev_knot (q) = p;
} while (q != h);
if (need_hull) {
h = mp_convex_hull (mp, h);
@<Make sure |h| isn't confused with an elliptical pen@>;
}
return h;
}
@ The only information required about an elliptical pen is the overall
transformation that has been applied to the original \&{pencircle}.
@:pencircle_}{\&{pencircle} primitive@>
Since it suffices to keep track of how the three points $(0,0)$, $(1,0)$,
and $(0,1)$ are transformed, an elliptical pen can be stored in a single
knot node and transformed as if it were a path.
@d pen_is_elliptical(A) ((A)==mp_next_knot((A)))
@c
static mp_knot mp_get_pen_circle (MP mp, mp_number diam) {
mp_knot h; /* the knot node to return */
h = mp_new_knot (mp);
mp_next_knot (h) = h;
mp_prev_knot (h) = h;
mp_originator (h) = mp_program_code;
set_number_to_zero(h->x_coord);
set_number_to_zero(h->y_coord);
number_clone(h->left_x, diam);
set_number_to_zero(h->left_y);
set_number_to_zero(h->right_x);
number_clone(h->right_y, diam);
return h;
}
@ If the polygon being returned by |make_pen| has only one vertex, it will
be interpreted as an elliptical pen. This is no problem since a degenerate
polygon can equally well be thought of as a degenerate ellipse. We need only
initialize the |left_x|, |left_y|, |right_x|, and |right_y| fields.
@<Make sure |h| isn't confused with an elliptical pen@>=
if (pen_is_elliptical (h)) {
number_clone(h->left_x, h->x_coord);
number_clone(h->left_y, h->y_coord);
number_clone(h->right_x, h->x_coord);
number_clone(h->right_y, h->y_coord);
}
@ Printing a polygonal pen is very much like printing a path
@<Declarations@>=
static void mp_pr_pen (MP mp, mp_knot h);
@ @c
void mp_pr_pen (MP mp, mp_knot h) {
mp_knot p, q; /* for list traversal */
if (pen_is_elliptical (h)) {
@<Print the elliptical pen |h|@>;
} else {
p = h;
do {
mp_print_two (mp, p->x_coord, p->y_coord);
mp_print_nl (mp, " .. ");
@<Advance |p| making sure the links are OK and |return| if there is
a problem@>;
} while (p != h);
mp_print (mp, "cycle");
}
}
@ @<Advance |p| making sure the links are OK and |return| if there is...@>=
q = mp_next_knot (p);
if ((q == NULL) || (mp_prev_knot (q) != p)) {
mp_print_nl (mp, "???");
return; /* this won't happen */
@.???@>
}
p = q
@ @<Print the elliptical pen |h|@>=
{
mp_number v1;
new_number (v1);
mp_print (mp, "pencircle transformed (");
print_number (h->x_coord);
mp_print_char (mp, xord (','));
print_number (h->y_coord);
mp_print_char (mp, xord (','));
set_number_from_substraction (v1, h->left_x, h->x_coord);
print_number (v1);
mp_print_char (mp, xord (','));
set_number_from_substraction (v1, h->right_x, h->x_coord);
print_number (v1);
mp_print_char (mp, xord (','));
set_number_from_substraction (v1, h->left_y, h->y_coord);
print_number (v1);
mp_print_char (mp, xord (','));
set_number_from_substraction (v1, h->right_y, h->y_coord);
print_number (v1);
mp_print_char (mp, xord (')'));
free_number (v1);
}
@ Here us another version of |pr_pen| that prints the pen as a diagnostic
message.
@<Declarations@>=
static void mp_print_pen (MP mp, mp_knot h, const char *s, boolean nuline);
@ @c
void mp_print_pen (MP mp, mp_knot h, const char *s, boolean nuline) {
mp_print_diagnostic (mp, "Pen", s, nuline);
mp_print_ln (mp);
@.Pen at line...@>;
mp_pr_pen (mp, h);
mp_end_diagnostic (mp, true);
}
@ Making a polygonal pen into a path involves restoring the |mp_left_type| and
|mp_right_type| fields and setting the control points so as to make a polygonal
path.
@c
static void mp_make_path (MP mp, mp_knot h) {
mp_knot p; /* for traversing the knot list */
quarterword k; /* a loop counter */
@<Other local variables in |make_path|@>;
FUNCTION_TRACE1 ("make_path()\n");
if (pen_is_elliptical (h)) {
FUNCTION_TRACE1 ("make_path(elliptical)\n");
@<Make the elliptical pen |h| into a path@>;
} else {
p = h;
do {
mp_left_type (p) = mp_explicit;
mp_right_type (p) = mp_explicit;
@<copy the coordinates of knot |p| into its control points@>;
p = mp_next_knot (p);
} while (p != h);
}
}
@ @<copy the coordinates of knot |p| into its control points@>=
number_clone (p->left_x, p->x_coord);
number_clone (p->left_y, p->y_coord);
number_clone (p->right_x, p->x_coord);
number_clone (p->right_y, p->y_coord)
@ We need an eight knot path to get a good approximation to an ellipse.
@<Make the elliptical pen |h| into a path@>=
{
mp_number center_x, center_y; /* translation parameters for an elliptical pen */
mp_number width_x, width_y; /* the effect of a unit change in $x$ */
mp_number height_x, height_y; /* the effect of a unit change in $y$ */
mp_number dx, dy; /* the vector from knot |p| to its right control point */
new_number (center_x);
new_number (center_y);
new_number (width_x);
new_number (width_y);
new_number (height_x);
new_number (height_y);
new_number (dx);
new_number (dy);
@<Extract the transformation parameters from the elliptical pen~|h|@>;
p = h;
for (k = 0; k <= 7; k++) {
@<Initialize |p| as the |k|th knot of a circle of unit diameter,
transforming it appropriately@>;
if (k == 7)
mp_next_knot (p) = h;
else
mp_next_knot (p) = mp_new_knot (mp);
p = mp_next_knot (p);
}
free_number (dx);
free_number (dy);
free_number (center_x);
free_number (center_y);
free_number (width_x);
free_number (width_y);
free_number (height_x);
free_number (height_y);
}
@ @<Extract the transformation parameters from the elliptical pen~|h|@>=
number_clone (center_x, h->x_coord);
number_clone (center_y, h->y_coord);
set_number_from_substraction (width_x, h->left_x, center_x);
set_number_from_substraction (width_y, h->left_y, center_y);
set_number_from_substraction (height_x, h->right_x, center_x);
set_number_from_substraction (height_y, h->right_y, center_y);
@ @<Other local variables in |make_path|@>=
integer kk;
/* |k| advanced $270^\circ$ around the ring (cf. $\sin\theta=\cos(\theta+270)$) */
@ The only tricky thing here are the tables |half_cos| and |d_cos| used to
find the point $k/8$ of the way around the circle and the direction vector
to use there.
@<Initialize |p| as the |k|th knot of a circle of unit diameter,...@>=
kk = (k + 6) % 8;
{
mp_number r1, r2;
new_fraction (r1);
new_fraction (r2);
take_fraction (r1, mp->half_cos[k], width_x);
take_fraction (r2, mp->half_cos[kk], height_x);
number_add (r1, r2);
set_number_from_addition (p->x_coord, center_x, r1);
take_fraction (r1, mp->half_cos[k], width_y);
take_fraction (r2, mp->half_cos[kk], height_y);
number_add (r1, r2);
set_number_from_addition (p->y_coord, center_y, r1);
take_fraction (r1, mp->d_cos[kk], width_x);
take_fraction (r2, mp->d_cos[k], height_x);
number_clone (dx, r1);
number_negate (dx);
number_add (dx, r2);
take_fraction (r1, mp->d_cos[kk], width_y);
take_fraction (r2, mp->d_cos[k], height_y);
number_clone (dy, r1);
number_negate (dy);
number_add (dy, r2);
set_number_from_addition (p->right_x, p->x_coord, dx);
set_number_from_addition (p->right_y, p->y_coord, dy);
set_number_from_substraction (p->left_x, p->x_coord, dx);
set_number_from_substraction (p->left_y, p->y_coord, dy);
free_number (r1);
free_number (r2);
}
mp_left_type (p) = mp_explicit;
mp_right_type (p) = mp_explicit;
mp_originator (p) = mp_program_code
@ @<Glob...@>=
mp_number half_cos[8]; /* ${1\over2}\cos(45k)$ */
mp_number d_cos[8]; /* a magic constant times $\cos(45k)$ */
@ The magic constant for |d_cos| is the distance between $({1\over2},0)$ and
$({1\over4}\sqrt2,{1\over4}\sqrt2)$ times the result of the |velocity|
function for $\theta=\phi=22.5^\circ$. This comes out to be
$$ d = {\sqrt{2-\sqrt2}\over 3+3\cos22.5^\circ}
\approx 0.132608244919772.
$$
@<Set init...@>=
for (k = 0; k <= 7; k++) {
new_fraction (mp->half_cos[k]);
new_fraction (mp->d_cos[k]);
}
number_clone (mp->half_cos[0], fraction_half_t);
number_clone (mp->half_cos[1], twentysixbits_sqrt2_t);
number_clone (mp->half_cos[2], zero_t);
number_clone (mp->d_cos[0], twentyeightbits_d_t);
number_clone (mp->d_cos[1], twentysevenbits_sqrt2_d_t);
number_clone (mp->d_cos[2], zero_t);
for (k = 3; k <= 4; k++) {
number_clone (mp->half_cos[k], mp->half_cos[4 - k]);
number_negate (mp->half_cos[k]);
number_clone (mp->d_cos[k], mp->d_cos[4 - k]);
number_negate (mp->d_cos[k]);
}
for (k = 5; k <= 7; k++) {
number_clone (mp->half_cos[k], mp->half_cos[8 - k]);
number_clone (mp->d_cos[k], mp->d_cos[8 - k]);
}
@ @<Dealloc...@>=
for (k = 0; k <= 7; k++) {
free_number (mp->half_cos[k]);
free_number (mp->d_cos[k]);
}
@ The |convex_hull| function forces a pen polygon to be convex when it is
returned by |make_pen| and after any subsequent transformation where rounding
error might allow the convexity to be lost.
The convex hull algorithm used here is described by F.~P. Preparata and
M.~I. Shamos [{\sl Computational Geometry}, Springer-Verlag, 1985].
@<Declarations@>=
static mp_knot mp_convex_hull (MP mp, mp_knot h);
@ @c
mp_knot mp_convex_hull (MP mp, mp_knot h) { /* Make a polygonal pen convex */
mp_knot l, r; /* the leftmost and rightmost knots */
mp_knot p, q; /* knots being scanned */
mp_knot s; /* the starting point for an upcoming scan */
mp_number dx, dy; /* a temporary pointer */
mp_knot ret;
new_number (dx);
new_number (dy);
if (pen_is_elliptical (h)) {
ret = h;
} else {
@<Set |l| to the leftmost knot in polygon~|h|@>;
@<Set |r| to the rightmost knot in polygon~|h|@>;
if (l != r) {
s = mp_next_knot (r);
@<Find any knots on the path from |l| to |r| above the |l|-|r| line and
move them past~|r|@>;
@<Find any knots on the path from |s| to |l| below the |l|-|r| line and
move them past~|l|@>;
@<Sort the path from |l| to |r| by increasing $x$@>;
@<Sort the path from |r| to |l| by decreasing $x$@>;
}
if (l != mp_next_knot (l)) {
@<Do a Gramm scan and remove vertices where there is no left turn@>;
}
ret = l;
}
free_number (dx);
free_number (dy);
return ret;
}
@ All comparisons are done primarily on $x$ and secondarily on $y$.
@<Set |l| to the leftmost knot in polygon~|h|@>=
l = h;
p = mp_next_knot (h);
while (p != h) {
if (number_lessequal (p->x_coord, l->x_coord))
if ((number_less (p->x_coord, l->x_coord)) ||
(number_less (p->y_coord, l->y_coord)))
l = p;
p = mp_next_knot (p);
}
@ @<Set |r| to the rightmost knot in polygon~|h|@>=
r = h;
p = mp_next_knot (h);
while (p != h) {
if (number_greaterequal(p->x_coord, r->x_coord))
if (number_greater (p->x_coord, r->x_coord) ||
number_greater (p->y_coord, r->y_coord))
r = p;
p = mp_next_knot (p);
}
@ @<Find any knots on the path from |l| to |r| above the |l|-|r| line...@>=
{
mp_number ab_vs_cd;
mp_number arg1, arg2;
new_number (arg1);
new_number (arg2);
new_number (ab_vs_cd);
set_number_from_substraction (dx, r->x_coord, l->x_coord);
set_number_from_substraction (dy, r->y_coord, l->y_coord);
p = mp_next_knot (l);
while (p != r) {
q = mp_next_knot (p);
set_number_from_substraction (arg1, p->y_coord, l->y_coord);
set_number_from_substraction (arg2, p->x_coord, l->x_coord);
ab_vs_cd (ab_vs_cd, dx, arg1, dy, arg2);
if (number_positive(ab_vs_cd))
mp_move_knot (mp, p, r);
p = q;
}
free_number (ab_vs_cd);
free_number (arg1);
free_number (arg2);
}
@ The |move_knot| procedure removes |p| from a doubly linked list and inserts
it after |q|.
@ @<Declarations@>=
static void mp_move_knot (MP mp, mp_knot p, mp_knot q);
@ @c
void mp_move_knot (MP mp, mp_knot p, mp_knot q) {
(void) mp;
mp_next_knot (mp_prev_knot (p)) = mp_next_knot (p);
mp_prev_knot (mp_next_knot (p)) = mp_prev_knot (p);
mp_prev_knot (p) = q;
mp_next_knot (p) = mp_next_knot (q);
mp_next_knot (q) = p;
mp_prev_knot (mp_next_knot (p)) = p;
}
@ @<Find any knots on the path from |s| to |l| below the |l|-|r| line...@>=
{
mp_number ab_vs_cd;
mp_number arg1, arg2;
new_number (ab_vs_cd);
new_number (arg1);
new_number (arg2);
p = s;
while (p != l) {
q = mp_next_knot (p);
set_number_from_substraction (arg1, p->y_coord, l->y_coord);
set_number_from_substraction (arg2, p->x_coord, l->x_coord);
ab_vs_cd (ab_vs_cd, dx, arg1, dy, arg2);
if (number_negative(ab_vs_cd))
mp_move_knot (mp, p, l);
p = q;
}
free_number (ab_vs_cd);
free_number (arg1);
free_number (arg2);
}
@ The list is likely to be in order already so we just do linear insertions.
Secondary comparisons on $y$ ensure that the sort is consistent with the
choice of |l| and |r|.
@<Sort the path from |l| to |r| by increasing $x$@>=
p = mp_next_knot (l);
while (p != r) {
q = mp_prev_knot (p);
while (number_greater(q->x_coord, p->x_coord))
q = mp_prev_knot (q);
while (number_equal(q->x_coord, p->x_coord)) {
if (number_greater(q->y_coord, p->y_coord))
q = mp_prev_knot (q);
else
break;
}
if (q == mp_prev_knot (p)) {
p = mp_next_knot (p);
} else {
p = mp_next_knot (p);
mp_move_knot (mp, mp_prev_knot (p), q);
}
}
@ @<Sort the path from |r| to |l| by decreasing $x$@>=
p = mp_next_knot (r);
while (p != l) {
q = mp_prev_knot (p);
while (number_less(q->x_coord, p->x_coord))
q = mp_prev_knot (q);
while (number_equal(q->x_coord, p->x_coord)) {
if (number_less (q->y_coord, p->y_coord))
q = mp_prev_knot (q);
else
break;
}
if (q == mp_prev_knot (p)) {
p = mp_next_knot (p);
} else {
p = mp_next_knot (p);
mp_move_knot (mp, mp_prev_knot (p), q);
}
}
@ The condition involving |ab_vs_cd| tests if there is not a left turn
at knot |q|. There usually will be a left turn so we streamline the case
where the |then| clause is not executed.
@<Do a Gramm scan and remove vertices where there...@>=
{
mp_number ab_vs_cd;
mp_number arg1, arg2;
new_number (arg1);
new_number (arg2);
new_number (ab_vs_cd);
p = l;
q = mp_next_knot (l);
while (1) {
set_number_from_substraction (dx, q->x_coord, p->x_coord);
set_number_from_substraction (dy, q->y_coord, p->y_coord);
p = q;
q = mp_next_knot (q);
if (p == l)
break;
if (p != r) {
set_number_from_substraction (arg1, q->y_coord, p->y_coord);
set_number_from_substraction (arg2, q->x_coord, p->x_coord);
ab_vs_cd (ab_vs_cd, dx, arg1, dy, arg2);
if (number_nonpositive(ab_vs_cd)) {
@<Remove knot |p| and back up |p| and |q| but don't go past |l|@>;
}
}
}
free_number (ab_vs_cd);
free_number (arg1);
free_number (arg2);
}
@ @<Remove knot |p| and back up |p| and |q| but don't go past |l|@>=
{
s = mp_prev_knot (p);
mp_xfree (p);
mp_next_knot (s) = q;
mp_prev_knot (q) = s;
if (s == l) {
p = s;
} else {
p = mp_prev_knot (s);
q = s;
}
}
@ The |find_offset| procedure sets global variables |(cur_x,cur_y)| to the
offset associated with the given direction |(x,y)|. If two different offsets
apply, it chooses one of them.
@c
static void mp_find_offset (MP mp, mp_number x_orig, mp_number y_orig, mp_knot h) {
mp_knot p, q; /* consecutive knots */
if (pen_is_elliptical (h)) {
mp_fraction xx, yy; /* untransformed offset for an elliptical pen */
mp_number wx, wy, hx, hy; /* the transformation matrix for an elliptical pen */
mp_fraction d; /* a temporary register */
new_fraction(xx);
new_fraction(yy);
new_number(wx);
new_number(wy);
new_number(hx);
new_number(hy);
new_fraction(d);
@<Find the offset for |(x,y)| on the elliptical pen~|h|@>
free_number (xx);
free_number (yy);
free_number (wx);
free_number (wy);
free_number (hx);
free_number (hy);
free_number (d);
} else {
mp_number ab_vs_cd;
mp_number arg1, arg2;
new_number (arg1);
new_number (arg2);
new_number (ab_vs_cd);
q = h;
do {
p = q;
q = mp_next_knot (q);
set_number_from_substraction (arg1, q->x_coord, p->x_coord);
set_number_from_substraction (arg2, q->y_coord, p->y_coord);
ab_vs_cd (ab_vs_cd, arg1, y_orig, arg2, x_orig);
} while (number_negative(ab_vs_cd));
do {
p = q;
q = mp_next_knot (q);
set_number_from_substraction (arg1, q->x_coord, p->x_coord);
set_number_from_substraction (arg2, q->y_coord, p->y_coord);
ab_vs_cd (ab_vs_cd, arg1, y_orig, arg2, x_orig);
} while (number_positive(ab_vs_cd));
number_clone (mp->cur_x, p->x_coord);
number_clone (mp->cur_y, p->y_coord);
free_number (ab_vs_cd);
free_number (arg1);
free_number (arg2);
}
}
@ @<Glob...@>=
mp_number cur_x;
mp_number cur_y; /* all-purpose return value registers */
@ @<Initialize table entries@>=
new_number (mp->cur_x);
new_number (mp->cur_y);
@ @<Dealloc...@>=
free_number (mp->cur_x);
free_number (mp->cur_y);
@ @<Find the offset for |(x,y)| on the elliptical pen~|h|@>=
if (number_zero(x_orig) && number_zero(y_orig)) {
number_clone(mp->cur_x, h->x_coord);
number_clone(mp->cur_y, h->y_coord);
} else {
mp_number x, y, abs_x, abs_y;
new_number(x);
new_number(y);
new_number(abs_x);
new_number(abs_y);
number_clone(x, x_orig);
number_clone(y, y_orig);
@<Find the non-constant part of the transformation for |h|@>;
number_clone(abs_x, x);
number_clone(abs_y, y);
number_abs(abs_x);
number_abs(abs_y);
while (number_less(abs_x, fraction_half_t) && number_less(abs_y, fraction_half_t)) {
number_double(x);
number_double(y);
number_clone(abs_x, x);
number_clone(abs_y, y);
number_abs(abs_x);
number_abs(abs_y);
}
@<Make |(xx,yy)| the offset on the untransformed \&{pencircle} for the
untransformed version of |(x,y)|@>;
{
mp_number r1, r2;
new_fraction (r1);
new_fraction (r2);
take_fraction (r1, xx, wx);
take_fraction (r2, yy, hx);
number_add(r1, r2);
set_number_from_addition(mp->cur_x, h->x_coord, r1);
take_fraction (r1, xx, wy);
take_fraction (r2, yy, hy);
number_add(r1, r2);
set_number_from_addition(mp->cur_y, h->y_coord, r1);
free_number (r1);
free_number (r2);
}
free_number(abs_x);
free_number(abs_y);
free_number(x);
free_number(y);
}
@ @<Find the non-constant part of the transformation for |h|@>=
{
set_number_from_substraction(wx, h->left_x, h->x_coord);
set_number_from_substraction(wy, h->left_y, h->y_coord);
set_number_from_substraction(hx, h->right_x, h->x_coord);
set_number_from_substraction(hy, h->right_y, h->y_coord);
}
@ @<Make |(xx,yy)| the offset on the untransformed \&{pencircle} for the...@>=
{
mp_number r1, r2, arg1;
new_number (arg1);
new_fraction (r1);
new_fraction (r2);
take_fraction (r1, x, hy);
number_clone (arg1, hx);
number_negate (arg1);
take_fraction (r2, y, arg1);
number_add (r1, r2);
number_negate (r1);
number_clone(yy, r1);
number_clone (arg1, wy);
number_negate (arg1);
take_fraction (r1, x, arg1);
take_fraction (r2, y, wx);
number_add (r1, r2);
number_clone(xx, r1);
free_number (arg1);
free_number (r1);
free_number (r2);
}
pyth_add (d, xx, yy);
if (number_positive(d)) {
mp_number ret;
new_fraction (ret);
make_fraction (ret, xx, d);
number_half(ret);
number_clone(xx, ret);
make_fraction (ret, yy, d);
number_half(ret);
number_clone(yy, ret);
free_number (ret);
}
@ Finding the bounding box of a pen is easy except if the pen is elliptical.
But we can handle that case by just calling |find_offset| twice. The answer
is stored in the global variables |minx|, |maxx|, |miny|, and |maxy|.
@c
static void mp_pen_bbox (MP mp, mp_knot h) {
mp_knot p; /* for scanning the knot list */
if (pen_is_elliptical (h)) {
@<Find the bounding box of an elliptical pen@>;
} else {
number_clone (mp_minx, h->x_coord);
number_clone (mp_maxx, mp_minx);
number_clone (mp_miny, h->y_coord);
number_clone (mp_maxy, mp_miny);
p = mp_next_knot (h);
while (p != h) {
if (number_less (p->x_coord, mp_minx))
number_clone (mp_minx, p->x_coord);
if (number_less (p->y_coord, mp_miny))
number_clone (mp_miny, p->y_coord);
if (number_greater (p->x_coord, mp_maxx))
number_clone (mp_maxx, p->x_coord);
if (number_greater (p->y_coord, mp_maxy))
number_clone (mp_maxy, p->y_coord);
p = mp_next_knot (p);
}
}
}
@ @<Find the bounding box of an elliptical pen@>=
{
mp_number arg1, arg2;
new_number(arg1);
new_fraction (arg2);
number_clone(arg2, fraction_one_t);
mp_find_offset (mp, arg1, arg2, h);
number_clone (mp_maxx, mp->cur_x);
number_clone (mp_minx, h->x_coord);
number_double (mp_minx);
number_substract (mp_minx, mp->cur_x);
number_negate (arg2);
mp_find_offset (mp, arg2, arg1, h);
number_clone (mp_maxy, mp->cur_y);
number_clone (mp_miny, h->y_coord);
number_double (mp_miny);
number_substract (mp_miny, mp->cur_y);
free_number(arg1);
free_number(arg2);
}
@* Numerical values.
This first set goes into the header
@<MPlib internal header stuff@>=
#define mp_fraction mp_number
#define mp_angle mp_number
#define new_number(A) (((math_data *)(mp->math))->allocate)(mp, &(A), mp_scaled_type)
#define new_fraction(A) (((math_data *)(mp->math))->allocate)(mp, &(A), mp_fraction_type)
#define new_angle(A) (((math_data *)(mp->math))->allocate)(mp, &(A), mp_angle_type)
#define free_number(A) (((math_data *)(mp->math))->free)(mp, &(A))
@
@d set_precision() (((math_data *)(mp->math))->set_precision)(mp)
@d free_math() (((math_data *)(mp->math))->free_math)(mp)
@d scan_numeric_token(A) (((math_data *)(mp->math))->scan_numeric)(mp, A)
@d scan_fractional_token(A) (((math_data *)(mp->math))->scan_fractional)(mp, A)
@d set_number_from_of_the_way(A,t,B,C) (((math_data *)(mp->math))->from_oftheway)(mp, &(A),t,B,C)
@d set_number_from_int(A,B) (((math_data *)(mp->math))->from_int)(&(A),B)
@d set_number_from_scaled(A,B) (((math_data *)(mp->math))->from_scaled)(&(A),B)
@d set_number_from_boolean(A,B) (((math_data *)(mp->math))->from_boolean)(&(A),B)
@d set_number_from_double(A,B) (((math_data *)(mp->math))->from_double)(&(A),B)
@d set_number_from_addition(A,B,C) (((math_data *)(mp->math))->from_addition)(&(A),B,C)
@d set_number_from_substraction(A,B,C) (((math_data *)(mp->math))->from_substraction)(&(A),B,C)
@d set_number_from_div(A,B,C) (((math_data *)(mp->math))->from_div)(&(A),B,C)
@d set_number_from_mul(A,B,C) (((math_data *)(mp->math))->from_mul)(&(A),B,C)
@d number_int_div(A,C) (((math_data *)(mp->math))->from_int_div)(&(A),A,C)
@d set_number_from_int_mul(A,B,C) (((math_data *)(mp->math))->from_int_mul)(&(A),B,C)
@#
@d set_number_to_unity(A) (((math_data *)(mp->math))->clone)(&(A), unity_t)
@d set_number_to_zero(A) (((math_data *)(mp->math))->clone)(&(A), zero_t)
@d set_number_to_inf(A) (((math_data *)(mp->math))->clone)(&(A), inf_t)
@d set_number_to_neg_inf(A) do { set_number_to_inf(A); number_negate (A); } while (0)
@#
@d init_randoms(A) (((math_data *)(mp->math))->init_randoms)(mp,A)
@d print_number(A) (((math_data *)(mp->math))->print)(mp,A)
@d number_tostring(A) (((math_data *)(mp->math))->tostring)(mp,A)
@d make_scaled(R,A,B) (((math_data *)(mp->math))->make_scaled)(mp,&(R),A,B)
@d take_scaled(R,A,B) (((math_data *)(mp->math))->take_scaled)(mp,&(R),A,B)
@d make_fraction(R,A,B) (((math_data *)(mp->math))->make_fraction)(mp,&(R),A,B)
@d take_fraction(R,A,B) (((math_data *)(mp->math))->take_fraction)(mp,&(R),A,B)
@d pyth_add(R,A,B) (((math_data *)(mp->math))->pyth_add)(mp,&(R),A,B)
@d pyth_sub(R,A,B) (((math_data *)(mp->math))->pyth_sub)(mp,&(R),A,B)
@d n_arg(R,A,B) (((math_data *)(mp->math))->n_arg)(mp,&(R),A,B)
@d m_log(R,A) (((math_data *)(mp->math))->m_log)(mp,&(R),A)
@d m_exp(R,A) (((math_data *)(mp->math))->m_exp)(mp,&(R),A)
@d m_unif_rand(R,A) (((math_data *)(mp->math))->m_unif_rand)(mp,&(R),A)
@d m_norm_rand(R) (((math_data *)(mp->math))->m_norm_rand)(mp,&(R))
@d velocity(R,A,B,C,D,E) (((math_data *)(mp->math))->velocity)(mp,&(R),A,B,C,D,E)
@d ab_vs_cd(R,A,B,C,D) (((math_data *)(mp->math))->ab_vs_cd)(mp,&(R),A,B,C,D)
@d crossing_point(R,A,B,C) (((math_data *)(mp->math))->crossing_point)(mp,&(R),A,B,C)
@d n_sin_cos(A,S,C) (((math_data *)(mp->math))->sin_cos)(mp,A,&(S),&(C))
@d square_rt(A,S) (((math_data *)(mp->math))->sqrt)(mp,&(A),S)
@d slow_add(R,A,B) (((math_data *)(mp->math))->slow_add)(mp,&(R),A,B)
@d round_unscaled(A) (((math_data *)(mp->math))->round_unscaled)(A)
@d floor_scaled(A) (((math_data *)(mp->math))->floor_scaled)(&(A))
@d fraction_to_round_scaled(A) (((math_data *)(mp->math))->fraction_to_round_scaled)(&(A))
@d number_to_int(A) (((math_data *)(mp->math))->to_int)(A)
@d number_to_boolean(A) (((math_data *)(mp->math))->to_boolean)(A)
@d number_to_scaled(A) (((math_data *)(mp->math))->to_scaled)(A)
@d number_to_double(A) (((math_data *)(mp->math))->to_double)(A)
@d number_negate(A) (((math_data *)(mp->math))->negate)(&(A))
@d number_add(A,B) (((math_data *)(mp->math))->add)(&(A),B)
@d number_substract(A,B) (((math_data *)(mp->math))->substract)(&(A),B)
@d number_half(A) (((math_data *)(mp->math))->half)(&(A))
@d number_halfp(A) (((math_data *)(mp->math))->halfp)(&(A))
@d number_double(A) (((math_data *)(mp->math))->do_double)(&(A))
@d number_add_scaled(A,B) (((math_data *)(mp->math))->add_scaled)(&(A),B)
@d number_multiply_int(A,B) (((math_data *)(mp->math))->multiply_int)(&(A),B)
@d number_divide_int(A,B) (((math_data *)(mp->math))->divide_int)(&(A),B)
@d number_abs(A) (((math_data *)(mp->math))->abs)(&(A))
@d number_modulo(A,B) (((math_data *)(mp->math))->modulo)(&(A), B)
@d number_nonequalabs(A,B) (((math_data *)(mp->math))->nonequalabs)(A,B)
@d number_odd(A) (((math_data *)(mp->math))->odd)(A)
@d number_equal(A,B) (((math_data *)(mp->math))->equal)(A,B)
@d number_greater(A,B) (((math_data *)(mp->math))->greater)(A,B)
@d number_less(A,B) (((math_data *)(mp->math))->less)(A,B)
@d number_clone(A,B) (((math_data *)(mp->math))->clone)(&(A),B)
@d number_swap(A,B) (((math_data *)(mp->math))->swap)(&(A),&(B));
@d convert_scaled_to_angle(A) (((math_data *)(mp->math))->scaled_to_angle)(&(A));
@d convert_angle_to_scaled(A) (((math_data *)(mp->math))->angle_to_scaled)(&(A));
@d convert_fraction_to_scaled(A) (((math_data *)(mp->math))->fraction_to_scaled)(&(A));
@d convert_scaled_to_fraction(A) (((math_data *)(mp->math))->scaled_to_fraction)(&(A));
@#
@d number_zero(A) number_equal(A, zero_t)
@d number_infinite(A) number_equal(A, inf_t)
@d number_unity(A) number_equal(A, unity_t)
@d number_negative(A) number_less(A, zero_t)
@d number_nonnegative(A) (!number_negative(A))
@d number_positive(A) number_greater(A, zero_t)
@d number_nonpositive(A) (!number_positive(A))
@d number_nonzero(A) (!number_zero(A))
@d number_greaterequal(A,B) (!number_less(A,B))
@d number_lessequal(A,B) (!number_greater(A,B))
@* Edge structures.
Now we come to \MP's internal scheme for representing pictures.
The representation is very different from \MF's edge structures
because \MP\ pictures contain \ps\ graphics objects instead of pixel
images. However, the basic idea is somewhat similar in that shapes
are represented via their boundaries.
The main purpose of edge structures is to keep track of graphical objects
until it is time to translate them into \ps. Since \MP\ does not need to
know anything about an edge structure other than how to translate it into
\ps\ and how to find its bounding box, edge structures can be just linked
lists of graphical objects. \MP\ has no easy way to determine whether
two such objects overlap, but it suffices to draw the first one first and
let the second one overwrite it if necessary.
@<MPlib header stuff@>=
enum mp_graphical_object_code {
@<Graphical object codes@>
mp_final_graphic
};
@ Let's consider the types of graphical objects one at a time.
First of all, a filled contour is represented by a eight-word node. The first
word contains |type| and |link| fields, and the next six words contain a
pointer to a cyclic path and the value to use for \ps' \&{currentrgbcolor}
parameter. If a pen is used for filling |pen_p|, |ljoin| and |miterlim|
give the relevant information.
@d mp_path_p(A) (A)->path_p_ /* a pointer to the path that needs filling */
@d mp_pen_p(A) (A)->pen_p_ /* a pointer to the pen to fill or stroke with */
@d mp_color_model(A) ((mp_fill_node)(A))->color_model_ /* the color model */
@d cyan red
@d grey red
@d magenta green
@d yellow blue
@d mp_pre_script(A) ((mp_fill_node)(A))->pre_script_
@d mp_post_script(A) ((mp_fill_node)(A))->post_script_
@<MPlib internal header stuff@>=
typedef struct mp_fill_node_data {
NODE_BODY;
halfword color_model_;
mp_number red;
mp_number green;
mp_number blue;
mp_number black;
mp_string pre_script_;
mp_string post_script_;
mp_knot path_p_;
mp_knot pen_p_;
unsigned char ljoin;
mp_number miterlim;
} mp_fill_node_data;
typedef struct mp_fill_node_data *mp_fill_node;
@ @<Graphical object codes@>=
mp_fill_code = 1,
@ Make a fill node for cyclic path |p| and color black.
@d fill_node_size sizeof(struct mp_fill_node_data)
@c
static mp_node mp_new_fill_node (MP mp, mp_knot p) {
mp_fill_node t = malloc_node (fill_node_size);
mp_type (t) = mp_fill_node_type;
mp_path_p (t) = p;
mp_pen_p (t) = NULL; /* |NULL| means don't use a pen */
new_number(t->red);
new_number(t->green);
new_number(t->blue);
new_number(t->black);
new_number(t->miterlim);
clear_color (t);
mp_color_model (t) = mp_uninitialized_model;
mp_pre_script (t) = NULL;
mp_post_script (t) = NULL;
/* Set the |ljoin| and |miterlim| fields in object |t| */
if (number_greater(internal_value (mp_linejoin), unity_t))
t->ljoin = 2;
else if (number_positive(internal_value (mp_linejoin)))
t->ljoin = 1;
else
t->ljoin = 0;
if (number_less(internal_value (mp_miterlimit), unity_t)) {
set_number_to_unity(t->miterlim);
} else {
number_clone(t->miterlim,internal_value (mp_miterlimit));
}
return (mp_node) t;
}
@ @c
static void mp_free_fill_node (MP mp, mp_fill_node p) {
mp_toss_knot_list (mp, mp_path_p (p));
if (mp_pen_p (p) != NULL)
mp_toss_knot_list (mp, mp_pen_p (p));
if (mp_pre_script (p) != NULL)
delete_str_ref (mp_pre_script (p));
if (mp_post_script (p) != NULL)
delete_str_ref (mp_post_script (p));
free_number(p->red);
free_number(p->green);
free_number(p->blue);
free_number(p->black);
free_number(p->miterlim);
mp_free_node (mp, (mp_node)p, fill_node_size);
}
@ A stroked path is represented by an eight-word node that is like a filled
contour node except that it contains the current \&{linecap} value, a scale
factor for the dash pattern, and a pointer that is non-NULL if the stroke
is to be dashed. The purpose of the scale factor is to allow a picture to
be transformed without touching the picture that |dash_p| points to.
@d mp_dash_p(A) ((mp_stroked_node)(A))->dash_p_ /* a pointer to the edge structure that gives the dash pattern */
@<MPlib internal header stuff@>=
typedef struct mp_stroked_node_data {
NODE_BODY;
halfword color_model_;
mp_number red;
mp_number green;
mp_number blue;
mp_number black;
mp_string pre_script_;
mp_string post_script_;
mp_knot path_p_;
mp_knot pen_p_;
unsigned char ljoin;
mp_number miterlim;
unsigned char lcap;
mp_node dash_p_;
mp_number dash_scale;
} mp_stroked_node_data;
typedef struct mp_stroked_node_data *mp_stroked_node;
@ @<Graphical object codes@>=
mp_stroked_code = 2,
@ Make a stroked node for path |p| with |mp_pen_p(p)| temporarily |NULL|.
@d stroked_node_size sizeof(struct mp_stroked_node_data)
@c
static mp_node mp_new_stroked_node (MP mp, mp_knot p) {
mp_stroked_node t = malloc_node (stroked_node_size);
mp_type (t) = mp_stroked_node_type;
mp_path_p (t) = p;
mp_pen_p (t) = NULL;
mp_dash_p (t) = NULL;
new_number(t->dash_scale);
set_number_to_unity(t->dash_scale);
new_number(t->red);
new_number(t->green);
new_number(t->blue);
new_number(t->black);
new_number(t->miterlim);
clear_color(t);
mp_pre_script (t) = NULL;
mp_post_script (t) = NULL;
/* Set the |ljoin| and |miterlim| fields in object |t| */
if (number_greater(internal_value (mp_linejoin), unity_t))
t->ljoin = 2;
else if (number_positive(internal_value (mp_linejoin)))
t->ljoin = 1;
else
t->ljoin = 0;
if (number_less(internal_value (mp_miterlimit), unity_t)) {
set_number_to_unity(t->miterlim);
} else {
number_clone(t->miterlim,internal_value (mp_miterlimit));
}
if (number_greater(internal_value (mp_linecap), unity_t))
t->lcap = 2;
else if (number_positive(internal_value (mp_linecap)))
t->lcap = 1;
else
t->lcap = 0;
return (mp_node) t;
}
@ @c
static mp_edge_header_node mp_free_stroked_node (MP mp, mp_stroked_node p) {
mp_edge_header_node e = NULL;
mp_toss_knot_list (mp, mp_path_p (p));
if (mp_pen_p (p) != NULL)
mp_toss_knot_list (mp, mp_pen_p (p));
if (mp_pre_script (p) != NULL)
delete_str_ref (mp_pre_script (p));
if (mp_post_script (p) != NULL)
delete_str_ref (mp_post_script (p));
e = (mp_edge_header_node)mp_dash_p (p);
free_number(p->dash_scale);
free_number(p->red);
free_number(p->green);
free_number(p->blue);
free_number(p->black);
free_number(p->miterlim);
mp_free_node (mp, (mp_node)p, stroked_node_size);
return e;
}
@ When a dashed line is computed in a transformed coordinate system, the dash
lengths get scaled like the pen shape and we need to compensate for this. Since
there is no unique scale factor for an arbitrary transformation, we use the
the square root of the determinant. The properties of the determinant make it
easier to maintain the |dash_scale|. The computation is fairly straight-forward
except for the initialization of the scale factor |s|. The factor of 64 is
needed because |square_rt| scales its result by $2^8$ while we need $2^{14}$
to counteract the effect of |take_fraction|.
@ @c
void mp_sqrt_det (MP mp, mp_number *ret, mp_number a_orig, mp_number b_orig, mp_number c_orig, mp_number d_orig) {
mp_number a,b,c,d;
mp_number maxabs; /* $max(|a|,|b|,|c|,|d|)$ */
unsigned s; /* amount by which the result of |square_rt| needs to be scaled */
new_number(a);
new_number(b);
new_number(c);
new_number(d);
new_number(maxabs);
number_clone(a, a_orig);
number_clone(b, b_orig);
number_clone(c, c_orig);
number_clone(d, d_orig);
/* Initialize |maxabs| */
{
mp_number tmp;
new_number (tmp);
number_clone(maxabs, a);
number_abs(maxabs);
number_clone(tmp, b);
number_abs(tmp);
if (number_greater(tmp, maxabs))
number_clone(maxabs, tmp);
number_clone(tmp, c);
number_abs(tmp);
if (number_greater(tmp, maxabs))
number_clone(maxabs, tmp);
number_clone(tmp, d);
number_abs(tmp);
if (number_greater(tmp, maxabs))
number_clone(maxabs, tmp);
free_number(tmp);
}
s = 64;
while ((number_less(maxabs, fraction_one_t)) && (s > 1)) {
number_double(a);
number_double(b);
number_double(c);
number_double(d);
number_double(maxabs);
s = s/2;
}
{
mp_number r1, r2;
new_fraction (r1);
new_fraction (r2);
take_fraction (r1, a, d);
take_fraction (r2, b, c);
number_substract (r1, r2);
number_abs (r1);
square_rt(*ret, r1);
number_multiply_int(*ret, s);
free_number (r1);
free_number (r2);
}
free_number(a);
free_number(b);
free_number(c);
free_number(d);
free_number(maxabs);
}
@#
static void mp_get_pen_scale (MP mp, mp_number *ret, mp_knot p) {
if (p == NULL) {
set_number_to_zero(*ret);
} else {
mp_number a,b,c,d;
new_number(a);
new_number(b);
new_number(c);
new_number(d);
set_number_from_substraction(a, p->left_x, p->x_coord);
set_number_from_substraction(b, p->right_x, p->x_coord);
set_number_from_substraction(c, p->left_y, p->y_coord);
set_number_from_substraction(d, p->right_y, p->y_coord);
mp_sqrt_det (mp, ret, a, b, c, d);
free_number(a);
free_number(b);
free_number(c);
free_number(d);
}
}
@ @<Declarations@>=
static void mp_sqrt_det (MP mp, mp_number *ret, mp_number a, mp_number b, mp_number c, mp_number d);
@ When a picture contains text, this is represented by a fourteen-word node
where the color information and |type| and |link| fields are augmented by
additional fields that describe the text and how it is transformed.
The |path_p| and |mp_pen_p| pointers are replaced by a number that identifies
the font and a string number that gives the text to be displayed.
The |width|, |height|, and |depth| fields
give the dimensions of the text at its design size, and the remaining six
words give a transformation to be applied to the text. The |new_text_node|
function initializes everything to default values so that the text comes out
black with its reference point at the origin.
@d mp_text_p(A) ((mp_text_node)(A))->text_p_ /* a string pointer for the text to display */
@d mp_font_n(A) ((mp_text_node)(A))->font_n_ /* the font number */
@<MPlib internal header stuff@>=
typedef struct mp_text_node_data {
NODE_BODY;
halfword color_model_;
mp_number red;
mp_number green;
mp_number blue;
mp_number black;
mp_string pre_script_;
mp_string post_script_;
mp_string text_p_;
halfword font_n_;
mp_number width;
mp_number height;
mp_number depth;
mp_number tx;
mp_number ty;
mp_number txx;
mp_number txy;
mp_number tyx;
mp_number tyy;
} mp_text_node_data;
typedef struct mp_text_node_data *mp_text_node;
@ @<Graphical object codes@>=
mp_text_code = 3,
@ Make a text node for font |f| and text string |s|.
@d text_node_size sizeof(struct mp_text_node_data)
@c
static mp_node mp_new_text_node (MP mp, char *f, mp_string s) {
mp_text_node t = malloc_node (text_node_size);
mp_type (t) = mp_text_node_type;
mp_text_p (t) = s;
add_str_ref(s);
mp_font_n (t) = (halfword) mp_find_font (mp, f); /* this identifies the font */
new_number(t->red);
new_number(t->green);
new_number(t->blue);
new_number(t->black);
new_number(t->width);
new_number(t->height);
new_number(t->depth);
clear_color (t);
mp_pre_script (t) = NULL;
mp_post_script (t) = NULL;
new_number(t->tx);
new_number(t->ty);
new_number(t->txx);
new_number(t->txy);
new_number(t->tyx);
new_number(t->tyy);
/* |tx_val (t) = 0; ty_val (t) = 0;| */
/* |txy_val (t) = 0; tyx_val (t) = 0;| */
set_number_to_unity(t->txx);
set_number_to_unity(t->tyy);
mp_set_text_box (mp, t); /* this finds the bounding box */
return (mp_node) t;
}
@ @c
static void mp_free_text_node (MP mp, mp_text_node p) {
/* |delete_str_ref (mp_text_p (p));| */ /* gives errors */
if (mp_pre_script (p) != NULL)
delete_str_ref (mp_pre_script (p));
if (mp_post_script (p) != NULL)
delete_str_ref (mp_post_script (p));
free_number(p->red);
free_number(p->green);
free_number(p->blue);
free_number(p->black);
free_number(p->width);
free_number(p->height);
free_number(p->depth);
free_number(p->tx);
free_number(p->ty);
free_number(p->txx);
free_number(p->txy);
free_number(p->tyx);
free_number(p->tyy);
mp_free_node (mp, (mp_node)p, text_node_size);
}
@ The last two types of graphical objects that can occur in an edge structure
are clipping paths and \&{setbounds} paths. These are slightly more difficult
@:set_bounds_}{\&{setbounds} primitive@>
to implement because we must keep track of exactly what is being clipped or
bounded when pictures get merged together. For this reason, each clipping or
\&{setbounds} operation is represented by a pair of nodes: first comes a
node whose |path_p| gives the relevant path, then there is the list
of objects to clip or bound followed by a closing node.
@d has_color(A) (mp_type((A))<mp_start_clip_node_type)
/* does a graphical object have color fields? */
@d has_pen(A) (mp_type((A))<mp_text_node_type)
/* does a graphical object have a |mp_pen_p| field? */
@d is_start_or_stop(A) (mp_type((A))>=mp_start_clip_node_type)
@d is_stop(A) (mp_type((A))>=mp_stop_clip_node_type)
@<MPlib internal header stuff@>=
typedef struct mp_start_clip_node_data {
NODE_BODY;
mp_knot path_p_;
} mp_start_clip_node_data;
typedef struct mp_start_clip_node_data *mp_start_clip_node;
typedef struct mp_start_bounds_node_data {
NODE_BODY;
mp_knot path_p_;
} mp_start_bounds_node_data;
typedef struct mp_start_bounds_node_data *mp_start_bounds_node;
typedef struct mp_stop_clip_node_data {
NODE_BODY;
} mp_stop_clip_node_data;
typedef struct mp_stop_clip_node_data *mp_stop_clip_node;
typedef struct mp_stop_bounds_node_data {
NODE_BODY;
} mp_stop_bounds_node_data;
typedef struct mp_stop_bounds_node_data *mp_stop_bounds_node;
@ @<Graphical object codes@>=
mp_start_clip_code = 4, /* |type| of a node that starts clipping */
mp_start_bounds_code = 5, /* |type| of a node that gives a \&{setbounds} path */
mp_stop_clip_code = 6, /* |type| of a node that stops clipping */
mp_stop_bounds_code = 7, /* |type| of a node that stops \&{setbounds} */
@
@d start_clip_size sizeof(struct mp_start_clip_node_data)
@d stop_clip_size sizeof(struct mp_stop_clip_node_data)
@d start_bounds_size sizeof(struct mp_start_bounds_node_data)
@d stop_bounds_size sizeof(struct mp_stop_bounds_node_data)
@c
static mp_node mp_new_bounds_node (MP mp, mp_knot p, quarterword c) {
/* make a node of type |c| where |p| is the clipping or \&{setbounds} path */
if (c == mp_start_clip_node_type) {
mp_start_clip_node t; /* the new node */
t = (mp_start_clip_node) malloc_node (start_clip_size);
t->path_p_ = p;
mp_type (t) = c;
t->link = NULL;
return (mp_node) t;
} else if (c == mp_start_bounds_node_type) {
mp_start_bounds_node t; /* the new node */
t = (mp_start_bounds_node) malloc_node (start_bounds_size);
t->path_p_ = p;
mp_type (t) = c;
t->link = NULL;
return (mp_node) t;
} else if (c == mp_stop_clip_node_type) {
mp_stop_clip_node t; /* the new node */
t = (mp_stop_clip_node) malloc_node (stop_clip_size);
mp_type (t) = c;
t->link = NULL;
return (mp_node) t;
} else if (c == mp_stop_bounds_node_type) {
mp_stop_bounds_node t; /* the new node */
t = (mp_stop_bounds_node) malloc_node (stop_bounds_size);
mp_type (t) = c;
t->link = NULL;
return (mp_node) t;
} else {
assert (0);
}
return NULL;
}
@ @c
static void mp_free_start_clip_node (MP mp, mp_start_clip_node p) {
mp_toss_knot_list (mp, mp_path_p (p));
mp_free_node (mp, (mp_node)p, start_clip_size);
}
static void mp_free_start_bounds_node (MP mp, mp_start_bounds_node p) {
mp_toss_knot_list (mp, mp_path_p (p));
mp_free_node (mp, (mp_node)p, start_bounds_size);
}
static void mp_free_stop_clip_node (MP mp, mp_stop_clip_node p) {
mp_free_node (mp, (mp_node)p, stop_clip_size);
}
static void mp_free_stop_bounds_node (MP mp, mp_stop_bounds_node p) {
mp_free_node (mp, (mp_node)p, stop_bounds_size);
}
@ All the essential information in an edge structure is encoded as a linked list
of graphical objects as we have just seen, but it is helpful to add some
redundant information. A single edge structure might be used as a dash pattern
many times, and it would be nice to avoid scanning the same structure
repeatedly. Thus, an edge structure known to be a suitable dash pattern
has a header that gives a list of dashes in a sorted order designed for rapid
translation into \ps.
Each dash is represented by a three-word node containing the initial and final
$x$~coordinates as well as the usual |link| field. The |link| fields points to
the dash node with the next higher $x$-coordinates and the final link points
to a special location called |null_dash|. (There should be no overlap between
dashes). Since the $y$~coordinate of the dash pattern is needed to determine
the period of repetition, this needs to be stored in the edge header along
with a pointer to the list of dash nodes.
The |dash_info| is explained below.
@d dash_list(A) (mp_dash_node)(((mp_dash_node)(A))->link) /* in an edge header this points to the first dash node */
@d set_dash_list(A,B) ((mp_dash_node)(A))->link=(mp_node)((B)) /* in an edge header this points to the first dash node */
@<MPlib internal header stuff@>=
typedef struct mp_dash_node_data {
NODE_BODY;
mp_number start_x; /* the starting $x$~coordinate in a dash node */
mp_number stop_x; /* the ending $x$~coordinate in a dash node */
mp_number dash_y; /* $y$ value for the dash list in an edge header */
mp_node dash_info_;
} mp_dash_node_data;
@ @<Types...@>=
typedef struct mp_dash_node_data *mp_dash_node;
@ @<Initialize table entries@>=
mp->null_dash = mp_get_dash_node (mp);
@ @<Free table entries@>=
mp_free_node (mp, (mp_node)mp->null_dash, dash_node_size);
@
@d dash_node_size sizeof(struct mp_dash_node_data)
@c
static mp_dash_node mp_get_dash_node (MP mp) {
mp_dash_node p = (mp_dash_node) malloc_node (dash_node_size);
p->has_number = 0;
new_number(p->start_x);
new_number(p->stop_x);
new_number(p->dash_y);
mp_type (p) = mp_dash_node_type;
return p;
}
@ It is also convenient for an edge header to contain the bounding
box information needed by the \&{llcorner} and \&{urcorner} operators
so that this does not have to be recomputed unnecessarily. This is done by
adding fields for the $x$~and $y$ extremes as well as a pointer that indicates
how far the bounding box computation has gotten. Thus if the user asks for
the bounding box and then adds some more text to the picture before asking
for more bounding box information, the second computation need only look at
the additional text.
When the bounding box has not been computed, the |bblast| pointer points
to a dummy link at the head of the graphical object list while the |minx_val|
and |miny_val| fields contain |EL_GORDO| and the |maxx_val| and |maxy_val|
fields contain |-EL_GORDO|.
Since the bounding box of pictures containing objects of type
|mp_start_bounds_node| depends on the value of \&{truecorners}, the bounding box
@:mp_true_corners_}{\&{truecorners} primitive@>
data might not be valid for all values of this parameter. Hence, the |bbtype|
field is needed to keep track of this.
@d bblast(A) ((mp_edge_header_node)(A))->bblast_ /* last item considered in bounding box computation */
@d edge_list(A) ((mp_edge_header_node)(A))->list_ /* where the object list begins in an edge header */
@<MPlib internal header stuff@>=
typedef struct mp_edge_header_node_data {
NODE_BODY;
mp_number start_x;
mp_number stop_x;
mp_number dash_y;
mp_node dash_info_;
mp_number minx;
mp_number miny;
mp_number maxx;
mp_number maxy;
mp_node bblast_;
int bbtype; /* tells how bounding box data depends on \&{truecorners} */
mp_node list_;
mp_node obj_tail_; /* explained below */
halfword ref_count_; /* explained below */
} mp_edge_header_node_data;
typedef struct mp_edge_header_node_data *mp_edge_header_node;
@
@d no_bounds 0 /* |bbtype| value when bounding box data is valid for all \&{truecorners} values */
@d bounds_set 1 /* |bbtype| value when bounding box data is for \&{truecorners}${}\le 0$ */
@d bounds_unset 2 /* |bbtype| value when bounding box data is for \&{truecorners}${}>0$ */
@c
static void mp_init_bbox (MP mp, mp_edge_header_node h) {
/* Initialize the bounding box information in edge structure |h| */
(void) mp;
bblast (h) = edge_list (h);
h->bbtype = no_bounds;
set_number_to_inf(h->minx);
set_number_to_inf(h->miny);
set_number_to_neg_inf(h->maxx);
set_number_to_neg_inf(h->maxy);
}
@ The only other entries in an edge header are a reference count in the first
word and a pointer to the tail of the object list in the last word.
@d obj_tail(A) ((mp_edge_header_node)(A))->obj_tail_ /* points to the last entry in the object list */
@d edge_ref_count(A) ((mp_edge_header_node)(A))->ref_count_
@d edge_header_size sizeof(struct mp_edge_header_node_data)
@c
static mp_edge_header_node mp_get_edge_header_node (MP mp) {
mp_edge_header_node p = (mp_edge_header_node) malloc_node (edge_header_size);
mp_type (p) = mp_edge_header_node_type;
new_number(p->start_x);
new_number(p->stop_x);
new_number(p->dash_y);
new_number(p->minx);
new_number(p->miny);
new_number(p->maxx);
new_number(p->maxy);
p->list_ = mp_get_token_node (mp); /* or whatever, just a need a link handle */
return p;
}
static void mp_init_edges (MP mp, mp_edge_header_node h) {
/* initialize an edge header to NULL values */
set_dash_list (h, mp->null_dash);
obj_tail (h) = edge_list (h);
mp_link (edge_list (h)) = NULL;
edge_ref_count (h) = 0;
mp_init_bbox (mp, h);
}
@ Here is how edge structures are deleted. The process can be recursive because
of the need to dereference edge structures that are used as dash patterns.
@^recursion@>
@d add_edge_ref(A) incr(edge_ref_count((A)))
@d delete_edge_ref(A) {
if ( edge_ref_count((A))==0 )
mp_toss_edges(mp, (mp_edge_header_node)(A));
else
decr(edge_ref_count((A)));
}
@<Declarations@>=
static void mp_flush_dash_list (MP mp, mp_edge_header_node h);
static mp_edge_header_node mp_toss_gr_object (MP mp, mp_node p);
static void mp_toss_edges (MP mp, mp_edge_header_node h);
@ @c
void mp_toss_edges (MP mp, mp_edge_header_node h) {
mp_node p, q; /* pointers that scan the list being recycled */
mp_edge_header_node r; /* an edge structure that object |p| refers to */
mp_flush_dash_list (mp, h);
q = mp_link (edge_list (h));
while ((q != NULL)) {
p = q;
q = mp_link (q);
r = mp_toss_gr_object (mp, p);
if (r != NULL)
delete_edge_ref (r);
}
free_number(h->start_x);
free_number(h->stop_x);
free_number(h->dash_y);
free_number(h->minx);
free_number(h->miny);
free_number(h->maxx);
free_number(h->maxy);
mp_free_token_node (mp, h->list_);
mp_free_node (mp, (mp_node)h, edge_header_size);
}
void mp_flush_dash_list (MP mp, mp_edge_header_node h) {
mp_dash_node p, q; /* pointers that scan the list being recycled */
q = dash_list (h);
while (q != mp->null_dash) { /* todo: NULL check should not be needed */
p = q;
q = (mp_dash_node)mp_link (q);
mp_free_node (mp, (mp_node)p, dash_node_size);
}
set_dash_list (h,mp->null_dash);
}
mp_edge_header_node mp_toss_gr_object (MP mp, mp_node p) {
/* returns an edge structure that needs to be dereferenced */
mp_edge_header_node e = NULL; /* the edge structure to return */
switch (mp_type (p)) {
case mp_fill_node_type:
mp_free_fill_node (mp, (mp_fill_node)p);
break;
case mp_stroked_node_type:
e = mp_free_stroked_node (mp, (mp_stroked_node)p);
break;
case mp_text_node_type:
mp_free_text_node(mp, (mp_text_node)p);
break;
case mp_start_clip_node_type:
mp_free_start_clip_node(mp, (mp_start_clip_node)p);
break;
case mp_start_bounds_node_type:
mp_free_start_bounds_node(mp, (mp_start_bounds_node)p);
break;
case mp_stop_clip_node_type:
mp_free_stop_clip_node(mp, (mp_stop_clip_node)p);
break;
case mp_stop_bounds_node_type:
mp_free_stop_bounds_node(mp, (mp_stop_bounds_node)p);
break;
default: /* there are no other valid cases, but please the compiler */
break;
}
return e;
}
@ If we use |add_edge_ref| to ``copy'' edge structures, the real copying needs
to be done before making a significant change to an edge structure. Much of
the work is done in a separate routine |copy_objects| that copies a list of
graphical objects into a new edge header.
@c
static mp_edge_header_node mp_private_edges (MP mp, mp_edge_header_node h) {
/* make a private copy of the edge structure headed by |h| */
mp_edge_header_node hh; /* the edge header for the new copy */
mp_dash_node p, pp; /* pointers for copying the dash list */
assert (mp_type (h) == mp_edge_header_node_type);
if (edge_ref_count (h) == 0) {
return h;
} else {
decr (edge_ref_count (h));
hh = (mp_edge_header_node)mp_copy_objects (mp, mp_link (edge_list (h)), NULL);
@<Copy the dash list from |h| to |hh|@>;
@<Copy the bounding box information from |h| to |hh| and make |bblast(hh)|
point into the new object list@>;
return hh;
}
}
@ Here we use the fact that |dash_list(hh)=mp_link(hh)|.
@^data structure assumptions@>
@<Copy the dash list from |h| to |hh|@>=
pp = (mp_dash_node)hh;
p = dash_list (h);
while ((p != mp->null_dash)) {
mp_link (pp) = (mp_node)mp_get_dash_node (mp);
pp = (mp_dash_node)mp_link (pp);
number_clone(pp->start_x, p->start_x);
number_clone(pp->stop_x, p->stop_x);
p = (mp_dash_node)mp_link (p);
}
mp_link (pp) = (mp_node)mp->null_dash;
number_clone(hh->dash_y, h->dash_y )
@ |h| is an edge structure
@c
static mp_dash_object *mp_export_dashes (MP mp, mp_stroked_node q, mp_number w) {
mp_dash_object *d;
mp_dash_node p, h;
mp_number scf; /* scale factor */
mp_number dashoff;
double *dashes = NULL;
int num_dashes = 1;
h = (mp_dash_node)mp_dash_p (q);
if (h == NULL || dash_list (h) == mp->null_dash)
return NULL;
new_number (scf);
p = dash_list (h);
mp_get_pen_scale (mp, &scf, mp_pen_p (q));
if (number_zero(scf)) {
if (number_zero(w)) {
number_clone(scf, q->dash_scale);
} else {
free_number(scf);
return NULL;
}
} else {
mp_number ret;
new_number (ret);
make_scaled (ret, w, scf);
take_scaled (scf, ret, q->dash_scale);
free_number (ret);
}
number_clone(w, scf);
d = xmalloc (1, sizeof (mp_dash_object));
add_var_used (sizeof (mp_dash_object));
set_number_from_addition(mp->null_dash->start_x, p->start_x, h->dash_y);
{
mp_number ret, arg1;
new_number (ret);
new_number (arg1);
new_number (dashoff);
while (p != mp->null_dash) {
dashes = xrealloc (dashes, (num_dashes + 2), sizeof (double));
set_number_from_substraction (arg1, p->stop_x, p->start_x);
take_scaled (ret, arg1, scf);
dashes[(num_dashes - 1)] = number_to_double (ret);
set_number_from_substraction (arg1, ((mp_dash_node)mp_link (p))->start_x, p->stop_x);
take_scaled (ret, arg1, scf);
dashes[(num_dashes)] = number_to_double (ret);
dashes[(num_dashes + 1)] = -1.0; /* terminus */
num_dashes += 2;
p = (mp_dash_node)mp_link (p);
}
d->array = dashes;
mp_dash_offset (mp, &dashoff, h);
take_scaled (ret, dashoff, scf);
d->offset = number_to_double(ret);
free_number (ret);
free_number (arg1);
}
free_number (dashoff);
free_number(scf);
return d;
}
@ @<Copy the bounding box information from |h| to |hh|...@>=
number_clone(hh->minx, h->minx);
number_clone(hh->miny, h->miny);
number_clone(hh->maxx, h->maxx);
number_clone(hh->maxy, h->maxy);
hh->bbtype = h->bbtype;
p = (mp_dash_node)edge_list (h);
pp = (mp_dash_node)edge_list (hh);
while ((p != (mp_dash_node)bblast (h))) {
if (p == NULL)
mp_confusion (mp, "bblast");
@:this can't happen bblast}{\quad bblast@>;
p = (mp_dash_node)mp_link (p);
pp = (mp_dash_node)mp_link (pp);
}
bblast (hh) = (mp_node)pp
@ Here is the promised routine for copying graphical objects into a new edge
structure. It starts copying at object~|p| and stops just before object~|q|.
If |q| is NULL, it copies the entire sublist headed at |p|. The resulting edge
structure requires further initialization by |init_bbox|.
@<Declarations@>=
static mp_edge_header_node mp_copy_objects (MP mp, mp_node p, mp_node q);
@ @c
mp_edge_header_node mp_copy_objects (MP mp, mp_node p, mp_node q) {
mp_edge_header_node hh; /* the new edge header */
mp_node pp; /* the last newly copied object */
quarterword k = 0; /* temporary register */
hh = mp_get_edge_header_node (mp);
set_dash_list (hh, mp->null_dash);
edge_ref_count (hh) = 0;
pp = edge_list (hh);
while (p != q) {
@<Make |mp_link(pp)| point to a copy of object |p|, and update |p| and |pp|@>;
}
obj_tail (hh) = pp;
mp_link (pp) = NULL;
return hh;
}
@ @<Make |mp_link(pp)| point to a copy of object |p|, and update |p| and |pp|@>=
{
switch (mp_type (p)) {
case mp_start_clip_node_type:
k = start_clip_size;
break;
case mp_start_bounds_node_type:
k = start_bounds_size;
break;
case mp_fill_node_type:
k = fill_node_size;
break;
case mp_stroked_node_type:
k = stroked_node_size;
break;
case mp_text_node_type:
k = text_node_size;
break;
case mp_stop_clip_node_type:
k = stop_clip_size;
break;
case mp_stop_bounds_node_type:
k = stop_bounds_size;
break;
default: /* there are no other valid cases, but please the compiler */
break;
}
mp_link (pp) = malloc_node ((size_t) k); /* |gr_object| */
pp = mp_link (pp);
memcpy (pp, p, (size_t) k);
pp->link = NULL;
@<Fix anything in graphical object |pp| that should differ from the
corresponding field in |p|@>;
p = mp_link (p);
}
@ @<Fix anything in graphical object |pp| that should differ from the...@>=
switch (mp_type (p)) {
case mp_start_clip_node_type:
{
mp_start_clip_node tt = (mp_start_clip_node)pp;
mp_start_clip_node t = (mp_start_clip_node)p;
mp_path_p (tt) = mp_copy_path (mp, mp_path_p (t));
}
break;
case mp_start_bounds_node_type:
{
mp_start_bounds_node tt = (mp_start_bounds_node)pp;
mp_start_bounds_node t = (mp_start_bounds_node)p;
mp_path_p (tt) = mp_copy_path (mp, mp_path_p (t));
}
break;
case mp_fill_node_type:
{
mp_fill_node tt = (mp_fill_node)pp;
mp_fill_node t = (mp_fill_node)p;
new_number(tt->red); number_clone(tt->red, t->red);
new_number(tt->green); number_clone(tt->green, t->green);
new_number(tt->blue); number_clone(tt->blue, t->blue);
new_number(tt->black); number_clone(tt->black, t->black);
new_number(tt->miterlim); number_clone(tt->miterlim,t->miterlim);
mp_path_p (tt) = mp_copy_path (mp, mp_path_p (t));
if (mp_pre_script (p) != NULL)
add_str_ref (mp_pre_script (p));
if (mp_post_script (p) != NULL)
add_str_ref (mp_post_script (p));
if (mp_pen_p (t) != NULL)
mp_pen_p (tt) = copy_pen (mp_pen_p (t));
}
break;
case mp_stroked_node_type:
{
mp_stroked_node tt = (mp_stroked_node)pp;
mp_stroked_node t = (mp_stroked_node)p;
new_number(tt->red); number_clone(tt->red, t->red);
new_number(tt->green); number_clone(tt->green, t->green);
new_number(tt->blue); number_clone(tt->blue, t->blue);
new_number(tt->black); number_clone(tt->black, t->black);
new_number(tt->miterlim); number_clone(tt->miterlim,t->miterlim);
new_number(tt->dash_scale); number_clone(tt->dash_scale,t->dash_scale);
if (mp_pre_script (p) != NULL)
add_str_ref (mp_pre_script (p));
if (mp_post_script (p) != NULL)
add_str_ref (mp_post_script (p));
mp_path_p (tt) = mp_copy_path (mp, mp_path_p (t));
mp_pen_p (tt) = copy_pen (mp_pen_p (t));
if (mp_dash_p (p) != NULL)
add_edge_ref (mp_dash_p (pp));
}
break;
case mp_text_node_type:
{
mp_text_node tt = (mp_text_node)pp;
mp_text_node t = (mp_text_node)p;
new_number(tt->red); number_clone(tt->red, t->red);
new_number(tt->green); number_clone(tt->green, t->green);
new_number(tt->blue); number_clone(tt->blue, t->blue);
new_number(tt->black); number_clone(tt->black, t->black);
new_number(tt->width); number_clone(tt->width, t->width);
new_number(tt->height); number_clone(tt->height, t->height);
new_number(tt->depth); number_clone(tt->depth, t->depth);
new_number(tt->tx); number_clone(tt->tx, t->tx);
new_number(tt->ty); number_clone(tt->ty, t->ty);
new_number(tt->txx); number_clone(tt->txx, t->txx);
new_number(tt->tyx); number_clone(tt->tyx, t->tyx);
new_number(tt->txy); number_clone(tt->txy, t->txy);
new_number(tt->tyy); number_clone(tt->tyy, t->tyy);
if (mp_pre_script (p) != NULL)
add_str_ref (mp_pre_script (p));
if (mp_post_script (p) != NULL)
add_str_ref (mp_post_script (p));
add_str_ref (mp_text_p (pp));
}
break;
case mp_stop_clip_node_type:
case mp_stop_bounds_node_type:
break;
default: /* there are no other valid cases, but please the compiler */
break;
}
@ Here is one way to find an acceptable value for the second argument to
|copy_objects|. Given a non-NULL graphical object list, |skip_1component|
skips past one picture component, where a ``picture component'' is a single
graphical object, or a start bounds or start clip object and everything up
through the matching stop bounds or stop clip object.
@c
static mp_node mp_skip_1component (MP mp, mp_node p) {
integer lev; /* current nesting level */
lev = 0;
(void) mp;
do {
if (is_start_or_stop (p)) {
if (is_stop (p))
decr (lev);
else
incr (lev);
}
p = mp_link (p);
} while (lev != 0);
return p;
}
@ Here is a diagnostic routine for printing an edge structure in symbolic form.
@<Declarations@>=
static void mp_print_edges (MP mp, mp_node h, const char *s, boolean nuline);
@ @c
void mp_print_edges (MP mp, mp_node h, const char *s, boolean nuline) {
mp_node p; /* a graphical object to be printed */
mp_number scf; /* a scale factor for the dash pattern */
boolean ok_to_dash; /* |false| for polygonal pen strokes */
new_number (scf);
mp_print_diagnostic (mp, "Edge structure", s, nuline);
p = edge_list (h);
while (mp_link (p) != NULL) {
p = mp_link (p);
mp_print_ln (mp);
switch (mp_type (p)) {
@<Cases for printing graphical object node |p|@>;
default:
mp_print (mp, "[unknown object type!]");
break;
}
}
mp_print_nl (mp, "End edges");
if (p != obj_tail (h))
mp_print (mp, "?");
@.End edges?@>;
mp_end_diagnostic (mp, true);
free_number (scf);
}
@ @<Cases for printing graphical object node |p|@>=
case mp_fill_node_type:
mp_print (mp, "Filled contour ");
mp_print_obj_color (mp, p);
mp_print_char (mp, xord (':'));
mp_print_ln (mp);
mp_pr_path (mp, mp_path_p ((mp_fill_node) p));
mp_print_ln (mp);
if ((mp_pen_p ((mp_fill_node) p) != NULL)) {
@<Print join type for graphical object |p|@>;
mp_print (mp, " with pen");
mp_print_ln (mp);
mp_pr_pen (mp, mp_pen_p ((mp_fill_node) p));
}
break;
@ @<Print join type for graphical object |p|@>=
switch (((mp_stroked_node)p)->ljoin) {
case 0:
mp_print (mp, "mitered joins limited ");
print_number (((mp_stroked_node)p)->miterlim);
break;
case 1:
mp_print (mp, "round joins");
break;
case 2:
mp_print (mp, "beveled joins");
break;
default:
mp_print (mp, "?? joins");
@.??@>;
break;
}
@ For stroked nodes, we need to print |lcap_val(p)| as well.
@<Print join and cap types for stroked node |p|@>=
switch (((mp_stroked_node)p)->lcap ) {
case 0:
mp_print (mp, "butt");
break;
case 1:
mp_print (mp, "round");
break;
case 2:
mp_print (mp, "square");
break;
default:
mp_print (mp, "??");
break;
@.??@>
}
mp_print (mp, " ends, ");
@<Print join type for graphical object |p|@>
@ Here is a routine that prints the color of a graphical object if it isn't
black (the default color).
@<Declarations@>=
static void mp_print_obj_color (MP mp, mp_node p);
@ @c
void mp_print_obj_color (MP mp, mp_node p) {
mp_stroked_node p0 = (mp_stroked_node) p;
if (mp_color_model (p) == mp_grey_model) {
if (number_positive(p0->grey)) {
mp_print (mp, "greyed ");
mp_print_char (mp, xord ('('));
print_number (p0->grey);
mp_print_char (mp, xord (')'));
};
} else if (mp_color_model (p) == mp_cmyk_model) {
if (number_positive(p0->cyan) || number_positive(p0->magenta) ||
number_positive(p0->yellow) || number_positive(p0->black)) {
mp_print (mp, "processcolored ");
mp_print_char (mp, xord ('('));
print_number (p0->cyan);
mp_print_char (mp, xord (','));
print_number (p0->magenta);
mp_print_char (mp, xord (','));
print_number (p0->yellow);
mp_print_char (mp, xord (','));
print_number (p0->black);
mp_print_char (mp, xord (')'));
};
} else if (mp_color_model (p) == mp_rgb_model) {
if (number_positive(p0->red) || number_positive(p0->green) ||
number_positive(p0->blue)) {
mp_print (mp, "colored ");
mp_print_char (mp, xord ('('));
print_number (p0->red);
mp_print_char (mp, xord (','));
print_number (p0->green);
mp_print_char (mp, xord (','));
print_number (p0->blue);
mp_print_char (mp, xord (')'));
};
}
}
@ @<Cases for printing graphical object node |p|@>=
case mp_stroked_node_type:
mp_print (mp, "Filled pen stroke ");
mp_print_obj_color (mp, p);
mp_print_char (mp, xord (':'));
mp_print_ln (mp);
mp_pr_path (mp, mp_path_p ((mp_stroked_node) p));
if (mp_dash_p (p) != NULL) {
mp_print_nl (mp, "dashed (");
@<Finish printing the dash pattern that |p| refers to@>;
}
mp_print_ln (mp);
@<Print join and cap types for stroked node |p|@>;
mp_print (mp, " with pen");
mp_print_ln (mp);
if (mp_pen_p ((mp_stroked_node) p) == NULL) {
mp_print (mp, "???"); /* shouldn't happen */
@.???@>
} else {
mp_pr_pen (mp, mp_pen_p ((mp_stroked_node) p));
}
break;
@ Normally, the |dash_list| field in an edge header is set to |null_dash|
when it is not known to define a suitable dash pattern. This is disallowed
here because the |mp_dash_p| field should never point to such an edge header.
Note that memory is allocated for |start_x(null_dash)| and we are free to
give it any convenient value.
@<Finish printing the dash pattern that |p| refers to@>=
{
mp_dash_node ppd, hhd;
ok_to_dash = pen_is_elliptical (mp_pen_p ((mp_stroked_node) p));
if (!ok_to_dash)
set_number_to_unity (scf);
else
number_clone(scf, ((mp_stroked_node) p)->dash_scale);
hhd = (mp_dash_node)mp_dash_p (p);
ppd = dash_list (hhd);
if ((ppd == mp->null_dash) || number_negative(hhd->dash_y)) {
mp_print (mp, " ??");
} else {
mp_number dashoff;
mp_number ret, arg1;
new_number (ret);
new_number (arg1);
new_number (dashoff);
set_number_from_addition(mp->null_dash->start_x, ppd->start_x, hhd->dash_y );
while (ppd != mp->null_dash) {
mp_print (mp, "on ");
set_number_from_substraction (arg1, ppd->stop_x, ppd->start_x);
take_scaled (ret, arg1, scf);
print_number ( ret);
mp_print (mp, " off ");
set_number_from_substraction (arg1, ((mp_dash_node)mp_link (ppd))->start_x, ppd->stop_x);
take_scaled (ret, arg1, scf);
print_number (ret);
ppd = (mp_dash_node)mp_link (ppd);
if (ppd != mp->null_dash)
mp_print_char (mp, xord (' '));
}
mp_print (mp, ") shifted ");
mp_dash_offset (mp, &dashoff, hhd);
take_scaled (ret, dashoff, scf);
number_negate (ret);
print_number (ret);
free_number (dashoff);
free_number (ret);
free_number (arg1);
if (!ok_to_dash || number_zero(hhd->dash_y) )
mp_print (mp, " (this will be ignored)");
}
}
@ @<Declarations@>=
static void mp_dash_offset (MP mp, mp_number *x, mp_dash_node h);
@ @c
void mp_dash_offset (MP mp, mp_number *x, mp_dash_node h) {
if (dash_list (h) == mp->null_dash || number_negative(h->dash_y ))
mp_confusion (mp, "dash0");
@:this can't happen dash0}{\quad dash0@>;
if (number_zero(h->dash_y)) {
set_number_to_zero(*x);
} else {
number_clone (*x, (dash_list (h))->start_x );
number_modulo (*x, h->dash_y);
number_negate (*x);
if (number_negative(*x))
number_add(*x, h->dash_y);
}
}
@ @<Cases for printing graphical object node |p|@>=
case mp_text_node_type:
{
mp_text_node p0 = (mp_text_node)p;
mp_print_char (mp, xord ('"'));
mp_print_str (mp, mp_text_p (p));
mp_print (mp, "\" infont \"");
mp_print (mp, mp->font_name[mp_font_n (p)]);
mp_print_char (mp, xord ('"'));
mp_print_ln (mp);
mp_print_obj_color (mp, p);
mp_print (mp, "transformed ");
mp_print_char (mp, xord ('('));
print_number (p0->tx);
mp_print_char (mp, xord (','));
print_number (p0->ty);
mp_print_char (mp, xord (','));
print_number (p0->txx);
mp_print_char (mp, xord (','));
print_number (p0->txy);
mp_print_char (mp, xord (','));
print_number (p0->tyx);
mp_print_char (mp, xord (','));
print_number (p0->tyy);
mp_print_char (mp, xord (')'));
}
break;
@ @<Cases for printing graphical object node |p|@>=
case mp_start_clip_node_type:
mp_print (mp, "clipping path:");
mp_print_ln (mp);
mp_pr_path (mp, mp_path_p ((mp_start_clip_node) p));
break;
case mp_stop_clip_node_type:
mp_print (mp, "stop clipping");
break;
@ @<Cases for printing graphical object node |p|@>=
case mp_start_bounds_node_type:
mp_print (mp, "setbounds path:");
mp_print_ln (mp);
mp_pr_path (mp, mp_path_p ((mp_start_bounds_node) p));
break;
case mp_stop_bounds_node_type:
mp_print (mp, "end of setbounds");
break;
@ To initialize the |dash_list| field in an edge header~|h|, we need a
subroutine that scans an edge structure and tries to interpret it as a dash
pattern. This can only be done when there are no filled regions or clipping
paths and all the pen strokes have the same color. The first step is to let
$y_0$ be the initial $y$~coordinate of the first pen stroke. Then we implicitly
project all the pen stroke paths onto the line $y=y_0$ and require that there
be no retracing. If the resulting paths cover a range of $x$~coordinates of
length $\Delta x$, we set |dash_y(h)| to the length of the dash pattern by
finding the maximum of $\Delta x$ and the absolute value of~$y_0$.
@c
static mp_edge_header_node mp_make_dashes (MP mp, mp_edge_header_node h) { /* returns |h| or |NULL| */
mp_node p; /* this scans the stroked nodes in the object list */
mp_node p0; /* if not |NULL| this points to the first stroked node */
mp_knot pp, qq, rr; /* pointers into |mp_path_p(p)| */
mp_dash_node d, dd; /* pointers used to create the dash list */
mp_number y0;
@<Other local variables in |make_dashes|@>;
if (dash_list (h) != mp->null_dash)
return h;
new_number (y0); /* the initial $y$ coordinate */
p0 = NULL;
p = mp_link (edge_list (h));
while (p != NULL) {
if (mp_type (p) != mp_stroked_node_type) {
@<Compain that the edge structure contains a node of the wrong type
and |goto not_found|@>;
}
pp = mp_path_p ((mp_stroked_node) p);
if (p0 == NULL) {
p0 = p;
number_clone(y0, pp->y_coord);
}
@<Make |d| point to a new dash node created from stroke |p| and path |pp|
or |goto not_found| if there is an error@>;
@<Insert |d| into the dash list and |goto not_found| if there is an error@>;
p = mp_link (p);
}
if (dash_list (h) == mp->null_dash)
goto NOT_FOUND; /* No error message */
@<Scan |dash_list(h)| and deal with any dashes that are themselves dashed@>;
@<Set |dash_y(h)| and merge the first and last dashes if necessary@>;
free_number (y0);
return h;
NOT_FOUND:
free_number (y0);
@<Flush the dash list, recycle |h| and return |NULL|@>;
}
@ @<Compain that the edge structure contains a node of the wrong type...@>=
{
const char *hlp[] = {
"When you say `dashed p', picture p should not contain any",
"text, filled regions, or clipping paths. This time it did",
"so I'll just make it a solid line instead.",
NULL };
mp_back_error (mp, "Picture is too complicated to use as a dash pattern", hlp, true);
mp_get_x_next (mp);
goto NOT_FOUND;
}
@ A similar error occurs when monotonicity fails.
@<Declarations@>=
static void mp_x_retrace_error (MP mp);
@ @c
void mp_x_retrace_error (MP mp) {
const char *hlp[] = {
"When you say `dashed p', every path in p should be monotone",
"in x and there must be no overlapping. This failed",
"so I'll just make it a solid line instead.",
NULL };
mp_back_error (mp, "Picture is too complicated to use as a dash pattern", hlp, true);
mp_get_x_next (mp);
}
@ We stash |p| in |dash_info(d)| if |mp_dash_p(p)<>0| so that subsequent processing can
handle the case where the pen stroke |p| is itself dashed.
@d dash_info(A) ((mp_dash_node)(A))->dash_info_ /* in an edge header this points to the first dash node */
@<Make |d| point to a new dash node created from stroke |p| and path...@>=
@<Make sure |p| and |p0| are the same color and |goto not_found| if there is
an error@>;
rr = pp;
if (mp_next_knot (pp) != pp) {
do {
qq = rr;
rr = mp_next_knot (rr);
@<Check for retracing between knots |qq| and |rr| and |goto not_found|
if there is a problem@>;
} while (mp_right_type (rr) != mp_endpoint);
}
d = (mp_dash_node)mp_get_dash_node (mp);
if (mp_dash_p (p) == NULL)
dash_info (d) = NULL;
else
dash_info (d) = p;
if (number_less (pp->x_coord, rr->x_coord)) {
number_clone(d->start_x, pp->x_coord);
number_clone(d->stop_x, rr->x_coord);
} else {
number_clone(d->start_x, rr->x_coord);
number_clone(d->stop_x, pp->x_coord);
}
@ We also need to check for the case where the segment from |qq| to |rr| is
monotone in $x$ but is reversed relative to the path from |pp| to |qq|.
@<Check for retracing between knots |qq| and |rr| and |goto not_found|...@>=
{
mp_number x0, x1, x2, x3; /* $x$ coordinates of the segment from |qq| to |rr| */
new_number(x0);
new_number(x1);
new_number(x2);
new_number(x3);
number_clone(x0, qq->x_coord);
number_clone(x1, qq->right_x);
number_clone(x2, rr->left_x);
number_clone(x3, rr->x_coord);
if (number_greater(x0, x1) || number_greater(x1, x2) || number_greater(x2, x3)) {
if (number_less(x0, x1) || number_less(x1, x2) || number_less(x2, x3)) {
mp_number a1, a2, a3, a4;
mp_number test;
new_number(test);
new_number(a1);
new_number(a2);
new_number(a3);
new_number(a4);
set_number_from_substraction(a1, x2, x1);
set_number_from_substraction(a2, x2, x1);
set_number_from_substraction(a3, x1, x0);
set_number_from_substraction(a4, x3, x2);
ab_vs_cd (test, a1, a2, a3, a4);
free_number(a1);
free_number(a2);
free_number(a3);
free_number(a4);
if (number_positive(test)) {
mp_x_retrace_error (mp);
free_number(x0);
free_number(x1);
free_number(x2);
free_number(x3);
free_number(test);
goto NOT_FOUND;
}
free_number(test);
}
}
if (number_greater(pp->x_coord, x0) || number_greater(x0, x3)) {
if (number_less (pp->x_coord, x0) || number_less(x0, x3)) {
mp_x_retrace_error (mp);
free_number(x0);
free_number(x1);
free_number(x2);
free_number(x3);
goto NOT_FOUND;
}
}
free_number(x0);
free_number(x1);
free_number(x2);
free_number(x3);
}
@ @<Make sure |p| and |p0| are the same color and |goto not_found|...@>=
if (!number_equal(((mp_stroked_node)p)->red, ((mp_stroked_node)p0)->red) ||
!number_equal(((mp_stroked_node)p)->black, ((mp_stroked_node)p0)->black) ||
!number_equal(((mp_stroked_node)p)->green, ((mp_stroked_node)p0)->green) ||
!number_equal(((mp_stroked_node)p)->blue, ((mp_stroked_node)p0)->blue)
) {
const char *hlp[] = {
"When you say `dashed p', everything in picture p should",
"be the same color. I can\'t handle your color changes",
"so I'll just make it a solid line instead.",
NULL };
mp_back_error (mp, "Picture is too complicated to use as a dash pattern", hlp, true);
mp_get_x_next (mp);
goto NOT_FOUND;
}
@ @<Insert |d| into the dash list and |goto not_found| if there is an error@>=
number_clone(mp->null_dash->start_x, d->stop_x);
dd = (mp_dash_node)h; /* this makes |mp_link(dd)=dash_list(h)| */
while (number_less(((mp_dash_node)mp_link (dd))->start_x, d->stop_x ))
dd = (mp_dash_node)mp_link (dd);
if (dd != (mp_dash_node)h) {
if (number_greater(dd->stop_x, d->start_x)) {
mp_x_retrace_error (mp);
goto NOT_FOUND;
};
}
mp_link (d) = mp_link (dd);
mp_link (dd) = (mp_node)d
@ @<Set |dash_y(h)| and merge the first and last dashes if necessary@>=
d = dash_list (h);
while ((mp_link (d) != (mp_node)mp->null_dash))
d = (mp_dash_node)mp_link (d);
dd = dash_list (h);
set_number_from_substraction(h->dash_y, d->stop_x, dd->start_x);
{
mp_number absval;
new_number (absval);
number_clone (absval, y0);
number_abs (absval);
if (number_greater (absval, h->dash_y) ) {
number_clone(h->dash_y, absval);
} else if (d != dd) {
set_dash_list (h, mp_link (dd));
set_number_from_addition(d->stop_x, dd->stop_x, h->dash_y);
mp_free_node (mp, (mp_node)dd, dash_node_size);
}
free_number (absval);
}
@ We get here when the argument is a NULL picture or when there is an error.
Recovering from an error involves making |dash_list(h)| empty to indicate
that |h| is not known to be a valid dash pattern. We also dereference |h|
since it is not being used for the return value.
@<Flush the dash list, recycle |h| and return |NULL|@>=
mp_flush_dash_list (mp, h);
delete_edge_ref (h);
return NULL
@ Having carefully saved the dashed stroked nodes in the
corresponding dash nodes, we must be prepared to break up these dashes into
smaller dashes.
@<Scan |dash_list(h)| and deal with any dashes that are themselves dashed@>=
{
mp_number hsf; /* the dash pattern from |hh| gets scaled by this */
new_number (hsf);
d = (mp_dash_node)h; /* now |mp_link(d)=dash_list(h)| */
while (mp_link (d) != (mp_node)mp->null_dash) {
ds = dash_info (mp_link (d));
if (ds == NULL) {
d = (mp_dash_node)mp_link (d);
} else {
hh = (mp_edge_header_node)mp_dash_p (ds);
number_clone(hsf, ((mp_stroked_node)ds)->dash_scale);
if (hh == NULL)
mp_confusion (mp, "dash1");
@:this can't happen dash0}{\quad dash1@>;
/* clang: dereference null pointer 'hh' */ assert(hh);
if (number_zero(((mp_dash_node)hh)->dash_y )) {
d = (mp_dash_node)mp_link (d);
} else {
if (dash_list (hh) == NULL)
mp_confusion (mp, "dash1");
@:this can't happen dash0}{\quad dash1@>;
@<Replace |mp_link(d)| by a dashed version as determined by edge header
|hh| and scale factor |ds|@>;
}
}
}
free_number (hsf);
}
@ @<Other local variables in |make_dashes|@>=
mp_dash_node dln; /* |mp_link(d)| */
mp_edge_header_node hh; /* an edge header that tells how to break up |dln| */
mp_node ds; /* the stroked node from which |hh| and |hsf| are derived */
@ @<Replace |mp_link(d)| by a dashed version as determined by edge header...@>=
{
mp_number xoff; /* added to $x$ values in |dash_list(hh)| to match |dln| */
mp_number dashoff;
mp_number r1, r2;
new_number (r1);
new_number (r2);
dln = (mp_dash_node)mp_link (d);
dd = dash_list (hh);
/* clang: dereference null pointer 'dd' */ assert(dd);
new_number (xoff);
new_number (dashoff);
mp_dash_offset (mp, &dashoff, (mp_dash_node)hh);
take_scaled (r1, hsf, dd->start_x);
take_scaled (r2, hsf, dashoff);
number_add (r1, r2);
set_number_from_substraction(xoff, dln->start_x, r1);
free_number (dashoff);
take_scaled (r1, hsf, dd->start_x);
take_scaled (r2, hsf, hh->dash_y);
set_number_from_addition(mp->null_dash->start_x, r1, r2);
number_clone(mp->null_dash->stop_x, mp->null_dash->start_x);
@<Advance |dd| until finding the first dash that overlaps |dln| when
offset by |xoff|@>;
while (number_lessequal(dln->start_x, dln->stop_x)) {
@<If |dd| has `fallen off the end', back up to the beginning and fix |xoff|@>;
@<Insert a dash between |d| and |dln| for the overlap with the offset version
of |dd|@>;
dd = (mp_dash_node)mp_link (dd);
take_scaled (r1, hsf, dd->start_x);
set_number_from_addition(dln->start_x , xoff, r1);
}
free_number(xoff);
free_number (r1);
free_number (r2);
mp_link (d) = mp_link (dln);
mp_free_node (mp, (mp_node)dln, dash_node_size);
}
@ The name of this module is a bit of a lie because we just find the
first |dd| where |take_scaled (hsf, stop_x(dd))| is large enough to make an
overlap possible. It could be that the unoffset version of dash |dln| falls
in the gap between |dd| and its predecessor.
@<Advance |dd| until finding the first dash that overlaps |dln| when...@>=
{
mp_number r1;
new_number (r1);
take_scaled (r1, hsf, dd->stop_x);
number_add (r1, xoff);
while (number_less(r1, dln->start_x)) {
dd = (mp_dash_node)mp_link (dd);
take_scaled (r1, hsf, dd->stop_x);
number_add (r1, xoff);
}
free_number (r1);
}
@ @<If |dd| has `fallen off the end', back up to the beginning and fix...@>=
if (dd == mp->null_dash) {
mp_number ret;
new_number (ret);
dd = dash_list (hh);
take_scaled (ret, hsf, hh->dash_y);
number_add(xoff, ret);
free_number (ret);
}
@ At this point we already know that |start_x(dln)<=xoff+take_scaled(hsf,stop_x(dd))|.
@<Insert a dash between |d| and |dln| for the overlap with the offset...@>=
{
mp_number r1;
new_number (r1);
take_scaled (r1, hsf, dd->start_x);
number_add (r1, xoff);
if (number_lessequal(r1, dln->stop_x)) {
mp_link (d) = (mp_node)mp_get_dash_node (mp);
d = (mp_dash_node)mp_link (d);
mp_link (d) = (mp_node)dln;
take_scaled (r1, hsf, dd->start_x );
number_add (r1, xoff);
if (number_greater(dln->start_x, r1))
number_clone(d->start_x, dln->start_x);
else {
number_clone(d->start_x, r1);
}
take_scaled (r1, hsf, dd->stop_x);
number_add (r1, xoff);
if (number_less(dln->stop_x, r1))
number_clone(d->stop_x, dln->stop_x );
else {
number_clone(d->stop_x, r1);
}
}
free_number (r1);
}
@ The next major task is to update the bounding box information in an edge
header~|h|. This is done via a procedure |adjust_bbox| that enlarges an edge
header's bounding box to accommodate the box computed by |path_bbox| or
|pen_bbox|. (This is stored in global variables |minx|, |miny|, |maxx|, and
|maxy|.)
@c
static void mp_adjust_bbox (MP mp, mp_edge_header_node h) {
if (number_less (mp_minx, h->minx))
number_clone(h->minx, mp_minx);
if (number_less (mp_miny, h->miny))
number_clone(h->miny, mp_miny);
if (number_greater (mp_maxx, h->maxx))
number_clone(h->maxx, mp_maxx);
if (number_greater (mp_maxy, h->maxy))
number_clone(h->maxy, mp_maxy);
}
@ Here is a special routine for updating the bounding box information in
edge header~|h| to account for the squared-off ends of a non-cyclic path~|p|
that is to be stroked with the pen~|pp|.
@c
static void mp_box_ends (MP mp, mp_knot p, mp_knot pp, mp_edge_header_node h) {
mp_knot q; /* a knot node adjacent to knot |p| */
mp_fraction dx, dy; /* a unit vector in the direction out of the path at~|p| */
mp_number d; /* a factor for adjusting the length of |(dx,dy)| */
mp_number z; /* a coordinate being tested against the bounding box */
mp_number xx, yy; /* the extreme pen vertex in the |(dx,dy)| direction */
integer i; /* a loop counter */
new_fraction(dx);
new_fraction(dy);
new_number(xx);
new_number(yy);
new_number(z);
new_number(d);
if (mp_right_type (p) != mp_endpoint) {
q = mp_next_knot (p);
while (1) {
@<Make |(dx,dy)| the final direction for the path segment from
|q| to~|p|; set~|d|@>;
pyth_add (d, dx, dy);
if (number_positive(d)) {
@<Normalize the direction |(dx,dy)| and find the pen offset |(xx,yy)|@>;
for (i = 1; i <= 2; i++) {
@<Use |(dx,dy)| to generate a vertex of the square end cap and
update the bounding box to accommodate it@>;
number_negate(dx);
number_negate(dy);
}
}
if (mp_right_type (p) == mp_endpoint) {
goto DONE;
} else {
@<Advance |p| to the end of the path and make |q| the previous knot@>;
}
}
}
DONE:
free_number (dx);
free_number (dy);
free_number (xx);
free_number (yy);
free_number (z);
free_number (d);
}
@ @<Make |(dx,dy)| the final direction for the path segment from...@>=
if (q == mp_next_knot (p)) {
set_number_from_substraction(dx, p->x_coord, p->right_x);
set_number_from_substraction(dy, p->y_coord, p->right_y);
if (number_zero(dx) && number_zero(dy)) {
set_number_from_substraction(dx, p->x_coord, q->left_x);
set_number_from_substraction(dy, p->y_coord, q->left_y);
}
} else {
set_number_from_substraction(dx, p->x_coord, p->left_x);
set_number_from_substraction(dy, p->y_coord, p->left_y);
if (number_zero(dx) && number_zero(dy)) {
set_number_from_substraction(dx, p->x_coord, q->right_x);
set_number_from_substraction(dy, p->y_coord, q->right_y);
}
}
set_number_from_substraction(dx, p->x_coord, q->x_coord);
set_number_from_substraction(dy, p->y_coord, q->y_coord);
@ @<Normalize the direction |(dx,dy)| and find the pen offset |(xx,yy)|@>=
{
mp_number arg1, r;
new_fraction (r);
new_number(arg1);
make_fraction (r, dx, d);
number_clone(dx, r);
make_fraction (r, dy, d);
number_clone(dy, r);
free_number (r);
number_clone(arg1, dy);
number_negate(arg1);
mp_find_offset (mp, arg1, dx, pp);
free_number(arg1);
number_clone(xx, mp->cur_x);
number_clone(yy, mp->cur_y);
}
@ @<Use |(dx,dy)| to generate a vertex of the square end cap and...@>=
{
mp_number r1, r2, arg1;
new_number (arg1);
new_fraction (r1);
new_fraction (r2);
mp_find_offset (mp, dx, dy, pp);
set_number_from_substraction (arg1, xx, mp->cur_x);
take_fraction (r1, arg1, dx);
set_number_from_substraction (arg1, yy, mp->cur_y);
take_fraction (r2, arg1, dy);
set_number_from_addition(d, r1, r2);
if ((number_negative(d) && (i == 1)) || (number_positive(d) && (i == 2)))
mp_confusion (mp, "box_ends");
@:this can't happen box ends}{\quad\\{box\_ends}@>;
take_fraction (r1, d, dx);
set_number_from_addition(z, p->x_coord, mp->cur_x);
number_add (z, r1);
if (number_less(z, h->minx))
number_clone(h->minx, z);
if (number_greater(z, h->maxx))
number_clone(h->maxx, z);
take_fraction (r1, d, dy);
set_number_from_addition(z, p->y_coord, mp->cur_y);
number_add (z, r1);
if (number_less(z, h->miny))
number_clone(h->miny, z);
if (number_greater(z, h->maxy))
number_clone(h->maxy, z);
free_number (r1);
free_number (r2);
free_number (arg1);
}
@ @<Advance |p| to the end of the path and make |q| the previous knot@>=
do {
q = p;
p = mp_next_knot (p);
} while (mp_right_type (p) != mp_endpoint)
@ The major difficulty in finding the bounding box of an edge structure is the
effect of clipping paths. We treat them conservatively by only clipping to the
clipping path's bounding box, but this still
requires recursive calls to |set_bbox| in order to find the bounding box of
@^recursion@>
the objects to be clipped. Such calls are distinguished by the fact that the
boolean parameter |top_level| is false.
@c
void mp_set_bbox (MP mp, mp_edge_header_node h, boolean top_level) {
mp_node p; /* a graphical object being considered */
integer lev; /* nesting level for |mp_start_bounds_node| nodes */
/* Wipe out any existing bounding box information if |bbtype(h)| is
incompatible with |internal[mp_true_corners]| */
switch (h->bbtype ) {
case no_bounds:
break;
case bounds_set:
if (number_positive(internal_value (mp_true_corners)))
mp_init_bbox (mp, h);
break;
case bounds_unset:
if (number_nonpositive(internal_value (mp_true_corners)))
mp_init_bbox (mp, h);
break;
} /* there are no other cases */
while (mp_link (bblast (h)) != NULL) {
p = mp_link (bblast (h));
bblast (h) = p;
switch (mp_type (p)) {
case mp_stop_clip_node_type:
if (top_level)
mp_confusion (mp, "bbox");
else
return;
@:this can't happen bbox}{\quad bbox@>;
break;
@<Other cases for updating the bounding box based on the type of object |p|@>;
default: /* there are no other valid cases, but please the compiler */
break;
}
}
if (!top_level)
mp_confusion (mp, "bbox");
}
@ @<Declarations@>=
static void mp_set_bbox (MP mp, mp_edge_header_node h, boolean top_level);
@ @<Other cases for updating the bounding box...@>=
case mp_fill_node_type:
mp_path_bbox (mp, mp_path_p ((mp_fill_node) p));
if (mp_pen_p ((mp_fill_node) p) != NULL) {
mp_number x0a, y0a, x1a, y1a;
new_number (x0a);
new_number (y0a);
new_number (x1a);
new_number (y1a);
number_clone (x0a, mp_minx);
number_clone (y0a, mp_miny);
number_clone (x1a, mp_maxx);
number_clone (y1a, mp_maxy);
mp_pen_bbox (mp, mp_pen_p ((mp_fill_node) p));
number_add (mp_minx, x0a);
number_add (mp_miny, y0a);
number_add (mp_maxx, x1a);
number_add (mp_maxy, y1a);
free_number (x0a);
free_number (y0a);
free_number (x1a);
free_number (y1a);
}
mp_adjust_bbox (mp, h);
break;
@ @<Other cases for updating the bounding box...@>=
case mp_start_bounds_node_type:
if (number_positive (internal_value (mp_true_corners))) {
h->bbtype = bounds_unset;
} else {
h->bbtype = bounds_set;
mp_path_bbox (mp, mp_path_p ((mp_start_bounds_node) p));
mp_adjust_bbox (mp, h);
@<Scan to the matching |mp_stop_bounds_node| node and update |p| and
|bblast(h)|@>;
}
break;
case mp_stop_bounds_node_type:
if (number_nonpositive (internal_value (mp_true_corners)))
mp_confusion (mp, "bbox2");
@:this can't happen bbox2}{\quad bbox2@>;
break;
@ @<Scan to the matching |mp_stop_bounds_node| node and update |p| and...@>=
lev = 1;
while (lev != 0) {
if (mp_link (p) == NULL)
mp_confusion (mp, "bbox2");
@:this can't happen bbox2}{\quad bbox2@>;
/* clang: dereference null pointer */ assert(mp_link(p));
p = mp_link (p);
if (mp_type (p) == mp_start_bounds_node_type)
incr (lev);
else if (mp_type (p) == mp_stop_bounds_node_type)
decr (lev);
}
bblast (h) = p
@ It saves a lot of grief here to be slightly conservative and not account for
omitted parts of dashed lines. We also don't worry about the material omitted
when using butt end caps. The basic computation is for round end caps and
|box_ends| augments it for square end caps.
@<Other cases for updating the bounding box...@>=
case mp_stroked_node_type:
mp_path_bbox (mp, mp_path_p ((mp_stroked_node) p));
{
mp_number x0a, y0a, x1a, y1a;
new_number (x0a);
new_number (y0a);
new_number (x1a);
new_number (y1a);
number_clone (x0a, mp_minx);
number_clone (y0a, mp_miny);
number_clone (x1a, mp_maxx);
number_clone (y1a, mp_maxy);
mp_pen_bbox (mp, mp_pen_p ((mp_stroked_node) p));
number_add (mp_minx, x0a);
number_add (mp_miny, y0a);
number_add (mp_maxx, x1a);
number_add (mp_maxy, y1a);
free_number (x0a);
free_number (y0a);
free_number (x1a);
free_number (y1a);
}
mp_adjust_bbox (mp, h);
if ((mp_left_type (mp_path_p ((mp_stroked_node) p)) == mp_endpoint)
&& (((mp_stroked_node) p)->lcap == 2))
mp_box_ends (mp, mp_path_p ((mp_stroked_node) p),
mp_pen_p ((mp_stroked_node) p), h);
break;
@ The height width and depth information stored in a text node determines a
rectangle that needs to be transformed according to the transformation
parameters stored in the text node.
@<Other cases for updating the bounding box...@>=
case mp_text_node_type:
{
mp_number x0a, y0a, x1a, y1a, arg1;
mp_text_node p0 = (mp_text_node)p;
new_number (x0a);
new_number (x1a);
new_number (y0a);
new_number (y1a);
new_number (arg1);
number_clone (arg1, p0->depth);
number_negate (arg1);
take_scaled (x1a, p0->txx, p0->width);
take_scaled (y0a, p0->txy, arg1);
take_scaled (y1a, p0->txy, p0->height);
number_clone (mp_minx, p0->tx);
number_clone (mp_maxx, mp_minx);
if (number_less(y0a, y1a)) {
number_add (mp_minx, y0a);
number_add (mp_maxx, y1a);
} else {
number_add (mp_minx, y1a);
number_add (mp_maxx, y0a);
}
if (number_negative(x1a))
number_add (mp_minx, x1a);
else
number_add (mp_maxx, x1a);
take_scaled (x1a, p0->tyx, p0->width);
number_clone (arg1, p0->depth);
number_negate (arg1);
take_scaled (y0a, p0->tyy, arg1);
take_scaled (y1a, p0->tyy, p0->height);
number_clone (mp_miny, p0->ty);
number_clone (mp_maxy, mp_miny);
if (number_less (y0a, y1a)) {
number_add (mp_miny, y0a);
number_add (mp_maxy, y1a);
} else {
number_add (mp_miny, y1a);
number_add (mp_maxy, y0a);
}
if (number_negative(x1a))
number_add (mp_miny, x1a);
else
number_add (mp_maxy, x1a);
mp_adjust_bbox (mp, h);
free_number (x0a);
free_number (y0a);
free_number (x1a);
free_number (y1a);
free_number (arg1);
}
break;
@ This case involves a recursive call that advances |bblast(h)| to the node of
type |mp_stop_clip_node| that matches |p|.
@<Other cases for updating the bounding box...@>=
case mp_start_clip_node_type:
{
mp_number sminx, sminy, smaxx, smaxy;
/* for saving the bounding box during recursive calls */
mp_number x0a, y0a, x1a, y1a;
new_number (x0a);
new_number (y0a);
new_number (x1a);
new_number (y1a);
new_number (sminx);
new_number (sminy);
new_number (smaxx);
new_number (smaxy);
mp_path_bbox (mp, mp_path_p ((mp_start_clip_node) p));
number_clone (x0a, mp_minx);
number_clone (y0a, mp_miny);
number_clone (x1a, mp_maxx);
number_clone (y1a, mp_maxy);
number_clone (sminx, h->minx);
number_clone (sminy, h->miny);
number_clone (smaxx, h->maxx);
number_clone (smaxy, h->maxy);
@<Reinitialize the bounding box in header |h| and call |set_bbox| recursively
starting at |mp_link(p)|@>;
@<Clip the bounding box in |h| to the rectangle given by |x0a|, |x1a|,
|y0a|, |y1a|@>;
number_clone (mp_minx, sminx);
number_clone (mp_miny, sminy);
number_clone (mp_maxx, smaxx);
number_clone (mp_maxy, smaxy);
mp_adjust_bbox (mp, h);
free_number (sminx);
free_number (sminy);
free_number (smaxx);
free_number (smaxy);
free_number (x0a);
free_number (y0a);
free_number (x1a);
free_number (y1a);
}
break;
@ @<Reinitialize the bounding box in header |h| and call |set_bbox|...@>=
set_number_to_inf(h->minx);
set_number_to_inf(h->miny);
set_number_to_neg_inf(h->maxx);
set_number_to_neg_inf(h->maxy);
mp_set_bbox (mp, h, false)
@ @<Clip the bounding box in |h| to the rectangle given by |x0a|, |x1a|,...@>=
if (number_less(h->minx, x0a))
number_clone(h->minx, x0a);
if (number_less(h->miny, y0a))
number_clone(h->miny, y0a);
if (number_greater(h->maxx, x1a))
number_clone(h->maxx, x1a);
if (number_greater(h->maxy, y1a))
number_clone(h->maxy, y1a);
@* Finding an envelope.
When \MP\ has a path and a polygonal pen, it needs to express the desired
shape in terms of things \ps\ can understand. The present task is to compute
a new path that describes the region to be filled. It is convenient to
define this as a two step process where the first step is determining what
offset to use for each segment of the path.
@ Given a pointer |c| to a cyclic path,
and a pointer~|h| to the first knot of a pen polygon,
the |offset_prep| routine changes the path into cubics that are
associated with particular pen offsets. Thus if the cubic between |p|
and~|q| is associated with the |k|th offset and the cubic between |q| and~|r|
has offset |l| then |mp_info(q)=zero_off+l-k|. (The constant |zero_off| is added
to because |l-k| could be negative.)
After overwriting the type information with offset differences, we no longer
have a true path so we refer to the knot list returned by |offset_prep| as an
``envelope spec.''
@^envelope spec@>
Since an envelope spec only determines relative changes in pen offsets,
|offset_prep| sets a global variable |spec_offset| to the relative change from
|h| to the first offset.
@d zero_off 16384 /* added to offset changes to make them positive */
@<Glob...@>=
integer spec_offset; /* number of pen edges between |h| and the initial offset */
@ The next function calculates $1/3 B'(t) = (-p + (3c_1 + (-3c_2 + q)))*t^2 + (2p + (-4c_1 + 2*c_2))t + (-p + c_1)$,
for cubic curve |B(t)| given by |p|,|c1|,|c2|,|q|
and it's used for |t| near 0 and |t| near 1. We use double mode, otherwise we have to
take care of overflow.
@<Declarations@>=
/* static void mp_dx_dy_approx(MP mp, mp_number *dx_ap, mp_number *dy_ap,mp_knot p, mp_knot q,mp_number t); */
@ @c
/* static void mp_dx_dy_approx(MP mp, mp_number *dx_ap, mp_number *dy_ap,mp_knot kp, mp_knot kq,mp_number t) { /\* find dx dy at |t| *\/ */
/* /\* 1/3 B'(t) = (-p + (3c1 + (-3c2 + q)))t^2 + (2p + (-4c1 + 2c2))t + (-p + c1) *\/ */
/* /\* 1/3 B'(u) = (p + (-3*c1 + (3c2 - q)))*u^2 + (2c1 + (-4c2 + 2q))u + (c2 - q) *\/ */
/* mp_number absval; */
/* mp_number max_coef; /\* used while scaling *\/ */
/* mp_number small_nr, big_nr; */
/* mp_number abs_dx, abs_dy; */
/* double p,c1,c2,q,dt,s1; */
/* new_number (absval); */
/* new_number(max_coef); */
/* new_number(small_nr); */
/* new_number(big_nr); */
/* new_number(abs_dx); */
/* new_number(abs_dy); */
/* set_number_from_double(small_nr,0.001); */
/* set_number_from_double(big_nr,1000); */
/* dt = number_to_double(t); */
/* p = number_to_double(kp->x_coord); */
/* c1 = number_to_double(kp->right_x); */
/* c2 = number_to_double(kq->left_x); */
/* q = number_to_double(kq->x_coord); */
/* s1 = (-p + (3*c1 + (-3*c2 + q)))*(dt*dt) + (2*p + (-4*c1 + 2*c2))*dt + (-p + c1); */
/* set_number_from_double(*dx_ap,s1); */
/* p = number_to_double(kp->y_coord); */
/* c1 = number_to_double(kp->right_y); */
/* c2 = number_to_double(kq->left_y); */
/* q = number_to_double(kq->y_coord); */
/* s1 = (-p + (3*c1 + (-3*c2 + q)))*(dt*dt) + (2*p + (-4*c1 + 2*c2))*dt + (-p + c1); */
/* set_number_from_double(*dy_ap,s1); */
/* if (!number_zero(*dx_ap) || !number_zero(*dy_ap)) { */
/* number_clone(absval, *dx_ap); */
/* number_abs(absval); */
/* number_clone(max_coef, *dy_ap); */
/* number_abs (max_coef); */
/* if (number_greater(absval, max_coef)) { */
/* number_clone(max_coef, absval); */
/* } */
/* while (number_less(max_coef, fraction_half_t)) { */
/* number_double (max_coef); */
/* number_double (*dx_ap); */
/* number_double (*dy_ap); */
/* } */
/* number_clone(abs_dx,*dx_ap); */
/* number_clone(abs_dy,*dy_ap); */
/* number_abs(abs_dx); */
/* number_abs(abs_dy); */
/* /\* This is an experimental approximation *\/ */
/* if (number_greaterequal(abs_dy,big_nr) && number_lessequal(abs_dx,small_nr)) { */
/* set_number_to_zero(*dx_ap); */
/* } */
/* if (number_greaterequal(abs_dx,big_nr) && number_lessequal(abs_dy,small_nr)) { */
/* set_number_to_zero(*dy_ap); */
/* } */
/* } */
/* free_number(absval); */
/* free_number(max_coef); */
/* free_number(small_nr); */
/* free_number(big_nr); */
/* free_number(abs_dx); */
/* free_number(abs_dy); */
/* } */
@ @c
static mp_knot mp_offset_prep (MP mp, mp_knot c, mp_knot h) {
int n; /* the number of vertices in the pen polygon */
mp_knot c0, p, q, q0, r, w, ww; /* for list manipulation */
int k_needed; /* amount to be added to |mp_info(p)| when it is computed */
mp_knot w0; /* a pointer to pen offset to use just before |p| */
mp_number dxin, dyin; /* the direction into knot |p| */
int turn_amt; /* change in pen offsets for the current cubic */
mp_number max_coef; /* used while scaling */
mp_number ss;
@<Other local variables for |offset_prep|@>;
new_number(max_coef);
new_number(dxin);
new_number(dyin);
new_number(dx0);
new_number(dy0);
new_number(x0);
new_number(y0);
new_number(x1);
new_number(y1);
new_number(x2);
new_number(y2);
new_number(du);
new_number(dv);
new_number(dx);
new_number(dy);
new_number(x0a);
new_number(y0a);
new_number(x1a);
new_number(y1a);
new_number(x2a);
new_number(y2a);
new_number(t0);
new_number(t1);
new_number(t2);
new_number(u0);
new_number(u1);
new_number(v0);
new_number(v1);
new_number(dx_m);
new_number(dy_m);
new_number(dxin_m);
new_number(dx_ap);
new_number(dy_ap);
new_number(dxin_ap);
new_number(dyin_ap);
new_number(ueps_ap);
new_fraction (ss);
new_fraction (s);
new_fraction (t);
@<Initialize the pen size~|n|@>;
@<Initialize the incoming direction and pen offset at |c|@>;
p = c;
c0 = c;
k_needed = 0;
#ifdef DEBUGENVELOPE
dbg_nl;dbg_str(--[==[BEGIN]==]);dbg_nl;
dbg_str(return {);dbg_nl;
dbg_n(w0->x_coord);
dbg_n(w0->y_coord);
#endif
do {
q = mp_next_knot (p);
#ifdef DEBUGENVELOPE
dbg_nl;dbg_open_t;dbg_str(--[==[begin loop]==]);dbg_nl;
dbg_n(p->x_coord);dbg_n(p->y_coord);
dbg_n(p->right_x);dbg_n(p->right_y);
dbg_n(q->left_x);dbg_n(q->left_y);
dbg_n(q->x_coord);dbg_n(q->y_coord);
dbg_n(w0->x_coord);
dbg_n(w0->y_coord);
#endif
@<Split the cubic between |p| and |q|, if necessary, into cubics
associated with single offsets, after which |q| should
point to the end of the final such cubic@>;
#ifdef DEBUGENVELOPE
dbg_key(end Split the cubic between |p| and |q|);dbg_open_t;dbg_nl;
dbg_n(w->x_coord);dbg_n(w->y_coord);
dbg_n(w0->x_coord);dbg_n(w0->y_coord);
dbg_close_t; dbg_comma;dbg_nl;
#endif
NOT_FOUND:
@<Advance |p| to node |q|, removing any ``dead'' cubics that
might have been introduced by the splitting process@>;
#ifdef DEBUGENVELOPE
dbg_n(w0->x_coord);dbg_n(w0->y_coord);
dbg_str(--[==[end loop]==]);dbg_nl; dbg_close_t;dbg_comma;dbg_nl;
#endif
} while (q != c);
#ifdef DEBUGENVELOPE
dbg_key(Fix the offset change);dbg_open_t;dbg_nl;
dbg_n(p->x_coord);dbg_n(p->y_coord);
dbg_key_ival(info pre,mp_knot_info(p));dbg_comma;dbg_nl;
dbg_n(c->x_coord);dbg_n(c->y_coord);
dbg_key_ival(info pre,mp_knot_info(c));dbg_close_t;dbg_comma;dbg_nl;
#endif
@<Fix the offset change in |mp_knot_info(c)| and set |c| to the return value of
|offset_prep|@>;
#ifdef DEBUGENVELOPE
dbg_n(p->x_coord);dbg_n(p->y_coord);
dbg_key_ival(info post,mp_knot_info(p));dbg_comma;dbg_nl;
dbg_n(c->x_coord);dbg_n(c->y_coord);
dbg_key_ival(info post,mp_knot_info(c));
dbg_close_t;
dbg_nl;dbg_str(--[==[END]==]);dbg_nl;
#endif
free_number (ss);
free_number (s);
free_number (dxin);
free_number (dyin);
free_number (dx0);
free_number (dy0);
free_number (x0);
free_number (y0);
free_number (x1);
free_number (y1);
free_number (x2);
free_number (y2);
free_number (max_coef);
free_number (du);
free_number (dv);
free_number (dx);
free_number (dy);
free_number (x0a);
free_number (y0a);
free_number (x1a);
free_number (y1a);
free_number (x2a);
free_number (y2a);
free_number (t0);
free_number (t1);
free_number (t2);
free_number (u0);
free_number (u1);
free_number (v0);
free_number (v1);
free_number(dx_m);
free_number(dy_m);
free_number(dxin_m);
free_number(dx_ap);
free_number(dy_ap);
free_number(dxin_ap);
free_number(dyin_ap);
free_number(ueps_ap);
free_number (t);
return c;
}
@ We shall want to keep track of where certain knots on the cyclic path
wind up in the envelope spec. It doesn't suffice just to keep pointers to
knot nodes because some nodes are deleted while removing dead cubics. Thus
|offset_prep| updates the following pointers
@<Glob...@>=
mp_knot spec_p1;
mp_knot spec_p2; /* pointers to distinguished knots */
@ @<Set init...@>=
mp->spec_p1 = NULL;
mp->spec_p2 = NULL;
@ @<Initialize the pen size~|n|@>=
n = 0;
p = h;
do {
incr (n);
p = mp_next_knot (p);
} while (p != h)
@ Since the true incoming direction isn't known yet, we just pick a direction
consistent with the pen offset~|h|. If this is wrong, it can be corrected
later.
@<Initialize the incoming direction and pen offset at |c|@>=
{
mp_knot hn = mp_next_knot (h);
mp_knot hp = mp_prev_knot (h);
set_number_from_substraction(dxin, hn->x_coord, hp->x_coord);
set_number_from_substraction(dyin, hn->y_coord, hp->y_coord);
if (number_zero(dxin) && number_zero(dyin)) {
set_number_from_substraction(dxin, hp->y_coord, h->y_coord);
set_number_from_substraction(dyin, h->x_coord, hp->x_coord);
}
}
w0 = h
@ We must be careful not to remove the only cubic in a cycle.
But we must also be careful for another reason. If the user-supplied
path starts with a set of degenerate cubics, the target node |q| can
be collapsed to the initial node |p| which might be the same as the
initial node |c| of the curve. This would cause the |offset_prep| routine
to bail out too early, causing distress later on. (See for example
the testcase reported by Bogus\l{}aw Jackowski in tracker id 267, case 52c
on Sarovar.)
@<Advance |p| to node |q|, removing any ``dead'' cubics...@>=
#ifdef DEBUGENVELOPE
dbg_comment(Advance |p| to node |q|);dbg_nl;
#endif
q0 = q;
do {
r = mp_next_knot (p);
if (number_equal (p->x_coord, p->right_x) &&
number_equal (p->y_coord, p->right_y) &&
number_equal (p->x_coord, r->left_x) &&
number_equal (p->y_coord, r->left_y) &&
number_equal (p->x_coord, r->x_coord) &&
number_equal (p->y_coord, r->y_coord) &&
r != p && r != q) {
@<Remove the cubic following |p| and update the data structures
to merge |r| into |p|@>;
}
p = r;
} while (p != q);
/* Check if we removed too much */
if ((q != q0) && (q != c || c == c0))
q = mp_next_knot (q)
@ @<Remove the cubic following |p| and update the data structures...@>=
{
#ifdef DEBUGENVELOPE
dbg_key(Remove the cubic following p);dbg_open_t;dbg_nl;
dbg_n(p->x_coord);dbg_n(p->y_coord);
dbg_key_ival(pre info p,mp_knot_info(p)); dbg_close_t;dbg_comma;dbg_nl;
#endif
k_needed = mp_knot_info (p) - zero_off;
if (r == q) {
q = p;
} else {
mp_knot_info (p) = k_needed + mp_knot_info (r);
k_needed = 0;
}
if (r == c) {
mp_knot_info (p) = mp_knot_info (c);
c = p;
}
if (r == mp->spec_p1)
mp->spec_p1 = p;
if (r == mp->spec_p2)
mp->spec_p2 = p;
r = p;
mp_remove_cubic (mp, p);
#ifdef DEBUGENVELOPE
dbg_key(Remove the cubic following p);dbg_open_t;dbg_nl;
dbg_n(p->x_coord);dbg_n(p->y_coord);
dbg_key_ival(post info p,mp_knot_info (p)); dbg_close_t;dbg_comma;dbg_nl;
#endif
}
@ Not setting the |info| field of the newly created knot allows the splitting
routine to work for paths.
@<Declarations@>=
static void mp_split_cubic (MP mp, mp_knot p, mp_number t);
@ @c
void mp_split_cubic (MP mp, mp_knot p, mp_number t) { /* splits the cubic after |p| */
mp_number v; /* an intermediate value */
mp_knot q, r; /* for list manipulation */
q = mp_next_knot (p);
r = mp_new_knot (mp);
mp_next_knot (p) = r;
mp_next_knot (r) = q;
mp_originator (r) = mp_program_code;
mp_left_type (r) = mp_explicit;
mp_right_type (r) = mp_explicit;
new_number(v);
set_number_from_of_the_way (v, t, p->right_x, q->left_x);
set_number_from_of_the_way (p->right_x, t, p->x_coord, p->right_x);
set_number_from_of_the_way (q->left_x, t, q->left_x, q->x_coord);
set_number_from_of_the_way (r->left_x, t, p->right_x, v);
set_number_from_of_the_way (r->right_x, t, v, q->left_x);
set_number_from_of_the_way (r->x_coord, t, r->left_x, r->right_x);
set_number_from_of_the_way (v, t, p->right_y, q->left_y);
set_number_from_of_the_way (p->right_y, t, p->y_coord, p->right_y);
set_number_from_of_the_way (q->left_y, t, q->left_y, q->y_coord);
set_number_from_of_the_way (r->left_y, t, p->right_y, v);
set_number_from_of_the_way (r->right_y, t, v, q->left_y);
set_number_from_of_the_way (r->y_coord, t, r->left_y, r->right_y);
free_number (v);
}
@ This does not set |mp_knot_info(p)| or |mp_right_type(p)|.
@<Declarations@>=
static void mp_remove_cubic (MP mp, mp_knot p);
@ @c
void mp_remove_cubic (MP mp, mp_knot p) { /* removes the dead cubic following~|p| */
mp_knot q; /* the node that disappears */
(void) mp;
q = mp_next_knot (p);
mp_next_knot (p) = mp_next_knot (q);
number_clone (p->right_x, q->right_x);
number_clone (p->right_y, q->right_y);
mp_xfree (q);
}
@ Let $d\prec d'$ mean that the counter-clockwise angle from $d$ to~$d'$ is
strictly between zero and $180^\circ$. Then we can define $d\preceq d'$ to
mean that the angle could be zero or $180^\circ$. If $w_k=(u_k,v_k)$ is the
$k$th pen offset, the $k$th pen edge direction is defined by the formula
$$d_k=(u\k-u_k,\,v\k-v_k).$$
When listed by increasing $k$, these directions occur in counter-clockwise
order so that $d_k\preceq d\k$ for all~$k$.
The goal of |offset_prep| is to find an offset index~|k| to associate with
each cubic, such that the direction $d(t)$ of the cubic satisfies
$$d_{k-1}\preceq d(t)\preceq d_k\qquad\hbox{for $0\le t\le 1$.}\eqno(*)$$
We may have to split a cubic into many pieces before each
piece corresponds to a unique offset.
@<Split the cubic between |p| and |q|, if necessary, into cubics...@>=
#ifdef DEBUGENVELOPE
dbg_comment(Split the cubic between |p| and |q|);dbg_nl;
dbg_key(Split the cubic);dbg_open_t;dbg_nl;
dbg_key_ival(pre info p,mp_knot_info(p));dbg_comma;
dbg_n(w0->x_coord);dbg_n(w0->y_coord);
#endif
mp_knot_info (p) = zero_off + k_needed;
#ifdef DEBUGENVELOPE
dbg_key_ival(post info p,mp_knot_info(p));dbg_close_t;dbg_comma; dbg_nl;
#endif
k_needed = 0;
@<Prepare for derivative computations;
|goto not_found| if the current cubic is dead@>;
@<Find the initial direction |(dx,dy)|@>;
@<Update |mp_knot_info(p)| and find the offset $w_k$ such that
$d_{k-1}\preceq(\\{dx},\\{dy})\prec d_k$; also advance |w0| for
the direction change at |p|@>;
@<Find the final direction |(dxin,dyin)|@>;
@<Decide on the net change in pen offsets and set |turn_amt|@>;
@<Complete the offset splitting process@>;
w0 = mp_pen_walk (mp, w0, turn_amt)
@ @<Declarations@>=
static mp_knot mp_pen_walk (MP mp, mp_knot w, integer k);
@ @c
mp_knot mp_pen_walk (MP mp, mp_knot w, integer k) {
/* walk |k| steps around a pen from |w| */
(void) mp;
while (k > 0) {
w = mp_next_knot (w);
decr (k);
}
while (k < 0) {
w = mp_prev_knot (w);
incr (k);
}
return w;
}
@ The direction of a cubic $B(z_0,z_1,z_2,z_3;t)=\bigl(x(t),y(t)\bigr)$ can be
calculated from the quadratic polynomials
${1\over3}x'(t)=B(x_1-x_0,x_2-x_1,x_3-x_2;t)$ and
${1\over3}y'(t)=B(y_1-y_0,y_2-y_1,y_3-y_2;t)$.
Since we may be calculating directions from several cubics
split from the current one, it is desirable to do these calculations
without losing too much precision. ``Scaled up'' values of the
derivatives, which will be less tainted by accumulated errors than
derivatives found from the cubics themselves, are maintained in
local variables |x0|, |x1|, and |x2|, representing $X_0=2^l(x_1-x_0)$,
$X_1=2^l(x_2-x_1)$, and $X_2=2^l(x_3-x_2)$; similarly |y0|, |y1|, and~|y2|
represent $Y_0=2^l(y_1-y_0)$, $Y_1=2^l(y_2-y_1)$, and $Y_2=2^l(y_3-y_2)$.
@<Other local variables for |offset_prep|@>=
mp_number x0, x1, x2, y0, y1, y2; /* representatives of derivatives */
mp_number t0, t1, t2; /* coefficients of polynomial for slope testing */
mp_number du, dv, dx, dy; /* for directions of the pen and the curve */
mp_number dx0, dy0; /* initial direction for the first cubic in the curve */
mp_number x0a, x1a, x2a, y0a, y1a, y2a; /* intermediate values */
mp_number t; /* where the derivative passes through zero */
mp_number s; /* a temporary value */
mp_number dx_m; /* signal a pertubation of dx */
mp_number dy_m; /* signal a pertubation of dx */
mp_number dxin_m; /* signal a pertubation of dxin */
@ @<Prepare for derivative computations...@>=
set_number_from_substraction(x0, p->right_x, p->x_coord);
set_number_from_substraction(x2, q->x_coord, q->left_x);
set_number_from_substraction(x1, q->left_x, p->right_x);
set_number_from_substraction(y0, p->right_y, p->y_coord);
set_number_from_substraction(y2, q->y_coord, q->left_y);
set_number_from_substraction(y1, q->left_y, p->right_y);
#ifdef DEBUGENVELOPE
dbg_key(Prepare for derivative computations);dbg_open_t;dbg_nl;
dbg_n(x0);dbg_n(y0);dbg_n(x1);dbg_n(y1);dbg_n(x2);dbg_n(y2);
dbg_close_t;dbg_comma;dbg_nl;
#endif
{
mp_number absval;
new_number (absval);
number_clone(absval, x1);
number_abs(absval);
number_clone(max_coef, x0);
number_abs (max_coef);
if (number_greater(absval, max_coef)) {
number_clone(max_coef, absval);
}
number_clone(absval, x2);
number_abs(absval);
if (number_greater(absval, max_coef)) {
number_clone(max_coef, absval);
}
number_clone(absval, y0);
number_abs(absval);
if (number_greater(absval, max_coef)) {
number_clone(max_coef, absval);
}
number_clone(absval, y1);
number_abs(absval);
if (number_greater(absval, max_coef)) {
number_clone(max_coef, absval);
}
number_clone(absval, y2);
number_abs(absval);
if (number_greater(absval, max_coef)) {
number_clone(max_coef, absval);
}
if (number_zero(max_coef)) {
goto NOT_FOUND;
}
free_number (absval);
}
while (number_less(max_coef, fraction_half_t)) {
number_double (max_coef);
number_double (x0);
number_double (x1);
number_double (x2);
number_double (y0);
number_double (y1);
number_double (y2);
}
@ Let us first solve a special case of the problem: Suppose we
know an index~$k$ such that either (i)~$d(t)\succeq d_{k-1}$ for all~$t$
and $d(0)\prec d_k$, or (ii)~$d(t)\preceq d_k$ for all~$t$ and
$d(0)\succ d_{k-1}$.
Then, in a sense, we're halfway done, since one of the two relations
in $(*)$ is satisfied, and the other couldn't be satisfied for
any other value of~|k|.
Actually, the conditions can be relaxed somewhat since a relation such as
$d(t)\succeq d_{k-1}$ restricts $d(t)$ to a half plane when all that really
matters is whether $d(t)$ crosses the ray in the $d_{k-1}$ direction from
the origin. The condition for case~(i) becomes $d_{k-1}\preceq d(0)\prec d_k$
and $d(t)$ never crosses the $d_{k-1}$ ray in the clockwise direction.
Case~(ii) is similar except $d(t)$ cannot cross the $d_k$ ray in the
counterclockwise direction.
The |fin_offset_prep| subroutine solves the stated subproblem.
It has a parameter called |rise| that is |1| in
case~(i), |-1| in case~(ii). Parameters |x0| through |y2| represent
the derivative of the cubic following |p|.
The |w| parameter should point to offset~$w_k$ and |mp_info(p)| should already
be set properly. The |turn_amt| parameter gives the absolute value of the
overall net change in pen offsets.
@<Declarations@>=
static void mp_fin_offset_prep (MP mp, mp_knot p, mp_knot w, mp_number
x0, mp_number x1, mp_number x2, mp_number y0,
mp_number y1, mp_number y2, integer rise,
integer turn_amt);
@ @c
void mp_fin_offset_prep (MP mp, mp_knot p, mp_knot w, mp_number
x0, mp_number x1, mp_number x2, mp_number y0, mp_number y1,
mp_number y2, integer rise, integer turn_amt) {
mp_knot ww; /* for list manipulation */
mp_number du, dv; /* for slope calculation */
mp_number t0, t1, t2; /* test coefficients */
mp_number t; /* place where the derivative passes a critical slope */
mp_number s; /* slope or reciprocal slope */
mp_number v; /* intermediate value for updating |x0..y2| */
mp_knot q; /* original |mp_next_knot(p)| */
q = mp_next_knot (p);
new_number(du);
new_number(dv);
new_number(v);
new_number(t0);
new_number(t1);
new_number(t2);
new_fraction(s);
new_fraction(t);
#ifdef DEBUGENVELOPE
dbg_key(mp_fin_offset_prep);dbg_open_t;dbg_nl;
#endif
while (1) {
if (rise > 0)
ww = mp_next_knot (w); /* a pointer to $w\k$ */
else
ww = mp_prev_knot (w); /* a pointer to $w_{k-1}$ */
#ifdef DEBUGENVELOPE
dbg_comment(begin iteration);
dbg_open_t;dbg_nl;
dbg_n(w->x_coord);dbg_n(w->y_coord);
dbg_n(ww->x_coord);dbg_n(ww->y_coord);
dbg_n(x0);dbg_n(x1);dbg_n(x2);
dbg_n(y0);dbg_n(y1);dbg_n(y2);
dbg_in(rise);
#endif
@<Compute test coefficients |(t0,t1,t2)|
for $d(t)$ versus $d_k$ or $d_{k-1}$@>;
#ifdef DEBUGENVELOPE
dbg_comment(crossing_point);
#endif
crossing_point (t, t0, t1, t2);
#ifdef DEBUGENVELOPE
dbg_n(t);dbg_n(t0);dbg_n(t1);dbg_n(t2);
dbg_in(number_greaterequal(t, fraction_one_t));
dbg_in(turn_amt);
dbg_close_t; dbg_comma;dbg_nl;
#endif
if (number_greaterequal(t, fraction_one_t)) {
if (turn_amt > 0)
number_clone(t, fraction_one_t);
else
goto RETURN;
}
#ifdef DEBUGENVELOPE
dbg_comment(Split the cubic at $t$ and split off another cubic if the derivative crosses back);
#endif
@<Split the cubic at $t$,
and split off another cubic if the derivative crosses back@>;
w = ww;
#ifdef DEBUGENVELOPE
dbg_comment(end iteration);
#endif
}
RETURN:
#ifdef DEBUGENVELOPE
dbg_comment(RETURN);
dbg_n(t);
#endif
free_number (s);
free_number (t);
free_number (du);
free_number (dv);
free_number (v);
free_number (t0);
free_number (t1);
free_number (t2);
#ifdef DEBUGENVELOPE
dbg_close_t; dbg_comma;dbg_nl;
#endif
}
@ We want $B(\\{t0},\\{t1},\\{t2};t)$ to be the dot product of $d(t)$ with a
$-90^\circ$ rotation of the vector from |w| to |ww|. This makes the resulting
function cross from positive to negative when $d_{k-1}\preceq d(t)\preceq d_k$
begins to fail.
@<Compute test coefficients |(t0,t1,t2)| for $d(t)$ versus...@>=
{
mp_number abs_du, abs_dv;
new_number (abs_du);
new_number (abs_dv);
#ifdef DEBUGENVELOPE
dbg_key(Compute test coefficients |(t0,t1,t2)| for $d(t)$ versus...);dbg_open_t;dbg_nl;
#endif
set_number_from_substraction(du, ww->x_coord, w->x_coord);
set_number_from_substraction(dv, ww->y_coord, w->y_coord);
number_clone(abs_du, du);
number_abs(abs_du);
number_clone(abs_dv, dv);
number_abs(abs_dv);
#ifdef DEBUGENVELOPE
dbg_CUBIC;
dbg_n(w->x_coord);dbg_n(w->y_coord);
dbg_n(ww->x_coord);dbg_n(ww->y_coord);
dbg_n(x0);dbg_n(x1);dbg_n(x2);
dbg_n(y0);dbg_n(y1);dbg_n(y2);
dbg_n(abs_du);dbg_n(abs_dv);
dbg_n(du);dbg_n(dv);
dbg_in(number_greaterequal(abs_du, abs_dv));
#endif
if (number_greaterequal(abs_du, abs_dv)) {
mp_number r1;
new_fraction (r1);
make_fraction (s, dv, du);
take_fraction (r1, x0, s);
set_number_from_substraction(t0, r1, y0);
take_fraction (r1, x1, s);
set_number_from_substraction(t1, r1, y1);
take_fraction (r1, x2, s);
set_number_from_substraction(t2, r1, y2);
if (number_negative(du)) {
number_negate (t0);
number_negate (t1);
number_negate (t2);
}
free_number (r1);
} else {
mp_number r1;
new_fraction (r1);
make_fraction (s, du, dv);
take_fraction (r1, y0, s);
set_number_from_substraction(t0, x0, r1);
take_fraction (r1, y1, s);
set_number_from_substraction(t1, x1, r1);
take_fraction (r1, y2, s);
set_number_from_substraction(t2, x2, r1);
if (number_negative(dv)) {
number_negate (t0);
number_negate (t1);
number_negate (t2);
}
free_number (r1);
}
free_number (abs_du);
free_number (abs_dv);
if (number_negative(t0))
set_number_to_zero(t0); /* should be positive without rounding error */
#ifdef DEBUGENVELOPE
dbg_n(t0);dbg_n(t1);dbg_n(t2);
dbg_close_t; dbg_comma;dbg_nl;
#endif
}
@ The curve has crossed $d_k$ or $d_{k-1}$; its initial segment satisfies
$(*)$, and it might cross again and return towards $s_{k-1}$ or $s_k$,
respectively, yielding another solution of $(*)$.
@<Split the cubic at $t$, and split off another...@>=
{
mp_split_cubic (mp, p, t);
p = mp_next_knot (p);
mp_knot_info (p) = zero_off + rise;
decr (turn_amt);
set_number_from_of_the_way(v, t, x0, x1);
set_number_from_of_the_way(x1, t, x1, x2);
set_number_from_of_the_way(x0, t, v, x1);
set_number_from_of_the_way(v, t, y0, y1);
set_number_from_of_the_way(y1, t, y1, y2);
set_number_from_of_the_way(y0, t, v, y1);
if (turn_amt < 0) {
mp_number arg1, arg2, arg3;
new_number (arg1);
new_number (arg2);
new_number (arg3);
set_number_from_of_the_way(t1, t, t1, t2);
if (number_positive(t1))
set_number_to_zero(t1); /* without rounding error, |t1| would be |<=0| */
number_clone(arg2, t1);
number_negate(arg2);
number_clone(arg3, t2);
number_negate(arg3);
crossing_point (t, arg1, arg2, arg3); /* arg1 is zero */
free_number (arg1);
free_number (arg2);
free_number (arg3);
if (number_greater(t, fraction_one_t))
number_clone(t, fraction_one_t);
incr (turn_amt);
if (number_equal(t,fraction_one_t) && (mp_next_knot (p) != q)) {
mp_knot_info (mp_next_knot (p)) = mp_knot_info (mp_next_knot (p)) - rise;
} else {
mp_split_cubic (mp, p, t);
mp_knot_info (mp_next_knot (p)) = zero_off - rise;
set_number_from_of_the_way(v, t, x1, x2);
set_number_from_of_the_way(x1, t, x0, x1);
set_number_from_of_the_way(x2, t, x1, v);
set_number_from_of_the_way(v, t, y1, y2);
set_number_from_of_the_way(y1, t, y0, y1);
set_number_from_of_the_way(y2, t, y1, v);
}
}
}
@ Now we must consider the general problem of |offset_prep|, when
nothing is known about a given cubic. We start by finding its
direction in the vicinity of |t=0|.
If $z'(t)=0$, the given cubic is numerically unstable but |offset_prep|
has not yet introduced any more numerical errors. Thus we can compute
the true initial direction for the given cubic, even if it is almost
degenerate.
@<Find the initial direction |(dx,dy)|@>=
#ifdef DEBUGENVELOPE
dbg_nl;
dbg_comment(Find the initial direction |(dx,dy)|);dbg_nl;
dbg_n(w0->x_coord);dbg_n(w0->y_coord);
#endif
number_clone(dx_m, zero_t);
number_clone(dy_m, zero_t);
number_clone(dx, x0);
number_clone(dy, y0);
if (number_zero(dx) && number_zero(dy)) {
number_clone(dx, x1);
number_clone(dy, y1);
if (number_zero(dx) && number_zero(dy)) {
number_clone(dx, x2);
number_clone(dy, y2);
}
}
if (p == c) {
number_clone(dx0, dx);
number_clone(dy0, dy);
}
/* BEGIN PATCH */
/* set_number_from_substraction(ueps_ap,unity_t,epsilon_t); /\* |1-eps| *\/ */
#ifdef DEBUGENVELOPE
dbg_nl;dbg_key(mp_dx_dy_approx_t_1);dbg_open_t;dbg_nl;
dbg_n(ueps_ap);
dbg_n(p->x_coord);dbg_n(p->y_coord);
dbg_n(p->right_x);dbg_n(p->right_y);
dbg_n(q->left_x);dbg_n(q->left_y);
dbg_n(q->x_coord);dbg_n(q->y_coord);
#endif
/* mp_dx_dy_approx(mp,&dxin_ap,&dyin_ap,p,q,ueps_ap); */
#ifdef DEBUGENVELOPE
dbg_n(dxin_ap);dbg_n(dyin_ap);
dbg_close_t;dbg_comma;dbg_nl;
#endif
/**/
/* number_clone(ueps_ap,epsilon_t); */
#ifdef DEBUGENVELOPE
dbg_nl;dbg_key(mp_dx_dy_approx_t_0);dbg_open_t;dbg_nl;
dbg_n(ueps_ap);
dbg_n(p->x_coord);dbg_n(p->y_coord);
dbg_n(p->right_x);dbg_n(p->right_y);
dbg_n(q->left_x);dbg_n(q->left_y);
dbg_n(q->x_coord);dbg_n(q->y_coord);
#endif
/* mp_dx_dy_approx(mp,&dx_ap,&dy_ap,p,q,ueps_ap); /\*|eps|*\/ */
#ifdef DEBUGENVELOPE
dbg_close_t;dbg_comma;dbg_nl;
dbg_key(derivatives);dbg_open_t;dbg_nl;
dbg_n(dx_m);dbg_n(dy_m);
dbg_n(dx);dbg_n(dy);dbg_n(dx_ap);dbg_n(dy_ap);dbg_close_t;dbg_comma;dbg_nl;
#endif
/* BEGIN PATCH */
/* it should be done also for dy */
/* TODO: if |p==c| we have also to set dx0 dy0 */
/* if (number_zero(dx) && !(number_zero(dy)) && number_zero(x0) && number_zero(x2) && !number_zero(dxin) ){ */
/* number_clone(dx_m, epsilon_t); */
/* if (number_positive(x1)){ */
/* /\*set_number_from_addition (dx, dx, epsilon_t); *\/ */
/* /\*mp_warn(mp,"x component of the derivative at t=0 approximated to epsilon.");*\/ */
/* } else if (number_negative(x1)) { */
/* /\* set_number_from_substraction (dx, dx, epsilon_t); *\/ */
/* /\* mp_warn(mp,"x component of the derivative at t=0 approximated to -epsilon.");*\/ */
/* } */
/* } */
#ifdef DEBUGENVELOPE
dbg_key(derivatives after first patch );dbg_open_t;dbg_nl;
dbg_n(dx_m);dbg_n(dy_m);
dbg_n(dx);dbg_n(dy);dbg_n(dx_ap);dbg_n(dy_ap);dbg_close_t;dbg_comma;dbg_nl;
#endif
/* this patch can conflict with the previous one */
/* hm what about dx=dy=0 ? */
/* if (number_zero(dx_ap) && !number_zero(dx) && number_zero(dx_m) ){ */
/* /\* set_number_to_zero(dx); */
/* set_number_from_substraction(dx_m, zero_t,epsilon_t); */
/* if (p == c) { */
/* set_number_to_zero(dx0); */
/* } */
/* *\/ */
/* /\*mp_warn(mp,"x component of the derivative at t=0 approximated to zero.");*\/ */
/* } */
/* if (number_zero(dy_ap) && !number_zero(dy) && number_zero(dy_m)){ */
/* /\* set_number_to_zero(dy); */
/* set_number_from_substraction(dy_m, zero_t,epsilon_t); */
/* if (p == c) { */
/* set_number_to_zero(dy0); */
/* } */
/* *\/ */
/* /\*mp_warn(mp,"y component of the derivative at t=0 approximated to zero.");*\/ */
/* } */
#ifdef DEBUGENVELOPE
dbg_key(derivatives patched);dbg_open_t;dbg_nl;
dbg_n(dx_m);dbg_n(dy_m);
dbg_n(dx);dbg_n(dy);dbg_n(dx_ap);dbg_n(dy_ap);dbg_close_t;dbg_comma;dbg_nl;
#endif
/* END PATCH */
@ @<Find the final direction |(dxin,dyin)|@>=
/* number_clone(dxin_m, zero_t); */
number_clone(dxin, x2);
number_clone(dyin, y2);
if (number_zero(dxin) && number_zero(dyin)) {
number_clone(dxin, x1);
number_clone(dyin, y1);
if (number_zero(dxin) && number_zero(dyin)) {
number_clone(dxin, x0);
number_clone(dyin, y0);
}
}
#ifdef DEBUGENVELOPE
dbg_key(dxin dyin before);dbg_open_t;dbg_nl;
dbg_n(dxin);dbg_n(dyin);
dbg_close_t;dbg_comma;
#endif
/* BEGIN PATCH */
/* if (number_zero(dxin_ap) && !number_zero(dxin)){ */
/* /\* set_number_to_zero(dxin);*\/ */
/* /\* mp_warn(mp,"x component of the derivative at t=1 approximated to zero.");*\/ */
/* } */
/* if (number_zero(dyin_ap) && !number_zero(dyin)){ */
/* /\* set_number_to_zero(dyin);*\/ */
/* /\* mp_warn(mp,"y component of the derivative at t=1 approximated to zero.");*\/ */
/* } */
/* END PATCH */
#ifdef DEBUGENVELOPE
dbg_key(dxin dyin after);dbg_open_t;dbg_nl;
dbg_n(dxin);dbg_n(dyin);
dbg_close_t;dbg_comma;
#endif
/* BEGIN PATCH \par
$ 1/3 B'(t,X_0,X_1,X_2) = (1-t)^2X_0+2(1-t)tX_1+3t^2X_2 $ \par
$ 1/3 B'(t,X_0,X_1,X_2) = (X_0 + (-2X_1 + X_2))t^2 + (-2X_0 + 2X_1)t + X_0 $ \par
$ 1/3 B'(s,0,X_1,0) = (-2s^2 + 2s)X_1 \approx 2sX_1 $ for $s\rightarrow 0$ \par
$ 1/3 B'(1-s,0,X_1,0) = (-2s^2 + 2s)X_1 \approx 2sX_1 $ for $s\rightarrow 0$ $\par
*/
/* Of course the same should be done for dy and dyin */
/*
if ( ((number_zero(dx) && number_positive(dx_m)) && number_positive(dy)) &&
(number_zero(dxin) && number_positive(dyin)) ){
number_clone(dx_m, epsilon_t);
number_clone(dxin_m, epsilon_t);
if (number_positive(x1)){
set_number_from_addition (dxin, dxin, epsilon_t);
set_number_from_addition (dx, dx, epsilon_t);
} else if (number_negative(x1)) {
set_number_from_substraction (dxin, dxin, epsilon_t);
set_number_from_substraction (dx, dx, epsilon_t);
} else if (number_positive(x0)) {
set_number_from_addition (dxin, dxin, epsilon_t);
set_number_from_addition (dx, dx, epsilon_t);
} else if (number_negative(x0)) {
set_number_from_substraction (dxin, dxin, epsilon_t);
set_number_from_substraction (dx, dx, epsilon_t);
}
}
*/
#ifdef DEBUGENVELOPE
dbg_key(dx dy dxin dyin after patch);dbg_open_t;dbg_nl;
dbg_n(dx);dbg_n(dy);dbg_n(dx_ap);dbg_n(dy_ap);
dbg_n(dxin);dbg_n(dyin);dbg_n(dxin_ap);dbg_n(dyin_ap);
dbg_close_t;dbg_comma;
#endif
/* END PATCH ****/
@ The next step is to bracket the initial direction between consecutive
edges of the pen polygon. We must be careful to turn clockwise only if
this makes the turn less than $180^\circ$. (A $180^\circ$ turn must be
counter-clockwise in order to make \&{doublepath} envelopes come out
@:double_path_}{\&{doublepath} primitive@>
right.) This code depends on |w0| being the offset for |(dxin,dyin)|.
@<Update |mp_knot_info(p)| and find the offset $w_k$ such that...@>=
{
mp_number ab_vs_cd;
new_number (ab_vs_cd);
ab_vs_cd (ab_vs_cd, dy, dxin, dx, dyin);
#ifdef DEBUGENVELOPE
dbg_nl;
dbg_comment(Update |mp_knot_info(p)|);dbg_nl;
dbg_key(mp_get_turn_amt_dx_dy);dbg_open_t;dbg_str(--[==[call mp_get_turn_amt]==]);dbg_nl;
dbg_n(w0->x_coord);dbg_n(w0->y_coord);dbg_n(dx);dbg_n(dy);dbg_in(number_nonnegative(ab_vs_cd));
dbg_n(ab_vs_cd);
#endif
is_dxdy=true;
turn_amt = mp_get_turn_amt (mp, w0, dx, dy, number_nonnegative(ab_vs_cd));
is_dxdy=false;
#ifdef DEBUGENVELOPE
dbg_dn(turn_amt);
dbg_close_t;dbg_comma;
dbg_nl;
#endif
free_number (ab_vs_cd);
#ifdef DEBUGENVELOPE
dbg_key(w0 before walk);dbg_open_t;dbg_nl;
dbg_n(w0->x_coord);dbg_n(w0->y_coord);
dbg_dn(turn_amt);
dbg_close_t;dbg_comma;
#endif
w = mp_pen_walk (mp, w0, turn_amt);
w0 = w;
#ifdef DEBUGENVELOPE
dbg_key(w0 after walk);dbg_open_t;dbg_nl;
dbg_n(w0->x_coord);dbg_n(w0->y_coord);
dbg_close_t;dbg_comma;
dbg_open_t;dbg_in(mp_knot_info(p));
#endif
mp_knot_info (p) = mp_knot_info (p) + turn_amt;
#ifdef DEBUGENVELOPE
dbg_in(mp_knot_info(p));dbg_close_t;dbg_comma;
#endif
}
@ Decide how many pen offsets to go away from |w| in order to find the offset
for |(dx,dy)|, going counterclockwise if |ccw| is |true|. This assumes that
|w| is the offset for some direction $(x',y')$ from which the angle to |(dx,dy)|
in the sense determined by |ccw| is less than or equal to $180^\circ$.
If the pen polygon has only two edges, they could both be parallel
to |(dx,dy)|. In this case, we must be careful to stop after crossing the first
such edge in order to avoid an infinite loop.
@<Declarations@>=
static integer mp_get_turn_amt (MP mp, mp_knot w, mp_number dx,
mp_number dy, boolean ccw);
@ @c
integer mp_get_turn_amt (MP mp, mp_knot w, mp_number dx, mp_number dy, boolean ccw) {
mp_knot ww; /* a neighbor of knot~|w| */
integer s; /* turn amount so far */
mp_number t; /* |ab_vs_cd| result */
mp_number t_ap; /* |ab_vs_cd| approx. result */
mp_number arg1, arg2;
s = 0;
new_number (arg1);
new_number (arg2);
new_number (t);
new_number (t_ap);
if (ccw) {
ww = mp_next_knot (w);
do {
set_number_from_substraction (arg1, ww->x_coord, w->x_coord);
set_number_from_substraction (arg2, ww->y_coord, w->y_coord);
ab_vs_cd (t, dy, arg1, dx, arg2);
#ifdef DEBUGENVELOPE
dbg_sp;
dbg_open_t;dbg_str(--[==[inside mp_get_turn_amt do loop ]==]);dbg_nl;
dbg_n(w->x_coord);dbg_n(w->y_coord);dbg_n(ww->x_coord);dbg_n(ww->y_coord);
dbg_n(t);dbg_n(dy);dbg_n(arg1);dbg_n(dx);dbg_n(arg2);
dbg_n(t_ap);dbg_n(dy_ap);dbg_n(dx_ap);dbg_n(dyin_ap);dbg_n(dxin_ap);
dbg_close_t;dbg_comma;
dbg_in(number_zero(dx) && number_zero(arg1) && number_positive(dy) && number_positive(arg2) && is_dxdy);
dbg_in(is_dxdy && number_zero(dx) && number_zero(arg1) && number_negative(dy) && number_negative(arg2) && number_positive(dyin_ap));
dbg_in(is_dxindyin && number_zero(dx) && number_zero(arg1) && number_positive(dy) && number_positive(arg2) && number_negative(dyin_ap));
dbg_in(number_zero(dy) && number_zero(arg2) && number_negative(dx) && number_negative(arg1));
dbg_in(number_zero(dx) && number_zero(arg1) && number_negative(dy) && number_positive(arg2));
dbg_in(number_zero(dy) && number_zero(arg2) && number_positive(dx) && number_negative(arg1));
dbg_nl;
#endif
/* BEGIN PATCH */
/*
if (number_zero(dx) && number_zero(arg1) && number_positive(dy) && number_positive(arg2) && is_dxdy)
break;
if (is_dxdy && number_zero(dx) && number_zero(arg1) && number_negative(dy) && number_negative(arg2) && number_positive(dyin_ap))
break;
if (is_dxindyin && number_zero(dx) && number_zero(arg1) && number_positive(dy) && number_positive(arg2) && number_negative(dyin_ap))
break;
if (number_zero(dx) && number_zero(arg1) && number_negative(dy) && number_negative(arg2) && !(is_dxdy))
break;
if (number_zero(dy) && number_zero(arg2) && number_negative(dx) && number_negative(arg1))
break;
if (number_zero(dx) && number_zero(arg1) && number_negative(dy) && number_positive(arg2))
set_number_to_unity(t);
if (number_zero(dy) && number_zero(arg2) && number_positive(dx) && number_negative(arg1))
set_number_to_unity(t);
*/
/* END PATCH */
if (number_negative(t))
break;
incr (s);
w = ww;
ww = mp_next_knot (ww);
} while (number_positive(t));
} else {
ww = mp_prev_knot (w);
set_number_from_substraction (arg1, w->x_coord, ww->x_coord);
set_number_from_substraction (arg2, w->y_coord, ww->y_coord);
ab_vs_cd (t, dy, arg1, dx, arg2);
#ifdef DEBUGENVELOPE
dbg_sp;
dbg_open_t;dbg_str(--[==[outside mp_get_turn_amt do loop ]==]);dbg_nl;
dbg_n(w->x_coord);dbg_n(w->y_coord);dbg_n(ww->x_coord);dbg_n(ww->y_coord);
dbg_n(t);dbg_n(dy);dbg_n(arg1);dbg_n(dx);dbg_n(arg2);
dbg_n(t_ap);dbg_n(dy_ap);dbg_n(dx_ap);dbg_n(dyin_ap);dbg_n(dxin_ap);
dbg_close_t;dbg_comma;
dbg_nl;
#endif
/* BEGIN PATCH */
/* if (number_negative(dy) && number_zero(arg1) && number_zero(dx) && number_negative(arg2)) {
set_number_to_unity(t);
number_negate(t);
}
*/
/* END PATCH */
while (number_negative(t)) {
decr (s);
w = ww;
ww = mp_prev_knot (ww);
set_number_from_substraction (arg1, w->x_coord, ww->x_coord);
set_number_from_substraction (arg2, w->y_coord, ww->y_coord);
ab_vs_cd (t, dy, arg1, dx, arg2);
#ifdef DEBUGENVELOPE
dbg_sp;
dbg_open_t;dbg_str(--[==[inside mp_get_turn_amt do loop for t<0 ]==]);dbg_nl;
dbg_n(w->x_coord);dbg_n(w->y_coord);dbg_n(ww->x_coord);dbg_n(ww->y_coord);
dbg_n(t);dbg_n(dy);dbg_n(arg1);dbg_n(dx);dbg_n(arg2);
dbg_n(t_ap);dbg_n(dy_ap);dbg_n(dx_ap);
dbg_close_t;dbg_comma;
dbg_nl;
#endif
}
}
free_number (t);
free_number (t_ap);
free_number (arg1);
free_number (arg2);
return s;
}
@ When we're all done, the final offset is |w0| and the final curve direction
is |(dxin,dyin)|. With this knowledge of the incoming direction at |c|, we
can correct |mp_info(c)| which was erroneously based on an incoming offset
of~|h|.
@d fix_by(A) mp_knot_info(c)=mp_knot_info(c)+(A)
@<Fix the offset change in |mp_knot_info(c)| and set |c| to the return value of...@>=
mp->spec_offset = mp_knot_info (c) - zero_off;
if (mp_next_knot (c) == c) {
mp_knot_info (c) = zero_off + n;
} else {
mp_number ab_vs_cd;
new_number (ab_vs_cd);
fix_by (k_needed);
while (w0 != h) {
fix_by (1);
w0 = mp_next_knot (w0);
}
while (mp_knot_info (c) <= zero_off - n)
fix_by (n);
while (mp_knot_info (c) > zero_off)
fix_by (-n);
ab_vs_cd (ab_vs_cd, dy0, dxin, dx0, dyin);
if ((mp_knot_info (c) != zero_off) && number_nonnegative(ab_vs_cd))
fix_by (n);
free_number (ab_vs_cd);
}
@ Finally we want to reduce the general problem to situations that
|fin_offset_prep| can handle. We split the cubic into at most three parts
with respect to $d_{k-1}$, and apply |fin_offset_prep| to each part.
@<Complete the offset splitting process@>=
ww = mp_prev_knot (w);
#ifdef DEBUGENVELOPE
dbg_key(Complete the offset splitting process);dbg_open_t;dbg_nl;
dbg_n(w->x_coord);dbg_n(w->y_coord);
dbg_n(ww->x_coord);dbg_n(ww->y_coord);
dbg_close_t; dbg_comma;dbg_nl;
#endif
@<Compute test coeff...@>;
#ifdef DEBUGENVELOPE
dbg_key(after Compute test coeff);dbg_open_t;dbg_nl;
dbg_n(w->x_coord);dbg_n(w->y_coord);
dbg_n(ww->x_coord);dbg_n(ww->y_coord);
dbg_close_t; dbg_comma;dbg_nl;
#endif
@<Find the first |t| where $d(t)$ crosses $d_{k-1}$ or set
|t:=fraction_one+1|@>;
if (number_greater(t, fraction_one_t)) {
#ifdef DEBUGENVELOPE
dbg_key(t > fraction_one_t);dbg_open_t;dbg_nl;
dbg_n(p->x_coord);dbg_n(p->y_coord);
dbg_n(w->x_coord);dbg_n(w->y_coord);
dbg_n(x0);dbg_n(x1);dbg_n(x2);
dbg_n(y0);dbg_n(y1);dbg_n(y2);
dbg_close_t; dbg_comma;dbg_nl;
#endif
mp_fin_offset_prep (mp, p, w, x0, x1, x2, y0, y1, y2, 1, turn_amt);
} else {
mp_split_cubic (mp, p, t);
r = mp_next_knot (p);
set_number_from_of_the_way(x1a, t, x0, x1);
set_number_from_of_the_way(x1, t, x1, x2);
set_number_from_of_the_way(x2a, t, x1a, x1);
set_number_from_of_the_way(y1a, t, y0, y1);
set_number_from_of_the_way(y1, t, y1, y2);
set_number_from_of_the_way(y2a, t, y1a, y1);
#ifdef DEBUGENVELOPE
dbg_key(t <= fraction_one_t);dbg_open_t;dbg_nl;
dbg_n(p->x_coord);dbg_n(p->y_coord);
dbg_n(t);
dbg_n(r->x_coord);dbg_n(r->y_coord);
dbg_n(w->x_coord);dbg_n(w->y_coord);
dbg_n(x0);dbg_n(x1a);dbg_n(x2a);
dbg_n(y0);dbg_n(y1a);dbg_n(y2a);
dbg_close_t; dbg_comma;dbg_nl;
#endif
mp_fin_offset_prep (mp, p, w, x0, x1a, x2a, y0, y1a, y2a, 1, 0);
number_clone(x0, x2a);
number_clone(y0, y2a);
mp_knot_info (r) = zero_off - 1;
if (turn_amt >= 0) {
mp_number arg1, arg2, arg3;
new_number(arg1);
new_number(arg2);
new_number(arg3);
set_number_from_of_the_way(t1, t, t1, t2);
if (number_positive(t1))
set_number_to_zero(t1);
number_clone(arg2, t1);
number_negate(arg2);
number_clone(arg3, t2);
number_negate(arg3);
crossing_point (t, arg1, arg2, arg3);
free_number (arg1);
free_number (arg2);
free_number (arg3);
if (number_greater(t, fraction_one_t))
number_clone (t, fraction_one_t);
@<Split off another rising cubic for |fin_offset_prep|@>;
mp_fin_offset_prep (mp, r, ww, x0, x1, x2, y0, y1, y2, -1, 0);
} else {
mp_fin_offset_prep (mp, r, ww, x0, x1, x2, y0, y1, y2, -1, (-1 - turn_amt));
}
}
#ifdef DEBUGENVELOPE
dbg_key(end Complete the offset splitting process);dbg_open_t;dbg_nl;
dbg_n(w->x_coord);dbg_n(w->y_coord);
dbg_n(w0->x_coord);dbg_n(w0->y_coord);
dbg_in(turn_amt);
dbg_close_t; dbg_comma;dbg_nl;
#endif
@ @<Split off another rising cubic for |fin_offset_prep|@>=
mp_split_cubic (mp, r, t);
mp_knot_info (mp_next_knot (r)) = zero_off + 1;
set_number_from_of_the_way(x1a, t, x1, x2);
set_number_from_of_the_way(x1, t, x0, x1);
set_number_from_of_the_way(x0a, t, x1, x1a);
set_number_from_of_the_way(y1a, t, y1, y2);
set_number_from_of_the_way(y1, t, y0, y1);
set_number_from_of_the_way(y0a, t, y1, y1a);
mp_fin_offset_prep (mp, mp_next_knot (r), w, x0a, x1a, x2, y0a, y1a, y2, 1, turn_amt);
number_clone(x2, x0a);
number_clone(y2, y0a)
@ At this point, the direction of the incoming pen edge is |(-du,-dv)|.
When the component of $d(t)$ perpendicular to |(-du,-dv)| crosses zero, we
need to decide whether the directions are parallel or antiparallel. We
can test this by finding the dot product of $d(t)$ and |(-du,-dv)|, but this
should be avoided when the value of |turn_amt| already determines the
answer. If |t2<0|, there is one crossing and it is antiparallel only if
|turn_amt>=0|. If |turn_amt<0|, there should always be at least one
crossing and the first crossing cannot be antiparallel.
@<Find the first |t| where $d(t)$ crosses $d_{k-1}$ or set...@>=
#ifdef DEBUGENVELOPE
dbg_key(Find the first |t| where);dbg_open_t;dbg_nl;
#endif
crossing_point (t, t0, t1, t2);
if (turn_amt >= 0) {
if (number_negative(t2)) {
number_clone(t, fraction_one_t);
number_add_scaled (t, 1);
} else {
mp_number tmp, arg1, r1;
new_fraction (r1);
new_number(tmp);
new_number(arg1);
set_number_from_of_the_way(u0, t, x0, x1);
set_number_from_of_the_way(u1, t, x1, x2);
set_number_from_of_the_way(tmp, t, u0, u1);
number_clone (arg1, du);
number_negate(arg1);
take_fraction (ss, arg1, tmp);
set_number_from_of_the_way(v0, t, y0, y1);
set_number_from_of_the_way(v1, t, y1, y2);
set_number_from_of_the_way(tmp, t, v0, v1);
number_clone (arg1, dv);
number_negate(arg1);
take_fraction (r1, arg1, tmp);
number_add (ss, r1);
free_number (tmp);
if (number_negative(ss)) {
number_clone(t, fraction_one_t);
number_add_scaled (t, 1);
}
free_number(arg1);
free_number(r1);
}
} else if (number_greater(t, fraction_one_t)) {
number_clone (t, fraction_one_t);
}
#ifdef DEBUGENVELOPE
dbg_n(t);
dbg_close_t; dbg_comma;dbg_nl;
#endif
@ @<Other local variables for |offset_prep|@>=
mp_number u0, u1, v0, v1; /* intermediate values for $d(t)$ calculation */
int d_sign; /* sign of overall change in direction for this cubic */
@ If the cubic almost has a cusp, it is a numerically ill-conditioned
problem to decide which way it loops around but that's OK as long we're
consistent. To make \&{doublepath} envelopes work properly, reversing
the path should always change the sign of |turn_amt|.
@<Decide on the net change in pen offsets and set |turn_amt|@>=
{
mp_number ab_vs_cd;
mp_number t_ap;
new_number (t_ap);
new_number (ab_vs_cd);
#ifdef DEBUGENVELOPE
dbg_sp;
dbg_key(Decide on the net change in pen offsets and set turn_amt);dbg_open_t;dbg_nl;
#endif
ab_vs_cd (ab_vs_cd, dx, dyin, dxin, dy);
#ifdef DEBUGENVELOPE
dbg_n(ab_vs_cd);dbg_n(dx);dbg_n(dyin);dbg_n(dxin);dbg_n(dy);
#endif
/* BEGIN PATCH */
/*
if (number_negative(dy) && number_equal(dy,dyin) && number_equal(dx,epsilon_t))
set_number_to_unity(ab_vs_cd);
*/
#ifdef DEBUGENVELOPE
dbg_key_nval(ab_vs_cd patched,ab_vs_cd);
dbg_close_t;dbg_comma;dbg_nl;
#endif
/* END PATCH */
if (number_negative (ab_vs_cd))
d_sign = -1;
else if (number_zero (ab_vs_cd))
d_sign = 0;
else
d_sign = 1;
free_number (ab_vs_cd);
free_number (t_ap);
}
if (d_sign == 0) {
@<Check rotation direction based on node position@>
}
if (d_sign == 0) {
if (number_zero(dx)) {
if (number_positive(dy))
d_sign = 1;
else
d_sign = -1;
} else {
if (number_positive(dx))
d_sign = 1;
else
d_sign = -1;
}
}
@<Make |ss| negative if and only if the total change in direction is
more than $180^\circ$@>;
#ifdef DEBUGENVELOPE
dbg_nl;
dbg_key(Make |ss| negative if and only if); dbg_open_t;dbg_nl;
dbg_key(mp_get_turn_amt_dxin_dyin);dbg_open_t;dbg_str(--[==[call mp_get_turn_amt]==]);dbg_nl; ;
dbg_n(w->x_coord);dbg_n(w->y_coord);dbg_n(dxin);dbg_n(dyin);dbg_in((d_sign > 0));
#endif
is_dxindyin=true;
turn_amt = mp_get_turn_amt (mp, w, dxin, dyin, (d_sign > 0));
is_dxindyin=false;
#ifdef DEBUGENVELOPE
dbg_key_dval(turn_amt 1,turn_amt);dbg_comma;dbg_nl;
dbg_key_nval(ss,ss);dbg_comma;dbg_nl;
dbg_key_ival(d_sign,d_sign);dbg_comma;dbg_nl;
dbg_key_ival(n,n);dbg_comma;dbg_nl;
#endif
if (number_negative(ss))
turn_amt = turn_amt - d_sign * n;
#ifdef DEBUGENVELOPE
dbg_key_dval(turn_amt 2,turn_amt);dbg_comma;dbg_nl;
dbg_close_t;dbg_comma;dbg_nl;
dbg_close_t;dbg_comma;dbg_nl;
#endif
@ We check rotation direction by looking at the vector connecting the current
node with the next. If its angle with incoming and outgoing tangents has the
same sign, we pick this as |d_sign|, since it means we have a flex, not a cusp.
Otherwise we proceed to the cusp code.
@<Check rotation direction based on node position@>=
{
mp_number ab_vs_cd1, ab_vs_cd2, t;
new_number (ab_vs_cd1);
new_number (ab_vs_cd2);
new_number (t);
set_number_from_substraction(u0, q->x_coord, p->x_coord);
set_number_from_substraction(u1, q->y_coord, p->y_coord);
ab_vs_cd (ab_vs_cd1, dx, u1, u0, dy);
ab_vs_cd (ab_vs_cd2, u0, dyin, dxin, u1);
set_number_from_addition (t, ab_vs_cd1, ab_vs_cd2);
number_half (t);
if (number_negative (t))
d_sign = -1;
else if (number_zero (t))
d_sign = 0;
else
d_sign = 1;
free_number (t);
free_number (ab_vs_cd1);
free_number (ab_vs_cd2);
}
@ In order to be invariant under path reversal, the result of this computation
should not change when |x0|, |y0|, $\ldots$ are all negated and |(x0,y0)| is
then swapped with |(x2,y2)|. We make use of the identities
|take_fraction(-a,-b)=take_fraction(a,b)| and
|t_of_the_way(-a,-b)=-(t_of_the_way(a,b))|.
@<Make |ss| negative if and only if the total change in direction is...@>=
{
mp_number r1, r2, arg1;
new_number (arg1);
new_fraction (r1);
new_fraction (r2);
take_fraction (r1, x0, y2);
take_fraction (r2, x2, y0);
#ifdef DEBUGENVELOPE
dbg_sp;
dbg_open_t;dbg_dn(d_sign);dbg_close_t;dbg_comma;dbg_nl;
#endif
number_half (r1);
number_half (r2);
set_number_from_substraction(t0, r1, r2);
set_number_from_addition (arg1, y0, y2);
take_fraction (r1, x1, arg1);
set_number_from_addition (arg1, x0, x2);
/*%take_fraction (r1, y1, arg1);*//* The old one, is it correct ?*/
take_fraction (r2, y1, arg1);
number_half (r1);
number_half (r2);
set_number_from_substraction(t1, r1, r2);
free_number (arg1);
free_number (r1);
free_number (r2);
}
if (number_zero(t0))
set_number_from_scaled(t0, d_sign); /* path reversal always negates |d_sign| */
if (number_positive(t0)) {
mp_number arg3;
new_number(arg3);
number_clone(arg3, t0);
number_negate(arg3);
crossing_point (t, t0, t1, arg3);
free_number (arg3);
set_number_from_of_the_way(u0, t, x0, x1);
set_number_from_of_the_way(u1, t, x1, x2);
set_number_from_of_the_way(v0, t, y0, y1);
set_number_from_of_the_way(v1, t, y1, y2);
} else {
mp_number arg1;
new_number(arg1);
number_clone(arg1, t0);
number_negate(arg1);
crossing_point (t, arg1, t1, t0);
free_number (arg1);
set_number_from_of_the_way(u0, t, x2, x1);
set_number_from_of_the_way(u1, t, x1, x0);
set_number_from_of_the_way(v0, t, y2, y1);
set_number_from_of_the_way(v1, t, y1, y0);
}
{
mp_number tmp1, tmp2, r1, r2, arg1;
mp_number abs_ss, eps_ss;
new_fraction (r1);
new_fraction (r2);
new_number(arg1);
new_number(tmp1);
new_number(tmp2);
set_number_from_of_the_way(tmp1, t, u0, u1);
set_number_from_of_the_way(tmp2, t, v0, v1);
set_number_from_addition(arg1, x0, x2);
take_fraction (r1, arg1, tmp1);
set_number_from_addition(arg1, y0, y2);
take_fraction (r2, arg1, tmp2);
set_number_from_addition (ss, r1, r2);
/* BEGIN PATCH */
#ifdef DEBUGENVELOPE
dbg_key(patch ss before);dbg_open_t;
dbg_n(ss);dbg_close_t;dbg_comma;
#endif
/* new_number(abs_ss); */
/* new_number(eps_ss); */
/* set_number_from_double(eps_ss,1e-6); */
/* number_clone(abs_ss,ss); */
/* number_abs(abs_ss); */
/* if (number_greaterequal(eps_ss,abs_ss)) { */
/* /\* set_number_to_zero(ss)*\/;/\* a warning here ? *\/ */
/* } */
#ifdef DEBUGENVELOPE
dbg_key(patch ss after);dbg_open_t;
dbg_n(ss);dbg_close_t;dbg_comma;
#endif
free_number(abs_ss);
free_number(eps_ss);
/* END PATCH */
free_number (arg1);
free_number (r1);
free_number (r2);
free_number (tmp1);
free_number (tmp2);
}
@ Here's a routine that prints an envelope spec in symbolic form. It assumes
that the |cur_pen| has not been walked around to the first offset.
@c
static void mp_print_spec (MP mp, mp_knot cur_spec, mp_knot cur_pen,
const char *s) {
mp_knot p, q; /* list traversal */
mp_knot w; /* the current pen offset */
mp_print_diagnostic (mp, "Envelope spec", s, true);
p = cur_spec;
w = mp_pen_walk (mp, cur_pen, mp->spec_offset);
mp_print_ln (mp);
mp_print_two (mp, cur_spec->x_coord, cur_spec->y_coord);
mp_print (mp, " % beginning with offset ");
mp_print_two (mp, w->x_coord, w->y_coord);
do {
while (1) {
q = mp_next_knot (p);
@<Print the cubic between |p| and |q|@>;
p = q;
if ((p == cur_spec) || (mp_knot_info (p) != zero_off))
break;
}
if (mp_knot_info (p) != zero_off) {
@<Update |w| as indicated by |mp_knot_info(p)| and print an explanation@>;
}
} while (p != cur_spec);
mp_print_nl (mp, " & cycle");
mp_end_diagnostic (mp, true);
}
@ @<Update |w| as indicated by |mp_knot_info(p)| and print an explanation@>=
{
w = mp_pen_walk (mp, w, (mp_knot_info (p) - zero_off));
mp_print (mp, " % ");
#ifdef DEBUGENVELOPE
dbg_nl;dbg_open_t;dbg_str(--[==[START]==]);dbg_nl;
dbg_key(Printing mp_knot_info (p));dbg_open_t;dbg_nl;
dbg_n(p->x_coord);dbg_n(p->y_coord);
dbg_in(mp_knot_info(p));
dbg_close_t;dbg_close_t;dbg_comma;dbg_nl;
dbg_nl;dbg_str(--[==[STOP]==]);dbg_nl;
#endif
if (mp_knot_info (p) > zero_off)
mp_print (mp, "counter");
mp_print (mp, "clockwise to offset ");
mp_print_two (mp, w->x_coord, w->y_coord);
}
@ @<Print the cubic between |p| and |q|@>=
{
mp_print_nl (mp, " ..controls ");
mp_print_two (mp, p->right_x, p->right_y);
mp_print (mp, " and ");
mp_print_two (mp, q->left_x, q->left_y);
mp_print_nl (mp, " ..");
mp_print_two (mp, q->x_coord, q->y_coord);
}
@ Once we have an envelope spec, the remaining task to construct the actual
envelope by offsetting each cubic as determined by the |info| fields in
the knots. First we use |offset_prep| to convert the |c| into an envelope
spec. Then we add the offsets so that |c| becomes a cyclic path that represents
the envelope.
The |ljoin| and |miterlim| parameters control the treatment of points where the
pen offset changes, and |lcap| controls the endpoints of a \&{doublepath}.
The endpoints are easily located because |c| is given in undoubled form
and then doubled in this procedure. We use |spec_p1| and |spec_p2| to keep
track of the endpoints and treat them like very sharp corners.
Butt end caps are treated like beveled joins; round end caps are treated like
round joins; and square end caps are achieved by setting |join_type:=3|.
None of these parameters apply to inside joins where the convolution tracing
has retrograde lines. In such cases we use a simple connect-the-endpoints
approach that is achieved by setting |join_type:=2|.
@c
static mp_knot mp_make_envelope (MP mp, mp_knot c, mp_knot h, quarterword ljoin,
quarterword lcap, mp_number miterlim) {
mp_knot p, q, r, q0; /* for manipulating the path */
mp_knot w, w0; /* the pen knot for the current offset */
halfword k, k0; /* controls pen edge insertion */
mp_number qx, qy; /* unshifted coordinates of |q| */
mp_fraction dxin, dyin, dxout, dyout; /* directions at |q| when square or mitered */
int join_type = 0; /* codes |0..3| for mitered, round, beveled, or square */
@<Other local variables for |make_envelope|@>;
new_number (max_ht);
new_number (tmp);
new_fraction(dxin);
new_fraction(dyin);
new_fraction(dxout);
new_fraction(dyout);
mp->spec_p1 = NULL;
mp->spec_p2 = NULL;
new_number(qx);
new_number(qy);
@<If endpoint, double the path |c|, and set |spec_p1| and |spec_p2|@>;
@<Use |offset_prep| to compute the envelope spec then walk |h| around to
the initial offset@>;
w = h;
p = c;
do {
q = mp_next_knot (p);
q0 = q;
number_clone (qx, q->x_coord);
number_clone (qy, q->y_coord);
k = mp_knot_info (q);
k0 = k;
w0 = w;
if (k != zero_off) {
@<Set |join_type| to indicate how to handle offset changes at~|q|@>;
}
@<Add offset |w| to the cubic from |p| to |q|@>;
while (k != zero_off) {
@<Step |w| and move |k| one step closer to |zero_off|@>;
if ((join_type == 1) || (k == zero_off)) {
mp_number xtot, ytot;
new_number(xtot);
new_number(ytot);
set_number_from_addition (xtot, qx, w->x_coord);
set_number_from_addition (ytot, qy, w->y_coord);
q = mp_insert_knot (mp, q, xtot, ytot);
}
}
if (q != mp_next_knot (p)) {
@<Set |p=mp_link(p)| and add knots between |p| and |q| as
required by |join_type|@>;
}
p = q;
} while (q0 != c);
free_number (max_ht);
free_number (tmp);
free_number (qx);
free_number (qy);
free_number (dxin);
free_number (dyin);
free_number (dxout);
free_number (dyout);
return c;
}
@ @<Use |offset_prep| to compute the envelope spec then walk |h| around to...@>=
c = mp_offset_prep (mp, c, h);
if (number_positive(internal_value (mp_tracing_specs)))
mp_print_spec (mp, c, h, "");
h = mp_pen_walk (mp, h, mp->spec_offset)
@ Mitered and squared-off joins depend on path directions that are difficult to
compute for degenerate cubics. The envelope spec computed by |offset_prep| can
have degenerate cubics only if the entire cycle collapses to a single
degenerate cubic. Setting |join_type:=2| in this case makes the computed
envelope degenerate as well.
@<Set |join_type| to indicate how to handle offset changes at~|q|@>=
if (k < zero_off) {
join_type = 2;
} else {
if ((q != mp->spec_p1) && (q != mp->spec_p2))
join_type = ljoin;
else if (lcap == 2)
join_type = 3;
else
join_type = 2 - lcap;
if ((join_type == 0) || (join_type == 3)) {
@<Set the incoming and outgoing directions at |q|; in case of
degeneracy set |join_type:=2|@>;
if (join_type == 0) {
@<If |miterlim| is less than the secant of half the angle at |q|
then set |join_type:=2|@>;
}
}
}
@ @<If |miterlim| is less than the secant of half the angle at |q|...@>=
{
mp_number r1, r2;
new_fraction (r1);
new_fraction (r2);
take_fraction (r1, dxin, dxout);
take_fraction (r2, dyin, dyout);
number_add (r1, r2);
number_half (r1);
number_add (r1, fraction_half_t);
take_fraction (tmp, miterlim, r1);
if (number_less(tmp, unity_t)) {
mp_number ret;
new_number (ret);
take_scaled (ret, miterlim, tmp);
if (number_less(ret, unity_t))
join_type = 2;
free_number (ret);
}
free_number (r1);
free_number (r2);
}
@ @<Other local variables for |make_envelope|@>=
mp_number tmp; /* a temporary value */
@ The coordinates of |p| have already been shifted unless |p| is the first
knot in which case they get shifted at the very end.
@<Add offset |w| to the cubic from |p| to |q|@>=
number_add (p->right_x, w->x_coord);
number_add (p->right_y, w->y_coord);
number_add (q->left_x, w->x_coord);
number_add (q->left_y, w->y_coord);
number_add (q->x_coord, w->x_coord);
number_add (q->y_coord, w->y_coord);
mp_left_type (q) = mp_explicit;
mp_right_type (q) = mp_explicit
@ @<Step |w| and move |k| one step closer to |zero_off|@>=
if (k > zero_off) {
w = mp_next_knot (w);
decr (k);
} else {
w = mp_prev_knot (w);
incr (k);
}
@ The cubic from |q| to the new knot at |(x,y)| becomes a line segment and
the |mp_right_x| and |mp_right_y| fields of |r| are set from |q|. This is done in
case the cubic containing these control points is ``yet to be examined.''
@<Declarations@>=
static mp_knot mp_insert_knot (MP mp, mp_knot q, mp_number x, mp_number y);
@ @c
mp_knot mp_insert_knot (MP mp, mp_knot q, mp_number x, mp_number y) {
/* returns the inserted knot */
mp_knot r; /* the new knot */
r = mp_new_knot (mp);
mp_next_knot (r) = mp_next_knot (q);
mp_next_knot (q) = r;
number_clone (r->right_x, q->right_x);
number_clone (r->right_y, q->right_y);
number_clone (r->x_coord, x);
number_clone (r->y_coord, y);
number_clone (q->right_x, q->x_coord);
number_clone (q->right_y, q->y_coord);
number_clone (r->left_x, r->x_coord);
number_clone (r->left_y, r->y_coord);
mp_left_type (r) = mp_explicit;
mp_right_type (r) = mp_explicit;
mp_originator (r) = mp_program_code;
return r;
}
@ After setting |p:=mp_link(p)|, either |join_type=1| or |q=mp_link(p)|.
@<Set |p=mp_link(p)| and add knots between |p| and |q| as...@>=
{
p = mp_next_knot (p);
if ((join_type == 0) || (join_type == 3)) {
if (join_type == 0) {
@<Insert a new knot |r| between |p| and |q| as required for a mitered join@>
} else {
@<Make |r| the last of two knots inserted between |p| and |q| to form a
squared join@>;
}
if (r != NULL) {
number_clone (r->right_x, r->x_coord);
number_clone (r->right_y, r->y_coord);
}
}
}
@ For very small angles, adding a knot is unnecessary and would cause numerical
problems, so we just set |r:=NULL| in that case.
@d near_zero_angle_k ((math_data *)mp->math)->near_zero_angle_t
@<Insert a new knot |r| between |p| and |q| as required for a mitered join@>=
{
mp_number det; /* a determinant used for mitered join calculations */
mp_number absdet;
mp_number r1, r2;
new_fraction (r1);
new_fraction (r2);
new_fraction (det);
new_fraction (absdet);
take_fraction (r1, dyout, dxin);
take_fraction (r2, dxout, dyin);
set_number_from_substraction(det, r1, r2);
number_clone (absdet, det);
number_abs (absdet);
if (number_less (absdet, near_zero_angle_k)) {
r = NULL; /* sine $<10^{-4}$ */
} else {
mp_number xtot, ytot, xsub, ysub;
new_fraction(xsub);
new_fraction(ysub);
new_number(xtot);
new_number(ytot);
set_number_from_substraction (tmp, q->x_coord, p->x_coord);
take_fraction (r1, tmp, dyout);
set_number_from_substraction (tmp, q->y_coord, p->y_coord);
take_fraction (r2, tmp, dxout);
set_number_from_substraction (tmp, r1, r2);
make_fraction (r1, tmp, det);
number_clone (tmp, r1);
take_fraction (xsub, tmp, dxin);
take_fraction (ysub, tmp, dyin);
set_number_from_addition(xtot, p->x_coord, xsub);
set_number_from_addition(ytot, p->y_coord, ysub);
r = mp_insert_knot (mp, p, xtot, ytot);
free_number (xtot);
free_number (ytot);
free_number (xsub);
free_number (ysub);
}
free_number (r1);
free_number (r2);
free_number (det);
free_number (absdet);
}
@ @<Make |r| the last of two knots inserted between |p| and |q| to form a...@>=
{
mp_number ht_x, ht_y; /* perpendicular to the segment from |p| to |q| */
mp_number ht_x_abs, ht_y_abs; /* absolutes */
mp_number xtot, ytot, xsub, ysub;
new_fraction(xsub);
new_fraction(ysub);
new_number(xtot);
new_number(ytot);
new_fraction (ht_x);
new_fraction (ht_y);
new_fraction (ht_x_abs);
new_fraction (ht_y_abs);
set_number_from_substraction(ht_x, w->y_coord, w0->y_coord);
set_number_from_substraction(ht_y, w0->x_coord, w->x_coord);
number_clone (ht_x_abs, ht_x);
number_clone (ht_y_abs, ht_y);
number_abs (ht_x_abs);
number_abs (ht_y_abs);
while (number_less(ht_x_abs, fraction_half_t) && number_less(ht_y_abs, fraction_half_t)) {
number_double(ht_x);
number_double(ht_y);
number_clone (ht_x_abs, ht_x);
number_clone (ht_y_abs, ht_y);
number_abs (ht_x_abs);
number_abs (ht_y_abs);
}
@<Scan the pen polygon between |w0| and |w| and make |max_ht| the range dot
product with |(ht_x,ht_y)|@>;
{
mp_number r1 ,r2;
new_fraction (r1);
new_fraction (r2);
take_fraction (r1, dxin, ht_x);
take_fraction (r2, dyin, ht_y);
number_add (r1, r2);
make_fraction (tmp, max_ht, r1);
free_number (r1);
free_number (r2);
}
take_fraction (xsub, tmp, dxin);
take_fraction (ysub, tmp, dyin);
set_number_from_addition(xtot, p->x_coord, xsub);
set_number_from_addition(ytot, p->y_coord, ysub);
r = mp_insert_knot (mp, p, xtot, ytot);
/* clang: value never read */ assert(r);
{
mp_number r1 ,r2;
new_fraction (r1);
new_fraction (r2);
take_fraction (r1, dxout, ht_x);
take_fraction (r2, dyout, ht_y);
number_add (r1, r2);
make_fraction (tmp, max_ht, r1);
free_number (r1);
free_number (r2);
}
take_fraction (xsub, tmp, dxout);
take_fraction (ysub, tmp, dyout);
set_number_from_addition(xtot, q->x_coord, xsub);
set_number_from_addition(ytot, q->y_coord, ysub);
r = mp_insert_knot (mp, p, xtot, ytot);
free_number (xsub);
free_number (ysub);
free_number (xtot);
free_number (ytot);
free_number (ht_x);
free_number (ht_y);
free_number (ht_x_abs);
free_number (ht_y_abs);
}
@ @<Other local variables for |make_envelope|@>=
mp_number max_ht; /* maximum height of the pen polygon above the |w0|-|w| line */
halfword kk; /* keeps track of the pen vertices being scanned */
mp_knot ww; /* the pen vertex being tested */
@ The dot product of the vector from |w0| to |ww| with |(ht_x,ht_y)| ranges
from zero to |max_ht|.
@<Scan the pen polygon between |w0| and |w| and make |max_ht| the range...@>=
set_number_to_zero (max_ht);
kk = zero_off;
ww = w;
while (1) {
@<Step |ww| and move |kk| one step closer to |k0|@>;
if (kk == k0)
break;
{
mp_number r1, r2;
new_fraction (r1);
new_fraction (r2);
set_number_from_substraction (tmp, ww->x_coord, w0->x_coord);
take_fraction (r1, tmp, ht_x);
set_number_from_substraction (tmp, ww->y_coord, w0->y_coord);
take_fraction (r2, tmp, ht_y);
set_number_from_addition (tmp, r1, r2);
free_number (r1);
free_number (r2);
}
if (number_greater(tmp, max_ht))
number_clone(max_ht, tmp);
}
@ @<Step |ww| and move |kk| one step closer to |k0|@>=
if (kk > k0) {
ww = mp_next_knot (ww);
decr (kk);
} else {
ww = mp_prev_knot (ww);
incr (kk);
}
@ @<If endpoint, double the path |c|, and set |spec_p1| and |spec_p2|@>=
if (mp_left_type (c) == mp_endpoint) {
mp->spec_p1 = mp_htap_ypoc (mp, c);
mp->spec_p2 = mp->path_tail;
mp_originator (mp->spec_p1) = mp_program_code;
mp_next_knot (mp->spec_p2) = mp_next_knot (mp->spec_p1);
mp_next_knot (mp->spec_p1) = c;
mp_remove_cubic (mp, mp->spec_p1);
c = mp->spec_p1;
if (c != mp_next_knot (c)) {
mp_originator (mp->spec_p2) = mp_program_code;
mp_remove_cubic (mp, mp->spec_p2);
} else {
@<Make |c| look like a cycle of length one@>;
}
}
@ @<Make |c| look like a cycle of length one@>=
{
mp_left_type (c) = mp_explicit;
mp_right_type (c) = mp_explicit;
number_clone(c->left_x, c->x_coord);
number_clone(c->left_y, c->y_coord);
number_clone(c->right_x, c->x_coord);
number_clone(c->right_y, c->y_coord);
}
@ In degenerate situations we might have to look at the knot preceding~|q|.
That knot is |p| but if |p<>c|, its coordinates have already been offset by |w|.
@<Set the incoming and outgoing directions at |q|; in case of...@>=
{
set_number_from_substraction(dxin, q->x_coord, q->left_x);
set_number_from_substraction(dyin, q->y_coord, q->left_y);
if (number_zero(dxin) && number_zero(dyin)) {
set_number_from_substraction(dxin, q->x_coord, p->right_x);
set_number_from_substraction(dyin, q->y_coord, p->right_y);
if (number_zero(dxin) && number_zero(dyin)) {
set_number_from_substraction(dxin, q->x_coord, p->x_coord);
set_number_from_substraction(dyin, q->y_coord, p->y_coord);
if (p != c) { /* the coordinates of |p| have been offset by |w| */
number_add(dxin, w->x_coord);
number_add(dyin, w->y_coord);
}
}
}
pyth_add (tmp, dxin, dyin);
if (number_zero(tmp)) {
join_type = 2;
} else {
mp_number r1;
new_fraction (r1);
make_fraction (r1, dxin, tmp);
number_clone(dxin, r1);
make_fraction (r1, dyin, tmp);
number_clone(dyin, r1);
free_number (r1);
@<Set the outgoing direction at |q|@>;
}
}
@ If |q=c| then the coordinates of |r| and the control points between |q|
and~|r| have already been offset by |h|.
@<Set the outgoing direction at |q|@>=
{
set_number_from_substraction(dxout, q->right_x, q->x_coord);
set_number_from_substraction(dyout, q->right_y, q->y_coord);
if (number_zero(dxout) && number_zero(dyout)) {
r = mp_next_knot (q);
set_number_from_substraction(dxout, r->left_x, q->x_coord);
set_number_from_substraction(dyout, r->left_y, q->y_coord);
if (number_zero(dxout) && number_zero(dyout)) {
set_number_from_substraction(dxout, r->x_coord, q->x_coord);
set_number_from_substraction(dyout, r->y_coord, q->y_coord);
}
}
if (q == c) {
number_substract(dxout, h->x_coord);
number_substract(dyout, h->y_coord);
}
pyth_add (tmp, dxout, dyout);
if (number_zero(tmp)) {
/* |mp_confusion (mp, "degenerate spec");| */
@:this can't happen degerate spec}{\quad degenerate spec@>;
/* But apparently, it actually can happen. The test case is this:
path p;
linejoin := mitered;
p:= (10,0)..(0,10)..(-10,0)..(0,-10)..cycle;
addto currentpicture contour p withpen pensquare;
The reason for failure here is the addition of |r != q| in revision 1757
in ``Advance |p| to node |q|, removing any ``dead'' cubics'', which itself
was needed to fix a bug with disappearing knots in a path that was rotated
exactly 45 degrees (luatex.org bug 530).
*/
} else {
mp_number r1;
new_fraction (r1);
make_fraction (r1, dxout, tmp);
number_clone(dxout, r1);
make_fraction (r1, dyout, tmp);
number_clone(dyout, r1);
free_number (r1);
}
}
@* Direction and intersection times.
A path of length $n$ is defined parametrically by functions $x(t)$ and
$y(t)$, for |0<=t<=n|; we can regard $t$ as the ``time'' at which the path
reaches the point $\bigl(x(t),y(t)\bigr)$. In this section of the program
we shall consider operations that determine special times associated with
given paths: the first time that a path travels in a given direction, and
a pair of times at which two paths cross each other.
@ Let's start with the easier task. The function |find_direction_time| is
given a direction |(x,y)| and a path starting at~|h|. If the path never
travels in direction |(x,y)|, the direction time will be~|-1|; otherwise
it will be nonnegative.
Certain anomalous cases can arise: If |(x,y)=(0,0)|, so that the given
direction is undefined, the direction time will be~0. If $\bigl(x'(t),
y'(t)\bigr)=(0,0)$, so that the path direction is undefined, it will be
assumed to match any given direction at time~|t|.
The routine solves this problem in nondegenerate cases by rotating the path
and the given direction so that |(x,y)=(1,0)|; i.e., the main task will be
to find when a given path first travels ``due east.''
@c
static void mp_find_direction_time (MP mp, mp_number *ret, mp_number x_orig, mp_number y_orig, mp_knot h) {
mp_number max; /* $\max\bigl(\vert x\vert,\vert y\vert\bigr)$ */
mp_knot p, q; /* for list traversal */
mp_number n; /* the direction time at knot |p| */
mp_number tt; /* the direction time within a cubic */
mp_number x, y;
mp_number abs_x, abs_y;
/* Other local variables for |find_direction_time| */
mp_number x1, x2, x3, y1, y2, y3; /* multiples of rotated derivatives */
mp_number phi; /* angles of exit and entry at a knot */
mp_number t; /* temp storage */
mp_number ab_vs_cd;
new_number(max);
new_number(x1);
new_number(x2);
new_number(x3);
new_number(y1);
new_number(y2);
new_number(y3);
new_fraction(t);
new_angle(phi);
new_number (ab_vs_cd);
set_number_to_zero (*ret); /* just in case */
new_number (x);
new_number (y);
new_number (abs_x);
new_number (abs_y);
new_number (n);
new_fraction (tt);
number_clone (x, x_orig);
number_clone (y, y_orig);
number_clone (abs_x, x_orig);
number_clone (abs_y, y_orig);
number_abs (abs_x);
number_abs (abs_y);
/* Normalize the given direction for better accuracy;
but |return| with zero result if it's zero */
if (number_less(abs_x, abs_y)) {
mp_number r1;
new_fraction (r1);
make_fraction (r1, x, abs_y);
number_clone(x, r1);
free_number (r1);
if (number_positive(y)) {
number_clone(y, fraction_one_t);
} else {
number_clone(y, fraction_one_t);
number_negate(y);
}
} else if (number_zero(x)) {
goto FREE;
} else {
mp_number r1;
new_fraction (r1);
make_fraction (r1, y, abs_x);
number_clone(y, r1);
free_number (r1);
if (number_positive(x)) {
number_clone(x, fraction_one_t);
} else {
number_clone(x, fraction_one_t);
number_negate(x);
}
}
p = h;
while (1) {
if (mp_right_type (p) == mp_endpoint)
break;
q = mp_next_knot (p);
@<Rotate the cubic between |p| and |q|; then
|goto found| if the rotated cubic travels due east at some time |tt|;
but |break| if an entire cyclic path has been traversed@>;
p = q;
number_add(n, unity_t);
}
set_number_to_unity (*ret);
number_negate(*ret);
goto FREE;
FOUND:
set_number_from_addition (*ret, n, tt);
goto FREE;
FREE:
free_number (x);
free_number (y);
free_number (abs_x);
free_number (abs_y);
/* Free local variables for |find_direction_time| */
free_number (x1);
free_number (x2);
free_number (x3);
free_number (y1);
free_number (y2);
free_number (y3);
free_number (t);
free_number (phi);
free_number (ab_vs_cd);
free_number (n);
free_number (max);
free_number (tt);
}
@ Since we're interested in the tangent directions, we work with the
derivative $${1\over3}B'(x_0,x_1,x_2,x_3;t)=
B(x_1-x_0,x_2-x_1,x_3-x_2;t)$$ instead of
$B(x_0,x_1,x_2,x_3;t)$ itself. The derived coefficients are also scale-d up
in order to achieve better accuracy.
The given path may turn abruptly at a knot, and it might pass the critical
tangent direction at such a time. Therefore we remember the direction |phi|
in which the previous rotated cubic was traveling. (The value of |phi| will be
undefined on the first cubic, i.e., when |n=0|.)
@d we_found_it {
number_clone (tt, t);
fraction_to_round_scaled (tt);
goto FOUND;
}
@<Rotate the cubic between |p| and |q|; then...@>=
set_number_to_zero(tt);
/* Set local variables |x1,x2,x3| and |y1,y2,y3| to multiples of the control
points of the rotated derivatives */
{
mp_number absval;
new_number (absval);
set_number_from_substraction(x1, p->right_x, p->x_coord);
set_number_from_substraction(x2, q->left_x, p->right_x);
set_number_from_substraction(x3, q->x_coord, q->left_x);
set_number_from_substraction(y1, p->right_y, p->y_coord);
set_number_from_substraction(y2, q->left_y, p->right_y);
set_number_from_substraction(y3, q->y_coord, q->left_y);
number_clone(absval, x2);
number_abs(absval);
number_clone(max, x1);
number_abs(max);
if (number_greater(absval, max)) {
number_clone(max, absval);
}
number_clone(absval, x3);
number_abs(absval);
if (number_greater(absval, max)) {
number_clone(max, absval);
}
number_clone(absval, y1);
number_abs(absval);
if (number_greater(absval, max)) {
number_clone(max, absval);
}
number_clone(absval, y2);
number_abs(absval);
if (number_greater(absval, max)) {
number_clone(max, absval);
}
number_clone(absval, y3);
number_abs(absval);
if (number_greater(absval, max)) {
number_clone(max, absval);
}
free_number (absval);
if (number_zero(max))
goto FOUND;
while (number_less (max, fraction_half_t)) {
number_double(max);
number_double(x1);
number_double(x2);
number_double(x3);
number_double(y1);
number_double(y2);
number_double(y3);
}
number_clone(t, x1);
{
mp_number r1, r2;
new_fraction (r1);
new_fraction (r2);
take_fraction (r1, x1, x);
take_fraction (r2, y1, y);
set_number_from_addition(x1, r1, r2);
take_fraction (r1, y1, x);
take_fraction (r2, t, y);
set_number_from_substraction(y1, r1, r2);
number_clone(t, x2);
take_fraction (r1, x2, x);
take_fraction (r2, y2, y);
set_number_from_addition(x2, r1, r2);
take_fraction (r1, y2, x);
take_fraction (r2, t, y);
set_number_from_substraction(y2, r1, r2);
number_clone(t, x3);
take_fraction (r1, x3 ,x);
take_fraction (r2, y3, y);
set_number_from_addition(x3, r1, r2);
take_fraction (r1, y3, x);
take_fraction (r2, t, y);
set_number_from_substraction(y3, r1, r2);
free_number (r1);
free_number (r2);
}
}
if (number_zero(y1))
if (number_zero(x1) || number_positive(x1))
goto FOUND;
if (number_positive(n)) {
/* Exit to |found| if an eastward direction occurs at knot |p| */
mp_number theta;
mp_number tmp;
new_angle (theta);
n_arg (theta, x1, y1);
new_angle (tmp);
set_number_from_substraction (tmp, theta, one_eighty_deg_t);
if (number_nonnegative(theta) && number_nonpositive(phi) && number_greaterequal(phi, tmp)) {
free_number (tmp);
free_number (theta);
goto FOUND;
}
set_number_from_addition (tmp, theta, one_eighty_deg_t);
if (number_nonpositive(theta) && number_nonnegative(phi) && number_lessequal(phi, tmp)) {
free_number (tmp);
free_number (theta);
goto FOUND;
}
free_number (tmp);
free_number (theta);
if (p == h)
break;
}
if (number_nonzero(x3) || number_nonzero(y3)) {
n_arg (phi, x3, y3);
}
/* Exit to |found| if the curve whose derivatives are specified by
|x1,x2,x3,y1,y2,y3| travels eastward at some time~|tt| */
/* In this step we want to use the |crossing_point| routine to find the
roots of the quadratic equation $B(y_1,y_2,y_3;t)=0$.
Several complications arise: If the quadratic equation has a double root,
the curve never crosses zero, and |crossing_point| will find nothing;
this case occurs iff $y_1y_3=y_2^2$ and $y_1y_2<0$. If the quadratic
equation has simple roots, or only one root, we may have to negate it
so that $B(y_1,y_2,y_3;t)$ crosses from positive to negative at its first root.
And finally, we need to do special things if $B(y_1,y_2,y_3;t)$ is
identically zero. */
if (number_negative(x1))
if (number_negative(x2))
if (number_negative(x3))
goto DONE;
{
ab_vs_cd (ab_vs_cd, y1, y3, y2, y2);
if (number_zero(ab_vs_cd)) {
/* Handle the test for eastward directions when $y_1y_3=y_2^2$;
either |goto found| or |goto done| */
{
ab_vs_cd (ab_vs_cd, y1, y2, zero_t, zero_t);
if (number_negative(ab_vs_cd)) {
mp_number tmp, arg2;
new_number(tmp);
new_number(arg2);
set_number_from_substraction (arg2, y1, y2);
make_fraction (t, y1, arg2);
free_number (arg2);
set_number_from_of_the_way(x1, t, x1, x2);
set_number_from_of_the_way(x2, t, x2, x3);
set_number_from_of_the_way(tmp, t, x1, x2);
if (number_zero(tmp) || number_positive(tmp)) {
free_number (tmp);
we_found_it;
}
free_number (tmp);
} else if (number_zero(y3)) {
if (number_zero(y1)) {
/* Exit to |found| if the derivative $B(x_1,x_2,x_3;t)$ becomes |>=0| */
/* At this point we know that the derivative of |y(t)| is identically zero,
and that |x1<0|; but either |x2>=0| or |x3>=0|, so there's some hope of
traveling east. */
{
mp_number arg1, arg2, arg3;
new_number (arg1);
new_number (arg2);
new_number (arg3);
number_clone(arg1, x1);
number_negate(arg1);
number_clone(arg2, x2);
number_negate(arg2);
number_clone(arg3, x3);
number_negate(arg3);
crossing_point (t, arg1, arg2, arg3);
free_number (arg1);
free_number (arg2);
free_number (arg3);
if (number_lessequal (t, fraction_one_t))
we_found_it;
ab_vs_cd (ab_vs_cd, x1, x3, x2, x2);
if (number_nonpositive(ab_vs_cd)) {
mp_number arg2;
new_number (arg2);
set_number_from_substraction (arg2, x1, x2);
make_fraction (t, x1, arg2);
free_number (arg2);
we_found_it;
}
}
} else if (number_zero(x3) || number_positive(x3)) {
set_number_to_unity(tt);
goto FOUND;
}
}
goto DONE;
}
}
}
if (number_zero(y1) || number_negative(y1)) {
if (number_negative(y1)) {
number_negate(y1);
number_negate(y2);
number_negate(y3);
} else if (number_positive(y2)) {
number_negate(y2);
number_negate(y3);
}
}
/* Check the places where $B(y_1,y_2,y_3;t)=0$ to see if
$B(x_1,x_2,x_3;t)\ge0$ */
/* The quadratic polynomial $B(y_1,y_2,y_3;t)$ begins |>=0| and has at most
two roots, because we know that it isn't identically zero.
It must be admitted that the |crossing_point| routine is not perfectly accurate;
rounding errors might cause it to find a root when $y_1y_3>y_2^2$, or to
miss the roots when $y_1y_3<y_2^2$. The rotation process is itself
subject to rounding errors. Yet this code optimistically tries to
do the right thing.
*/
crossing_point (t, y1, y2, y3);
if (number_greater (t, fraction_one_t))
goto DONE;
set_number_from_of_the_way(y2, t, y2, y3);
set_number_from_of_the_way(x1, t, x1, x2);
set_number_from_of_the_way(x2, t, x2, x3);
set_number_from_of_the_way(x1, t, x1, x2);
if (number_zero(x1) || number_positive(x1))
we_found_it;
if (number_positive(y2))
set_number_to_zero(y2);
number_clone(tt, t);
{
mp_number arg1, arg2, arg3;
new_number (arg1);
new_number (arg2);
new_number (arg3);
number_clone(arg2, y2);
number_negate(arg2);
number_clone(arg3, y3);
number_negate(arg3);
crossing_point (t, arg1, arg2, arg3);
free_number (arg1);
free_number (arg2);
free_number (arg3);
}
if (number_greater (t, fraction_one_t))
goto DONE;
{
mp_number tmp;
new_number(tmp);
set_number_from_of_the_way(x1, t, x1, x2);
set_number_from_of_the_way(x2, t, x2, x3);
set_number_from_of_the_way(tmp, t, x1, x2);
if (number_nonnegative(tmp)) {
free_number (tmp);
set_number_from_of_the_way (t, t, tt, fraction_one_t);
we_found_it;
}
free_number (tmp);
}
DONE:
@ The intersection of two cubics can be found by an interesting variant
of the general bisection scheme described in the introduction to
|crossing_point|.\
Given $w(t)=B(w_0,w_1,w_2,w_3;t)$ and $z(t)=B(z_0,z_1,z_2,z_3;t)$,
we wish to find a pair of times $(t_1,t_2)$ such that $w(t_1)=z(t_2)$,
if an intersection exists. First we find the smallest rectangle that
encloses the points $\{w_0,w_1,w_2,w_3\}$ and check that it overlaps
the smallest rectangle that encloses
$\{z_0,z_1,z_2,z_3\}$; if not, the cubics certainly don't intersect.
But if the rectangles do overlap, we bisect the intervals, getting
new cubics $w'$ and~$w''$, $z'$~and~$z''$; the intersection routine first
tries for an intersection between $w'$ and~$z'$, then (if unsuccessful)
between $w'$ and~$z''$, then (if still unsuccessful) between $w''$ and~$z'$,
finally (if thrice unsuccessful) between $w''$ and~$z''$. After $l$~successful
levels of bisection we will have determined the intersection times $t_1$
and~$t_2$ to $l$~bits of accuracy.
\def\submin{_{\rm min}} \def\submax{_{\rm max}}
As before, it is better to work with the numbers $W_k=2^l(w_k-w_{k-1})$
and $Z_k=2^l(z_k-z_{k-1})$ rather than the coefficients $w_k$ and $z_k$
themselves. We also need one other quantity, $\Delta=2^l(w_0-z_0)$,
to determine when the enclosing rectangles overlap. Here's why:
The $x$~coordinates of~$w(t)$ are between $u\submin$ and $u\submax$,
and the $x$~coordinates of~$z(t)$ are between $x\submin$ and $x\submax$,
if we write $w_k=(u_k,v_k)$ and $z_k=(x_k,y_k)$ and $u\submin=
\min(u_0,u_1,u_2,u_3)$, etc. These intervals of $x$~coordinates
overlap if and only if $u\submin\L x\submax$ and
$x\submin\L u\submax$. Letting
$$U\submin=\min(0,U_1,U_1+U_2,U_1+U_2+U_3),\;
U\submax=\max(0,U_1,U_1+U_2,U_1+U_2+U_3),$$
we have $2^lu\submin=2^lu_0+U\submin$, etc.; the condition for overlap
reduces to
$$X\submin-U\submax\L 2^l(u_0-x_0)\L X\submax-U\submin.$$
Thus we want to maintain the quantity $2^l(u_0-x_0)$; similarly,
the quantity $2^l(v_0-y_0)$ accounts for the $y$~coordinates. The
coordinates of $\Delta=2^l(w_0-z_0)$ must stay bounded as $l$ increases,
because of the overlap condition; i.e., we know that $X\submin$,
$X\submax$, and their relatives are bounded, hence $X\submax-
U\submin$ and $X\submin-U\submax$ are bounded.
@ Incidentally, if the given cubics intersect more than once, the process
just sketched will not necessarily find the lexicographically smallest pair
$(t_1,t_2)$. The solution actually obtained will be smallest in ``shuffled
order''; i.e., if $t_1=(.a_1a_2\ldots a_{16})_2$ and
$t_2=(.b_1b_2\ldots b_{16})_2$, then we will minimize
$a_1b_1a_2b_2\ldots a_{16}b_{16}$, not
$a_1a_2\ldots a_{16}b_1b_2\ldots b_{16}$.
Shuffled order agrees with lexicographic order if all pairs of solutions
$(t_1,t_2)$ and $(t_1',t_2')$ have the property that $t_1<t_1'$ iff
$t_2<t_2'$; but in general, lexicographic order can be quite different,
and the bisection algorithm would be substantially less efficient if it were
constrained by lexicographic order.
For example, suppose that an overlap has been found for $l=3$ and
$(t_1,t_2)= (.101,.011)$ in binary, but that no overlap is produced by
either of the alternatives $(.1010,.0110)$, $(.1010,.0111)$ at level~4.
Then there is probably an intersection in one of the subintervals
$(.1011,.011x)$; but lexicographic order would require us to explore
$(.1010,.1xxx)$ and $(.1011,.00xx)$ and $(.1011,.010x)$ first. We wouldn't
want to store all of the subdivision data for the second path, so the
subdivisions would have to be regenerated many times. Such inefficiencies
would be associated with every `1' in the binary representation of~$t_1$.
@ The subdivision process introduces rounding errors, hence we need to
make a more liberal test for overlap. It is not hard to show that the
computed values of $U_i$ differ from the truth by at most~$l$, on
level~$l$, hence $U\submin$ and $U\submax$ will be at most $3l$ in error.
If $\beta$ is an upper bound on the absolute error in the computed
components of $\Delta=(|delx|,|dely|)$ on level~$l$, we will replace
the test `$X\submin-U\submax\L|delx|$' by the more liberal test
`$X\submin-U\submax\L|delx|+|tol|$', where $|tol|=6l+\beta$.
More accuracy is obtained if we try the algorithm first with |tol=0|;
the more liberal tolerance is used only if an exact approach fails.
It is convenient to do this double-take by letting `3' in the preceding
paragraph be a parameter, which is first 0, then 3.
@<Glob...@>=
unsigned int tol_step; /* either 0 or 3, usually */
@ We shall use an explicit stack to implement the recursive bisection
method described above. The |bisect_stack| array will contain numerous 5-word
packets like $(U_1,U_2,U_3,U\submin,U\submax)$, as well as 20-word packets
comprising the 5-word packets for $U$, $V$, $X$, and~$Y$.
The following macros define the allocation of stack positions to
the quantities needed for bisection-intersection.
@d stack_1(A) mp->bisect_stack[(A)] /* $U_1$, $V_1$, $X_1$, or $Y_1$ */
@d stack_2(A) mp->bisect_stack[(A)+1] /* $U_2$, $V_2$, $X_2$, or $Y_2$ */
@d stack_3(A) mp->bisect_stack[(A)+2] /* $U_3$, $V_3$, $X_3$, or $Y_3$ */
@d stack_min(A) mp->bisect_stack[(A)+3]
/* $U\submin$, $V\submin$, $X\submin$, or $Y\submin$ */
@d stack_max(A) mp->bisect_stack[(A)+4]
/* $U\submax$, $V\submax$, $X\submax$, or $Y\submax$ */
@d int_packets 20 /* number of words to represent $U_k$, $V_k$, $X_k$, and $Y_k$ */
@#
@d u_packet(A) ((A)-5)
@d v_packet(A) ((A)-10)
@d x_packet(A) ((A)-15)
@d y_packet(A) ((A)-20)
@d l_packets (mp->bisect_ptr-int_packets)
@d r_packets mp->bisect_ptr
@d ul_packet u_packet(l_packets) /* base of $U'_k$ variables */
@d vl_packet v_packet(l_packets) /* base of $V'_k$ variables */
@d xl_packet x_packet(l_packets) /* base of $X'_k$ variables */
@d yl_packet y_packet(l_packets) /* base of $Y'_k$ variables */
@d ur_packet u_packet(r_packets) /* base of $U''_k$ variables */
@d vr_packet v_packet(r_packets) /* base of $V''_k$ variables */
@d xr_packet x_packet(r_packets) /* base of $X''_k$ variables */
@d yr_packet y_packet(r_packets) /* base of $Y''_k$ variables */
@#
@d u1l stack_1(ul_packet) /* $U'_1$ */
@d u2l stack_2(ul_packet) /* $U'_2$ */
@d u3l stack_3(ul_packet) /* $U'_3$ */
@d v1l stack_1(vl_packet) /* $V'_1$ */
@d v2l stack_2(vl_packet) /* $V'_2$ */
@d v3l stack_3(vl_packet) /* $V'_3$ */
@d x1l stack_1(xl_packet) /* $X'_1$ */
@d x2l stack_2(xl_packet) /* $X'_2$ */
@d x3l stack_3(xl_packet) /* $X'_3$ */
@d y1l stack_1(yl_packet) /* $Y'_1$ */
@d y2l stack_2(yl_packet) /* $Y'_2$ */
@d y3l stack_3(yl_packet) /* $Y'_3$ */
@d u1r stack_1(ur_packet) /* $U''_1$ */
@d u2r stack_2(ur_packet) /* $U''_2$ */
@d u3r stack_3(ur_packet) /* $U''_3$ */
@d v1r stack_1(vr_packet) /* $V''_1$ */
@d v2r stack_2(vr_packet) /* $V''_2$ */
@d v3r stack_3(vr_packet) /* $V''_3$ */
@d x1r stack_1(xr_packet) /* $X''_1$ */
@d x2r stack_2(xr_packet) /* $X''_2$ */
@d x3r stack_3(xr_packet) /* $X''_3$ */
@d y1r stack_1(yr_packet) /* $Y''_1$ */
@d y2r stack_2(yr_packet) /* $Y''_2$ */
@d y3r stack_3(yr_packet) /* $Y''_3$ */
@#
@d stack_dx mp->bisect_stack[mp->bisect_ptr] /* stacked value of |delx| */
@d stack_dy mp->bisect_stack[mp->bisect_ptr+1] /* stacked value of |dely| */
@d stack_tol mp->bisect_stack[mp->bisect_ptr+2] /* stacked value of |tol| */
@d stack_uv mp->bisect_stack[mp->bisect_ptr+3] /* stacked value of |uv| */
@d stack_xy mp->bisect_stack[mp->bisect_ptr+4] /* stacked value of |xy| */
@d int_increment (int_packets+int_packets+5) /* number of stack words per level */
@<Glob...@>=
mp_number *bisect_stack;
integer bisect_ptr;
@ @<Allocate or initialize ...@>=
mp->bisect_stack = xmalloc ((bistack_size + 1), sizeof (mp_number));
{
int i;
for (i=0;i<bistack_size + 1;i++) {
new_number (mp->bisect_stack[i]);
}
}
@ @<Dealloc variables@>=
{
int i;
for (i=0;i<bistack_size + 1;i++) {
free_number (mp->bisect_stack[i]);
}
}
xfree (mp->bisect_stack);
@ @<Check the ``constant''...@>=
if (int_packets + 17 * int_increment > bistack_size)
mp->bad = 19;
@ Computation of the min and max is a tedious but fairly fast sequence of
instructions; exactly four comparisons are made in each branch.
@d set_min_max(A)
debug_number (stack_1(A));
debug_number (stack_3(A));
debug_number (stack_2(A));
debug_number (stack_min(A));
debug_number (stack_max(A));
if ( number_negative(stack_1((A))) ) {
if ( number_nonnegative (stack_3((A))) ) {
if ( number_negative (stack_2((A))) )
set_number_from_addition (stack_min((A)), stack_1((A)), stack_2((A)));
else
number_clone (stack_min((A)), stack_1((A)));
set_number_from_addition (stack_max((A)), stack_1((A)), stack_2((A)));
number_add (stack_max((A)), stack_3((A)));
if ( number_negative (stack_max((A))) )
set_number_to_zero (stack_max((A)));
} else {
set_number_from_addition (stack_min((A)), stack_1((A)), stack_2((A)));
number_add (stack_min((A)), stack_3((A)));
if ( number_greater (stack_min((A)), stack_1((A))))
number_clone (stack_min((A)), stack_1((A)));
set_number_from_addition (stack_max((A)), stack_1((A)), stack_2((A)));
if ( number_negative (stack_max((A))) )
set_number_to_zero (stack_max((A)));
}
} else if ( number_nonpositive (stack_3((A)))) {
if ( number_positive (stack_2((A))) )
set_number_from_addition (stack_max((A)), stack_1((A)), stack_2((A)));
else
number_clone (stack_max((A)), stack_1((A)));
set_number_from_addition (stack_min((A)), stack_1((A)), stack_2((A)));
number_add (stack_min((A)), stack_3((A)));
if ( number_positive (stack_min((A))) )
set_number_to_zero (stack_min((A)));
} else {
set_number_from_addition (stack_max((A)), stack_1((A)), stack_2((A)));
number_add (stack_max((A)), stack_3((A)));
if ( number_less (stack_max((A)), stack_1((A))))
number_clone (stack_max((A)), stack_1((A)));
set_number_from_addition (stack_min((A)), stack_1((A)), stack_2((A)));
if ( number_positive (stack_min((A))) )
set_number_to_zero (stack_min((A)));
}
@ It's convenient to keep the current values of $l$, $t_1$, and $t_2$ in
the integer form $2^l+2^lt_1$ and $2^l+2^lt_2$. The |cubic_intersection|
routine uses global variables |cur_t| and |cur_tt| for this purpose;
after successful completion, |cur_t| and |cur_tt| will contain |unity|
plus the |scaled| values of $t_1$ and~$t_2$.
The values of |cur_t| and |cur_tt| will be set to zero if |cubic_intersection|
finds no intersection. The routine gives up and gives an approximate answer
if it has backtracked
more than 5000 times (otherwise there are cases where several minutes
of fruitless computation would be possible).
@d max_patience 5000
@<Glob...@>=
mp_number cur_t;
mp_number cur_tt; /* controls and results of |cubic_intersection| */
integer time_to_go; /* this many backtracks before giving up */
mp_number max_t; /* maximum of $2^{l+1}$ so far achieved */
@ @<Initialize table ...@>=
new_number (mp->cur_t);
new_number (mp->cur_tt);
new_number (mp->max_t);
@ @<Dealloc ...@>=
free_number (mp->cur_t);
free_number (mp->cur_tt);
free_number (mp->max_t);
@ The given cubics $B(w_0,w_1,w_2,w_3;t)$ and
$B(z_0,z_1,z_2,z_3;t)$ are specified in adjacent knot nodes |(p,mp_link(p))|
and |(pp,mp_link(pp))|, respectively.
@d half(A) ((A)/2)
@c
static void mp_cubic_intersection (MP mp, mp_knot p, mp_knot pp) {
mp_knot q, qq; /* |mp_link(p)|, |mp_link(pp)| */
mp->time_to_go = max_patience;
set_number_from_scaled (mp->max_t, 2);
@<Initialize for intersections at level zero@>;
CONTINUE:
while (1) {
if (number_to_scaled (mp->delx) - mp->tol <=
number_to_scaled (stack_max (x_packet (mp->xy))) - number_to_scaled (stack_min (u_packet (mp->uv))))
if (number_to_scaled (mp->delx) + mp->tol >=
number_to_scaled (stack_min (x_packet (mp->xy))) - number_to_scaled (stack_max (u_packet (mp->uv))))
if (number_to_scaled (mp->dely) - mp->tol <=
number_to_scaled (stack_max (y_packet (mp->xy))) - number_to_scaled (stack_min (v_packet (mp->uv))))
if (number_to_scaled (mp->dely) + mp->tol >=
number_to_scaled (stack_min (y_packet (mp->xy))) - number_to_scaled (stack_max (v_packet (mp->uv)))) {
if (number_to_scaled (mp->cur_t) >= number_to_scaled (mp->max_t)) {
if (number_equal(mp->max_t, two_t)) { /* we've done 17 bisections */
set_number_from_scaled (mp->cur_t, ((number_to_scaled (mp->cur_t) + 1)/2));
set_number_from_scaled (mp->cur_tt, ((number_to_scaled (mp->cur_tt) + 1)/2));
return;
}
number_double(mp->max_t);
number_clone (mp->appr_t, mp->cur_t);
number_clone (mp->appr_tt, mp->cur_tt);
}
@<Subdivide for a new level of intersection@>;
goto CONTINUE;
}
if (mp->time_to_go > 0) {
decr (mp->time_to_go);
} else {
while (number_less (mp->appr_t, unity_t)) {
number_double(mp->appr_t);
number_double(mp->appr_tt);
}
number_clone (mp->cur_t, mp->appr_t);
number_clone (mp->cur_tt, mp->appr_tt);
return;
}
NOT_FOUND:
/* Advance to the next pair |(cur_t,cur_tt)| */
if (odd (number_to_scaled (mp->cur_tt))) {
if (odd (number_to_scaled (mp->cur_t))) {
/* Descend to the previous level and |goto not_found| */
{
set_number_from_scaled (mp->cur_t, half (number_to_scaled (mp->cur_t)));
set_number_from_scaled (mp->cur_tt, half (number_to_scaled (mp->cur_tt)));
if (number_to_scaled (mp->cur_t) == 0)
return;
mp->bisect_ptr -= int_increment;
mp->three_l -= (integer) mp->tol_step;
number_clone (mp->delx, stack_dx);
number_clone (mp->dely, stack_dy);
mp->tol = number_to_scaled (stack_tol);
mp->uv = number_to_scaled (stack_uv);
mp->xy = number_to_scaled (stack_xy);
goto NOT_FOUND;
}
} else {
set_number_from_scaled (mp->cur_t, number_to_scaled (mp->cur_t) + 1);
number_add (mp->delx, stack_1 (u_packet (mp->uv)));
number_add (mp->delx, stack_2 (u_packet (mp->uv)));
number_add (mp->delx, stack_3 (u_packet (mp->uv)));
number_add (mp->dely, stack_1 (v_packet (mp->uv)));
number_add (mp->dely, stack_2 (v_packet (mp->uv)));
number_add (mp->dely, stack_3 (v_packet (mp->uv)));
mp->uv = mp->uv + int_packets; /* switch from |l_packets| to |r_packets| */
set_number_from_scaled (mp->cur_tt, number_to_scaled (mp->cur_tt) - 1);
mp->xy = mp->xy - int_packets;
number_add (mp->delx, stack_1 (x_packet (mp->xy)));
number_add (mp->delx, stack_2 (x_packet (mp->xy)));
number_add (mp->delx, stack_3 (x_packet (mp->xy)));
number_add (mp->dely, stack_1 (y_packet (mp->xy)));
number_add (mp->dely, stack_2 (y_packet (mp->xy)));
number_add (mp->dely, stack_3 (y_packet (mp->xy)));
}
} else {
set_number_from_scaled (mp->cur_tt, number_to_scaled (mp->cur_tt) + 1);
mp->tol = mp->tol + mp->three_l;
number_substract (mp->delx, stack_1 (x_packet (mp->xy)));
number_substract (mp->delx, stack_2 (x_packet (mp->xy)));
number_substract (mp->delx, stack_3 (x_packet (mp->xy)));
number_substract (mp->dely, stack_1 (y_packet (mp->xy)));
number_substract (mp->dely, stack_2 (y_packet (mp->xy)));
number_substract (mp->dely, stack_3 (y_packet (mp->xy)));
mp->xy = mp->xy + int_packets; /* switch from |l_packets| to |r_packets| */
}
}
}
@ The following variables are global, although they are used only by
|cubic_intersection|, because it is necessary on some machines to
split |cubic_intersection| up into two procedures.
@<Glob...@>=
mp_number delx;
mp_number dely; /* the components of $\Delta=2^l(w_0-z_0)$ */
integer tol; /* bound on the uncertainty in the overlap test */
integer uv;
integer xy; /* pointers to the current packets of interest */
integer three_l; /* |tol_step| times the bisection level */
mp_number appr_t;
mp_number appr_tt; /* best approximations known to the answers */
@ @<Initialize table ...@>=
new_number (mp->delx);
new_number (mp->dely);
new_number (mp->appr_t);
new_number (mp->appr_tt);
@ @<Dealloc...@>=
free_number (mp->delx);
free_number (mp->dely);
free_number (mp->appr_t);
free_number (mp->appr_tt);
@ We shall assume that the coordinates are sufficiently non-extreme that
integer overflow will not occur.
@^overflow in arithmetic@>
@<Initialize for intersections at level zero@>=
q = mp_next_knot (p);
qq = mp_next_knot (pp);
mp->bisect_ptr = int_packets;
set_number_from_substraction (u1r, p->right_x, p->x_coord);
set_number_from_substraction (u2r, q->left_x, p->right_x);
set_number_from_substraction (u3r, q->x_coord, q->left_x);
set_min_max (ur_packet);
set_number_from_substraction (v1r, p->right_y, p->y_coord );
set_number_from_substraction (v2r, q->left_y, p->right_y);
set_number_from_substraction (v3r, q->y_coord, q->left_y );
set_min_max (vr_packet);
set_number_from_substraction (x1r, pp->right_x, pp->x_coord );
set_number_from_substraction (x2r, qq->left_x, pp->right_x );
set_number_from_substraction (x3r, qq->x_coord, qq->left_x );
set_min_max (xr_packet);
set_number_from_substraction (y1r, pp->right_y, pp->y_coord );
set_number_from_substraction (y2r, qq->left_y, pp->right_y);
set_number_from_substraction (y3r, qq->y_coord, qq->left_y);
set_min_max (yr_packet);
set_number_from_substraction (mp->delx, p->x_coord, pp->x_coord );
set_number_from_substraction (mp->dely, p->y_coord, pp->y_coord );
mp->tol = 0;
mp->uv = r_packets;
mp->xy = r_packets;
mp->three_l = 0;
set_number_from_scaled (mp->cur_t, 1);
set_number_from_scaled (mp->cur_tt, 1)
@
@<Subdivide for a new level of intersection@>=
number_clone (stack_dx, mp->delx);
number_clone (stack_dy, mp->dely);
set_number_from_scaled (stack_tol, mp->tol);
set_number_from_scaled (stack_uv, mp->uv);
set_number_from_scaled (stack_xy, mp->xy);
mp->bisect_ptr = mp->bisect_ptr + int_increment;
number_double (mp->cur_t);
number_double (mp->cur_tt);
number_clone (u1l, stack_1 (u_packet (mp->uv)));
number_clone (u3r, stack_3 (u_packet (mp->uv)));
set_number_from_addition (u2l, u1l, stack_2 (u_packet (mp->uv))); number_half (u2l);
set_number_from_addition (u2r, u3r, stack_2 (u_packet (mp->uv))); number_half (u2r);
set_number_from_addition (u3l, u2l, u2r); number_half (u3l);
number_clone (u1r, u3l);
set_min_max (ul_packet);
set_min_max (ur_packet);
number_clone (v1l, stack_1 (v_packet (mp->uv)));
number_clone (v3r, stack_3 (v_packet (mp->uv)));
set_number_from_addition (v2l, v1l, stack_2 (v_packet (mp->uv))); number_half(v2l);
set_number_from_addition (v2r, v3r, stack_2 (v_packet (mp->uv))); number_half(v2r);
set_number_from_addition (v3l, v2l, v2r); number_half(v3l);
number_clone (v1r, v3l);
set_min_max (vl_packet);
set_min_max (vr_packet);
number_clone (x1l, stack_1 (x_packet (mp->xy)));
number_clone (x3r, stack_3 (x_packet (mp->xy)));
set_number_from_addition (x2l, x1l, stack_2 (x_packet (mp->xy))); number_half(x2l);
set_number_from_addition (x2r, x3r, stack_2 (x_packet (mp->xy))); number_half(x2r);
set_number_from_addition (x3l, x2l, x2r); number_half(x3l);
number_clone (x1r, x3l);
set_min_max (xl_packet);
set_min_max (xr_packet);
number_clone (y1l, stack_1 (y_packet (mp->xy)));
number_clone (y3r, stack_3 (y_packet (mp->xy)));
set_number_from_addition (y2l, y1l, stack_2 (y_packet (mp->xy))); number_half (y2l);
set_number_from_addition (y2r, y3r, stack_2 (y_packet (mp->xy))); number_half (y2r);
set_number_from_addition (y3l, y2l, y2r); number_half (y3l);
number_clone (y1r, y3l);
set_min_max (yl_packet);
set_min_max (yr_packet);
mp->uv = l_packets;
mp->xy = l_packets;
number_double(mp->delx);
number_double(mp->dely);
mp->tol = mp->tol - mp->three_l + (integer) mp->tol_step;
mp->tol += mp->tol;
mp->three_l = mp->three_l + (integer) mp->tol_step
@ The |path_intersection| procedure is much simpler.
It invokes |cubic_intersection| in lexicographic order until finding a
pair of cubics that intersect. The final intersection times are placed in
|cur_t| and~|cur_tt|.
@c
static void mp_path_intersection (MP mp, mp_knot h, mp_knot hh) {
mp_knot p, pp; /* link registers that traverse the given paths */
mp_number n, nn; /* integer parts of intersection times, minus |unity| */
@<Change one-point paths into dead cycles@>;
new_number (n);
new_number (nn);
mp->tol_step = 0;
do {
set_number_to_unity(n);
number_negate (n);
p = h;
do {
if (mp_right_type (p) != mp_endpoint) {
set_number_to_unity(nn);
number_negate (nn);
pp = hh;
do {
if (mp_right_type (pp) != mp_endpoint) {
mp_cubic_intersection (mp, p, pp);
if (number_positive (mp->cur_t)) {
number_add (mp->cur_t, n);
number_add (mp->cur_tt, nn);
goto DONE;
}
}
number_add(nn, unity_t);
pp = mp_next_knot (pp);
} while (pp != hh);
}
number_add(n, unity_t);
p = mp_next_knot (p);
} while (p != h);
mp->tol_step = mp->tol_step + 3;
} while (mp->tol_step <= 3);
number_clone (mp->cur_t, unity_t);
number_negate (mp->cur_t);
number_clone (mp->cur_tt, unity_t);
number_negate (mp->cur_tt);
DONE:
free_number (n);
free_number (nn);
}
@ @<Change one-point paths...@>=
if (mp_right_type (h) == mp_endpoint) {
number_clone (h->right_x, h->x_coord);
number_clone (h->left_x, h->x_coord);
number_clone (h->right_y, h->y_coord);
number_clone (h->left_y, h->y_coord);
mp_right_type (h) = mp_explicit;
}
if (mp_right_type (hh) == mp_endpoint) {
number_clone (hh->right_x, hh->x_coord);
number_clone (hh->left_x, hh->x_coord);
number_clone (hh->right_y, hh->y_coord);
number_clone (hh->left_y, hh->y_coord);
mp_right_type (hh) = mp_explicit;
}
@* Dynamic linear equations.
\MP\ users define variables implicitly by stating equations that should be
satisfied; the computer is supposed to be smart enough to solve those equations.
And indeed, the computer tries valiantly to do so, by distinguishing five
different types of numeric values:
\smallskip\hang
|type(p)=mp_known| is the nice case, when |value(p)| is the |scaled| value
of the variable whose address is~|p|.
\smallskip\hang
|type(p)=mp_dependent| means that |value(p)| is not present, but |dep_list(p)|
points to a {\sl dependency list\/} that expresses the value of variable~|p|
as a |scaled| number plus a sum of independent variables with |fraction|
coefficients.
\smallskip\hang
|type(p)=mp_independent| means that |indep_value(p)=s|, where |s>0| is a ``serial
number'' reflecting the time this variable was first used in an equation;
and there is an extra field |indep_scale(p)=m|, with |0<=m<64|, each dependent
variable that refers to this one is actually referring to the future value of
this variable times~$2^m$. (Usually |m=0|, but higher degrees of
scaling are sometimes needed to keep the coefficients in dependency lists
from getting too large. The value of~|m| will always be even.)
\smallskip\hang
|type(p)=mp_numeric_type| means that variable |p| hasn't appeared in an
equation before, but it has been explicitly declared to be numeric.
\smallskip\hang
|type(p)=undefined| means that variable |p| hasn't appeared before.
\smallskip\noindent
We have actually discussed these five types in the reverse order of their
history during a computation: Once |known|, a variable never again
becomes |dependent|; once |dependent|, it almost never again becomes
|mp_independent|; once |mp_independent|, it never again becomes |mp_numeric_type|;
and once |mp_numeric_type|, it never again becomes |undefined| (except
of course when the user specifically decides to scrap the old value
and start again). A backward step may, however, take place: Sometimes
a |dependent| variable becomes |mp_independent| again, when one of the
independent variables it depends on is reverting to |undefined|.
@d indep_scale(A) ((mp_value_node)(A))->data.indep.scale
@d set_indep_scale(A,B) ((mp_value_node)(A))->data.indep.scale=(B)
@d indep_value(A) ((mp_value_node)(A))->data.indep.serial
@d set_indep_value(A,B) ((mp_value_node)(A))->data.indep.serial=(B)
@c
void mp_new_indep(MP mp, mp_node p) { /* create a new independent variable */
if ( mp->serial_no>=max_integer ) {
mp_fatal_error(mp, "variable instance identifiers exhausted");
}
mp_type(p)=mp_independent;
mp->serial_no=mp->serial_no+1;
set_indep_scale(p,0);
set_indep_value(p,mp->serial_no);
}
@ @<Declarations@>=
void mp_new_indep(MP mp, mp_node p);
@ @<Glob...@>=
integer serial_no; /* the most recent serial number */
@ But how are dependency lists represented? It's simple: The linear combination
$\alpha_1v_1+\cdots+\alpha_kv_k+\beta$ appears in |k+1| value nodes. If
|q=dep_list(p)| points to this list, and if |k>0|, then |dep_value(q)=
@t$\alpha_1$@>| (which is a |fraction|); |dep_info(q)| points to the location
of $\alpha_1$; and |mp_link(p)| points to the dependency list
$\alpha_2v_2+\cdots+\alpha_kv_k+\beta$. On the other hand if |k=0|,
then |dep_value(q)=@t$\beta$@>| (which is |scaled|) and |dep_info(q)=NULL|.
The independent variables $v_1$, \dots,~$v_k$ have been sorted so that
they appear in decreasing order of their |value| fields (i.e., of
their serial numbers). \ (It is convenient to use decreasing order,
since |value(NULL)=0|. If the independent variables were not sorted by
serial number but by some other criterion, such as their location in |mem|,
the equation-solving mechanism would be too system-dependent, because
the ordering can affect the computed results.)
The |link| field in the node that contains the constant term $\beta$ is
called the {\sl final link\/} of the dependency list. \MP\ maintains
a doubly-linked master list of all dependency lists, in terms of a permanently
allocated node
in |mem| called |dep_head|. If there are no dependencies, we have
|mp_link(dep_head)=dep_head| and |prev_dep(dep_head)=dep_head|;
otherwise |mp_link(dep_head)| points to the first dependent variable, say~|p|,
and |prev_dep(p)=dep_head|. We have |type(p)=mp_dependent|, and |dep_list(p)|
points to its dependency list. If the final link of that dependency list
occurs in location~|q|, then |mp_link(q)| points to the next dependent
variable (say~|r|); and we have |prev_dep(r)=q|, etc.
Dependency nodes sometimes mutate into value nodes and vice versa, so their
structures have to match.
@d dep_value(A) ((mp_value_node)(A))->data.n
@d set_dep_value(A,B) do_set_dep_value(mp,(A),(B))
@d dep_info(A) get_dep_info(mp, (A))
@d set_dep_info(A,B) do {
mp_value_node d = (mp_value_node)(B);
FUNCTION_TRACE4("set_dep_info(%p,%p) on %d\n",(A),d,__LINE__);
((mp_value_node)(A))->parent_ = (mp_node)d;
} while (0)
@d dep_list(A) ((mp_value_node)(A))->attr_head_ /* half of the |value| field in a |dependent| variable */
@d set_dep_list(A,B) do {
mp_value_node d = (mp_value_node)(B);
FUNCTION_TRACE4("set_dep_list(%p,%p) on %d\n",(A),d,__LINE__);
dep_list((A)) = (mp_node)d;
} while (0)
@d prev_dep(A) ((mp_value_node)(A))->subscr_head_ /* the other half; makes a doubly linked list */
@d set_prev_dep(A,B) do {
mp_value_node d = (mp_value_node)(B);
FUNCTION_TRACE4("set_prev_dep(%p,%p) on %d\n",(A),d,__LINE__);
prev_dep((A)) = (mp_node)d;
} while (0)
@c
static mp_node get_dep_info (MP mp, mp_value_node p) {
mp_node d;
d = p->parent_; /* half of the |value| field in a |dependent| variable */
FUNCTION_TRACE3 ("%p = dep_info(%p)\n", d, p);
return d;
}
static void do_set_dep_value (MP mp, mp_value_node p, mp_number q) {
number_clone (p->data.n, q); /* half of the |value| field in a |dependent| variable */
FUNCTION_TRACE3("set_dep_value(%p,%d)\n", p, q);
p->attr_head_ = NULL;
p->subscr_head_ = NULL;
}
@ @<Declarations...@>=
static mp_node get_dep_info (MP mp, mp_value_node p);
@
@c
static mp_value_node mp_get_dep_node (MP mp) {
mp_value_node p = (mp_value_node) mp_get_value_node (mp);
mp_type (p) = mp_dep_node_type;
return p;
}
static void mp_free_dep_node (MP mp, mp_value_node p) {
mp_free_value_node (mp, (mp_node) p);
}
@ @<Declarations...@>=
static void mp_free_dep_node (MP mp, mp_value_node p);
@ @<Initialize table entries@>=
mp->serial_no = 0;
mp->dep_head = mp_get_dep_node (mp);
set_mp_link (mp->dep_head, (mp_node) mp->dep_head);
set_prev_dep (mp->dep_head, (mp_node) mp->dep_head);
set_dep_info (mp->dep_head, NULL);
set_dep_list (mp->dep_head, NULL);
@ @<Free table entries@>=
mp_free_dep_node (mp, mp->dep_head);
@ Actually the description above contains a little white lie. There's
another kind of variable called |mp_proto_dependent|, which is
just like a |dependent| one except that the $\alpha$ coefficients
in its dependency list are |scaled| instead of being fractions.
Proto-dependency lists are mixed with dependency lists in the
nodes reachable from |dep_head|.
@ Here is a procedure that prints a dependency list in symbolic form.
The second parameter should be either |dependent| or |mp_proto_dependent|,
to indicate the scaling of the coefficients.
@<Declarations@>=
static void mp_print_dependency (MP mp, mp_value_node p, quarterword t);
@ @c
void mp_print_dependency (MP mp, mp_value_node p, quarterword t) {
mp_number v; /* a coefficient */
mp_value_node pp; /* for list manipulation */
mp_node q;
pp = p;
new_number (v);
while (true) {
number_clone (v, dep_value (p));
number_abs (v);
q = dep_info (p);
if (q == NULL) { /* the constant term */
if (number_nonzero(v) || (p == pp)) {
if (number_positive(dep_value (p)))
if (p != pp)
mp_print_char (mp, xord ('+'));
print_number (dep_value (p));
}
return;
}
/* Print the coefficient, unless it's $\pm1.0$ */
if (number_negative(dep_value (p)))
mp_print_char (mp, xord ('-'));
else if (p != pp)
mp_print_char (mp, xord ('+'));
if (t == mp_dependent) {
fraction_to_round_scaled (v);
}
if (!number_equal (v, unity_t))
print_number (v);
if (mp_type (q) != mp_independent)
mp_confusion (mp, "dep");
mp_print_variable_name (mp, q);
set_number_from_scaled (v, indep_scale(q));
while (number_positive (v)) {
mp_print (mp, "*4");
number_add_scaled (v, -2);
}
p = (mp_value_node) mp_link (p);
}
}
@ The maximum absolute value of a coefficient in a given dependency list
is returned by the following simple function.
@c
static void mp_max_coef (MP mp, mp_number *x, mp_value_node p) {
mp_number (absv);
new_number (absv);
set_number_to_zero (*x);
while (dep_info (p) != NULL) {
number_clone (absv, dep_value (p));
number_abs (absv);
if (number_greater (absv, *x)) {
number_clone (*x, absv);
}
p = (mp_value_node) mp_link (p);
}
free_number (absv);
}
@ One of the main operations needed on dependency lists is to add a multiple
of one list to the other; we call this |p_plus_fq|, where |p| and~|q| point
to dependency lists and |f| is a fraction.
If the coefficient of any independent variable becomes |coef_bound| or
more, in absolute value, this procedure changes the type of that variable
to `|independent_needing_fix|', and sets the global variable |fix_needed|
to~|true|. The value of $|coef_bound|=\mu$ is chosen so that
$\mu^2+\mu<8$; this means that the numbers we deal with won't
get too large. (Instead of the ``optimum'' $\mu=(\sqrt{33}-1)/2\approx
2.3723$, the safer value 7/3 is taken as the threshold.)
The changes mentioned in the preceding paragraph are actually done only if
the global variable |watch_coefs| is |true|. But it usually is; in fact,
it is |false| only when \MP\ is making a dependency list that will soon
be equated to zero.
Several procedures that act on dependency lists, including |p_plus_fq|,
set the global variable |dep_final| to the final (constant term) node of
the dependency list that they produce.
@d independent_needing_fix 0
@<Glob...@>=
boolean fix_needed; /* does at least one |independent| variable need scaling? */
boolean watch_coefs; /* should we scale coefficients that exceed |coef_bound|? */
mp_value_node dep_final; /* location of the constant term and final link */
@ @<Set init...@>=
mp->fix_needed = false;
mp->watch_coefs = true;
@ The |p_plus_fq| procedure has a fourth parameter, |t|, that should be
set to |mp_proto_dependent| if |p| is a proto-dependency list. In this
case |f| will be |scaled|, not a |fraction|. Similarly, the fifth parameter~|tt|
should be |mp_proto_dependent| if |q| is a proto-dependency list.
List |q| is unchanged by the operation; but list |p| is totally destroyed.
The final link of the dependency list or proto-dependency list returned
by |p_plus_fq| is the same as the original final link of~|p|. Indeed, the
constant term of the result will be located in the same |mem| location
as the original constant term of~|p|.
Coefficients of the result are assumed to be zero if they are less than
a certain threshold. This compensates for inevitable rounding errors,
and tends to make more variables `|known|'. The threshold is approximately
$10^{-5}$ in the case of normal dependency lists, $10^{-4}$ for
proto-dependencies.
@d fraction_threshold_k ((math_data *)mp->math)->fraction_threshold_t
@d half_fraction_threshold_k ((math_data *)mp->math)->half_fraction_threshold_t
@d scaled_threshold_k ((math_data *)mp->math)->scaled_threshold_t
@d half_scaled_threshold_k ((math_data *)mp->math)->half_scaled_threshold_t
@<Declarations@>=
static mp_value_node mp_p_plus_fq (MP mp, mp_value_node p, mp_number f,
mp_value_node q, mp_variable_type t,
mp_variable_type tt);
@ @c
static mp_value_node mp_p_plus_fq (MP mp, mp_value_node p, mp_number f,
mp_value_node q, mp_variable_type t,
mp_variable_type tt) {
mp_node pp, qq; /* |dep_info(p)| and |dep_info(q)|, respectively */
mp_value_node r, s; /* for list manipulation */
mp_number threshold, half_threshold; /* defines a neighborhood of zero */
mp_number v, vv; /* temporary registers */
new_number (v);
new_number (vv);
new_number (threshold);
new_number (half_threshold);
if (t == mp_dependent) {
number_clone (threshold, fraction_threshold_k);
number_clone (half_threshold, half_fraction_threshold_k);
} else {
number_clone (threshold, scaled_threshold_k);
number_clone (half_threshold, half_scaled_threshold_k);
}
r = (mp_value_node) mp->temp_head;
pp = dep_info (p);
qq = dep_info (q);
while (1) {
if (pp == qq) {
if (pp == NULL) {
break;
} else {
/* Contribute a term from |p|, plus |f| times the
corresponding term from |q| */
mp_number r1;
mp_number absv;
new_fraction (r1);
new_number (absv);
if (tt == mp_dependent) {
take_fraction (r1, f, dep_value (q));
} else {
take_scaled (r1, f, dep_value (q));
}
set_number_from_addition (v, dep_value (p), r1);
free_number (r1);
set_dep_value (p, v);
s = p;
p = (mp_value_node) mp_link (p);
number_clone (absv, v);
number_abs(absv);
if (number_less (absv, threshold)) {
mp_free_dep_node (mp, s);
} else {
if (number_greaterequal (absv, coef_bound_k) && mp->watch_coefs) {
mp_type (qq) = independent_needing_fix;
/* If we set this , then we can drop |(mp_type(pp) == independent_needing_fix && mp->fix_needed)| later */
/* |set_number_from_scaled (value_number (qq), indep_value(qq));| */
mp->fix_needed = true;
}
set_mp_link (r, (mp_node) s);
r = s;
}
free_number (absv);
pp = dep_info (p);
q = (mp_value_node) mp_link (q);
qq = dep_info (q);
}
} else {
if (pp == NULL)
set_number_to_neg_inf(v);
else if (mp_type(pp) == mp_independent || (mp_type(pp) == independent_needing_fix && mp->fix_needed))
set_number_from_scaled(v, indep_value(pp));
else
number_clone (v, value_number (pp));
if (qq == NULL)
set_number_to_neg_inf(vv);
else if (mp_type(qq) == mp_independent || (mp_type(qq) == independent_needing_fix && mp->fix_needed))
set_number_from_scaled(vv, indep_value(qq));
else
number_clone (vv, value_number (qq));
if (number_less (v, vv)) {
/* Contribute a term from |q|, multiplied by~|f| */
mp_number absv;
new_number (absv);
{
mp_number r1;
mp_number arg1, arg2;
new_fraction (r1);
new_number (arg1);
new_number (arg2);
number_clone (arg1, f);
number_clone (arg2, dep_value (q));
if (tt == mp_dependent) {
take_fraction (r1, arg1, arg2);
} else {
take_scaled (r1, arg1, arg2);
}
number_clone (v, r1);
free_number (r1);
free_number (arg1);
free_number (arg2);
}
number_clone (absv, v);
number_abs(absv);
if (number_greater (absv, half_threshold)) {
s = mp_get_dep_node (mp);
set_dep_info (s, qq);
set_dep_value (s, v);
if (number_greaterequal(absv, coef_bound_k) && mp->watch_coefs) {
/* clang: dereference of a null pointer ('qq') */ assert(qq);
mp_type (qq) = independent_needing_fix;
mp->fix_needed = true;
}
set_mp_link (r, (mp_node) s);
r = s;
}
q = (mp_value_node) mp_link (q);
qq = dep_info (q);
free_number (absv);
} else {
set_mp_link (r, (mp_node) p);
r = p;
p = (mp_value_node) mp_link (p);
pp = dep_info (p);
}
}
}
{
mp_number r1;
mp_number arg1, arg2;
new_fraction (r1);
new_number (arg1);
new_number (arg2);
number_clone (arg1, dep_value (q));
number_clone (arg2, f);
if (t == mp_dependent) {
take_fraction (r1, arg1, arg2);
} else {
take_scaled (r1, arg1, arg2);
}
slow_add (arg1, dep_value (p), r1);
set_dep_value (p, arg1);
free_number (r1);
free_number (arg1);
free_number (arg2);
}
set_mp_link (r, (mp_node) p);
mp->dep_final = p;
free_number (threshold);
free_number (half_threshold);
free_number (v);
free_number (vv);
return (mp_value_node) mp_link (mp->temp_head);
}
@ It is convenient to have another subroutine for the special case
of |p_plus_fq| when |f=1.0|. In this routine lists |p| and |q| are
both of the same type~|t| (either |dependent| or |mp_proto_dependent|).
@c
static mp_value_node mp_p_plus_q (MP mp, mp_value_node p, mp_value_node q,
mp_variable_type t) {
mp_node pp, qq; /* |dep_info(p)| and |dep_info(q)|, respectively */
mp_value_node s; /* for list manipulation */
mp_value_node r; /* for list manipulation */
mp_number threshold; /* defines a neighborhood of zero */
mp_number v, vv; /* temporary register */
new_number (v);
new_number (vv);
new_number (threshold);
if (t == mp_dependent)
number_clone (threshold, fraction_threshold_k);
else
number_clone (threshold, scaled_threshold_k);
r = (mp_value_node) mp->temp_head;
pp = dep_info (p);
qq = dep_info (q);
while (1) {
if (pp == qq) {
if (pp == NULL) {
break;
} else {
/* Contribute a term from |p|, plus the corresponding term from |q| */
mp_number test;
new_number (test);
set_number_from_addition (v, dep_value (p), dep_value (q));
set_dep_value (p, v);
s = p;
p = (mp_value_node) mp_link (p);
pp = dep_info (p);
number_clone (test, v);
number_abs(test);
if (number_less (test, threshold)) {
mp_free_dep_node (mp, s);
} else {
if (number_greaterequal(test, coef_bound_k) && mp->watch_coefs) {
mp_type (qq) = independent_needing_fix;
/* If we set this , then we can drop |(mp_type(pp) == independent_needing_fix && mp->fix_needed)| later */
/* |set_number_from_scaled (value_number (qq), indep_value(qq));| */
mp->fix_needed = true;
}
set_mp_link (r, (mp_node) s);
r = s;
}
free_number (test);
q = (mp_value_node) mp_link (q);
qq = dep_info (q);
}
} else {
if (pp == NULL)
set_number_to_zero (v);
else if (mp_type(pp) == mp_independent || (mp_type(pp) == independent_needing_fix && mp->fix_needed))
set_number_from_scaled (v, indep_value(pp));
else
number_clone (v, value_number (pp));
if (qq == NULL)
set_number_to_zero (vv);
else if (mp_type(qq) == mp_independent || (mp_type(qq) == independent_needing_fix && mp->fix_needed))
set_number_from_scaled (vv, indep_value(qq));
else
number_clone (vv, value_number (qq));
if (number_less (v, vv)) {
s = mp_get_dep_node (mp);
set_dep_info (s, qq);
set_dep_value (s, dep_value (q));
q = (mp_value_node) mp_link (q);
qq = dep_info (q);
set_mp_link (r, (mp_node) s);
r = s;
} else {
set_mp_link (r, (mp_node) p);
r = p;
p = (mp_value_node) mp_link (p);
pp = dep_info (p);
}
}
}
{
mp_number r1;
new_number (r1);
slow_add (r1, dep_value (p), dep_value (q));
set_dep_value (p, r1);
free_number (r1);
}
set_mp_link (r, (mp_node) p);
mp->dep_final = p;
free_number (v);
free_number (vv);
free_number (threshold);
return (mp_value_node) mp_link (mp->temp_head);
}
@ A somewhat simpler routine will multiply a dependency list
by a given constant~|v|. The constant is either a |fraction| less than
|fraction_one|, or it is |scaled|. In the latter case we might be forced to
convert a dependency list to a proto-dependency list.
Parameters |t0| and |t1| are the list types before and after;
they should agree unless |t0=mp_dependent| and |t1=mp_proto_dependent|
and |v_is_scaled=true|.
@c
static mp_value_node mp_p_times_v (MP mp, mp_value_node p, mp_number v,
quarterword t0, quarterword t1,
boolean v_is_scaled) {
mp_value_node r, s; /* for list manipulation */
mp_number w; /* tentative coefficient */
mp_number threshold;
boolean scaling_down;
new_number (threshold);
new_number (w);
if (t0 != t1)
scaling_down = true;
else
scaling_down = (!v_is_scaled);
if (t1 == mp_dependent)
number_clone (threshold, half_fraction_threshold_k);
else
number_clone (threshold, half_scaled_threshold_k);
r = (mp_value_node) mp->temp_head;
while (dep_info (p) != NULL) {
mp_number test;
new_number (test);
if (scaling_down) {
take_fraction (w, v, dep_value (p));
} else {
take_scaled (w, v, dep_value (p));
}
number_clone (test, w);
number_abs(test);
if (number_lessequal (test, threshold)) {
s = (mp_value_node) mp_link (p);
mp_free_dep_node (mp, p);
p = s;
} else {
if (number_greaterequal(test, coef_bound_k)) {
mp->fix_needed = true;
mp_type (dep_info (p)) = independent_needing_fix;
}
set_mp_link (r, (mp_node) p);
r = p;
set_dep_value (p, w);
p = (mp_value_node) mp_link (p);
}
free_number (test);
}
set_mp_link (r, (mp_node) p);
{
mp_number r1;
new_number (r1);
if (v_is_scaled) {
take_scaled (r1, dep_value (p), v);
} else {
take_fraction (r1, dep_value (p), v);
}
set_dep_value (p, r1);
free_number (r1);
}
free_number (w);
free_number (threshold);
return (mp_value_node) mp_link (mp->temp_head);
}
@ Similarly, we sometimes need to divide a dependency list
by a given |scaled| constant.
@<Declarations@>=
static mp_value_node mp_p_over_v (MP mp, mp_value_node p, mp_number v, quarterword
t0, quarterword t1);
@
@d p_over_v_threshold_k ((math_data *)mp->math)->p_over_v_threshold_t
@c
mp_value_node mp_p_over_v (MP mp, mp_value_node p, mp_number v_orig, quarterword
t0, quarterword t1) {
mp_value_node r, s; /* for list manipulation */
mp_number w; /* tentative coefficient */
mp_number threshold;
mp_number v;
boolean scaling_down;
new_number (v);
new_number (w);
new_number (threshold);
number_clone (v, v_orig);
if (t0 != t1)
scaling_down = true;
else
scaling_down = false;
if (t1 == mp_dependent)
number_clone (threshold, half_fraction_threshold_k);
else
number_clone (threshold, half_scaled_threshold_k);
r = (mp_value_node) mp->temp_head;
while (dep_info (p) != NULL) {
if (scaling_down) {
mp_number x, absv;
new_number (x);
new_number (absv);
number_clone (absv, v);
number_abs (absv);
if (number_less (absv, p_over_v_threshold_k)) {
number_clone (x, v);
convert_scaled_to_fraction (x);
make_scaled (w, dep_value (p), x);
} else {
number_clone (x, dep_value (p));
fraction_to_round_scaled (x);
make_scaled (w, x, v);
}
free_number (x);
free_number (absv);
} else {
make_scaled (w, dep_value (p), v);
}
{
mp_number test;
new_number (test);
number_clone (test, w);
number_abs(test);
if (number_lessequal (test, threshold)) {
s = (mp_value_node) mp_link (p);
mp_free_dep_node (mp, p);
p = s;
} else {
if (number_greaterequal (test, coef_bound_k)) {
mp->fix_needed = true;
mp_type (dep_info (p)) = independent_needing_fix;
}
set_mp_link (r, (mp_node) p);
r = p;
set_dep_value (p, w);
p = (mp_value_node) mp_link (p);
}
free_number (test);
}
}
set_mp_link (r, (mp_node) p);
{
mp_number ret;
new_number (ret);
make_scaled (ret, dep_value (p), v);
set_dep_value (p, ret);
free_number (ret);
}
free_number (v);
free_number (w);
free_number (threshold);
return (mp_value_node) mp_link (mp->temp_head);
}
@ Here's another utility routine for dependency lists. When an independent
variable becomes dependent, we want to remove it from all existing
dependencies. The |p_with_x_becoming_q| function computes the
dependency list of~|p| after variable~|x| has been replaced by~|q|.
This procedure has basically the same calling conventions as |p_plus_fq|:
List~|q| is unchanged; list~|p| is destroyed; the constant node and the
final link are inherited from~|p|; and the fourth parameter tells whether
or not |p| is |mp_proto_dependent|. However, the global variable |dep_final|
is not altered if |x| does not occur in list~|p|.
@c
static mp_value_node mp_p_with_x_becoming_q (MP mp, mp_value_node p,
mp_node x, mp_node q,
quarterword t) {
mp_value_node r, s; /* for list manipulation */
integer sx; /* serial number of |x| */
s = p;
r = (mp_value_node) mp->temp_head;
sx = indep_value (x);
while (dep_info (s) != NULL && indep_value (dep_info (s)) > sx) {
r = s;
s = (mp_value_node) mp_link (s);
}
if (dep_info (s) == NULL || dep_info (s) != x) {
return p;
} else {
mp_value_node ret;
mp_number v1;
new_number (v1);
set_mp_link (mp->temp_head, (mp_node) p);
set_mp_link (r, mp_link (s));
number_clone (v1, dep_value (s));
mp_free_dep_node (mp, s);
ret = mp_p_plus_fq (mp, (mp_value_node) mp_link (mp->temp_head), v1,
(mp_value_node) q, t, mp_dependent);
free_number (v1);
return ret;
}
}
@ Here's a simple procedure that reports an error when a variable
has just received a known value that's out of the required range.
@<Declarations@>=
static void mp_val_too_big (MP mp, mp_number x);
@ @c
static void mp_val_too_big (MP mp, mp_number x) {
if (number_positive (internal_value (mp_warning_check))) {
char msg[256];
const char *hlp[] = {
"The equation I just processed has given some variable a",
"value outside of the safetyp range. Continue and I'll try",
"to cope with that big value; but it might be dangerous.",
"(Set warningcheck:=0 to suppress this message.)",
NULL };
mp_snprintf (msg, 256, "Value is too large (%s)", number_tostring(x));
mp_error (mp, msg, hlp, true);
}
}
@ When a dependent variable becomes known, the following routine
removes its dependency list. Here |p| points to the variable, and
|q| points to the dependency list (which is one node long).
@<Declarations@>=
static void mp_make_known (MP mp, mp_value_node p, mp_value_node q);
@ @c
void mp_make_known (MP mp, mp_value_node p, mp_value_node q) {
mp_variable_type t; /* the previous type */
mp_number absp;
new_number (absp);
set_prev_dep (mp_link (q), prev_dep (p));
set_mp_link (prev_dep (p), mp_link (q));
t = mp_type (p);
mp_type (p) = mp_known;
set_value_number (p, dep_value (q));
mp_free_dep_node (mp, q);
number_clone (absp, value_number (p));
number_abs (absp);
if (number_greaterequal (absp, warning_limit_t))
mp_val_too_big (mp, value_number (p));
if ((number_positive(internal_value (mp_tracing_equations)))
&& mp_interesting (mp, (mp_node) p)) {
mp_begin_diagnostic (mp);
mp_print_nl (mp, "#### ");
mp_print_variable_name (mp, (mp_node) p);
mp_print_char (mp, xord ('='));
print_number (value_number (p));
mp_end_diagnostic (mp, false);
}
if (cur_exp_node () == (mp_node) p && mp->cur_exp.type == t) {
mp->cur_exp.type = mp_known;
set_cur_exp_value_number (value_number (p));
mp_free_value_node (mp, (mp_node) p);
}
free_number (absp);
}
@ The |fix_dependencies| routine is called into action when |fix_needed|
has been triggered. The program keeps a list~|s| of independent variables
whose coefficients must be divided by~4.
In unusual cases, this fixup process might reduce one or more coefficients
to zero, so that a variable will become known more or less by default.
@<Declarations@>=
static void mp_fix_dependencies (MP mp);
@
@d independent_being_fixed 1 /* this variable already appears in |s| */
@c
static void mp_fix_dependencies (MP mp) {
mp_value_node p, q, r, s, t; /* list manipulation registers */
mp_node x; /* an independent variable */
r = (mp_value_node) mp_link (mp->dep_head);
s = NULL;
while (r != mp->dep_head) {
t = r;
/* Run through the dependency list for variable |t|, fixing
all nodes, and ending with final link~|q| */
while (1) {
if (t==r) {
q = (mp_value_node) dep_list(t);
} else {
q = (mp_value_node) mp_link (r);
}
x = dep_info (q);
if (x == NULL)
break;
if (mp_type (x) <= independent_being_fixed) {
if (mp_type (x) < independent_being_fixed) {
p = mp_get_dep_node (mp);
set_mp_link (p, (mp_node) s);
s = p;
set_dep_info (s, x);
mp_type (x) = independent_being_fixed;
}
set_dep_value (q, dep_value (q));
number_divide_int (dep_value (q), 4);
if (number_zero(dep_value (q))) {
set_mp_link (r, mp_link (q));
mp_free_dep_node (mp, q);
q = r;
}
}
r = q;
}
r = (mp_value_node) mp_link (q);
if (q == (mp_value_node) dep_list (t))
mp_make_known (mp, t, q);
}
while (s != NULL) {
p = (mp_value_node) mp_link (s);
x = dep_info (s);
mp_free_dep_node (mp, s);
s = p;
mp_type (x) = mp_independent;
set_indep_scale (x, indep_scale (x) + 2);
}
mp->fix_needed = false;
}
@ The |new_dep| routine installs a dependency list~|p| based on the value node~|q|,
linking it into the list of all known dependencies. It replaces |q| with the new
dependency node. We assume that |dep_final| points to the final node of list~|p|.
@c
static void mp_new_dep (MP mp, mp_node q, mp_variable_type newtype,
mp_value_node p) {
mp_node r; /* what used to be the first dependency */
FUNCTION_TRACE4 ("mp_new_dep(%p,%d,%p)\n", q, newtype, p);
mp_type (q) = newtype;
set_dep_list (q, p);
set_prev_dep (q, (mp_node) mp->dep_head);
r = mp_link (mp->dep_head);
set_mp_link (mp->dep_final, r);
set_prev_dep (r, (mp_node) mp->dep_final);
set_mp_link (mp->dep_head, q);
}
@ Here is one of the ways a dependency list gets started.
The |const_dependency| routine produces a list that has nothing but
a constant term.
@c
static mp_value_node mp_const_dependency (MP mp, mp_number v) {
mp->dep_final = mp_get_dep_node (mp);
set_dep_value (mp->dep_final, v);
set_dep_info (mp->dep_final, NULL);
FUNCTION_TRACE3 ("%p = mp_const_dependency(%d)\n", mp->dep_final, number_to_scaled (v));
return mp->dep_final;
}
@ And here's a more interesting way to start a dependency list from scratch:
The parameter to |single_dependency| is the location of an
independent variable~|x|, and the result is the simple dependency list
`|x+0|'.
In the unlikely event that the given independent variable has been doubled so
often that we can't refer to it with a nonzero coefficient,
|single_dependency| returns the simple list `0'. This case can be
recognized by testing that the returned list pointer is equal to
|dep_final|.
@d two_to_the(A) (1<<(unsigned)(A))
@c
static mp_value_node mp_single_dependency (MP mp, mp_node p) {
mp_value_node q, rr; /* the new dependency list */
integer m; /* the number of doublings */
m = indep_scale (p);
if (m > 28) {
q = mp_const_dependency (mp, zero_t);
} else {
q = mp_get_dep_node (mp);
set_dep_value (q, zero_t);
set_number_from_scaled (dep_value (q), (integer) two_to_the (28 - m));
set_dep_info (q, p);
rr = mp_const_dependency (mp, zero_t);
set_mp_link (q, (mp_node) rr);
}
FUNCTION_TRACE3 ("%p = mp_single_dependency(%p)\n", q, p);
return q;
}
@ We sometimes need to make an exact copy of a dependency list.
@c
static mp_value_node mp_copy_dep_list (MP mp, mp_value_node p) {
mp_value_node q; /* the new dependency list */
FUNCTION_TRACE2 ("mp_copy_dep_list(%p)\n", p);
q = mp_get_dep_node (mp);
mp->dep_final = q;
while (1) {
set_dep_info (mp->dep_final, dep_info (p));
set_dep_value (mp->dep_final, dep_value (p));
if (dep_info (mp->dep_final) == NULL)
break;
set_mp_link (mp->dep_final, (mp_node) mp_get_dep_node (mp));
mp->dep_final = (mp_value_node) mp_link (mp->dep_final);
p = (mp_value_node) mp_link (p);
}
return q;
}
@ But how do variables normally become known? Ah, now we get to the heart of the
equation-solving mechanism. The |linear_eq| procedure is given a |dependent|
or |mp_proto_dependent| list,~|p|, in which at least one independent variable
appears. It equates this list to zero, by choosing an independent variable
with the largest coefficient and making it dependent on the others. The
newly dependent variable is eliminated from all current dependencies,
thereby possibly making other dependent variables known.
The given list |p| is, of course, totally destroyed by all this processing.
@c
static mp_value_node find_node_with_largest_coefficient(MP mp, mp_value_node p, mp_number *v);
static void display_new_dependency (MP mp, mp_value_node p, mp_node x, integer n);
static void change_to_known (MP mp, mp_value_node p, mp_node x, mp_value_node final_node, integer n);
static mp_value_node divide_p_by_minusv_removing_q (MP mp, mp_value_node p, mp_value_node q,
mp_value_node *final_node, mp_number v, quarterword t);
static mp_value_node divide_p_by_2_n (MP mp, mp_value_node p, integer n);
static void mp_linear_eq (MP mp, mp_value_node p, quarterword t) {
mp_value_node r; /* for link manipulation */
mp_node x; /* the variable that loses its independence */
integer n; /* the number of times |x| had been halved */
mp_number v; /* the coefficient of |x| in list |p| */
mp_value_node prev_r; /* lags one step behind |r| */
mp_value_node final_node; /* the constant term of the new dependency list */
mp_value_node qq;
new_number (v);
FUNCTION_TRACE3 ("mp_linear_eq(%p,%d)\n", p, t);
qq = find_node_with_largest_coefficient(mp, p, &v);
x = dep_info (qq);
n = indep_scale (x);
p = divide_p_by_minusv_removing_q(mp, p, qq, &final_node, v, t);
if (number_positive (internal_value (mp_tracing_equations))) {
display_new_dependency(mp,p,(mp_node)x,n);
}
prev_r = (mp_value_node) mp->dep_head;
r = (mp_value_node) mp_link (mp->dep_head);
while (r != mp->dep_head) {
mp_value_node s = (mp_value_node) dep_list (r);
mp_value_node q = mp_p_with_x_becoming_q (mp, s, x, (mp_node) p, mp_type (r));
if (dep_info (q) == NULL) {
mp_make_known (mp, r, q);
} else {
set_dep_list (r, q);
do {
q = (mp_value_node) mp_link (q);
} while (dep_info (q) != NULL);
prev_r = q;
}
r = (mp_value_node) mp_link (prev_r);
}
if (n > 0) {
p = divide_p_by_2_n(mp, p, n);
}
change_to_known(mp,p,(mp_node)x,final_node,n);
if (mp->fix_needed)
mp_fix_dependencies (mp);
free_number (v);
}
@
@c
static mp_value_node find_node_with_largest_coefficient(MP mp, mp_value_node p, mp_number *v) {
mp_number vabs; /* its absolute value of v*/
mp_number rabs; /* the absolute value of |dep_value(r)| */
mp_value_node q = p;
mp_value_node r = (mp_value_node) mp_link (p);
new_number (vabs);
new_number (rabs);
number_clone (*v, dep_value (q));
while (dep_info (r) != NULL) {
number_clone (vabs, *v);
number_abs (vabs);
number_clone (rabs, dep_value (r));
number_abs (rabs);
if (number_greater (rabs, vabs)) {
q = r;
number_clone (*v, dep_value (r));
}
r = (mp_value_node) mp_link (r);
}
free_number (vabs);
free_number (rabs);
return q;
}
@ Here we want to change the coefficients from |scaled| to |fraction|,
except in the constant term. In the common case of a trivial equation
like `\.{x=3.14}', we will have |v=-fraction_one|, |q=p|, and |t=mp_dependent|.
@c
static mp_value_node divide_p_by_minusv_removing_q (MP mp, mp_value_node p, mp_value_node q,
mp_value_node *final_node, mp_number v, quarterword t) {
mp_value_node r; /* for link manipulation */
mp_value_node s;
s = (mp_value_node) mp->temp_head;
set_mp_link (s, (mp_node) p);
r = p;
do {
if (r == q) {
set_mp_link (s, mp_link (r));
mp_free_dep_node (mp, r);
} else {
mp_number w; /* a tentative coefficient */
mp_number absw;
new_number (w);
new_number (absw);
make_fraction (w, dep_value (r), v);
number_clone (absw, w);
number_abs (absw);
if (number_lessequal (absw, half_fraction_threshold_k)) {
set_mp_link (s, mp_link (r));
mp_free_dep_node (mp, r);
} else {
number_negate (w);
set_dep_value (r, w);
s = r;
}
free_number(w);
free_number (absw);
}
r = (mp_value_node) mp_link (s);
} while (dep_info (r) != NULL);
if (t == mp_proto_dependent) {
mp_number ret;
new_number (ret);
make_scaled (ret, dep_value (r), v);
number_negate (ret);
set_dep_value (r, ret);
free_number (ret);
} else if (number_to_scaled (v) != -number_to_scaled (fraction_one_t)) {
mp_number ret;
new_fraction (ret);
make_fraction (ret, dep_value (r), v);
number_negate (ret);
set_dep_value (r, ret);
free_number (ret);
}
*final_node = r;
return (mp_value_node) mp_link (mp->temp_head);
}
@
@c
static void display_new_dependency (MP mp, mp_value_node p, mp_node x, integer n) {
if (mp_interesting (mp, x)) {
int w0;
mp_begin_diagnostic (mp);
mp_print_nl (mp, "## ");
mp_print_variable_name (mp, x);
w0 = n;
while (w0 > 0) {
mp_print (mp, "*4");
w0 = w0 - 2;
}
mp_print_char (mp, xord ('='));
mp_print_dependency (mp, p, mp_dependent);
mp_end_diagnostic (mp, false);
}
}
@ The |n > 0| test is repeated here because it is of vital importance to the
function's functioning.
@c
static mp_value_node divide_p_by_2_n (MP mp, mp_value_node p, integer n) {
mp_value_node pp = NULL;
if (n > 0) {
/* Divide list |p| by $2^n$ */
mp_value_node r;
mp_value_node s;
mp_number absw;
mp_number w; /* a tentative coefficient */
new_number (w);
new_number (absw);
s = (mp_value_node) mp->temp_head;
set_mp_link (mp->temp_head, (mp_node) p);
r = p;
do {
if (n > 30) {
set_number_to_zero (w);
} else {
number_clone (w, dep_value (r));
number_divide_int (w, two_to_the (n));
}
number_clone (absw, w);
number_abs (absw);
if (number_lessequal(absw, half_fraction_threshold_k) && (dep_info (r) != NULL)) {
set_mp_link (s, mp_link (r));
mp_free_dep_node (mp, r);
} else {
set_dep_value (r, w);
s = r;
}
r = (mp_value_node) mp_link (s);
} while (dep_info (s) != NULL);
pp = (mp_value_node) mp_link (mp->temp_head);
free_number (absw);
free_number (w);
}
return pp;
}
@
@c
static void change_to_known (MP mp, mp_value_node p, mp_node x, mp_value_node final_node, integer n) {
if (dep_info (p) == NULL) {
mp_number absx;
new_number (absx);
mp_type (x) = mp_known;
set_value_number (x, dep_value (p));
number_clone (absx, value_number (x));
number_abs (absx);
if (number_greaterequal (absx, warning_limit_t))
mp_val_too_big (mp, value_number (x));
free_number (absx);
mp_free_dep_node (mp, p);
if (cur_exp_node () == x && mp->cur_exp.type == mp_independent) {
set_cur_exp_value_number (value_number (x));
mp->cur_exp.type = mp_known;
mp_free_value_node (mp, x);
}
} else {
mp->dep_final = final_node;
mp_new_dep (mp, x, mp_dependent, p);
if (cur_exp_node () == x && mp->cur_exp.type == mp_independent) {
mp->cur_exp.type = mp_dependent;
}
}
}
@* Dynamic nonlinear equations.
Variables of numeric type are maintained by the general scheme of
independent, dependent, and known values that we have just studied;
and the components of pair and transform variables are handled in the
same way. But \MP\ also has five other types of values: \&{boolean},
\&{string}, \&{pen}, \&{path}, and \&{picture}; what about them?
Equations are allowed between nonlinear quantities, but only in a
simple form. Two variables that haven't yet been assigned values are
either equal to each other, or they're not.
Before a boolean variable has received a value, its type is |mp_unknown_boolean|;
similarly, there are variables whose type is |mp_unknown_string|, |mp_unknown_pen|,
|mp_unknown_path|, and |mp_unknown_picture|. In such cases the value is either
|NULL| (which means that no other variables are equivalent to this one), or
it points to another variable of the same undefined type. The pointers in the
latter case form a cycle of nodes, which we shall call a ``ring.''
Rings of undefined variables may include capsules, which arise as
intermediate results within expressions or as \&{expr} parameters to macros.
When one member of a ring receives a value, the same value is given to
all the other members. In the case of paths and pictures, this implies
making separate copies of a potentially large data structure; users should
restrain their enthusiasm for such generality, unless they have lots and
lots of memory space.
@ The following procedure is called when a capsule node is being
added to a ring (e.g., when an unknown variable is mentioned in an expression).
@c
static mp_node mp_new_ring_entry (MP mp, mp_node p) {
mp_node q; /* the new capsule node */
q = mp_get_value_node (mp);
mp_name_type (q) = mp_capsule;
mp_type (q) = mp_type (p);
if (value_node (p) == NULL)
set_value_node (q, p);
else
set_value_node (q, value_node (p));
set_value_node (p, q);
return q;
}
@ Conversely, we might delete a capsule or a variable before it becomes known.
The following procedure simply detaches a quantity from its ring,
without recycling the storage.
@<Declarations@>=
static void mp_ring_delete (MP mp, mp_node p);
@ @c
void mp_ring_delete (MP mp, mp_node p) {
mp_node q;
(void) mp;
q = value_node (p);
if (q != NULL && q != p) {
while (value_node (q) != p)
q = value_node (q);
set_value_node (q, value_node (p));
}
}
@ Eventually there might be an equation that assigns values to all of the
variables in a ring. The |nonlinear_eq| subroutine does the necessary
propagation of values.
If the parameter |flush_p| is |true|, node |p| itself needn't receive a
value, it will soon be recycled.
@c
static void mp_nonlinear_eq (MP mp, mp_value v, mp_node p, boolean flush_p) {
mp_variable_type t; /* the type of ring |p| */
mp_node q, r; /* link manipulation registers */
t = (mp_type (p) - unknown_tag);
q = value_node (p);
if (flush_p)
mp_type (p) = mp_vacuous;
else
p = q;
do {
r = value_node (q);
mp_type (q) = t;
switch (t) {
case mp_boolean_type:
set_value_number (q, v.data.n);
break;
case mp_string_type:
set_value_str (q, v.data.str);
add_str_ref (v.data.str);
break;
case mp_pen_type:
set_value_knot (q, copy_pen (v.data.p));
break;
case mp_path_type:
set_value_knot (q, mp_copy_path (mp, v.data.p));
break;
case mp_picture_type:
set_value_node (q, v.data.node);
add_edge_ref (v.data.node);
break;
default:
break;
} /* there ain't no more cases */
q = r;
} while (q != p);
}
@ If two members of rings are equated, and if they have the same type,
the |ring_merge| procedure is called on to make them equivalent.
@c
static void mp_ring_merge (MP mp, mp_node p, mp_node q) {
mp_node r; /* traverses one list */
r = value_node (p);
while (r != p) {
if (r == q) {
exclaim_redundant_equation(mp);
return;
};
r = value_node (r);
}
r = value_node (p);
set_value_node (p, value_node (q));
set_value_node (q, r);
}
@ @c
static void exclaim_redundant_equation (MP mp) {
const char *hlp[] = {
"I already knew that this equation was true.",
"But perhaps no harm has been done; let's continue.",
NULL };
mp_back_error (mp, "Redundant equation", hlp, true);
mp_get_x_next (mp);
}
@ @<Declarations@>=
static void exclaim_redundant_equation (MP mp);
@* Introduction to the syntactic routines.
Let's pause a moment now and try to look at the Big Picture.
The \MP\ program consists of three main parts: syntactic routines,
semantic routines, and output routines. The chief purpose of the
syntactic routines is to deliver the user's input to the semantic routines,
while parsing expressions and locating operators and operands. The
semantic routines act as an interpreter responding to these operators,
which may be regarded as commands. And the output routines are
periodically called on to produce compact font descriptions that can be
used for typesetting or for making interim proof drawings. We have
discussed the basic data structures and many of the details of semantic
operations, so we are good and ready to plunge into the part of \MP\ that
actually controls the activities.
Our current goal is to come to grips with the |get_next| procedure,
which is the keystone of \MP's input mechanism. Each call of |get_next|
sets the value of three variables |cur_cmd|, |cur_mod|, and |cur_sym|,
representing the next input token.
$$\vbox{\halign{#\hfil\cr
\hbox{|cur_cmd| denotes a command code from the long list of codes
given earlier;}\cr
\hbox{|cur_mod| denotes a modifier or operand of the command code;}\cr
\hbox{|cur_sym| is the hash address of the symbolic token that was
just scanned,}\cr
\hbox{\qquad or zero in the case of a numeric or string
or capsule token.}\cr}}$$
Underlying this external behavior of |get_next| is all the machinery
necessary to convert from character files to tokens. At a given time we
may be only partially finished with the reading of several files (for
which \&{input} was specified), and partially finished with the expansion
of some user-defined macros and/or some macro parameters, and partially
finished reading some text that the user has inserted online,
and so on. When reading a character file, the characters must be
converted to tokens; comments and blank spaces must
be removed, numeric and string tokens must be evaluated.
To handle these situations, which might all be present simultaneously,
\MP\ uses various stacks that hold information about the incomplete
activities, and there is a finite state control for each level of the
input mechanism. These stacks record the current state of an implicitly
recursive process, but the |get_next| procedure is not recursive.
@d cur_cmd() (unsigned)(mp->cur_mod_->type)
@d set_cur_cmd(A) mp->cur_mod_->type=(A)
@d cur_mod_int() number_to_int (mp->cur_mod_->data.n) /* operand of current command */
@d cur_mod() number_to_scaled (mp->cur_mod_->data.n) /* operand of current command */
@d cur_mod_number() mp->cur_mod_->data.n /* operand of current command */
@d set_cur_mod(A) set_number_from_scaled (mp->cur_mod_->data.n, (A))
@d set_cur_mod_number(A) number_clone (mp->cur_mod_->data.n, (A))
@d cur_mod_node() mp->cur_mod_->data.node
@d set_cur_mod_node(A) mp->cur_mod_->data.node=(A)
@d cur_mod_str() mp->cur_mod_->data.str
@d set_cur_mod_str(A) mp->cur_mod_->data.str=(A)
@d cur_sym() mp->cur_mod_->data.sym
@d set_cur_sym(A) mp->cur_mod_->data.sym=(A)
@d cur_sym_mod() mp->cur_mod_->name_type
@d set_cur_sym_mod(A) mp->cur_mod_->name_type=(A)
@<Glob...@>=
mp_node cur_mod_; /* current command, symbol, and its operands */
@ @<Initialize table...@>=
mp->cur_mod_ = mp_get_symbolic_node(mp);
@ @<Free table...@>=
mp_free_symbolic_node(mp, mp->cur_mod_);
@ The |print_cmd_mod| routine prints a symbolic interpretation of a
command code and its modifier.
It consists of a rather tedious sequence of print
commands, and most of it is essentially an inverse to the |primitive|
routine that enters a \MP\ primitive into |hash| and |eqtb|. Therefore almost
all of this procedure appears elsewhere in the program, together with the
corresponding |primitive| calls.
@<Declarations@>=
static void mp_print_cmd_mod (MP mp, integer c, integer m);
@ @c
void mp_print_cmd_mod (MP mp, integer c, integer m) {
switch (c) {
@<Cases of |print_cmd_mod| for symbolic printing of primitives@>
default:
mp_print (mp, "[unknown command code!]");
break;
}
}
@ Here is a procedure that displays a given command in braces, in the
user's transcript file.
@d show_cur_cmd_mod mp_show_cmd_mod(mp, cur_cmd(),cur_mod())
@c
static void mp_show_cmd_mod (MP mp, integer c, integer m) {
mp_begin_diagnostic (mp);
mp_print_nl (mp, "{");
mp_print_cmd_mod (mp, c, m);
mp_print_char (mp, xord ('}'));
mp_end_diagnostic (mp, false);
}
@* Input stacks and states.
The state of \MP's input mechanism appears in the input stack, whose
entries are records with five fields, called |index|, |start|, |loc|,
|limit|, and |name|. The top element of this stack is maintained in a
global variable for which no subscripting needs to be done; the other
elements of the stack appear in an array. Hence the stack is declared thus:
@<Types...@>=
typedef struct {
char *long_name_field;
halfword start_field, loc_field, limit_field;
mp_node nstart_field, nloc_field;
mp_string name_field;
quarterword index_field;
} in_state_record;
@ @<Glob...@>=
in_state_record *input_stack;
integer input_ptr; /* first unused location of |input_stack| */
integer max_in_stack; /* largest value of |input_ptr| when pushing */
in_state_record cur_input; /* the ``top'' input state */
int stack_size; /* maximum number of simultaneous input sources */
@ @<Allocate or initialize ...@>=
mp->stack_size = 16;
mp->input_stack = xmalloc ((mp->stack_size + 1), sizeof (in_state_record));
@ @<Dealloc variables@>=
xfree (mp->input_stack);
@ We've already defined the special variable |loc==cur_input.loc_field|
in our discussion of basic input-output routines. The other components of
|cur_input| are defined in the same way:
@d iindex mp->cur_input.index_field /* reference for buffer information */
@d start mp->cur_input.start_field /* starting position in |buffer| */
@d limit mp->cur_input.limit_field /* end of current line in |buffer| */
@d name mp->cur_input.name_field /* name of the current file */
@ Let's look more closely now at the five control variables
(|index|,~|start|,~|loc|,~|limit|,~|name|),
assuming that \MP\ is reading a line of characters that have been input
from some file or from the user's terminal. There is an array called
|buffer| that acts as a stack of all lines of characters that are
currently being read from files, including all lines on subsidiary
levels of the input stack that are not yet completed. \MP\ will return to
the other lines when it is finished with the present input file.
(Incidentally, on a machine with byte-oriented addressing, it would be
appropriate to combine |buffer| with the |str_pool| array,
letting the buffer entries grow downward from the top of the string pool
and checking that these two tables don't bump into each other.)
The line we are currently working on begins in position |start| of the
buffer; the next character we are about to read is |buffer[loc]|; and
|limit| is the location of the last character present. We always have
|loc<=limit|. For convenience, |buffer[limit]| has been set to |"%"|, so
that the end of a line is easily sensed.
The |name| variable is a string number that designates the name of
the current file, if we are reading an ordinary text file. Special codes
|is_term..max_spec_src| indicate other sources of input text.
@d is_term (mp_string)0 /* |name| value when reading from the terminal for normal input */
@d is_read (mp_string)1 /* |name| value when executing a \&{readstring} or \&{readfrom} */
@d is_scantok (mp_string)2 /* |name| value when reading text generated by \&{scantokens} */
@d max_spec_src is_scantok
@ Additional information about the current line is available via the
|index| variable, which counts how many lines of characters are present
in the buffer below the current level. We have |index=0| when reading
from the terminal and prompting the user for each line; then if the user types,
e.g., `\.{input figs}', we will have |index=1| while reading
the file \.{figs.mp}. However, it does not follow that |index| is the
same as the input stack pointer, since many of the levels on the input
stack may come from token lists and some |index| values may correspond
to \.{MPX} files that are not currently on the stack.
The global variable |in_open| is equal to the highest |index| value counting
\.{MPX} files but excluding token-list input levels. Thus, the number of
partially read lines in the buffer is |in_open+1| and we have |in_open>=index|
when we are not reading a token list.
If we are not currently reading from the terminal,
we are reading from the file variable |input_file[index]|. We use
the notation |terminal_input| as a convenient abbreviation for |name=is_term|,
and |cur_file| as an abbreviation for |input_file[index]|.
When \MP\ is not reading from the terminal, the global variable |line| contains
the line number in the current file, for use in error messages. More precisely,
|line| is a macro for |line_stack[index]| and the |line_stack| array gives
the line number for each file in the |input_file| array.
When an \.{MPX} file is opened the file name is stored in the |mpx_name|
array so that the name doesn't get lost when the file is temporarily removed
from the input stack.
Thus when |input_file[k]| is an \.{MPX} file, its name is |mpx_name[k]|
and it contains translated \TeX\ pictures for |input_file[k-1]|.
Since this is not an \.{MPX} file, we have
$$ \hbox{|mpx_name[k-1]<=absent|}. $$
This |name| field is set to |finished| when |input_file[k]| is completely
read.
If more information about the input state is needed, it can be
included in small arrays like those shown here. For example,
the current page or segment number in the input file might be put
into a variable |page|, that is really a macro for the current entry
in `\ignorespaces|page_stack:array[0..max_in_open] of integer|\unskip'
by analogy with |line_stack|.
@^system dependencies@>
@d terminal_input (name==is_term) /* are we reading from the terminal? */
@d cur_file mp->input_file[iindex] /* the current |void *| variable */
@d line mp->line_stack[iindex] /* current line number in the current source file */
@d in_ext mp->inext_stack[iindex] /* a string used to construct \.{MPX} file names */
@d in_name mp->iname_stack[iindex] /* a string used to construct \.{MPX} file names */
@d in_area mp->iarea_stack[iindex] /* another string for naming \.{MPX} files */
@d absent (mp_string)1 /* |name_field| value for unused |mpx_in_stack| entries */
@d mpx_reading (mp->mpx_name[iindex]>absent)
/* when reading a file, is it an \.{MPX} file? */
@d mpx_finished 0
/* |name_field| value when the corresponding \.{MPX} file is finished */
@<Glob...@>=
integer in_open; /* the number of lines in the buffer, less one */
integer in_open_max; /* highest value of |in_open| ever seen */
unsigned int open_parens; /* the number of open text files */
void **input_file;
integer *line_stack; /* the line number for each file */
char **inext_stack; /* used for naming \.{MPX} files */
char **iname_stack; /* used for naming \.{MPX} files */
char **iarea_stack; /* used for naming \.{MPX} files */
mp_string *mpx_name;
@ @<Declarations@>=
static void mp_reallocate_input_stack (MP mp, int newsize);
@ @c
static void mp_reallocate_input_stack (MP mp, int newsize) {
int k;
int n = newsize +1;
XREALLOC (mp->input_file, n, void *);
XREALLOC (mp->line_stack, n, integer);
XREALLOC (mp->inext_stack, n, char *);
XREALLOC (mp->iname_stack, n, char *);
XREALLOC (mp->iarea_stack, n, char *);
XREALLOC (mp->mpx_name, n, mp_string);
for (k = mp->max_in_open; k <= n; k++) {
mp->input_file[k] = NULL;
mp->line_stack[k] = 0;
mp->inext_stack[k] = NULL;
mp->iname_stack[k] = NULL;
mp->iarea_stack[k] = NULL;
mp->mpx_name[k] = NULL;
}
mp->max_in_open = newsize;
}
@ This has to be more than |file_bottom|, so:
@<Allocate or ...@>=
mp_reallocate_input_stack (mp, file_bottom+4);
@ @<Dealloc variables@>=
{
int l;
for (l = 0; l <= mp->max_in_open; l++) {
xfree (mp->inext_stack[l]);
xfree (mp->iname_stack[l]);
xfree (mp->iarea_stack[l]);
}
}
xfree (mp->input_file);
xfree (mp->line_stack);
xfree (mp->inext_stack);
xfree (mp->iname_stack);
xfree (mp->iarea_stack);
xfree (mp->mpx_name);
@ However, all this discussion about input state really applies only to the
case that we are inputting from a file. There is another important case,
namely when we are currently getting input from a token list. In this case
|iindex>max_in_open|, and the conventions about the other state variables
are different:
\yskip\hang|nloc| is a pointer to the current node in the token list, i.e.,
the node that will be read next. If |nloc=NULL|, the token list has been
fully read.
\yskip\hang|start| points to the first node of the token list; this node
may or may not contain a reference count, depending on the type of token
list involved.
\yskip\hang|token_type|, which takes the place of |iindex| in the
discussion above, is a code number that explains what kind of token list
is being scanned.
\yskip\hang|name| points to the |eqtb| address of the control sequence
being expanded, if the current token list is a macro not defined by
\&{vardef}. Macros defined by \&{vardef} have |name=NULL|; their name
can be deduced by looking at their first two parameters.
\yskip\hang|param_start|, which takes the place of |limit|, tells where
the parameters of the current macro or loop text begin in the |param_stack|.
\yskip\noindent The |token_type| can take several values, depending on
where the current token list came from:
\yskip
\indent|forever_text|, if the token list being scanned is the body of
a \&{forever} loop;
\indent|loop_text|, if the token list being scanned is the body of
a \&{for} or \&{forsuffixes} loop;
\indent|parameter|, if a \&{text} or \&{suffix} parameter is being scanned;
\indent|backed_up|, if the token list being scanned has been inserted as
`to be read again'.
\indent|inserted|, if the token list being scanned has been inserted as
part of error recovery;
\indent|macro|, if the expansion of a user-defined symbolic token is being
scanned.
\yskip\noindent
The token list begins with a reference count if and only if |token_type=
macro|.
@^reference counts@>
@d nloc mp->cur_input.nloc_field /* location of next node node */
@d nstart mp->cur_input.nstart_field /* location of next node node */
@d token_type iindex /* type of current token list */
@d token_state (iindex<=macro) /* are we scanning a token list? */
@d file_state (iindex>macro) /* are we scanning a file line? */
@d param_start limit /* base of macro parameters in |param_stack| */
@d forever_text 0 /* |token_type| code for loop texts */
@d loop_text 1 /* |token_type| code for loop texts */
@d parameter 2 /* |token_type| code for parameter texts */
@d backed_up 3 /* |token_type| code for texts to be reread */
@d inserted 4 /* |token_type| code for inserted texts */
@d macro 5 /* |token_type| code for macro replacement texts */
@d file_bottom 6 /* lowest file code */
@ The |param_stack| is an auxiliary array used to hold pointers to the token
lists for parameters at the current level and subsidiary levels of input.
This stack grows at a different rate from the others, and is dynamically reallocated
when needed.
@<Glob...@>=
mp_node *param_stack; /* token list pointers for parameters */
integer param_ptr; /* first unused entry in |param_stack| */
integer max_param_stack; /* largest value of |param_ptr| */
@ @<Allocate or initialize ...@>=
mp->param_stack = xmalloc ((mp->param_size + 1), sizeof (mp_node));
@ @c
static void mp_check_param_size (MP mp, int k) {
while (k >= mp->param_size) {
XREALLOC (mp->param_stack, (k + k / 4), mp_node);
mp->param_size = k + k / 4;
}
}
@ @<Dealloc variables@>=
xfree (mp->param_stack);
@ Notice that the |line| isn't valid when |token_state| is true because it
depends on |iindex|. If we really need to know the line number for the
topmost file in the iindex stack we use the following function. If a page
number or other information is needed, this routine should be modified to
compute it as well.
@^system dependencies@>
@<Declarations@>=
static integer mp_true_line (MP mp);
@ @c
integer mp_true_line (MP mp) {
int k; /* an index into the input stack */
if (file_state && (name > max_spec_src)) {
return line;
} else {
k = mp->input_ptr;
while ((k > 0) &&
((mp->input_stack[(k - 1)].index_field < file_bottom) ||
(mp->input_stack[(k - 1)].name_field <= max_spec_src))) {
decr (k);
}
return (k > 0 ? mp->line_stack[(k - 1) + file_bottom] : 0);
}
}
@ Thus, the ``current input state'' can be very complicated indeed; there
can be many levels and each level can arise in a variety of ways. The
|show_context| procedure, which is used by \MP's error-reporting routine to
print out the current input state on all levels down to the most recent
line of characters from an input file, illustrates most of these conventions.
The global variable |file_ptr| contains the lowest level that was
displayed by this procedure.
@<Glob...@>=
integer file_ptr; /* shallowest level shown by |show_context| */
@ The status at each level is indicated by printing two lines, where the first
line indicates what was read so far and the second line shows what remains
to be read. The context is cropped, if necessary, so that the first line
contains at most |half_error_line| characters, and the second contains
at most |error_line|. Non-current input levels whose |token_type| is
`|backed_up|' are shown only if they have not been fully read.
@c
void mp_show_context (MP mp) { /* prints where the scanner is */
unsigned old_setting; /* saved |selector| setting */
@<Local variables for formatting calculations@>;
mp->file_ptr = mp->input_ptr;
mp->input_stack[mp->file_ptr] = mp->cur_input;
/* store current state */
while (1) {
mp->cur_input = mp->input_stack[mp->file_ptr]; /* enter into the context */
@<Display the current context@>;
if (file_state)
if ((name > max_spec_src) || (mp->file_ptr == 0))
break;
decr (mp->file_ptr);
}
mp->cur_input = mp->input_stack[mp->input_ptr]; /* restore original state */
}
@ @<Display the current context@>=
if ((mp->file_ptr == mp->input_ptr) || file_state ||
(token_type != backed_up) || (nloc != NULL)) {
/* we omit backed-up token lists that have already been read */
mp->tally = 0; /* get ready to count characters */
old_setting = mp->selector;
if (file_state) {
@<Print location of current line@>;
@<Pseudoprint the line@>;
} else {
@<Print type of token list@>;
@<Pseudoprint the token list@>;
}
mp->selector = old_setting; /* stop pseudoprinting */
@<Print two lines using the tricky pseudoprinted information@>;
}
@ This routine should be changed, if necessary, to give the best possible
indication of where the current line resides in the input file.
For example, on some systems it is best to print both a page and line number.
@^system dependencies@>
@<Print location of current line@>=
if (name > max_spec_src) {
mp_print_nl (mp, "l.");
mp_print_int (mp, mp_true_line (mp));
} else if (terminal_input) {
if (mp->file_ptr == 0)
mp_print_nl (mp, "<*>");
else
mp_print_nl (mp, "<insert>");
} else if (name == is_scantok) {
mp_print_nl (mp, "<scantokens>");
} else {
mp_print_nl (mp, "<read>");
}
mp_print_char (mp, xord (' '))
@ Can't use case statement here because the |token_type| is not
a constant expression.
@<Print type of token list@>=
{
if (token_type == forever_text) {
mp_print_nl (mp, "<forever> ");
} else if (token_type == loop_text) {
@<Print the current loop value@>;
} else if (token_type == parameter) {
mp_print_nl (mp, "<argument> ");
} else if (token_type == backed_up) {
if (nloc == NULL)
mp_print_nl (mp, "<recently read> ");
else
mp_print_nl (mp, "<to be read again> ");
} else if (token_type == inserted) {
mp_print_nl (mp, "<inserted text> ");
} else if (token_type == macro) {
mp_print_ln (mp);
if (name != NULL)
mp_print_str (mp, name);
else
@<Print the name of a \&{vardef}'d macro@>;
mp_print (mp, "->");
} else {
mp_print_nl (mp, "?"); /* this should never happen */
@.?\relax@>
}
}
@ The parameter that corresponds to a loop text is either a token list
(in the case of \&{forsuffixes}) or a ``capsule'' (in the case of \&{for}).
We'll discuss capsules later; for now, all we need to know is that
the |link| field in a capsule parameter is |void| and that
|print_exp(p,0)| displays the value of capsule~|p| in abbreviated form.
@<Print the current loop value@>=
{
mp_node pp;
mp_print_nl (mp, "<for(");
pp = mp->param_stack[param_start];
if (pp != NULL) {
if (mp_link (pp) == MP_VOID)
mp_print_exp (mp, pp, 0); /* we're in a \&{for} loop */
else
mp_show_token_list (mp, pp, NULL, 20, mp->tally);
}
mp_print (mp, ")> ");
}
@ The first two parameters of a macro defined by \&{vardef} will be token
lists representing the macro's prefix and ``at point.'' By putting these
together, we get the macro's full name.
@<Print the name of a \&{vardef}'d macro@>=
{
mp_node pp = mp->param_stack[param_start];
if (pp == NULL) {
mp_show_token_list (mp, mp->param_stack[param_start + 1], NULL, 20,
mp->tally);
} else {
mp_node qq = pp;
while (mp_link (qq) != NULL)
qq = mp_link (qq);
mp_link (qq) = mp->param_stack[param_start + 1];
mp_show_token_list (mp, pp, NULL, 20, mp->tally);
mp_link (qq) = NULL;
}
}
@ Now it is necessary to explain a little trick. We don't want to store a long
string that corresponds to a token list, because that string might take up
lots of memory; and we are printing during a time when an error message is
being given, so we dare not do anything that might overflow one of \MP's
tables. So `pseudoprinting' is the answer: We enter a mode of printing
that stores characters into a buffer of length |error_line|, where character
$k+1$ is placed into \hbox{|trick_buf[k mod error_line]|} if
|k<trick_count|, otherwise character |k| is dropped. Initially we set
|tally:=0| and |trick_count:=1000000|; then when we reach the
point where transition from line 1 to line 2 should occur, we
set |first_count:=tally| and |trick_count:=@tmax@>(error_line,
tally+1+error_line-half_error_line)|. At the end of the
pseudoprinting, the values of |first_count|, |tally|, and
|trick_count| give us all the information we need to print the two lines,
and all of the necessary text is in |trick_buf|.
Namely, let |l| be the length of the descriptive information that appears
on the first line. The length of the context information gathered for that
line is |k=first_count|, and the length of the context information
gathered for line~2 is $m=\min(|tally|, |trick_count|)-k$. If |l+k<=h|,
where |h=half_error_line|, we print |trick_buf[0..k-1]| after the
descriptive information on line~1, and set |n:=l+k|; here |n| is the
length of line~1. If $l+k>h$, some cropping is necessary, so we set |n:=h|
and print `\.{...}' followed by
$$\hbox{|trick_buf[(l+k-h+3)..k-1]|,}$$
where subscripts of |trick_buf| are circular modulo |error_line|. The
second line consists of |n|~spaces followed by |trick_buf[k..(k+m-1)]|,
unless |n+m>error_line|; in the latter case, further cropping is done.
This is easier to program than to explain.
@<Local variables for formatting...@>=
int i; /* index into |buffer| */
integer l; /* length of descriptive information on line 1 */
integer m; /* context information gathered for line 2 */
int n; /* length of line 1 */
integer p; /* starting or ending place in |trick_buf| */
integer q; /* temporary index */
@ The following code tells the print routines to gather
the desired information.
@d begin_pseudoprint {
l=mp->tally; mp->tally=0; mp->selector=pseudo;
mp->trick_count=1000000;
}
@d set_trick_count() {
mp->first_count=mp->tally;
mp->trick_count=mp->tally+1+mp->error_line-mp->half_error_line;
if ( mp->trick_count<mp->error_line ) mp->trick_count=mp->error_line;
}
@ And the following code uses the information after it has been gathered.
@<Print two lines using the tricky pseudoprinted information@>=
if (mp->trick_count == 1000000)
set_trick_count();
/* |set_trick_count| must be performed */
if (mp->tally < mp->trick_count)
m = mp->tally - mp->first_count;
else
m = mp->trick_count - mp->first_count; /* context on line 2 */
if (l + mp->first_count <= mp->half_error_line) {
p = 0;
n = l + mp->first_count;
} else {
mp_print (mp, "...");
p = l + mp->first_count - mp->half_error_line + 3;
n = mp->half_error_line;
}
for (q = p; q <= mp->first_count - 1; q++) {
mp_print_char (mp, mp->trick_buf[q % mp->error_line]);
}
mp_print_ln (mp);
for (q = 1; q <= n; q++) {
mp_print_char (mp, xord (' ')); /* print |n| spaces to begin line~2 */
}
if (m + n <= mp->error_line)
p = mp->first_count + m;
else
p = mp->first_count + (mp->error_line - n - 3);
for (q = mp->first_count; q <= p - 1; q++) {
mp_print_char (mp, mp->trick_buf[q % mp->error_line]);
}
if (m + n > mp->error_line)
mp_print (mp, "...")
@ But the trick is distracting us from our current goal, which is to
understand the input state. So let's concentrate on the data structures that
are being pseudoprinted as we finish up the |show_context| procedure.
@<Pseudoprint the line@>=
begin_pseudoprint;
if (limit > 0) {
for (i = start; i <= limit - 1; i++) {
if (i == loc)
set_trick_count();
mp_print_char (mp, mp->buffer[i]);
}
}
@ @<Pseudoprint the token list@>=
begin_pseudoprint;
if (token_type != macro)
mp_show_token_list (mp, nstart, nloc, 100000, 0);
else
mp_show_macro (mp, nstart, nloc, 100000)
@* Maintaining the input stacks.
The following subroutines change the input status in commonly needed ways.
First comes |push_input|, which stores the current state and creates a
new level (having, initially, the same properties as the old).
@d push_input { /* enter a new input level, save the old */
if ( mp->input_ptr>mp->max_in_stack ) {
mp->max_in_stack=mp->input_ptr;
if ( mp->input_ptr==mp->stack_size ) {
int l = (mp->stack_size+(mp->stack_size/4));
XREALLOC(mp->input_stack, l, in_state_record);
mp->stack_size = l;
}
}
mp->input_stack[mp->input_ptr]=mp->cur_input; /* stack the record */
incr(mp->input_ptr);
}
@ And of course what goes up must come down.
@d pop_input { /* leave an input level, re-enter the old */
decr(mp->input_ptr); mp->cur_input=mp->input_stack[mp->input_ptr];
}
@ Here is a procedure that starts a new level of token-list input, given
a token list |p| and its type |t|. If |t=macro|, the calling routine should
set |name|, reset~|loc|, and increase the macro's reference count.
@d back_list(A) mp_begin_token_list(mp, (A), (quarterword)backed_up) /* backs up a simple token list */
@c
static void mp_begin_token_list (MP mp, mp_node p, quarterword t) {
push_input;
nstart = p;
token_type = t;
param_start = mp->param_ptr;
nloc = p;
}
@ When a token list has been fully scanned, the following computations
should be done as we leave that level of input.
@^inner loop@>
@c
static void mp_end_token_list (MP mp) { /* leave a token-list input level */
mp_node p; /* temporary register */
if (token_type >= backed_up) { /* token list to be deleted */
if (token_type <= inserted) {
mp_flush_token_list (mp, nstart);
goto DONE;
} else {
mp_delete_mac_ref (mp, nstart); /* update reference count */
}
}
while (mp->param_ptr > param_start) { /* parameters must be flushed */
decr (mp->param_ptr);
p = mp->param_stack[mp->param_ptr];
if (p != NULL) {
if (mp_link (p) == MP_VOID) { /* it's an \&{expr} parameter */
mp_recycle_value (mp, p);
mp_free_value_node (mp, p);
} else {
mp_flush_token_list (mp, p); /* it's a \&{suffix} or \&{text} parameter */
}
}
}
DONE:
pop_input;
check_interrupt;
}
@ The contents of |cur_cmd,cur_mod,cur_sym| are placed into an equivalent
token by the |cur_tok| routine.
@^inner loop@>
@c
@<Declare the procedure called |make_exp_copy|@>;
static mp_node mp_cur_tok (MP mp) {
mp_node p; /* a new token node */
if (cur_sym() == NULL && (cur_sym_mod() == 0 || cur_sym_mod() == mp_normal_sym)) {
if (cur_cmd() == mp_capsule_token) {
mp_number save_exp_num; /* possible |cur_exp| numerical to be restored */
mp_value save_exp = mp->cur_exp; /* |cur_exp| to be restored */
new_number (save_exp_num);
number_clone (save_exp_num, cur_exp_value_number());
mp_make_exp_copy (mp, cur_mod_node());
p = mp_stash_cur_exp (mp);
mp_link (p) = NULL;
mp->cur_exp = save_exp;
number_clone (mp->cur_exp.data.n, save_exp_num);
free_number (save_exp_num);
} else {
p = mp_get_token_node (mp);
mp_name_type (p) = mp_token;
if (cur_cmd() == mp_numeric_token) {
set_value_number (p, cur_mod_number());
mp_type (p) = mp_known;
} else {
set_value_str (p, cur_mod_str());
mp_type (p) = mp_string_type;
}
}
} else {
p = mp_get_symbolic_node (mp);
set_mp_sym_sym (p, cur_sym());
mp_name_type (p) = cur_sym_mod();
}
return p;
}
@ Sometimes \MP\ has read too far and wants to ``unscan'' what it has
seen. The |back_input| procedure takes care of this by putting the token
just scanned back into the input stream, ready to be read again.
If |cur_sym<>0|, the values of |cur_cmd| and |cur_mod| are irrelevant.
@<Declarations@>=
static void mp_back_input (MP mp);
@ @c
void mp_back_input (MP mp) { /* undoes one token of input */
mp_node p; /* a token list of length one */
p = mp_cur_tok (mp);
while (token_state && (nloc == NULL))
mp_end_token_list (mp); /* conserve stack space */
back_list (p);
}
@ The |back_error| routine is used when we want to restore or replace an
offending token just before issuing an error message. We disable interrupts
during the call of |back_input| so that the help message won't be lost.
@<Declarations@>=
static void mp_back_error (MP mp, const char *msg, const char **hlp, boolean deletions_allowed) ;
@ @c
static void mp_back_error (MP mp, const char *msg, const char **hlp, boolean deletions_allowed) {
/* back up one token and call |error| */
mp->OK_to_interrupt = false;
mp_back_input (mp);
mp->OK_to_interrupt = true;
mp_error (mp, msg, hlp, deletions_allowed);
}
static void mp_ins_error (MP mp, const char *msg, const char **hlp, boolean deletions_allowed) {
/* back up one inserted token and call |error| */
mp->OK_to_interrupt = false;
mp_back_input (mp);
token_type = (quarterword) inserted;
mp->OK_to_interrupt = true;
mp_error (mp, msg, hlp, deletions_allowed);
}
@ The |begin_file_reading| procedure starts a new level of input for lines
of characters to be read from a file, or as an insertion from the
terminal. It does not take care of opening the file, nor does it set |loc|
or |limit| or |line|.
@^system dependencies@>
@c
void mp_begin_file_reading (MP mp) {
if (mp->in_open == (mp->max_in_open-1))
mp_reallocate_input_stack (mp, (mp->max_in_open + mp->max_in_open / 4));
if (mp->first == mp->buf_size)
mp_reallocate_buffer (mp, (mp->buf_size + mp->buf_size / 4));
mp->in_open++;
push_input;
iindex = (quarterword) mp->in_open;
if (mp->in_open_max < mp->in_open)
mp->in_open_max = mp->in_open;
mp->mpx_name[iindex] = absent;
start = (halfword) mp->first;
name = is_term; /* |terminal_input| is now |true| */
}
@ Conversely, the variables must be downdated when such a level of input
is finished. Any associated \.{MPX} file must also be closed and popped
off the file stack. While finishing preloading, it is possible that the file
does not actually end with 'dump', so we capture that case here as well.
@c
static void mp_end_file_reading (MP mp) {
if (mp->reading_preload && mp->input_ptr == 0) {
set_cur_sym(mp->frozen_dump);
mp_back_input (mp);
return;
}
if (mp->in_open > iindex) {
if ((mp->mpx_name[mp->in_open] == absent) || (name <= max_spec_src)) {
mp_confusion (mp, "endinput");
@:this can't happen endinput}{\quad endinput@>;
} else {
(mp->close_file) (mp, mp->input_file[mp->in_open]); /* close an \.{MPX} file */
delete_str_ref (mp->mpx_name[mp->in_open]);
decr (mp->in_open);
}
}
mp->first = (size_t) start;
if (iindex != mp->in_open)
mp_confusion (mp, "endinput");
if (name > max_spec_src) {
(mp->close_file) (mp, cur_file);
xfree (in_ext);
xfree (in_name);
xfree (in_area);
}
pop_input;
decr (mp->in_open);
}
@ Here is a function that tries to resume input from an \.{MPX} file already
associated with the current input file. It returns |false| if this doesn't
work.
@c
static boolean mp_begin_mpx_reading (MP mp) {
if (mp->in_open != iindex + 1) {
return false;
} else {
if (mp->mpx_name[mp->in_open] <= absent)
mp_confusion (mp, "mpx");
if (mp->first == mp->buf_size)
mp_reallocate_buffer (mp, (mp->buf_size + (mp->buf_size / 4)));
push_input;
iindex = (quarterword) mp->in_open;
start = (halfword) mp->first;
name = mp->mpx_name[mp->in_open];
add_str_ref (name);
/* Put an empty line in the input buffer */
/* We want to make it look as though we have just read a blank line
without really doing so. */
mp->last = mp->first;
limit = (halfword) mp->last;
/* simulate |input_ln| and |firm_up_the_line| */
mp->buffer[limit] = xord ('%');
mp->first = (size_t) (limit + 1);
loc = start;
return true;
}
}
@ This procedure temporarily stops reading an \.{MPX} file.
@c
static void mp_end_mpx_reading (MP mp) {
if (mp->in_open != iindex)
mp_confusion (mp, "mpx");
@:this can't happen mpx}{\quad mpx@>;
if (loc < limit) {
/* Complain that we are not at the end of a line in the \.{MPX} file */
/* Here we enforce a restriction that simplifies the input stacks considerably.
This should not inconvenience the user because \.{MPX} files are generated
by an auxiliary program called \.{DVItoMP}. */
const char *hlp[] = {
"This file contains picture expressions for btex...etex",
"blocks. Such files are normally generated automatically",
"but this one seems to be messed up. I'm going to ignore",
"the rest of this line.",
NULL };
mp_error (mp, "`mpxbreak' must be at the end of a line", hlp, true);
}
mp->first = (size_t) start;
pop_input;
}
@ In order to keep the stack from overflowing during a long sequence of
inserted `\.{show}' commands, the following routine removes completed
error-inserted lines from memory.
@c
void mp_clear_for_error_prompt (MP mp) {
while (file_state && terminal_input && (mp->input_ptr > 0) && (loc == limit))
mp_end_file_reading (mp);
mp_print_ln (mp);
clear_terminal();
}
@ To get \MP's whole input mechanism going, we perform the following
actions.
@<Initialize the input routines@>=
{
mp->input_ptr = 0;
mp->max_in_stack = file_bottom;
mp->in_open = file_bottom;
mp->open_parens = 0;
mp->max_buf_stack = 0;
mp->param_ptr = 0;
mp->max_param_stack = 0;
mp->first = 0;
start = 0;
iindex = file_bottom;
line = 0;
name = is_term;
mp->mpx_name[file_bottom] = absent;
mp->force_eof = false;
if (!mp_init_terminal (mp))
mp_jump_out (mp);
limit = (halfword) mp->last;
mp->first = mp->last + 1;
/* |init_terminal| has set |loc| and |last| */
}
@* Getting the next token.
The heart of \MP's input mechanism is the |get_next| procedure, which
we shall develop in the next few sections of the program. Perhaps we
shouldn't actually call it the ``heart,'' however; it really acts as \MP's
eyes and mouth, reading the source files and gobbling them up. And it also
helps \MP\ to regurgitate stored token lists that are to be processed again.
The main duty of |get_next| is to input one token and to set |cur_cmd|
and |cur_mod| to that token's command code and modifier. Furthermore, if
the input token is a symbolic token, that token's |hash| address
is stored in |cur_sym|; otherwise |cur_sym| is set to zero.
Underlying this simple description is a certain amount of complexity
because of all the cases that need to be handled.
However, the inner loop of |get_next| is reasonably short and fast.
@ Before getting into |get_next|, we need to consider a mechanism by which
\MP\ helps keep errors from propagating too far. Whenever the program goes
into a mode where it keeps calling |get_next| repeatedly until a certain
condition is met, it sets |scanner_status| to some value other than |normal|.
Then if an input file ends, or if an `\&{outer}' symbol appears,
an appropriate error recovery will be possible.
The global variable |warning_info| helps in this error recovery by providing
additional information. For example, |warning_info| might indicate the
name of a macro whose replacement text is being scanned.
@d normal 0 /* |scanner_status| at ``quiet times'' */
@d skipping 1 /* |scanner_status| when false conditional text is being skipped */
@d flushing 2 /* |scanner_status| when junk after a statement is being ignored */
@d absorbing 3 /* |scanner_status| when a \&{text} parameter is being scanned */
@d var_defining 4 /* |scanner_status| when a \&{vardef} is being scanned */
@d op_defining 5 /* |scanner_status| when a macro \&{def} is being scanned */
@d loop_defining 6 /* |scanner_status| when a \&{for} loop is being scanned */
@<Glob...@>=
#define tex_flushing 7 /* |scanner_status| when skipping \TeX\ material */
integer scanner_status; /* are we scanning at high speed? */
mp_sym warning_info; /* if so, what else do we need to know,
in case an error occurs? */
integer warning_line;
mp_node warning_info_node;
@ @<Initialize the input routines@>=
mp->scanner_status = normal;
@ The following subroutine
is called when an `\&{outer}' symbolic token has been scanned or
when the end of a file has been reached. These two cases are distinguished
by |cur_sym|, which is zero at the end of a file.
@c
static boolean mp_check_outer_validity (MP mp) {
mp_node p; /* points to inserted token list */
if (mp->scanner_status == normal) {
return true;
} else if (mp->scanner_status == tex_flushing) {
@<Check if the file has ended while flushing \TeX\ material and set the
result value for |check_outer_validity|@>;
} else {
@<Back up an outer symbolic token so that it can be reread@>;
if (mp->scanner_status > skipping) {
@<Tell the user what has run away and try to recover@>;
} else {
char msg[256];
const char *hlp[] = {
"A forbidden `outer' token occurred in skipped text.",
"This kind of error happens when you say `if...' and forget",
"the matching `fi'. I've inserted a `fi'; this might work.",
NULL };
mp_snprintf(msg, 256, "Incomplete if; all text was ignored after line %d", (int)mp->warning_line);
@.Incomplete if...@>;
if (cur_sym() == NULL) {
hlp[0] = "The file ended while I was skipping conditional text.";
}
set_cur_sym (mp->frozen_fi);
mp_ins_error (mp, msg, hlp, false);
}
return false;
}
}
@ @<Check if the file has ended while flushing \TeX\ material and set...@>=
if (cur_sym() != NULL) {
return true;
} else {
char msg[256];
const char *hlp[] = {
"The file ended while I was looking for the `etex' to",
"finish this TeX material. I've inserted `etex' now.",
NULL };
mp_snprintf(msg, 256, "TeX mode didn't end; all text was ignored after line %d", (int)mp->warning_line);
set_cur_sym(mp->frozen_etex);
mp_ins_error (mp, msg, hlp, false);
return false;
}
@ @<Back up an outer symbolic token so that it can be reread@>=
if (cur_sym() != NULL) {
p = mp_get_symbolic_node (mp);
set_mp_sym_sym (p, cur_sym());
mp_name_type (p) = cur_sym_mod();
back_list (p); /* prepare to read the symbolic token again */
}
@ @<Tell the user what has run away...@>=
{
char msg[256];
const char *msg_start = NULL;
const char *hlp[] = {
"I suspect you have forgotten an `enddef',",
"causing me to read past where you wanted me to stop.",
"I'll try to recover; but if the error is serious,",
"you'd better type `E' or `X' now and fix your file.",
NULL };
mp_runaway (mp); /* print the definition-so-far */
if (cur_sym() == NULL) {
msg_start = "File ended while scanning";
@.File ended while scanning...@>
} else {
msg_start = "Forbidden token found while scanning";
@.Forbidden token found...@>
}
switch (mp->scanner_status) {
@<Complete the error message,
and set |cur_sym| to a token that might help recover from the error@>
} /* there are no other cases */
mp_ins_error (mp, msg, hlp, true);
}
@ As we consider various kinds of errors, it is also appropriate to
change the first line of the help message just given; |help_line[3]|
points to the string that might be changed.
@<Complete the error message,...@>=
case flushing:
mp_snprintf (msg, 256, "%s to the end of the statement", msg_start);
hlp[0] = "A previous error seems to have propagated,";
set_cur_sym(mp->frozen_semicolon);
break;
case absorbing:
mp_snprintf (msg, 256, "%s a text argument", msg_start);
hlp[0] = "It seems that a right delimiter was left out,";
if (mp->warning_info == NULL) {
set_cur_sym(mp->frozen_end_group);
} else {
set_cur_sym(mp->frozen_right_delimiter);
/* the next line makes sure that the inserted delimiter will
match the delimiter that already was read. */
set_equiv_sym (cur_sym(), mp->warning_info);
}
break;
case var_defining:
{
mp_string s;
int old_setting = mp->selector;
mp->selector = new_string;
mp_print_variable_name (mp, mp->warning_info_node);
s = mp_make_string (mp);
mp->selector = old_setting;
mp_snprintf (msg, 256, "%s the definition of %s", msg_start, s->str);
delete_str_ref(s);
}
set_cur_sym(mp->frozen_end_def);
break;
case op_defining:
{
char *s = mp_str(mp, text(mp->warning_info));
mp_snprintf (msg, 256, "%s the definition of %s", msg_start, s);
}
set_cur_sym(mp->frozen_end_def);
break;
case loop_defining:
{
char *s = mp_str(mp, text(mp->warning_info));
mp_snprintf (msg, 256, "%s the text of a %s loop", msg_start, s);
}
hlp[0] = "I suspect you have forgotten an `endfor',";
set_cur_sym(mp->frozen_end_for);
break;
@ The |runaway| procedure displays the first part of the text that occurred
when \MP\ began its special |scanner_status|, if that text has been saved.
@<Declarations@>=
static void mp_runaway (MP mp);
@ @c
void mp_runaway (MP mp) {
if (mp->scanner_status > flushing) {
mp_print_nl (mp, "Runaway ");
switch (mp->scanner_status) {
case absorbing:
mp_print (mp, "text?");
break;
case var_defining:
case op_defining:
mp_print (mp, "definition?");
break;
case loop_defining:
mp_print (mp, "loop?");
break;
} /* there are no other cases */
mp_print_ln (mp);
mp_show_token_list (mp, mp_link (mp->hold_head), NULL, mp->error_line - 10,
0);
}
}
@ We need to mention a procedure that may be called by |get_next|.
@<Declarations@>=
static void mp_firm_up_the_line (MP mp);
@ And now we're ready to take the plunge into |get_next| itself.
Note that the behavior depends on the |scanner_status| because percent signs
and double quotes need to be passed over when skipping TeX material.
@c
void mp_get_next (MP mp) {
/* sets |cur_cmd|, |cur_mod|, |cur_sym| to next token */
mp_sym cur_sym_; /* speed up access */
RESTART:
set_cur_sym(NULL);
set_cur_sym_mod(0);
if (file_state) {
int k; /* an index into |buffer| */
ASCII_code c; /* the current character in the buffer */
int cclass; /* its class number */
/* Input from external file; |goto restart| if no input found,
or |return| if a non-symbolic token is found */
/* A percent sign appears in |buffer[limit]|; this makes it unnecessary
to have a special test for end-of-line. */
SWITCH:
c = mp->buffer[loc];
incr (loc);
cclass = mp->char_class[c];
switch (cclass) {
case digit_class:
scan_numeric_token((c - '0'));
return;
break;
case period_class:
cclass = mp->char_class[mp->buffer[loc]];
if (cclass > period_class) {
goto SWITCH;
} else if (cclass < period_class) { /* |class=digit_class| */
scan_fractional_token(0);
return;
}
break;
case space_class:
goto SWITCH;
break;
case percent_class:
if (mp->scanner_status == tex_flushing) {
if (loc < limit)
goto SWITCH;
}
/* Move to next line of file, or |goto restart| if there is no next line */
switch (move_to_next_line(mp)) {
case 1: goto RESTART; break;
case 2: goto COMMON_ENDING; break;
default: break;
}
check_interrupt;
goto SWITCH;
break;
case string_class:
if (mp->scanner_status == tex_flushing) {
goto SWITCH;
} else {
if (mp->buffer[loc] == '"') {
set_cur_mod_str(mp_rts(mp,""));
} else {
k = loc;
mp->buffer[limit + 1] = xord ('"');
do {
incr (loc);
} while (mp->buffer[loc] != '"');
if (loc > limit) {
/* Decry the missing string delimiter and |goto restart| */
/* We go to |restart| after this error message, not to |SWITCH|,
because the |clear_for_error_prompt| routine might have reinstated
|token_state| after |error| has finished. */
const char *hlp[] = {
"Strings should finish on the same line as they began.",
"I've deleted the partial string; you might want to",
"insert another by typing, e.g., `I\"new string\"'.",
NULL };
loc = limit; /* the next character to be read on this line will be |"%"| */
mp_error (mp, "Incomplete string token has been flushed", hlp, false);
goto RESTART;
}
str_room ((size_t) (loc - k));
do {
append_char (mp->buffer[k]);
incr (k);
} while (k != loc);
set_cur_mod_str(mp_make_string (mp));
}
incr (loc);
set_cur_cmd((mp_variable_type)mp_string_token);
return;
}
break;
case isolated_classes:
k = loc - 1;
goto FOUND;
break;
case invalid_class:
if (mp->scanner_status == tex_flushing) {
goto SWITCH;
} else {
/* Decry the invalid character and |goto restart| */
/* We go to |restart| instead of to |SWITCH|, because we might enter
|token_state| after the error has been dealt with
(cf.\ |clear_for_error_prompt|). */
const char *hlp[] = {
"A funny symbol that I can\'t read has just been input.",
"Continue, and I'll forget that it ever happened.",
NULL };
mp_error(mp, "Text line contains an invalid character", hlp, false);
goto RESTART;
}
break;
default:
break; /* letters, etc. */
}
k = loc - 1;
while (mp->char_class[mp->buffer[loc]] == cclass)
incr (loc);
FOUND:
set_cur_sym(mp_id_lookup (mp, (char *) (mp->buffer + k), (size_t) (loc - k), true));
} else {
/* Input from token list; |goto restart| if end of list or
if a parameter needs to be expanded,
or |return| if a non-symbolic token is found */
if (nloc != NULL && mp_type (nloc) == mp_symbol_node) { /* symbolic token */
int cur_sym_mod_ = mp_name_type (nloc);
halfword cur_info = mp_sym_info (nloc);
set_cur_sym(mp_sym_sym (nloc));
set_cur_sym_mod(cur_sym_mod_);
nloc = mp_link (nloc); /* move to next */
if (cur_sym_mod_ == mp_expr_sym) {
set_cur_cmd((mp_variable_type)mp_capsule_token);
set_cur_mod_node(mp->param_stack[param_start + cur_info]);
set_cur_sym_mod(0);
set_cur_sym(NULL);
return;
} else if (cur_sym_mod_ == mp_suffix_sym || cur_sym_mod_ == mp_text_sym) {
mp_begin_token_list (mp,
mp->param_stack[param_start + cur_info],
(quarterword) parameter);
goto RESTART;
}
} else if (nloc != NULL) {
/* Get a stored numeric or string or capsule token and |return| */
if (mp_name_type (nloc) == mp_token) {
if (mp_type (nloc) == mp_known) {
set_cur_mod_number(value_number (nloc));
set_cur_cmd((mp_variable_type)mp_numeric_token);
} else {
set_cur_mod_str(value_str (nloc));
set_cur_cmd((mp_variable_type)mp_string_token);
add_str_ref (cur_mod_str());
}
} else {
set_cur_mod_node(nloc);
set_cur_cmd((mp_variable_type)mp_capsule_token);
}
nloc = mp_link (nloc);
return;
} else { /* we are done with this token list */
mp_end_token_list (mp);
goto RESTART; /* resume previous level */
}
}
COMMON_ENDING:
/* When a symbolic token is declared to be `\&{outer}', its command code
is increased by |outer_tag|. */
cur_sym_ = cur_sym();
set_cur_cmd(eq_type (cur_sym_));
set_cur_mod(equiv (cur_sym_));
set_cur_mod_node(equiv_node (cur_sym_));
if (cur_cmd() >= mp_outer_tag) {
if (mp_check_outer_validity (mp))
set_cur_cmd(cur_cmd() - mp_outer_tag);
else
goto RESTART;
}
}
@ The global variable |force_eof| is normally |false|; it is set |true|
by an \&{endinput} command.
@<Glob...@>=
boolean force_eof; /* should the next \&{input} be aborted early? */
@ @<Declarations@>=
static int move_to_next_line (MP mp);
@ @c
static int move_to_next_line (MP mp) {
if (name > max_spec_src) {
/* Read next line of file into |buffer|, or return 1
(|goto restart|) if the file has ended */
/* We must decrement |loc| in order to leave the buffer in a valid state
when an error condition causes us to |goto restart| without calling
|end_file_reading|. */
{
incr (line);
mp->first = (size_t) start;
if (!mp->force_eof) {
if (mp_input_ln (mp, cur_file)) /* not end of file */
mp_firm_up_the_line (mp); /* this sets |limit| */
else
mp->force_eof = true;
};
if (mp->force_eof) {
mp->force_eof = false;
decr (loc);
if (mpx_reading) {
/* Complain that the \.{MPX} file ended unexpectly; then set
|cur_sym:=mp->frozen_mpx_break| and |goto comon_ending| */
/* We should never actually come to the end of an \.{MPX} file because such
files should have an \&{mpxbreak} after the translation of the last
\&{btex}$\,\ldots\,$\&{etex} block. */
const char *hlp[] = {"The file had too few picture expressions for btex...etex",
"blocks. Such files are normally generated automatically",
"but this one got messed up. You might want to insert a",
"picture expression now.",
NULL };
mp->mpx_name[iindex] = mpx_finished;
mp_error (mp, "mpx file ended unexpectedly", hlp, false);
set_cur_sym(mp->frozen_mpx_break);
return 2;
} else {
mp_print_char (mp, xord (')'));
decr (mp->open_parens);
update_terminal(); /* show user that file has been read */
mp_end_file_reading (mp); /* resume previous level */
if (mp_check_outer_validity (mp))
return 1;
else
return 1;
}
}
mp->buffer[limit] = xord ('%');
mp->first = (size_t) (limit + 1);
loc = start; /* ready to read */
}
} else {
if (mp->input_ptr > 0) {
/* text was inserted during error recovery or by \&{scantokens} */
mp_end_file_reading (mp);
/* goto RESTART */
return 1; /* resume previous level */
}
if (mp->job_name == NULL
&& (mp->selector < log_only || mp->selector >= write_file))
mp_open_log_file (mp);
if (mp->interaction > mp_nonstop_mode) {
if (limit == start) /* previous line was empty */
mp_print_nl (mp, "(Please type a command or say `end')");
mp_print_ln (mp);
mp->first = (size_t) start;
prompt_input ("*"); /* input on-line into |buffer| */
limit = (halfword) mp->last;
mp->buffer[limit] = xord ('%');
mp->first = (size_t) (limit + 1);
loc = start;
} else {
mp_fatal_error (mp, "*** (job aborted, no legal end found)");
/* nonstop mode, which is intended for overnight batch processing,
never waits for on-line input */
}
}
return 0;
}
@ If the user has set the |mp_pausing| parameter to some positive value,
and if nonstop mode has not been selected, each line of input is displayed
on the terminal and the transcript file, followed by `\.{=>}'.
\MP\ waits for a response. If the response is NULL (i.e., if nothing is
typed except perhaps a few blank spaces), the original
line is accepted as it stands; otherwise the line typed is
used instead of the line in the file.
@c
void mp_firm_up_the_line (MP mp) {
size_t k; /* an index into |buffer| */
limit = (halfword) mp->last;
if ((!mp->noninteractive)
&& (number_positive (internal_value (mp_pausing)))
&& (mp->interaction > mp_nonstop_mode)) {
wake_up_terminal();
mp_print_ln (mp);
if (start < limit) {
for (k = (size_t) start; k < (size_t) limit; k++) {
mp_print_char (mp, mp->buffer[k]);
}
}
mp->first = (size_t) limit;
prompt_input ("=>"); /* wait for user response */
@.=>@>;
if (mp->last > mp->first) {
for (k = mp->first; k < mp->last; k++) { /* move line down in buffer */
mp->buffer[k + (size_t) start - mp->first] = mp->buffer[k];
}
limit = (halfword) ((size_t) start + mp->last - mp->first);
}
}
}
@* Dealing with \TeX\ material.
The \&{btex}$\,\ldots\,$\&{etex} and \&{verbatimtex}$\,\ldots\,$\&{etex}
features need to be implemented at a low level in the scanning process
so that \MP\ can stay in synch with the a preprocessor that treats
blocks of \TeX\ material as they occur in the input file without trying
to expand \MP\ macros. Thus we need a special version of |get_next|
that does not expand macros and such but does handle \&{btex},
\&{verbatimtex}, etc.
The special version of |get_next| is called |get_t_next|. It works by flushing
\&{btex}$\,\ldots\,$\&{etex} and \&{verbatimtex}\allowbreak
$\,\ldots\,$\&{etex} blocks, switching to the \.{MPX} file when it sees
\&{btex}, and switching back when it sees \&{mpxbreak}.
@d btex_code 0
@d verbatim_code 1
@ @<Put each...@>=
mp_primitive (mp, "btex", mp_start_tex, btex_code);
@:btex_}{\&{btex} primitive@>;
mp_primitive (mp, "verbatimtex", mp_start_tex, verbatim_code);
@:verbatimtex_}{\&{verbatimtex} primitive@>;
mp_primitive (mp, "etex", mp_etex_marker, 0);
mp->frozen_etex = mp_frozen_primitive (mp, "etex", mp_etex_marker, 0);
@:etex_}{\&{etex} primitive@>;
mp_primitive (mp, "mpxbreak", mp_mpx_break, 0);
mp->frozen_mpx_break = mp_frozen_primitive (mp, "mpxbreak", mp_mpx_break, 0);
@:mpx_break_}{\&{mpxbreak} primitive@>
@ @<Cases of |print_cmd...@>=
case mp_start_tex:
if (m == btex_code)
mp_print (mp, "btex");
else
mp_print (mp, "verbatimtex");
break;
case mp_etex_marker:
mp_print (mp, "etex");
break;
case mp_mpx_break:
mp_print (mp, "mpxbreak");
break;
@ Actually, |get_t_next| is a macro that avoids procedure overhead except
in the unusual case where \&{btex}, \&{verbatimtex}, \&{etex}, or \&{mpxbreak}
is encountered.
@d get_t_next(a) do {
mp_get_next (mp);
if (cur_cmd() <= mp_max_pre_command)
mp_t_next (mp);
} while (0)
@c
@ @<Declarations@>=
static void mp_t_next (MP mp);
static void mp_start_mpx_input (MP mp);
@ @c
static void mp_t_next (MP mp) {
int old_status; /* saves the |scanner_status| */
integer old_info; /* saves the |warning_info| */
if ((mp->extensions == 1) && (cur_cmd() == mp_start_tex)) {
@<Pass btex ... etex to script@>;
} else {
while (cur_cmd() <= mp_max_pre_command) {
if (cur_cmd() == mp_mpx_break) {
if (!file_state || (mp->mpx_name[iindex] == absent)) {
@<Complain about a misplaced \&{mpxbreak}@>;
} else {
mp_end_mpx_reading (mp);
goto TEX_FLUSH;
}
} else if (cur_cmd() == mp_start_tex) {
if (token_state || (name <= max_spec_src)) {
@<Complain that we are not reading a file@>;
} else if (mpx_reading) {
@<Complain that \.{MPX} files cannot contain \TeX\ material@>;
} else if ((cur_mod() != verbatim_code) &&
(mp->mpx_name[iindex] != mpx_finished)) {
if (!mp_begin_mpx_reading (mp))
mp_start_mpx_input (mp);
} else {
goto TEX_FLUSH;
}
} else {
@<Complain about a misplaced \&{etex}@>;
}
goto COMMON_ENDING;
TEX_FLUSH:
@<Flush the \TeX\ material@>;
COMMON_ENDING:
mp_get_next (mp);
}
}
}
@ We could be in the middle of an operation such as skipping false conditional
text when \TeX\ material is encountered, so we must be careful to save the
|scanner_status|.
@<Flush the \TeX\ material@>=
old_status = mp->scanner_status;
old_info = mp->warning_line;
mp->scanner_status = tex_flushing;
mp->warning_line = line;
do {
mp_get_next (mp);
} while (cur_cmd() != mp_etex_marker);
mp->scanner_status = old_status;
mp->warning_line = old_info
@ @<Complain that \.{MPX} files cannot contain \TeX\ material@>=
{
const char *hlp[] = {
"This file contains picture expressions for btex...etex",
"blocks. Such files are normally generated automatically",
"but this one seems to be messed up. I'll just keep going",
"and hope for the best.",
NULL };
mp_error (mp, "An mpx file cannot contain btex or verbatimtex blocks", hlp, true);
}
@ @<Complain that we are not reading a file@>=
{
const char *hlp[] = {
"I'll have to ignore this preprocessor command because it",
"only works when there is a file to preprocess. You might",
"want to delete everything up to the next `etex`.",
NULL };
mp_error (mp, "You can only use `btex' or `verbatimtex' in a file", hlp, true);
}
@ @<Complain about a misplaced \&{mpxbreak}@>=
{
const char *hlp[] = {
"I'll ignore this preprocessor command because it",
"doesn't belong here",
NULL };
mp_error (mp, "Misplaced mpxbreak", hlp, true);
}
@ @<Complain about a misplaced \&{etex}@>=
{
const char *hlp[] = {
"There is no btex or verbatimtex for this to match",
NULL };
mp_error (mp, "Extra etex will be ignored", hlp, true);
}
@* Scanning macro definitions.
\MP\ has a variety of ways to tuck tokens away into token lists for later
use: Macros can be defined with \&{def}, \&{vardef}, \&{primarydef}, etc.;
repeatable code can be defined with \&{for}, \&{forever}, \&{forsuffixes}.
All such operations are handled by the routines in this part of the program.
The modifier part of each command code is zero for the ``ending delimiters''
like \&{enddef} and \&{endfor}.
@d start_def 1 /* command modifier for \&{def} */
@d var_def 2 /* command modifier for \&{vardef} */
@d end_def 0 /* command modifier for \&{enddef} */
@d start_forever 1 /* command modifier for \&{forever} */
@d start_for 2 /* command modifier for \&{forever} */
@d start_forsuffixes 3 /* command modifier for \&{forever} */
@d end_for 0 /* command modifier for \&{endfor} */
@<Put each...@>=
mp_primitive (mp, "def", mp_macro_def, start_def);
@:def_}{\&{def} primitive@>;
mp_primitive (mp, "vardef", mp_macro_def, var_def);
@:var_def_}{\&{vardef} primitive@>;
mp_primitive (mp, "primarydef", mp_macro_def, mp_secondary_primary_macro);
@:primary_def_}{\&{primarydef} primitive@>;
mp_primitive (mp, "secondarydef", mp_macro_def, mp_tertiary_secondary_macro);
@:secondary_def_}{\&{secondarydef} primitive@>;
mp_primitive (mp, "tertiarydef", mp_macro_def, mp_expression_tertiary_macro);
@:tertiary_def_}{\&{tertiarydef} primitive@>;
mp_primitive (mp, "enddef", mp_macro_def, end_def);
mp->frozen_end_def = mp_frozen_primitive (mp, "enddef", mp_macro_def, end_def);
@:end_def_}{\&{enddef} primitive@>;
mp_primitive (mp, "for", mp_iteration, start_for);
@:for_}{\&{for} primitive@>;
mp_primitive (mp, "forsuffixes", mp_iteration, start_forsuffixes);
@:for_suffixes_}{\&{forsuffixes} primitive@>;
mp_primitive (mp, "forever", mp_iteration, start_forever);
@:forever_}{\&{forever} primitive@>;
mp_primitive (mp, "endfor", mp_iteration, end_for);
mp->frozen_end_for = mp_frozen_primitive (mp, "endfor", mp_iteration, end_for);
@:end_for_}{\&{endfor} primitive@>
@ @<Cases of |print_cmd...@>=
case mp_macro_def:
if (m <= var_def) {
if (m == start_def)
mp_print (mp, "def");
else if (m < start_def)
mp_print (mp, "enddef");
else
mp_print (mp, "vardef");
} else if (m == mp_secondary_primary_macro) {
mp_print (mp, "primarydef");
} else if (m == mp_tertiary_secondary_macro) {
mp_print (mp, "secondarydef");
} else {
mp_print (mp, "tertiarydef");
}
break;
case mp_iteration:
if (m == start_forever)
mp_print (mp, "forever");
else if (m == end_for)
mp_print (mp, "endfor");
else if (m == start_for)
mp_print (mp, "for");
else
mp_print (mp, "forsuffixes");
break;
@ Different macro-absorbing operations have different syntaxes, but they
also have a lot in common. There is a list of special symbols that are to
be replaced by parameter tokens; there is a special command code that
ends the definition; the quotation conventions are identical. Therefore
it makes sense to have most of the work done by a single subroutine. That
subroutine is called |scan_toks|.
The first parameter to |scan_toks| is the command code that will
terminate scanning (either |macro_def| or |iteration|).
The second parameter, |subst_list|, points to a (possibly empty) list
of non-symbolic nodes whose |info| and |value| fields specify symbol tokens
before and after replacement. The list will be returned to free storage
by |scan_toks|.
The third parameter is simply appended to the token list that is built.
And the final parameter tells how many of the special operations
\.{\#\AT!}, \.{\AT!}, and \.{\AT!\#} are to be replaced by suffix parameters.
When such parameters are present, they are called \.{(SUFFIX0)},
\.{(SUFFIX1)}, and \.{(SUFFIX2)}.
@<Types...@>=
typedef struct mp_subst_list_item {
mp_name_type_type info_mod;
quarterword value_mod;
mp_sym info;
halfword value_data;
struct mp_subst_list_item *link;
} mp_subst_list_item;
@
@c
static mp_node mp_scan_toks (MP mp, mp_command_code terminator,
mp_subst_list_item * subst_list, mp_node tail_end,
quarterword suffix_count) {
mp_node p; /* tail of the token list being built */
mp_subst_list_item *q = NULL; /* temporary for link management */
integer balance; /* left delimiters minus right delimiters */
halfword cur_data;
quarterword cur_data_mod = 0;
p = mp->hold_head;
balance = 1;
mp_link (mp->hold_head) = NULL;
while (1) {
get_t_next (mp);
cur_data = -1;
if (cur_sym() != NULL) {
@<Substitute for |cur_sym|, if it's on the |subst_list|@>;
if (cur_cmd() == terminator) {
@<Adjust the balance; |break| if it's zero@>;
} else if (cur_cmd() == mp_macro_special) {
/* Handle quoted symbols, \.{\#\AT!}, \.{\AT!}, or \.{\AT!\#} */
if (cur_mod() == quote) {
get_t_next (mp);
} else if (cur_mod() <= suffix_count) {
cur_data = cur_mod() - 1;
cur_data_mod = mp_suffix_sym;
}
}
}
if (cur_data != -1) {
mp_node pp = mp_get_symbolic_node (mp);
set_mp_sym_info (pp, cur_data);
mp_name_type (pp) = cur_data_mod;
mp_link (p) = pp;
} else {
mp_link (p) = mp_cur_tok (mp);
}
p = mp_link (p);
}
mp_link (p) = tail_end;
while (subst_list) {
q = subst_list->link;
xfree (subst_list);
subst_list = q;
}
return mp_link (mp->hold_head);
}
@
@c
void mp_print_sym (mp_sym sym) {
printf("{type = %d, v = {type = %d, data = {indep = {scale = %d, serial = %d}, n = %d, str = %p, sym = %p, node = %p, p = %p}}, text = %p}\n", sym->type, sym->v.type, (int)sym->v.data.indep.scale, (int)sym->v.data.indep.serial,
sym->v.data.n.type, sym->v.data.str, sym->v.data.sym, sym->v.data.node, sym->v.data.p, sym->text);
if (is_number(sym->v.data.n)) {
mp_number n = sym->v.data.n;
printf("{data = {dval = %f, val = %d}, type = %d}\n", n.data.dval, n.data.val, n.type);
}
if (sym->text != NULL) {
mp_string t = sym->text;
printf ("{str = %p \"%s\", len = %d, refs = %d}\n", t->str, t->str, (int)t->len, t->refs);
}
}
@
@<Declarations@>=
void mp_print_sym (mp_sym sym) ;
@ @<Substitute for |cur_sym|...@>=
{
q = subst_list;
while (q != NULL) {
if (q->info == cur_sym() && q->info_mod == cur_sym_mod()) {
cur_data = q->value_data;
cur_data_mod = q->value_mod;
set_cur_cmd((mp_variable_type)mp_relax);
break;
}
q = q->link;
}
}
@ @<Adjust the balance; |break| if it's zero@>=
if (cur_mod() > 0) {
incr (balance);
} else {
decr (balance);
if (balance == 0)
break;
}
@ Four commands are intended to be used only within macro texts: \&{quote},
\.{\#\AT!}, \.{\AT!}, and \.{\AT!\#}. They are variants of a single command
code called |macro_special|.
@d quote 0 /* |macro_special| modifier for \&{quote} */
@d macro_prefix 1 /* |macro_special| modifier for \.{\#\AT!} */
@d macro_at 2 /* |macro_special| modifier for \.{\AT!} */
@d macro_suffix 3 /* |macro_special| modifier for \.{\AT!\#} */
@<Put each...@>=
mp_primitive (mp, "quote", mp_macro_special, quote);
@:quote_}{\&{quote} primitive@>;
mp_primitive (mp, "#@@", mp_macro_special, macro_prefix);
@:]]]\#\AT!_}{\.{\#\AT!} primitive@>;
mp_primitive (mp, "@@", mp_macro_special, macro_at);
@:]]]\AT!_}{\.{\AT!} primitive@>;
mp_primitive (mp, "@@#", mp_macro_special, macro_suffix);
@:]]]\AT!\#_}{\.{\AT!\#} primitive@>
@ @<Cases of |print_cmd...@>=
case mp_macro_special:
switch (m) {
case macro_prefix:
mp_print (mp, "#@@");
break;
case macro_at:
mp_print_char (mp, xord ('@@'));
break;
case macro_suffix:
mp_print (mp, "@@#");
break;
default:
mp_print (mp, "quote");
break;
}
break;
@ Here is a routine that's used whenever a token will be redefined. If
the user's token is unredefinable, the `|mp->frozen_inaccessible|' token is
substituted; the latter is redefinable but essentially impossible to use,
hence \MP's tables won't get fouled up.
@c
static void mp_get_symbol (MP mp) { /* sets |cur_sym| to a safe symbol */
RESTART:
get_t_next (mp);
if ((cur_sym() == NULL) || mp_is_frozen(mp, cur_sym())) {
const char *hlp[] = {
"Sorry: You can\'t redefine a number, string, or expr.",
"I've inserted an inaccessible symbol so that your",
"definition will be completed without mixing me up too badly.",
NULL };
if (cur_sym() != NULL)
hlp[0] = "Sorry: You can\'t redefine my error-recovery tokens.";
else if (cur_cmd() == mp_string_token)
delete_str_ref (cur_mod_str());
set_cur_sym(mp->frozen_inaccessible);
mp_ins_error (mp, "Missing symbolic token inserted", hlp, true);
@.Missing symbolic token...@>;
goto RESTART;
}
}
@ Before we actually redefine a symbolic token, we need to clear away its
former value, if it was a variable. The following stronger version of
|get_symbol| does that.
@c
static void mp_get_clear_symbol (MP mp) {
mp_get_symbol (mp);
mp_clear_symbol (mp, cur_sym(), false);
}
@ Here's another little subroutine; it checks that an equals sign
or assignment sign comes along at the proper place in a macro definition.
@c
static void mp_check_equals (MP mp) {
if (cur_cmd() != mp_equals)
if (cur_cmd() != mp_assignment) {
const char *hlp[] = {
"The next thing in this `def' should have been `=',",
"because I've already looked at the definition heading.",
"But don't worry; I'll pretend that an equals sign",
"was present. Everything from here to `enddef'",
"will be the replacement text of this macro.",
NULL };
mp_back_error (mp, "Missing `=' has been inserted", hlp, true);
@.Missing `='@>;
}
}
@ A \&{primarydef}, \&{secondarydef}, or \&{tertiarydef} is rather easily
handled now that we have |scan_toks|. In this case there are
two parameters, which will be \.{EXPR0} and \.{EXPR1}.
@c
static void mp_make_op_def (MP mp) {
mp_command_code m; /* the type of definition */
mp_node q, r; /* for list manipulation */
mp_subst_list_item *qm = NULL, *qn = NULL;
m = cur_mod();
mp_get_symbol (mp);
qm = xmalloc (1, sizeof (mp_subst_list_item));
qm->link = NULL;
qm->info = cur_sym();
qm->info_mod = cur_sym_mod();
qm->value_data = 0;
qm->value_mod = mp_expr_sym;
mp_get_clear_symbol (mp);
mp->warning_info = cur_sym();
mp_get_symbol (mp);
qn = xmalloc (1, sizeof (mp_subst_list_item));
qn->link = qm;
qn->info = cur_sym();
qn->info_mod = cur_sym_mod();
qn->value_data = 1;
qn->value_mod = mp_expr_sym;
get_t_next (mp);
mp_check_equals (mp);
mp->scanner_status = op_defining;
q = mp_get_symbolic_node (mp);
set_ref_count (q, 0);
r = mp_get_symbolic_node (mp);
mp_link (q) = r;
set_mp_sym_info (r, mp_general_macro);
mp_name_type (r) = mp_macro_sym;
mp_link (r) = mp_scan_toks (mp, mp_macro_def, qn, NULL, 0);
mp->scanner_status = normal;
set_eq_type (mp->warning_info, m);
set_equiv_node (mp->warning_info, q);
mp_get_x_next (mp);
}
@ Parameters to macros are introduced by the keywords \&{expr},
\&{suffix}, \&{text}, \&{primary}, \&{secondary}, and \&{tertiary}.
@<Put each...@>=
mp_primitive (mp, "expr", mp_param_type, mp_expr_param);
@:expr_}{\&{expr} primitive@>;
mp_primitive (mp, "suffix", mp_param_type, mp_suffix_param);
@:suffix_}{\&{suffix} primitive@>;
mp_primitive (mp, "text", mp_param_type, mp_text_param);
@:text_}{\&{text} primitive@>;
mp_primitive (mp, "primary", mp_param_type, mp_primary_macro);
@:primary_}{\&{primary} primitive@>;
mp_primitive (mp, "secondary", mp_param_type, mp_secondary_macro);
@:secondary_}{\&{secondary} primitive@>;
mp_primitive (mp, "tertiary", mp_param_type, mp_tertiary_macro);
@:tertiary_}{\&{tertiary} primitive@>
@ @<Cases of |print_cmd...@>=
case mp_param_type:
if (m == mp_expr_param)
mp_print (mp, "expr");
else if (m == mp_suffix_param)
mp_print (mp, "suffix");
else if (m == mp_text_param)
mp_print (mp, "text");
else if (m == mp_primary_macro)
mp_print (mp, "primary");
else if (m == mp_secondary_macro)
mp_print (mp, "secondary");
else
mp_print (mp, "tertiary");
break;
@ Let's turn next to the more complex processing associated with \&{def}
and \&{vardef}. When the following procedure is called, |cur_mod|
should be either |start_def| or |var_def|.
Note that although the macro scanner allows |def = := enddef| and
|def := = enddef|; |def = = enddef| and |def := := enddef| will generate
an error because by the time the second of the two identical tokens is
seen, its meaning has already become undefined.
@c
static void mp_scan_def (MP mp) {
int m; /* the type of definition */
int n; /* the number of special suffix parameters */
int k; /* the total number of parameters */
int c; /* the kind of macro we're defining */
mp_subst_list_item *r = NULL, *rp = NULL; /* parameter-substitution list */
mp_node q; /* tail of the macro token list */
mp_node p; /* temporary storage */
quarterword sym_type; /* |expr_sym|, |suffix_sym|, or |text_sym| */
mp_sym l_delim, r_delim; /* matching delimiters */
m = cur_mod();
c = mp_general_macro;
mp_link (mp->hold_head) = NULL;
q = mp_get_symbolic_node (mp);
set_ref_count (q, 0);
r = NULL;
/* Scan the token or variable to be defined;
set |n|, |scanner_status|, and |warning_info| */
if (m == start_def) {
mp_get_clear_symbol (mp);
mp->warning_info = cur_sym();
get_t_next (mp);
mp->scanner_status = op_defining;
n = 0;
set_eq_type (mp->warning_info, mp_defined_macro);
set_equiv_node (mp->warning_info, q);
} else { /* |var_def| */
p = mp_scan_declared_variable (mp);
mp_flush_variable (mp, equiv_node (mp_sym_sym (p)), mp_link (p), true);
mp->warning_info_node = mp_find_variable (mp, p);
mp_flush_node_list (mp, p);
if (mp->warning_info_node == NULL) {
/* Change to `\.{a bad variable}' */
const char *hlp[] = {
"After `vardef a' you can\'t say `vardef a.b'.",
"So I'll have to discard this definition.",
NULL };
mp_error (mp, "This variable already starts with a macro", hlp, true);
mp->warning_info_node = mp->bad_vardef;
}
mp->scanner_status = var_defining;
n = 2;
if (cur_cmd() == mp_macro_special && cur_mod() == macro_suffix) { /* \.{\AT!\#} */
n = 3;
get_t_next (mp);
}
mp_type (mp->warning_info_node) = (quarterword) (mp_unsuffixed_macro - 2 + n);
/* |mp_suffixed_macro=mp_unsuffixed_macro+1| */
set_value_node (mp->warning_info_node, q);
}
k = n;
if (cur_cmd() == mp_left_delimiter) {
/* Absorb delimited parameters, putting them into lists |q| and |r| */
do {
l_delim = cur_sym();
r_delim = equiv_sym (cur_sym());
get_t_next (mp);
if ((cur_cmd() == mp_param_type) && (cur_mod() == mp_expr_param)) {
sym_type = mp_expr_sym;
} else if ((cur_cmd() == mp_param_type) && (cur_mod() == mp_suffix_param)) {
sym_type = mp_suffix_sym;
} else if ((cur_cmd() == mp_param_type) && (cur_mod() == mp_text_param)) {
sym_type = mp_text_sym;
} else {
const char *hlp[] = { "You should've had `expr' or `suffix' or `text' here.", NULL };
mp_back_error (mp, "Missing parameter type; `expr' will be assumed", hlp, true);
sym_type = mp_expr_sym;
}
/* Absorb parameter tokens for type |sym_type| */
do {
mp_link (q) = mp_get_symbolic_node (mp);
q = mp_link (q);
mp_name_type (q) = sym_type;
set_mp_sym_info (q, k);
mp_get_symbol (mp);
rp = xmalloc (1, sizeof (mp_subst_list_item));
rp->link = NULL;
rp->value_data = k;
rp->value_mod = sym_type;
rp->info = cur_sym();
rp->info_mod = cur_sym_mod();
mp_check_param_size (mp, k);
incr (k);
rp->link = r;
r = rp;
get_t_next (mp);
} while (cur_cmd() == mp_comma);
mp_check_delimiter (mp, l_delim, r_delim);
get_t_next (mp);
} while (cur_cmd() == mp_left_delimiter);
}
if (cur_cmd() == mp_param_type) {
/* Absorb undelimited parameters, putting them into list |r| */
rp = xmalloc (1, sizeof (mp_subst_list_item));
rp->link = NULL;
rp->value_data = k;
if (cur_mod() == mp_expr_param) {
rp->value_mod = mp_expr_sym;
c = mp_expr_macro;
} else if (cur_mod() == mp_suffix_param) {
rp->value_mod = mp_suffix_sym;
c = mp_suffix_macro;
} else if (cur_mod() == mp_text_param) {
rp->value_mod = mp_text_sym;
c = mp_text_macro;
} else {
c = cur_mod();
rp->value_mod = mp_expr_sym;
}
mp_check_param_size (mp, k);
incr (k);
mp_get_symbol (mp);
rp->info = cur_sym();
rp->info_mod = cur_sym_mod();
rp->link = r;
r = rp;
get_t_next (mp);
if (c == mp_expr_macro) {
if (cur_cmd() == mp_of_token) {
c = mp_of_macro;
rp = xmalloc (1, sizeof (mp_subst_list_item));
rp->link = NULL;
mp_check_param_size (mp, k);
rp->value_data = k;
rp->value_mod = mp_expr_sym;
mp_get_symbol (mp);
rp->info = cur_sym();
rp->info_mod = cur_sym_mod();
rp->link = r;
r = rp;
get_t_next (mp);
}
}
}
mp_check_equals (mp);
p = mp_get_symbolic_node (mp);
set_mp_sym_info (p, c);
mp_name_type (p) = mp_macro_sym;
mp_link (q) = p;
/* Attach the replacement text to the tail of node |p| */
/* We don't put `|mp->frozen_end_group|' into the replacement text of
a \&{vardef}, because the user may want to redefine `\.{endgroup}'. */
if (m == start_def) {
mp_link (p) = mp_scan_toks (mp, mp_macro_def, r, NULL, (quarterword) n);
} else {
mp_node qq = mp_get_symbolic_node (mp);
set_mp_sym_sym (qq, mp->bg_loc);
mp_link (p) = qq;
p = mp_get_symbolic_node (mp);
set_mp_sym_sym (p, mp->eg_loc);
mp_link (qq) = mp_scan_toks (mp, mp_macro_def, r, p, (quarterword) n);
}
if (mp->warning_info_node == mp->bad_vardef)
mp_flush_token_list (mp, value_node (mp->bad_vardef));
mp->scanner_status = normal;
mp_get_x_next (mp);
}
@ @<Glob...@>=
mp_sym bg_loc;
mp_sym eg_loc; /* hash addresses of `\.{begingroup}' and `\.{endgroup}' */
@ @<Initialize table entries@>=
mp->bad_vardef = mp_get_value_node (mp);
mp_name_type (mp->bad_vardef) = mp_root;
set_value_sym (mp->bad_vardef, mp->frozen_bad_vardef);
@ @<Free table entries@>=
mp_free_value_node (mp, mp->bad_vardef);
@* Expanding the next token.
Only a few command codes |<min_command| can possibly be returned by
|get_t_next|; in increasing order, they are
|if_test|, |fi_or_else|, |input|, |iteration|, |repeat_loop|,
|exit_test|, |relax|, |scan_tokens|, |run_script|, |expand_after|, and |defined_macro|.
\MP\ usually gets the next token of input by saying |get_x_next|. This is
like |get_t_next| except that it keeps getting more tokens until
finding |cur_cmd>=min_command|. In other words, |get_x_next| expands
macros and removes conditionals or iterations or input instructions that
might be present.
It follows that |get_x_next| might invoke itself recursively. In fact,
there is massive recursion, since macro expansion can involve the
scanning of arbitrarily complex expressions, which in turn involve
macro expansion and conditionals, etc.
@^recursion@>
Therefore it's necessary to declare a whole bunch of |forward|
procedures at this point, and to insert some other procedures
that will be invoked by |get_x_next|.
@<Declarations@>=
static void mp_scan_primary (MP mp);
static void mp_scan_secondary (MP mp);
static void mp_scan_tertiary (MP mp);
static void mp_scan_expression (MP mp);
static void mp_scan_suffix (MP mp);
static void mp_pass_text (MP mp);
static void mp_conditional (MP mp);
static void mp_start_input (MP mp);
static void mp_begin_iteration (MP mp);
static void mp_resume_iteration (MP mp);
static void mp_stop_iteration (MP mp);
@ A recursion depth counter is used to discover infinite recursions.
(Near) infinite recursion is a problem because it translates into
C function calls that eat up the available call stack. A better solution
would be to depend on signal trapping, but that is problematic when
Metapost is used as a library.
@<Global...@>=
int expand_depth_count; /* current expansion depth */
int expand_depth; /* current expansion depth */
@ The limit is set at |10000|, which should be enough to allow
normal usages of metapost while preventing the most obvious
crashes on most all operating systems, but the value can be
raised if the runtime system allows a larger C stack.
@^system dependencies@>
@<Set initial...@>=
mp->expand_depth = 10000;
@ Even better would be if the system allows discovery of the amount of
space available on the call stack.
@^system dependencies@>
In any case, when the limit is crossed, that is a fatal error.
@d check_expansion_depth() if (++mp->expand_depth_count >= mp->expand_depth)
mp_expansion_depth_error(mp)
@c
static void mp_expansion_depth_error (MP mp) {
const char *hlp[] = {
"Recursive macro expansion cannot be unlimited because of runtime",
"stack constraints. The limit is 10000 recursion levels in total.",
NULL };
if ( mp->interaction==mp_error_stop_mode )
mp->interaction=mp_scroll_mode; /* no more interaction */
if ( mp->log_opened )
mp_error(mp, "Maximum expansion depth reached", hlp, true);
mp->history=mp_fatal_error_stop;
mp_jump_out(mp);
}
@ An auxiliary subroutine called |expand| is used by |get_x_next|
when it has to do exotic expansion commands.
@c
static void mp_expand (MP mp) {
size_t k; /* something that we hope is |<=buf_size| */
size_t j; /* index into |str_pool| */
check_expansion_depth();
if (number_greater (internal_value (mp_tracing_commands), unity_t))
if (cur_cmd() != mp_defined_macro)
show_cur_cmd_mod;
switch (cur_cmd()) {
case mp_if_test:
mp_conditional (mp); /* this procedure is discussed in Part 36 below */
break;
case mp_fi_or_else:
@<Terminate the current conditional and skip to \&{fi}@>;
break;
case mp_input:
@<Initiate or terminate input from a file@>;
break;
case mp_iteration:
if (cur_mod() == end_for) {
@<Scold the user for having an extra \&{endfor}@>;
} else {
mp_begin_iteration (mp); /* this procedure is discussed in Part 37 below */
}
break;
case mp_repeat_loop:
@<Repeat a loop@>;
break;
case mp_exit_test:
@<Exit a loop if the proper time has come@>;
break;
case mp_relax:
break;
case mp_expand_after:
@<Expand the token after the next token@>;
break;
case mp_scan_tokens:
@<Put a string into the input buffer@>;
break;
case mp_runscript:
@<Put a script result string into the input buffer@>;
break;
case mp_maketext:
@<Put a maketext result string into the input buffer@>;
break;
case mp_defined_macro:
mp_macro_call (mp, cur_mod_node(), NULL, cur_sym());
break;
default:
break; /* make the compiler happy */
}; /* there are no other cases */
mp->expand_depth_count--;
}
@ @<Scold the user...@>=
{
const char *hlp[] = {
"I'm not currently working on a for loop,",
"so I had better not try to end anything.",
NULL };
mp_error (mp, "Extra `endfor'", hlp, true);
@.Extra `endfor'@>;
}
@ The processing of \&{input} involves the |start_input| subroutine,
which will be declared later; the processing of \&{endinput} is trivial.
@<Put each...@>=
mp_primitive (mp, "input", mp_input, 0);
@:input_}{\&{input} primitive@>;
mp_primitive (mp, "endinput", mp_input, 1);
@:end_input_}{\&{endinput} primitive@>
@ @<Cases of |print_cmd_mod|...@>=
case mp_input:
if (m == 0)
mp_print (mp, "input");
else
mp_print (mp, "endinput");
break;
@ @<Initiate or terminate input...@>=
if (cur_mod() > 0)
mp->force_eof = true;
else
mp_start_input (mp)
@ We'll discuss the complicated parts of loop operations later. For now
it suffices to know that there's a global variable called |loop_ptr|
that will be |NULL| if no loop is in progress.
@<Repeat a loop@>=
{
while (token_state && (nloc == NULL))
mp_end_token_list (mp); /* conserve stack space */
if (mp->loop_ptr == NULL) {
const char *hlp[] = {
"I'm confused; after exiting from a loop, I still seem",
"to want to repeat it. I'll try to forget the problem.",
NULL };
mp_error (mp, "Lost loop", hlp, true);
@.Lost loop@>;
} else {
mp_resume_iteration (mp); /* this procedure is in Part 37 below */
}
}
@ @<Exit a loop if the proper time has come@>=
{
mp_get_boolean (mp);
if (number_greater (internal_value (mp_tracing_commands), unity_t))
mp_show_cmd_mod (mp, mp_nullary, cur_exp_value_boolean ());
if (cur_exp_value_boolean () == mp_true_code) {
if (mp->loop_ptr == NULL) {
const char *hlp[] = {
"Why say `exitif' when there's nothing to exit from?",
NULL };
if (cur_cmd() == mp_semicolon)
mp_error (mp, "No loop is in progress", hlp, true);
else
mp_back_error (mp, "No loop is in progress", hlp, true);
@.No loop is in progress@>;
} else {
@<Exit prematurely from an iteration@>;
}
} else if (cur_cmd() != mp_semicolon) {
const char *hlp[] = {
"After `exitif <boolean exp>' I expect to see a semicolon.",
"I shall pretend that one was there.",
NULL };
mp_back_error (mp, "Missing `;' has been inserted", hlp, true);
@.Missing `;'@>;
}
}
@ Here we use the fact that |forever_text| is the only |token_type| that
is less than |loop_text|.
@<Exit prematurely...@>=
{
mp_node p = NULL;
do {
if (file_state) {
mp_end_file_reading (mp);
} else {
if (token_type <= loop_text)
p = nstart;
mp_end_token_list (mp);
}
} while (p == NULL);
if (p != mp->loop_ptr->info)
mp_fatal_error (mp, "*** (loop confusion)");
@.loop confusion@>;
mp_stop_iteration (mp); /* this procedure is in Part 34 below */
}
@ @<Expand the token after the next token@>=
{
mp_node p;
get_t_next (mp);
p = mp_cur_tok (mp);
get_t_next (mp);
if (cur_cmd() < mp_min_command)
mp_expand (mp);
else
mp_back_input (mp);
back_list (p);
}
@ @<Put a string into the input buffer@>=
{
mp_get_x_next (mp);
mp_scan_primary (mp);
if (mp->cur_exp.type != mp_string_type) {
mp_value new_expr;
const char *hlp[] = {
"I'm going to flush this expression, since",
"scantokens should be followed by a known string.",
NULL };
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
mp_disp_err (mp, NULL);
mp_back_error (mp, "Not a string", hlp, true);
@.Not a string@>;
mp_get_x_next (mp);
mp_flush_cur_exp (mp, new_expr);
} else {
mp_back_input (mp);
if (cur_exp_str ()->len > 0)
@<Pretend we're reading a new one-line file@>;
}
}
@ @<Run a script@>=
if (s != NULL) {
int k ;
size_t size = strlen(s);
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
mp_begin_file_reading (mp);
name = is_scantok;
mp->last = mp->first;
k = mp->first + size;
if (k >= mp->max_buf_stack) {
while (k >= mp->buf_size) {
mp_reallocate_buffer (mp, (mp->buf_size + (mp->buf_size / 4)));
}
mp->max_buf_stack = k + 1;
}
limit = (halfword) k;
(void) memcpy ((mp->buffer + mp->first), s, size);
free(s);
mp->buffer[limit] = xord ('%');
mp->first = (size_t) (limit + 1);
loc = start;
mp_flush_cur_exp (mp, new_expr);
}
@ @<Put a script result string into the input buffer@>=
{
if (mp->extensions == 0) {
return ;
}
mp_get_x_next (mp);
mp_scan_primary (mp);
if (mp->cur_exp.type != mp_string_type) {
mp_value new_expr;
const char *hlp[] = {
"I'm going to flush this expression, since",
"runscript should be followed by a known string.",
NULL };
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
mp_disp_err (mp, NULL);
mp_back_error (mp, "Not a string", hlp, true);
@.Not a string@>;
mp_get_x_next (mp);
mp_flush_cur_exp (mp, new_expr);
} else {
mp_back_input (mp);
if (cur_exp_str ()->len > 0) {
mp_value new_expr;
char *s = mp->run_script(mp,(const char*) cur_exp_str()->str) ;
@<Run a script@>
}
}
}
@ @<Pass btex ... etex to script@>=
{
int first ;
while ((loc < limit - 4) && (mp->buffer[loc] == ' ')) {
incr(loc);
}
first = loc ;
if (mp->buffer[loc-1] == ' ') {
decr(loc);
}
while (loc < limit - 5) {
if (mp->buffer[loc] == ' ') {
incr(loc);
if (mp->buffer[loc] == 'e') {
incr(loc);
if (mp->buffer[loc] == 't') {
incr(loc) ;
if (mp->buffer[loc] == 'e') {
incr(loc) ;
if (mp->buffer[loc] == 'x') {
/* start action */
char *s, *txt ;
int size ;
mp_value new_expr;
size = loc - first + 1 - 4 ;
if (size < 0) {
size = 0 ;
} else {
while ((size > 1) && (mp->buffer[first+size-1] == ' ')) {
decr(size);
}
}
txt = malloc(size+1);
if (size > 0) {
(void) memcpy (txt, mp->buffer + first, size);
}
txt[size] = '\0';
incr(loc);
s = mp->make_text(mp,txt,(cur_mod() == verbatim_code)) ; /* we could pass the size */
@<Run a script@>
/* done */
free(txt);
break ;
} else {
// decr(loc) ;
}
}
}
}
} else {
incr(loc);
}
}
}
@ @<Put a maketext result string into the input buffer@>=
{
if (mp->extensions == 0) {
return ;
}
mp_get_x_next (mp);
mp_scan_primary (mp);
if (mp->cur_exp.type != mp_string_type) {
mp_value new_expr;
const char *hlp[] = {
"I'm going to flush this expression, since",
"makete should be followed by a known string.",
NULL };
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
mp_disp_err (mp, NULL);
mp_back_error (mp, "Not a string", hlp, true);
@.Not a string@>;
mp_get_x_next (mp);
mp_flush_cur_exp (mp, new_expr);
} else {
mp_back_input (mp);
if (cur_exp_str ()->len > 0) {
mp_value new_expr;
char *s = mp->make_text(mp,(const char*) cur_exp_str()->str,0) ;
@<Run a script@>
}
}
}
@ @<Pretend we're reading a new one-line file@>=
{
mp_value new_expr;
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
mp_begin_file_reading (mp);
name = is_scantok;
k = mp->first + (size_t) cur_exp_str ()->len;
if (k >= mp->max_buf_stack) {
while (k >= mp->buf_size) {
mp_reallocate_buffer (mp, (mp->buf_size + (mp->buf_size / 4)));
}
mp->max_buf_stack = k + 1;
}
j = 0;
limit = (halfword) k;
while (mp->first < (size_t) limit) {
mp->buffer[mp->first] = *(cur_exp_str ()->str + j);
j++;
incr (mp->first);
}
mp->buffer[limit] = xord ('%');
mp->first = (size_t) (limit + 1);
loc = start;
mp_flush_cur_exp (mp, new_expr);
}
@ Here finally is |get_x_next|.
The expression scanning routines to be considered later
communicate via the global quantities |cur_type| and |cur_exp|;
we must be very careful to save and restore these quantities while
macros are being expanded.
@^inner loop@>
@<Declarations@>=
static void mp_get_x_next (MP mp);
@ @c
void mp_get_x_next (MP mp) {
mp_node save_exp; /* a capsule to save |cur_type| and |cur_exp| */
get_t_next (mp);
if (cur_cmd() < mp_min_command) {
save_exp = mp_stash_cur_exp (mp);
do {
if (cur_cmd() == mp_defined_macro)
mp_macro_call (mp, cur_mod_node(), NULL, cur_sym());
else
mp_expand (mp);
get_t_next (mp);
} while (cur_cmd() < mp_min_command);
mp_unstash_cur_exp (mp, save_exp); /* that restores |cur_type| and |cur_exp| */
}
}
@ Now let's consider the |macro_call| procedure, which is used to start up
all user-defined macros. Since the arguments to a macro might be expressions,
|macro_call| is recursive.
@^recursion@>
The first parameter to |macro_call| points to the reference count of the
token list that defines the macro. The second parameter contains any
arguments that have already been parsed (see below). The third parameter
points to the symbolic token that names the macro. If the third parameter
is |NULL|, the macro was defined by \&{vardef}, so its name can be
reconstructed from the prefix and ``at'' arguments found within the
second parameter.
What is this second parameter? It's simply a linked list of symbolic items,
whose |info| fields point to the arguments. In other words, if |arg_list=NULL|,
no arguments have been scanned yet; otherwise |mp_info(arg_list)| points to
the first scanned argument, and |mp_link(arg_list)| points to the list of
further arguments (if any).
Arguments of type \&{expr} are so-called capsules, which we will
discuss later when we concentrate on expressions; they can be
recognized easily because their |link| field is |void|. Arguments of type
\&{suffix} and \&{text} are token lists without reference counts.
@ After argument scanning is complete, the arguments are moved to the
|param_stack|. (They can't be put on that stack any sooner, because
the stack is growing and shrinking in unpredictable ways as more arguments
are being acquired.) Then the macro body is fed to the scanner; i.e.,
the replacement text of the macro is placed at the top of the \MP's
input stack, so that |get_t_next| will proceed to read it next.
@<Declarations@>=
static void mp_macro_call (MP mp, mp_node def_ref, mp_node arg_list,
mp_sym macro_name);
@ @c
void mp_macro_call (MP mp, mp_node def_ref, mp_node arg_list, mp_sym macro_name) {
/* invokes a user-defined control sequence */
mp_node r; /* current node in the macro's token list */
mp_node p, q; /* for list manipulation */
integer n; /* the number of arguments */
mp_node tail = 0; /* tail of the argument list */
mp_sym l_delim = NULL, r_delim = NULL; /* a delimiter pair */
r = mp_link (def_ref);
add_mac_ref (def_ref);
if (arg_list == NULL) {
n = 0;
} else {
@<Determine the number |n| of arguments already supplied,
and set |tail| to the tail of |arg_list|@>;
}
if (number_positive (internal_value (mp_tracing_macros))) {
@<Show the text of the macro being expanded, and the existing arguments@>;
}
@<Scan the remaining arguments, if any; set |r| to the first token
of the replacement text@>;
@<Feed the arguments and replacement text to the scanner@>;
}
@ @<Show the text of the macro...@>=
mp_begin_diagnostic (mp);
mp_print_ln (mp);
mp_print_macro_name (mp, arg_list, macro_name);
if (n == 3)
mp_print (mp, "@@#"); /* indicate a suffixed macro */
mp_show_macro (mp, def_ref, NULL, 100000);
if (arg_list != NULL) {
n = 0;
p = arg_list;
do {
q = (mp_node)mp_sym_sym (p);
mp_print_arg (mp, q, n, 0, 0);
incr (n);
p = mp_link (p);
} while (p != NULL);
}
mp_end_diagnostic (mp, false)
@ @<Declarations@>=
static void mp_print_macro_name (MP mp, mp_node a, mp_sym n);
@ @c
void mp_print_macro_name (MP mp, mp_node a, mp_sym n) {
mp_node p, q; /* they traverse the first part of |a| */
if (n != NULL) {
mp_print_text (n);
} else {
p = (mp_node)mp_sym_sym (a);
if (p == NULL) {
mp_print_text (mp_sym_sym ((mp_node)mp_sym_sym (mp_link (a))));
} else {
q = p;
while (mp_link (q) != NULL)
q = mp_link (q);
mp_link (q) = (mp_node)mp_sym_sym (mp_link (a));
mp_show_token_list (mp, p, NULL, 1000, 0);
mp_link (q) = NULL;
}
}
}
@ @<Declarations@>=
static void mp_print_arg (MP mp, mp_node q, integer n, halfword b,
quarterword bb);
@ @c
void mp_print_arg (MP mp, mp_node q, integer n, halfword b, quarterword bb) {
if (q && mp_link (q) == MP_VOID) {
mp_print_nl (mp, "(EXPR");
} else {
if ((bb < mp_text_sym) && (b != mp_text_macro))
mp_print_nl (mp, "(SUFFIX");
else
mp_print_nl (mp, "(TEXT");
}
mp_print_int (mp, n);
mp_print (mp, ")<-");
if (q && mp_link (q) == MP_VOID)
mp_print_exp (mp, q, 1);
else
mp_show_token_list (mp, q, NULL, 1000, 0);
}
@ @<Determine the number |n| of arguments already supplied...@>=
{
n = 1;
tail = arg_list;
while (mp_link (tail) != NULL) {
incr (n);
tail = mp_link (tail);
}
}
@ @<Scan the remaining arguments, if any; set |r|...@>=
set_cur_cmd(mp_comma + 1); /* anything |<>comma| will do */
while (mp_name_type (r) == mp_expr_sym ||
mp_name_type (r) == mp_suffix_sym || mp_name_type (r) == mp_text_sym) {
@<Scan the delimited argument represented by |mp_sym_info(r)|@>;
r = mp_link (r);
}
if (cur_cmd() == mp_comma) {
char msg[256];
const char *hlp[] = {
"I'm going to assume that the comma I just read was a",
"right delimiter, and then I'll begin expanding the macro.",
"You might want to delete some tokens before continuing.",
NULL };
mp_string rname;
int old_setting = mp->selector;
mp->selector = new_string;
mp_print_macro_name (mp, arg_list, macro_name);
rname = mp_make_string(mp);
mp->selector = old_setting;
mp_snprintf (msg, 256, "Too many arguments to %s; Missing `%s' has been inserted",
mp_str(mp, rname), mp_str(mp, text(r_delim)));
delete_str_ref(rname);
@.Too many arguments...@>;
@.Missing `)'...@>;
mp_error (mp, msg, hlp, true);
}
if (mp_sym_info (r) != mp_general_macro) {
@<Scan undelimited argument(s)@>;
}
r = mp_link (r)
@ At this point, the reader will find it advisable to review the explanation
of token list format that was presented earlier, paying special attention to
the conventions that apply only at the beginning of a macro's token list.
On the other hand, the reader will have to take the expression-parsing
aspects of the following program on faith; we will explain |cur_type|
and |cur_exp| later. (Several things in this program depend on each other,
and it's necessary to jump into the circle somewhere.)
@<Scan the delimited argument represented by |mp_sym_info(r)|@>=
if (cur_cmd() != mp_comma) {
mp_get_x_next (mp);
if (cur_cmd() != mp_left_delimiter) {
char msg[256];
const char *hlp[] = {
"That macro has more parameters than you thought.",
"I'll continue by pretending that each missing argument",
"is either zero or null.",
NULL };
mp_string sname;
int old_setting = mp->selector;
mp->selector = new_string;
mp_print_macro_name (mp, arg_list, macro_name);
sname = mp_make_string(mp);
mp->selector = old_setting;
mp_snprintf (msg, 256, "Missing argument to %s", mp_str(mp, sname));
@.Missing argument...@>;
delete_str_ref(sname);
if (mp_name_type (r) == mp_suffix_sym || mp_name_type (r) == mp_text_sym) {
set_cur_exp_value_number (zero_t); /* todo: this was |null| */
mp->cur_exp.type = mp_token_list;
} else {
set_cur_exp_value_number (zero_t);
mp->cur_exp.type = mp_known;
}
mp_back_error (mp, msg, hlp, true);
set_cur_cmd((mp_variable_type)mp_right_delimiter);
goto FOUND;
}
l_delim = cur_sym();
r_delim = equiv_sym (cur_sym());
}
@<Scan the argument represented by |mp_sym_info(r)|@>;
if (cur_cmd() != mp_comma)
@<Check that the proper right delimiter was present@>;
FOUND:
@<Append the current expression to |arg_list|@>
@ @<Check that the proper right delim...@>=
if ((cur_cmd() != mp_right_delimiter) || (equiv_sym (cur_sym()) != l_delim)) {
if (mp_name_type (mp_link (r)) == mp_expr_sym ||
mp_name_type (mp_link (r)) == mp_suffix_sym ||
mp_name_type (mp_link (r)) == mp_text_sym) {
const char *hlp[] = {
"I've finished reading a macro argument and am about to",
"read another; the arguments weren't delimited correctly.",
"You might want to delete some tokens before continuing.",
NULL };
mp_back_error (mp, "Missing `,' has been inserted", hlp, true);
@.Missing `,'@>;
set_cur_cmd((mp_variable_type)mp_comma);
} else {
char msg[256];
const char *hlp[] = {
"I've gotten to the end of the macro parameter list.",
"You might want to delete some tokens before continuing.",
NULL };
mp_snprintf(msg, 256, "Missing `%s' has been inserted", mp_str(mp, text(r_delim)));
@.Missing `)'@>;
mp_back_error (mp, msg, hlp, true);
}
}
@ A \&{suffix} or \&{text} parameter will have been scanned as
a token list pointed to by |cur_exp|, in which case we will have
|cur_type=token_list|.
@<Append the current expression to |arg_list|@>=
{
p = mp_get_symbolic_node (mp);
if (mp->cur_exp.type == mp_token_list)
set_mp_sym_sym (p, mp->cur_exp.data.node);
else
set_mp_sym_sym (p, mp_stash_cur_exp (mp));
if (number_positive (internal_value (mp_tracing_macros))) {
mp_begin_diagnostic (mp);
mp_print_arg (mp, (mp_node)mp_sym_sym (p), n, mp_sym_info (r), mp_name_type (r));
mp_end_diagnostic (mp, false);
}
if (arg_list == NULL) {
arg_list = p;
} else {
mp_link (tail) = p;
}
tail = p;
incr (n);
}
@ @<Scan the argument represented by |mp_sym_info(r)|@>=
if (mp_name_type (r) == mp_text_sym) {
mp_scan_text_arg (mp, l_delim, r_delim);
} else {
mp_get_x_next (mp);
if (mp_name_type (r) == mp_suffix_sym)
mp_scan_suffix (mp);
else
mp_scan_expression (mp);
}
@ The parameters to |scan_text_arg| are either a pair of delimiters
or zero; the latter case is for undelimited text arguments, which
end with the first semicolon or \&{endgroup} or \&{end} that is not
contained in a group.
@<Declarations@>=
static void mp_scan_text_arg (MP mp, mp_sym l_delim, mp_sym r_delim);
@ @c
void mp_scan_text_arg (MP mp, mp_sym l_delim, mp_sym r_delim) {
integer balance; /* excess of |l_delim| over |r_delim| */
mp_node p; /* list tail */
mp->warning_info = l_delim;
mp->scanner_status = absorbing;
p = mp->hold_head;
balance = 1;
mp_link (mp->hold_head) = NULL;
while (1) {
get_t_next (mp);
if (l_delim == NULL) {
@<Adjust the balance for an undelimited argument; |break| if done@>;
} else {
@<Adjust the balance for a delimited argument; |break| if done@>;
}
mp_link (p) = mp_cur_tok (mp);
p = mp_link (p);
}
set_cur_exp_node (mp_link (mp->hold_head));
mp->cur_exp.type = mp_token_list;
mp->scanner_status = normal;
}
@ @<Adjust the balance for a delimited argument...@>=
if (cur_cmd() == mp_right_delimiter) {
if (equiv_sym (cur_sym()) == l_delim) {
decr (balance);
if (balance == 0)
break;
}
} else if (cur_cmd() == mp_left_delimiter) {
if (equiv_sym (cur_sym()) == r_delim)
incr (balance);
}
@ @<Adjust the balance for an undelimited...@>=
if (mp_end_of_statement) { /* |cur_cmd=semicolon|, |end_group|, or |stop| */
if (balance == 1) {
break;
} else {
if (cur_cmd() == mp_end_group)
decr (balance);
}
} else if (cur_cmd() == mp_begin_group) {
incr (balance);
}
@ @<Scan undelimited argument(s)@>=
{
if (mp_sym_info (r) < mp_text_macro) {
mp_get_x_next (mp);
if (mp_sym_info (r) != mp_suffix_macro) {
if ((cur_cmd() == mp_equals) || (cur_cmd() == mp_assignment))
mp_get_x_next (mp);
}
}
switch (mp_sym_info (r)) {
case mp_primary_macro:
mp_scan_primary (mp);
break;
case mp_secondary_macro:
mp_scan_secondary (mp);
break;
case mp_tertiary_macro:
mp_scan_tertiary (mp);
break;
case mp_expr_macro:
mp_scan_expression (mp);
break;
case mp_of_macro:
@<Scan an expression followed by `\&{of} $\langle$primary$\rangle$'@>;
break;
case mp_suffix_macro:
@<Scan a suffix with optional delimiters@>;
break;
case mp_text_macro:
mp_scan_text_arg (mp, NULL, NULL);
break;
} /* there are no other cases */
mp_back_input (mp);
@<Append the current expression to |arg_list|@>;
}
@ @<Scan an expression followed by `\&{of} $\langle$primary$\rangle$'@>=
{
mp_scan_expression (mp);
p = mp_get_symbolic_node (mp);
set_mp_sym_sym (p, mp_stash_cur_exp (mp));
if (number_positive (internal_value (mp_tracing_macros))) {
mp_begin_diagnostic (mp);
mp_print_arg (mp, (mp_node)mp_sym_sym (p), n, 0, 0);
mp_end_diagnostic (mp, false);
}
if (arg_list == NULL)
arg_list = p;
else
mp_link (tail) = p;
tail = p;
incr (n);
if (cur_cmd() != mp_of_token) {
char msg[256];
mp_string sname;
const char *hlp[] = {
"I've got the first argument; will look now for the other.",
NULL };
int old_setting = mp->selector;
mp->selector = new_string;
mp_print_macro_name (mp, arg_list, macro_name);
sname = mp_make_string(mp);
mp->selector = old_setting;
mp_snprintf (msg, 256, "Missing `of' has been inserted for %s", mp_str(mp, sname));
delete_str_ref(sname);
@.Missing `of'@>;
mp_back_error (mp, msg, hlp, true);
}
mp_get_x_next (mp);
mp_scan_primary (mp);
}
@ @<Scan a suffix with optional delimiters@>=
{
if (cur_cmd() != mp_left_delimiter) {
l_delim = NULL;
} else {
l_delim = cur_sym();
r_delim = equiv_sym (cur_sym());
mp_get_x_next (mp);
}
mp_scan_suffix (mp);
if (l_delim != NULL) {
if ((cur_cmd() != mp_right_delimiter) || (equiv_sym (cur_sym()) != l_delim)) {
char msg[256];
const char *hlp[] = {
"I've gotten to the end of the macro parameter list.",
"You might want to delete some tokens before continuing.",
NULL };
mp_snprintf(msg, 256, "Missing `%s' has been inserted", mp_str (mp, text (r_delim)));
@.Missing `)'@>;
mp_back_error (mp, msg, hlp, true);
}
mp_get_x_next (mp);
}
}
@ Before we put a new token list on the input stack, it is wise to clean off
all token lists that have recently been depleted. Then a user macro that ends
with a call to itself will not require unbounded stack space.
@<Feed the arguments and replacement text to the scanner@>=
while (token_state && (nloc == NULL))
mp_end_token_list (mp); /* conserve stack space */
if (mp->param_ptr + n > mp->max_param_stack) {
mp->max_param_stack = mp->param_ptr + n;
mp_check_param_size (mp, mp->max_param_stack);
@:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
}
mp_begin_token_list (mp, def_ref, (quarterword) macro);
if (macro_name)
name = text (macro_name);
else
name = NULL;
nloc = r;
if (n > 0) {
p = arg_list;
do {
mp->param_stack[mp->param_ptr] = (mp_node)mp_sym_sym (p);
incr (mp->param_ptr);
p = mp_link (p);
} while (p != NULL);
mp_flush_node_list (mp, arg_list);
}
@ It's sometimes necessary to put a single argument onto |param_stack|.
The |stack_argument| subroutine does this.
@c
static void mp_stack_argument (MP mp, mp_node p) {
if (mp->param_ptr == mp->max_param_stack) {
incr (mp->max_param_stack);
mp_check_param_size (mp, mp->max_param_stack);
}
mp->param_stack[mp->param_ptr] = p;
incr (mp->param_ptr);
}
@* Conditional processing.
Let's consider now the way \&{if} commands are handled.
Conditions can be inside conditions, and this nesting has a stack
that is independent of other stacks.
Four global variables represent the top of the condition stack:
|cond_ptr| points to pushed-down entries, if~any; |cur_if| tells whether
we are processing \&{if} or \&{elseif}; |if_limit| specifies
the largest code of a |fi_or_else| command that is syntactically legal;
and |if_line| is the line number at which the current conditional began.
If no conditions are currently in progress, the condition stack has the
special state |cond_ptr=NULL|, |if_limit=normal|, |cur_if=0|, |if_line=0|.
Otherwise |cond_ptr| points to a non-symbolic node; the |type|, |name_type|, and
|link| fields of the first word contain |if_limit|, |cur_if|, and
|cond_ptr| at the next level, and the second word contains the
corresponding |if_line|.
@d if_line_field(A) ((mp_if_node)(A))->if_line_field_
@d if_code 1 /* code for \&{if} being evaluated */
@d fi_code 2 /* code for \&{fi} */
@d else_code 3 /* code for \&{else} */
@d else_if_code 4 /* code for \&{elseif} */
@<MPlib internal header stuff@>=
typedef struct mp_if_node_data {
NODE_BODY;
int if_line_field_;
} mp_if_node_data;
typedef struct mp_if_node_data *mp_if_node;
@
@d if_node_size sizeof(struct mp_if_node_data) /* number of words in stack entry for conditionals */
@c
static mp_node mp_get_if_node (MP mp) {
mp_if_node p = (mp_if_node) malloc_node (if_node_size);
mp_type (p) = mp_if_node_type;
return (mp_node) p;
}
@ @<Glob...@>=
mp_node cond_ptr; /* top of the condition stack */
integer if_limit; /* upper bound on |fi_or_else| codes */
quarterword cur_if; /* type of conditional being worked on */
integer if_line; /* line where that conditional began */
@ @<Set init...@>=
mp->cond_ptr = NULL;
mp->if_limit = normal;
mp->cur_if = 0;
mp->if_line = 0;
@ @<Put each...@>=
mp_primitive (mp, "if", mp_if_test, if_code);
@:if_}{\&{if} primitive@>;
mp_primitive (mp, "fi", mp_fi_or_else, fi_code);
mp->frozen_fi = mp_frozen_primitive (mp, "fi", mp_fi_or_else, fi_code);
@:fi_}{\&{fi} primitive@>;
mp_primitive (mp, "else", mp_fi_or_else, else_code);
@:else_}{\&{else} primitive@>;
mp_primitive (mp, "elseif", mp_fi_or_else, else_if_code);
@:else_if_}{\&{elseif} primitive@>
@ @<Cases of |print_cmd_mod|...@>=
case mp_if_test:
case mp_fi_or_else:
switch (m) {
case if_code:
mp_print (mp, "if");
break;
case fi_code:
mp_print (mp, "fi");
break;
case else_code:
mp_print (mp, "else");
break;
default:
mp_print (mp, "elseif");
break;
}
break;
@ Here is a procedure that ignores text until coming to an \&{elseif},
\&{else}, or \&{fi} at level zero of $\&{if}\ldots\&{fi}$
nesting. After it has acted, |cur_mod| will indicate the token that
was found.
\MP's smallest two command codes are |if_test| and |fi_or_else|; this
makes the skipping process a bit simpler.
@c
void mp_pass_text (MP mp) {
integer l = 0;
mp->scanner_status = skipping;
mp->warning_line = mp_true_line (mp);
while (1) {
get_t_next (mp);
if (cur_cmd() <= mp_fi_or_else) {
if (cur_cmd() < mp_fi_or_else) {
incr (l);
} else {
if (l == 0)
break;
if (cur_mod() == fi_code)
decr (l);
}
} else {
@<Decrease the string reference count,
if the current token is a string@>;
}
}
mp->scanner_status = normal;
}
@ @<Decrease the string reference count...@>=
if (cur_cmd() == mp_string_token) {
delete_str_ref (cur_mod_str());
}
@ When we begin to process a new \&{if}, we set |if_limit:=if_code|; then
if \&{elseif} or \&{else} or \&{fi} occurs before the current \&{if}
condition has been evaluated, a colon will be inserted.
A construction like `\.{if fi}' would otherwise get \MP\ confused.
@<Push the condition stack@>=
{
p = mp_get_if_node (mp);
mp_link (p) = mp->cond_ptr;
mp_type (p) = (quarterword) mp->if_limit;
mp_name_type (p) = mp->cur_if;
if_line_field (p) = mp->if_line;
mp->cond_ptr = p;
mp->if_limit = if_code;
mp->if_line = mp_true_line (mp);
mp->cur_if = if_code;
}
@ @<Pop the condition stack@>=
{
mp_node p = mp->cond_ptr;
mp->if_line = if_line_field (p);
mp->cur_if = mp_name_type (p);
mp->if_limit = mp_type (p);
mp->cond_ptr = mp_link (p);
mp_free_node (mp, p, if_node_size);
}
@ Here's a procedure that changes the |if_limit| code corresponding to
a given value of |cond_ptr|.
@c
static void mp_change_if_limit (MP mp, quarterword l, mp_node p) {
mp_node q;
if (p == mp->cond_ptr) {
mp->if_limit = l; /* that's the easy case */
} else {
q = mp->cond_ptr;
while (1) {
if (q == NULL)
mp_confusion (mp, "if");
@:this can't happen if}{\quad if@>;
/* clang: dereference of null pointer */ assert(q);
if (mp_link (q) == p) {
mp_type (q) = l;
return;
}
q = mp_link (q);
}
}
}
@ The user is supposed to put colons into the proper parts of conditional
statements. Therefore, \MP\ has to check for their presence.
@c
static void mp_check_colon (MP mp) {
if (cur_cmd() != mp_colon) {
const char *hlp[] = {
"There should've been a colon after the condition.",
"I shall pretend that one was there.",
NULL };
mp_back_error (mp, "Missing `:' has been inserted", hlp, true);
@.Missing `:'@>;
}
}
@ A condition is started when the |get_x_next| procedure encounters
an |if_test| command; in that case |get_x_next| calls |conditional|,
which is a recursive procedure.
@^recursion@>
@c
void mp_conditional (MP mp) {
mp_node save_cond_ptr; /* |cond_ptr| corresponding to this conditional */
int new_if_limit; /* future value of |if_limit| */
mp_node p; /* temporary register */
@<Push the condition stack@>;
save_cond_ptr = mp->cond_ptr;
RESWITCH:
mp_get_boolean (mp);
new_if_limit = else_if_code;
if (number_greater (internal_value (mp_tracing_commands), unity_t)) {
@<Display the boolean value of |cur_exp|@>;
}
FOUND:
mp_check_colon (mp);
if (cur_exp_value_boolean () == mp_true_code) {
mp_change_if_limit (mp, (quarterword) new_if_limit, save_cond_ptr);
return; /* wait for \&{elseif}, \&{else}, or \&{fi} */
};
@<Skip to \&{elseif} or \&{else} or \&{fi}, then |goto done|@>;
DONE:
mp->cur_if = (quarterword) cur_mod();
mp->if_line = mp_true_line (mp);
if (cur_mod() == fi_code) {
@<Pop the condition stack@>
} else if (cur_mod() == else_if_code) {
goto RESWITCH;
} else {
set_cur_exp_value_boolean (mp_true_code);
new_if_limit = fi_code;
mp_get_x_next (mp);
goto FOUND;
}
}
@ In a construction like `\&{if} \&{if} \&{true}: $0=1$: \\{foo}
\&{else}: \\{bar} \&{fi}', the first \&{else}
that we come to after learning that the \&{if} is false is not the
\&{else} we're looking for. Hence the following curious logic is needed.
@<Skip to \&{elseif}...@>=
while (1) {
mp_pass_text (mp);
if (mp->cond_ptr == save_cond_ptr)
goto DONE;
else if (cur_mod() == fi_code)
@<Pop the condition stack@>;
}
@ @<Display the boolean value...@>=
{
mp_begin_diagnostic (mp);
if (cur_exp_value_boolean () == mp_true_code)
mp_print (mp, "{true}");
else
mp_print (mp, "{false}");
mp_end_diagnostic (mp, false);
}
@ The processing of conditionals is complete except for the following
code, which is actually part of |get_x_next|. It comes into play when
\&{elseif}, \&{else}, or \&{fi} is scanned.
@<Terminate the current conditional and skip to \&{fi}@>=
if (cur_mod() > mp->if_limit) {
if (mp->if_limit == if_code) { /* condition not yet evaluated */
const char *hlp[] = { "Something was missing here", NULL };
mp_back_input (mp);
set_cur_sym(mp->frozen_colon);
mp_ins_error (mp, "Missing `:' has been inserted", hlp, true);
@.Missing `:'@>;
} else {
const char *hlp[] = {"I'm ignoring this; it doesn't match any if.", NULL};
if (cur_mod() == fi_code) {
mp_error(mp, "Extra fi", hlp, true);
@.Extra fi@>;
} else if (cur_mod() == else_code) {
mp_error(mp, "Extra else", hlp, true);
@.Extra else@>
} else {
mp_error(mp, "Extra elseif", hlp, true);
@.Extra elseif@>
}
}
} else {
while (cur_mod() != fi_code)
mp_pass_text (mp); /* skip to \&{fi} */
@<Pop the condition stack@>;
}
@* Iterations.
To bring our treatment of |get_x_next| to a close, we need to consider what
\MP\ does when it sees \&{for}, \&{forsuffixes}, and \&{forever}.
There's a global variable |loop_ptr| that keeps track of the \&{for} loops
that are currently active. If |loop_ptr=NULL|, no loops are in progress;
otherwise |loop_ptr.info| points to the iterative text of the current
(innermost) loop, and |loop_ptr.link| points to the data for any other
loops that enclose the current one.
A loop-control node also has two other fields, called |type| and
|list|, whose contents depend on the type of loop:
\yskip\indent|loop_ptr.type=NULL| means that the link of |loop_ptr.list|
points to a list of symbolic nodes whose |info| fields point to the
remaining argument values of a suffix list and expression list.
In this case, an extra field |loop_ptr.start_list| is needed to
make sure that |resume_operation| skips ahead.
\yskip\indent|loop_ptr.type=MP_VOID| means that the current loop is
`\&{forever}'.
\yskip\indent|loop_ptr.type=PROGRESSION_FLAG| means that
|loop_ptr.value|, |loop_ptr.step_size|, and |loop_ptr.final_value|
contain the data for an arithmetic progression.
\yskip\indent|loop_ptr.type=p>PROGRESSION_FLAG| means that |p| points to an edge
header and |loop_ptr.list| points into the graphical object list for
that edge header.
@d PROGRESSION_FLAG (mp_node)(2) /* |NULL+2| */
/* |loop_type| value when |loop_list| points to a progression node */
@<Types...@>=
typedef struct mp_loop_data {
mp_sym var ; /* the var of the loop */
mp_node info; /* iterative text of this loop */
mp_node type; /* the special type of this loop, or a pointer into
mem */
mp_node list; /* the remaining list elements */
mp_node list_start; /* head fo the list of elements */
mp_number old_value; /* previous value of current arithmetic value */
mp_number value; /* current arithmetic value */
mp_number step_size; /* arithmetic step size */
mp_number final_value; /* end arithmetic value */
struct mp_loop_data *link; /* the enclosing loop, if any */
} mp_loop_data;
@ @<Glob...@>=
mp_loop_data *loop_ptr; /* top of the loop-control-node stack */
@ @<Set init...@>=
mp->loop_ptr = NULL;
@ If the expressions that define an arithmetic progression in a
\&{for} loop don't have known numeric values, the |bad_for| subroutine
screams at the user.
@c
static void mp_bad_for (MP mp, const char *s) {
char msg[256];
mp_value new_expr;
const char *hlp[] = {"When you say `for x=a step b until c',",
"the initial value `a' and the step size `b'",
"and the final value `c' must have known numeric values.",
"I'm zeroing this one. Proceed, with fingers crossed.",
NULL };
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
mp_disp_err (mp, NULL);
/* show the bad expression above the message */
mp_snprintf(msg, 256, "Improper %s has been replaced by 0", s);
@.Improper...replaced by 0@>;
mp_back_error (mp, msg, hlp, true);
mp_get_x_next (mp);
mp_flush_cur_exp (mp, new_expr);
}
@ Here's what \MP\ does when \&{for}, \&{forsuffixes}, or \&{forever}
has just been scanned. (This code requires slight familiarity with
expression-parsing routines that we have not yet discussed; but it
seems to belong in the present part of the program, even though the
original author didn't write it until later. The reader may wish to
come back to it.)
@c
void mp_begin_iteration (MP mp) {
halfword m; /* |start_for| (\&{for}) or |start_forsuffixes|
(\&{forsuffixes}) */
mp_sym n; /* hash address of the current symbol */
mp_loop_data *s; /* the new loop-control node */
mp_subst_list_item *p = NULL; /* substitution list for |scan_toks|
*/
mp_node q; /* link manipulation register */
m = cur_mod();
n = cur_sym();
s = xmalloc (1, sizeof (mp_loop_data));
s->type = s->list = s->info = s->list_start = NULL;
s->link = NULL; s->var = NULL;
new_number (s->value);new_number (s->old_value);
new_number (s->step_size);
new_number (s->final_value);
if (m == start_forever) {
s->type = MP_VOID;
p = NULL;
mp_get_x_next (mp);
} else {
mp_get_symbol (mp);
p = xmalloc (1, sizeof (mp_subst_list_item));
p->link = NULL;
p->info = cur_sym();
s->var = cur_sym();
p->info_mod = cur_sym_mod();
p->value_data = 0;
if (m == start_for) {
p->value_mod = mp_expr_sym;
} else { /* |start_forsuffixes| */
p->value_mod = mp_suffix_sym;
}
mp_get_x_next (mp);
if (cur_cmd() == mp_within_token) {
@<Set up a picture iteration@>;
} else {
@<Check for the assignment in a loop header@>;
@<Scan the values to be used in the loop@>;
}
}
@<Check for the presence of a colon@>;
@<Scan the loop text and put it on the loop control stack@>;
mp_resume_iteration (mp);
}
@ @<Check for the assignment in a loop header@>=
if ((cur_cmd() != mp_equals) && (cur_cmd() != mp_assignment)) {
const char *hlp[] = {
"The next thing in this loop should have been `=' or `:='.",
"But don't worry; I'll pretend that an equals sign",
"was present, and I'll look for the values next.",
NULL };
mp_back_error (mp, "Missing `=' has been inserted", hlp, true);
@.Missing `='@>;
}
@ @<Check for the presence of a colon@>=
if (cur_cmd() != mp_colon) {
const char *hlp[] = {
"The next thing in this loop should have been a `:'.",
"So I'll pretend that a colon was present;",
"everything from here to `endfor' will be iterated.",
NULL };
mp_back_error (mp, "Missing `:' has been inserted", hlp, true);
@.Missing `:'@>;
}
@ We append a special |mp->frozen_repeat_loop| token in place of the
`\&{endfor}' at the end of the loop. This will come through \MP's
scanner at the proper time to cause the loop to be repeated.
(If the user tries some shenanigan like `\&{for} $\ldots$ \&{let}
\&{endfor}', he will be foiled by the |get_symbol| routine, which
keeps frozen tokens unchanged. Furthermore the
|mp->frozen_repeat_loop| is an \&{outer} token, so it won't be lost
accidentally.)
@ @<Scan the loop text...@>=
q = mp_get_symbolic_node (mp);
set_mp_sym_sym (q, mp->frozen_repeat_loop);
mp->scanner_status = loop_defining;
mp->warning_info = n;
s->info = mp_scan_toks (mp, mp_iteration, p, q, 0);
mp->scanner_status = normal;
s->link = mp->loop_ptr;
mp->loop_ptr = s
@ @<Initialize table...@>=
mp->frozen_repeat_loop =
mp_frozen_primitive (mp, " ENDFOR", mp_repeat_loop + mp_outer_tag, 0);
@ The loop text is inserted into \MP's scanning apparatus by the
|resume_iteration| routine.
@c
void mp_resume_iteration (MP mp) {
mp_node p, q; /* link registers */
p = mp->loop_ptr->type;
if (p == PROGRESSION_FLAG) {
set_cur_exp_value_number (mp->loop_ptr->value);
if (@<The arithmetic progression has ended@>) {
mp_stop_iteration (mp);
return;
}
mp->cur_exp.type = mp_known;
q = mp_stash_cur_exp (mp); /* make |q| an \&{expr} argument */
number_clone (mp->loop_ptr->old_value, cur_exp_value_number ());
set_number_from_addition (mp->loop_ptr->value, cur_exp_value_number (), mp->loop_ptr->step_size);
/* set |value(p)| for the next iteration */
/* detect numeric overflow */
if (number_positive(mp->loop_ptr->step_size) &&
number_less(mp->loop_ptr->value, cur_exp_value_number ())) {
if (number_positive(mp->loop_ptr->final_value)) {
number_clone (mp->loop_ptr->value, mp->loop_ptr->final_value);
number_add_scaled (mp->loop_ptr->final_value, -1);
} else {
number_clone (mp->loop_ptr->value, mp->loop_ptr->final_value);
number_add_scaled (mp->loop_ptr->value, 1);
}
} else if (number_negative(mp->loop_ptr->step_size) &&
number_greater (mp->loop_ptr->value, cur_exp_value_number ())) {
if (number_negative (mp->loop_ptr->final_value)) {
number_clone (mp->loop_ptr->value, mp->loop_ptr->final_value);
number_add_scaled (mp->loop_ptr->final_value, 1);
} else {
number_clone (mp->loop_ptr->value, mp->loop_ptr->final_value);
number_add_scaled (mp->loop_ptr->value, -1);
}
}
} else if (p == NULL) {
p = mp->loop_ptr->list;
if (p != NULL && p == mp->loop_ptr->list_start) {
q = p;
p = mp_link (p);
mp_free_symbolic_node (mp, q);
mp->loop_ptr->list = p;
}
if (p == NULL) {
mp_stop_iteration (mp);
return;
}
mp->loop_ptr->list = mp_link (p);
q = (mp_node)mp_sym_sym (p);
if (q)
number_clone (mp->loop_ptr->old_value, q->data.n);
mp_free_symbolic_node (mp, p);
} else if (p == MP_VOID) {
mp_begin_token_list (mp, mp->loop_ptr->info, (quarterword) forever_text);
return;
} else {
@<Make |q| a capsule containing the next picture component from
|loop_list(loop_ptr)| or |goto not_found|@>;
}
mp_begin_token_list (mp, mp->loop_ptr->info, (quarterword) loop_text);
mp_stack_argument (mp, q);
if (number_greater (internal_value (mp_tracing_commands), unity_t)) {
@<Trace the start of a loop@>;
}
return;
NOT_FOUND:
mp_stop_iteration (mp);
}
@ @<The arithmetic progression has ended@>=
(number_positive(mp->loop_ptr->step_size) && number_greater(cur_exp_value_number (), mp->loop_ptr->final_value))
||
(number_negative(mp->loop_ptr->step_size) && number_less(cur_exp_value_number (), mp->loop_ptr->final_value))
@ @<Trace the start of a loop@>=
{
mp_begin_diagnostic (mp);
mp_print_nl (mp, "{loop value=");
@.loop value=n@>;
if ((q != NULL) && (mp_link (q) == MP_VOID))
mp_print_exp (mp, q, 1);
else
mp_show_token_list (mp, q, NULL, 50, 0);
mp_print_char (mp, xord ('}'));
mp_end_diagnostic (mp, false);
}
@ @<Make |q| a capsule containing the next picture component
from...@>=
{
q = mp->loop_ptr->list;
if (q == NULL)
goto NOT_FOUND;
if ( ! is_start_or_stop(q) )
q=mp_link(q);
else if ( ! is_stop(q) )
q=mp_skip_1component(mp, q);
else
goto NOT_FOUND;
set_cur_exp_node ((mp_node)mp_copy_objects (mp, mp->loop_ptr->list, q));
mp_init_bbox (mp, (mp_edge_header_node)cur_exp_node ());
mp->cur_exp.type = mp_picture_type;
mp->loop_ptr->list = q;
q = mp_stash_cur_exp (mp);
}
@ A level of loop control disappears when |resume_iteration| has
decided not to resume, or when an \&{exitif} construction has removed
the loop text from the input stack.
@c
void mp_stop_iteration (MP mp) {
mp_node p, q; /* the usual */
mp_loop_data *tmp; /* for free() */
p = mp->loop_ptr->type;
if (p == PROGRESSION_FLAG) {
mp_free_symbolic_node (mp, mp->loop_ptr->list);
} else if (p == NULL) {
q = mp->loop_ptr->list;
while (q != NULL) {
p = (mp_node)mp_sym_sym (q);
if (p != NULL) {
if (mp_link (p) == MP_VOID) { /* it's an \&{expr} parameter */
mp_recycle_value (mp, p);
mp_free_value_node (mp, p);
} else {
mp_flush_token_list (mp, p); /* it's a \&{suffix} or \&{text}
parameter */
}
}
p = q;
q = mp_link (q);
mp_free_symbolic_node (mp, p);
}
} else if (p > PROGRESSION_FLAG) {
delete_edge_ref (p);
}
tmp = mp->loop_ptr;
mp->loop_ptr = tmp->link;
mp_flush_token_list (mp, tmp->info);
free_number (tmp->value);
free_number (tmp->step_size);
free_number (tmp->final_value);
xfree (tmp);
}
@ Now that we know all about loop control, we can finish up the
missing portion of |begin_iteration| and we'll be done.
The following code is performed after the `\.=' has been scanned in a
\&{for} construction (if |m=start_for|) or a \&{forsuffixes}
construction (if |m=start_forsuffixes|).
@<Scan the values to be used in the loop@>=
s->type = NULL;
s->list = mp_get_symbolic_node (mp);
s->list_start = s->list;
q = s->list;
do {
mp_get_x_next (mp);
if (m != start_for) {
mp_scan_suffix (mp);
} else {
if (cur_cmd() >= mp_colon)
if (cur_cmd() <= mp_comma)
goto CONTINUE;
mp_scan_expression (mp);
if (cur_cmd() == mp_step_token)
if (q == s->list) {
@<Prepare for step-until construction and |break|@>;
}
set_cur_exp_node (mp_stash_cur_exp (mp));
}
mp_link (q) = mp_get_symbolic_node (mp);
q = mp_link (q);
set_mp_sym_sym (q, mp->cur_exp.data.node);
if (m == start_for)
mp_name_type (q) = mp_expr_sym;
else if (m == start_forsuffixes)
mp_name_type (q) = mp_suffix_sym;
mp->cur_exp.type = mp_vacuous;
CONTINUE:
;
} while (cur_cmd() == mp_comma)
@ @<Prepare for step-until construction and |break|@>=
{
if (mp->cur_exp.type != mp_known)
mp_bad_for (mp, "initial value");
number_clone (s->value, cur_exp_value_number ());
number_clone (s->old_value, cur_exp_value_number ());
mp_get_x_next (mp);
mp_scan_expression (mp);
if (mp->cur_exp.type != mp_known)
mp_bad_for (mp, "step size");
number_clone (s->step_size, cur_exp_value_number ());
if (cur_cmd() != mp_until_token) {
const char *hlp[] = {
"I assume you meant to say `until' after `step'.",
"So I'll look for the final value and colon next.",
NULL };
mp_back_error (mp, "Missing `until' has been inserted", hlp, true);
@.Missing `until'@>;
}
mp_get_x_next (mp);
mp_scan_expression (mp);
if (mp->cur_exp.type != mp_known)
mp_bad_for (mp, "final value");
number_clone (s->final_value, cur_exp_value_number ());
s->type = PROGRESSION_FLAG;
break;
}
@ The last case is when we have just seen ``\&{within}'', and we need to
parse a picture expression and prepare to iterate over it.
@<Set up a picture iteration@>=
{
mp_get_x_next (mp);
mp_scan_expression (mp);
@<Make sure the current expression is a known picture@>;
s->type = mp->cur_exp.data.node;
mp->cur_exp.type = mp_vacuous;
q = mp_link (edge_list (mp->cur_exp.data.node));
if (q != NULL)
if (is_start_or_stop (q))
if (mp_skip_1component (mp, q) == NULL)
q = mp_link (q);
s->list = q;
}
@ @<Make sure the current expression is a known picture@>=
if (mp->cur_exp.type != mp_picture_type) {
mp_value new_expr;
const char *hlp[] = { "When you say `for x in p', p must be a known picture.", NULL };
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
new_expr.data.node = (mp_node)mp_get_edge_header_node (mp);
mp_disp_err (mp, NULL);
mp_back_error (mp,"Improper iteration spec has been replaced by nullpicture", hlp, true);
mp_get_x_next (mp);
mp_flush_cur_exp (mp, new_expr);
mp_init_edges (mp, (mp_edge_header_node)mp->cur_exp.data.node);
mp->cur_exp.type = mp_picture_type;
}
@* File names.
It's time now to fret about file names. Besides the fact that different
operating systems treat files in different ways, we must cope with the
fact that completely different naming conventions are used by different
groups of people. The following programs show what is required for one
particular operating system; similar routines for other systems are not
difficult to devise.
@^system dependencies@>
\MP\ assumes that a file name has three parts: the name proper; its
``extension''; and a ``file area'' where it is found in an external file
system. The extension of an input file is assumed to be
`\.{.mp}' unless otherwise specified; it is `\.{.log}' on the
transcript file that records each run of \MP; it is `\.{.tfm}' on the font
metric files that describe characters in any fonts created by \MP; it is
`\.{.ps}' or `.{\it nnn}' for some number {\it nnn} on the \ps\ output files.
The file area can be arbitrary on input files, but files are usually
output to the user's current area. If an input file cannot be
found on the specified area, \MP\ will look for it on a special system
area; this special area is intended for commonly used input files.
Simple uses of \MP\ refer only to file names that have no explicit
extension or area. For example, a person usually says `\.{input} \.{cmr10}'
instead of `\.{input} \.{cmr10.new}'. Simple file
names are best, because they make the \MP\ source files portable;
whenever a file name consists entirely of letters and digits, it should be
treated in the same way by all implementations of \MP. However, users
need the ability to refer to other files in their environment, especially
when responding to error messages concerning unopenable files; therefore
we want to let them use the syntax that appears in their favorite
operating system.
@ \MP\ uses the same conventions that have proved to be satisfactory for
\TeX\ and \MF. In order to isolate the system-dependent aspects of file names,
@^system dependencies@>
the system-independent parts of \MP\ are expressed in terms
of three system-dependent
procedures called |begin_name|, |more_name|, and |end_name|. In
essence, if the user-specified characters of the file name are $c_1\ldots c_n$,
the system-independent driver program does the operations
$$|begin_name|;\,|more_name|(c_1);\,\ldots\,;\,|more_name|(c_n);
\,|end_name|.$$
These three procedures communicate with each other via global variables.
Afterwards the file name will appear in the string pool as three strings
called |cur_name|\penalty10000\hskip-.05em,
|cur_area|, and |cur_ext|; the latter two are NULL (i.e.,
|""|), unless they were explicitly specified by the user.
Actually the situation is slightly more complicated, because \MP\ needs
to know when the file name ends. The |more_name| routine is a function
(with side effects) that returns |true| on the calls |more_name|$(c_1)$,
\dots, |more_name|$(c_{n-1})$. The final call |more_name|$(c_n)$
returns |false|; or, it returns |true| and $c_n$ is the last character
on the current input line. In other words,
|more_name| is supposed to return |true| unless it is sure that the
file name has been completely scanned; and |end_name| is supposed to be able
to finish the assembly of |cur_name|, |cur_area|, and |cur_ext| regardless of
whether $|more_name|(c_n)$ returned |true| or |false|.
@<Glob...@>=
char *cur_name; /* name of file just scanned */
char *cur_area; /* file area just scanned, or \.{""} */
char *cur_ext; /* file extension just scanned, or \.{""} */
@ It is easier to maintain reference counts if we assign initial values.
@<Set init...@>=
mp->cur_name = xstrdup ("");
mp->cur_area = xstrdup ("");
mp->cur_ext = xstrdup ("");
@ @<Dealloc variables@>=
xfree (mp->cur_area);
xfree (mp->cur_name);
xfree (mp->cur_ext);
@ The file names we shall deal with for illustrative purposes have the
following structure: If the name contains `\.>' or `\.:', the file area
consists of all characters up to and including the final such character;
otherwise the file area is null. If the remaining file name contains
`\..', the file extension consists of all such characters from the first
remaining `\..' to the end, otherwise the file extension is null.
@^system dependencies@>
We can scan such file names easily by using two global variables that keep track
of the occurrences of area and extension delimiters.
@<Glob...@>=
integer area_delimiter;
/* most recent `\.>' or `\.:' relative to |str_start[str_ptr]| */
integer ext_delimiter; /* the relevant `\..', if any */
boolean quoted_filename; /* whether the filename is wrapped in " markers */
@ Here now is the first of the system-dependent routines for file name scanning.
@^system dependencies@>
@<Declarations@>=
static void mp_begin_name (MP mp);
static boolean mp_more_name (MP mp, ASCII_code c);
static void mp_end_name (MP mp);
@ @c
void mp_begin_name (MP mp) {
xfree (mp->cur_name);
xfree (mp->cur_area);
xfree (mp->cur_ext);
mp->area_delimiter = -1;
mp->ext_delimiter = -1;
mp->quoted_filename = false;
}
@ And here's the second.
@^system dependencies@>
@c
#ifndef IS_DIR_SEP
#define IS_DIR_SEP(c) (c=='/' || c=='\\')
#endif
boolean mp_more_name (MP mp, ASCII_code c) {
if (c == '"') {
mp->quoted_filename = !mp->quoted_filename;
} else if ((c == ' ' || c == '\t') && (mp->quoted_filename == false)) {
return false;
} else {
if (IS_DIR_SEP (c)) {
mp->area_delimiter = (integer) mp->cur_length;
mp->ext_delimiter = -1;
} else if (c == '.') {
mp->ext_delimiter = (integer) mp->cur_length;
}
append_char (c); /* contribute |c| to the current string */
}
return true;
}
@ The third.
@^system dependencies@>
@d copy_pool_segment(A,B,C) {
A = xmalloc(C+1,sizeof(char));
(void)memcpy(A,(char *)(mp->cur_string+B),C);
A[C] = 0;}
@c
void mp_end_name (MP mp) {
size_t s = 0; /* length of area, name, and extension */
size_t len;
/* "my/w.mp" */
if (mp->area_delimiter < 0) {
mp->cur_area = xstrdup ("");
} else {
len = (size_t) mp->area_delimiter - s + 1;
copy_pool_segment (mp->cur_area, s, len);
s += len;
}
if (mp->ext_delimiter < 0) {
mp->cur_ext = xstrdup ("");
len = (unsigned) (mp->cur_length - s);
} else {
copy_pool_segment (mp->cur_ext, mp->ext_delimiter,
(mp->cur_length - (size_t) mp->ext_delimiter));
len = (size_t) mp->ext_delimiter - s;
}
copy_pool_segment (mp->cur_name, s, len);
mp_reset_cur_string (mp);
}
@ Conversely, here is a routine that takes three strings and prints a file
name that might have produced them. (The routine is system dependent, because
some operating systems put the file area last instead of first.)
@^system dependencies@>
@<Basic printing...@>=
static void mp_print_file_name (MP mp, char *n, char *a, char *e) {
boolean must_quote = false;
if (((a != NULL) && (strchr (a, ' ') != NULL)) ||
((n != NULL) && (strchr (n, ' ') != NULL)) ||
((e != NULL) && (strchr (e, ' ') != NULL)))
must_quote = true;
if (must_quote)
mp_print_char (mp, (ASCII_code) '"');
mp_print (mp, a);
mp_print (mp, n);
mp_print (mp, e);
if (must_quote)
mp_print_char (mp, (ASCII_code) '"');
}
@ Another system-dependent routine is needed to convert three internal
\MP\ strings
to the |name_of_file| value that is used to open files. The present code
allows both lowercase and uppercase letters in the file name.
@^system dependencies@>
@d append_to_name(A) { mp->name_of_file[k++]=(char)xchr(xord((ASCII_code)(A))); }
@ @c
void mp_pack_file_name (MP mp, const char *n, const char *a, const char *e) {
integer k; /* number of positions filled in |name_of_file| */
const char *j; /* a character index */
size_t slen;
k = 0;
assert (n != NULL);
xfree (mp->name_of_file);
slen = strlen (n) + 1;
if (a != NULL)
slen += strlen (a);
if (e != NULL)
slen += strlen (e);
mp->name_of_file = xmalloc (slen, 1);
if (a != NULL) {
for (j = a; *j != '\0'; j++) {
append_to_name (*j);
}
}
for (j = n; *j != '\0'; j++) {
append_to_name (*j);
}
if (e != NULL) {
for (j = e; *j != '\0'; j++) {
append_to_name (*j);
}
}
mp->name_of_file[k] = 0;
}
@ @<Internal library declarations@>=
void mp_pack_file_name (MP mp, const char *n, const char *a, const char *e);
@ @<Option variables@>=
char *mem_name; /* for commandline */
@ Stripping a |.mem| extension here is for backward compatibility.
@<Find and load preload file, if required@>=
if (!opt->ini_version) {
mp->mem_name = xstrdup (opt->mem_name);
if (mp->mem_name) {
size_t l = strlen (mp->mem_name);
if (l > 4) {
char *test = strstr (mp->mem_name, ".mem");
if (test == mp->mem_name + l - 4) {
*test = 0;
}
}
}
if (mp->mem_name != NULL) {
if (!mp_open_mem_file (mp)) {
mp->history = mp_fatal_error_stop;
mp_jump_out (mp);
}
}
}
@ @<Dealloc variables@>=
xfree (mp->mem_name);
@ This part of the program becomes active when a ``virgin'' \MP\ is
trying to get going, just after the preliminary initialization.
The buffer contains the first line of input in |buffer[loc..(last-1)]|,
where |loc<last| and |buffer[loc]<>""|.
@<Declarations@>=
static boolean mp_open_mem_name (MP mp);
static boolean mp_open_mem_file (MP mp);
@ @c
boolean mp_open_mem_name (MP mp) {
if (mp->mem_name != NULL) {
size_t l = strlen (mp->mem_name);
char *s = xstrdup (mp->mem_name);
if (l > 4) {
char *test = strstr (s, ".mp");
if (test == NULL || test != s + l - 4) {
s = xrealloc (s, l + 5, 1);
strcat (s, ".mp");
}
} else {
s = xrealloc (s, l + 5, 1);
strcat (s, ".mp");
}
s = (mp->find_file) (mp, s, "r", mp_filetype_program);
xfree(mp->name_of_file);
if (s == NULL)
return false;
mp->name_of_file = xstrdup(s);
mp->mem_file = (mp->open_file) (mp, s, "r", mp_filetype_program);
free (s);
if (mp->mem_file)
return true;
}
return false;
}
boolean mp_open_mem_file (MP mp) {
if (mp->mem_file != NULL)
return true;
if (mp_open_mem_name (mp))
return true;
if (mp_xstrcmp (mp->mem_name, "plain")) {
wake_up_terminal();
wterm ("Sorry, I can\'t find the '");
wterm (mp->mem_name);
wterm ("' preload file; will try 'plain'.");
wterm_cr;
@.Sorry, I can't find...@>;
update_terminal();
/* now pull out all the stops: try for the system \.{plain} file */
xfree (mp->mem_name);
mp->mem_name = xstrdup ("plain");
if (mp_open_mem_name (mp))
return true;
}
wake_up_terminal();
wterm_ln ("I can't find the 'plain' preload file!\n");
@.I can't find PLAIN...@>
@.plain@>;
return false;
}
@ Operating systems often make it possible to determine the exact name (and
possible version number) of a file that has been opened. The following routine,
which simply makes a \MP\ string from the value of |name_of_file|, should
ideally be changed to deduce the full name of file~|f|, which is the file
most recently opened, if it is possible to do this.
@^system dependencies@>
@ @c
static mp_string mp_make_name_string (MP mp) {
int k; /* index into |name_of_file| */
int name_length = (int) strlen (mp->name_of_file);
str_room (name_length);
for (k = 0; k < name_length; k++) {
append_char (xord ((ASCII_code) mp->name_of_file[k]));
}
return mp_make_string (mp);
}
@ Now let's consider the ``driver''
routines by which \MP\ deals with file names
in a system-independent manner. First comes a procedure that looks for a
file name in the input by taking the information from the input buffer.
(We can't use |get_next|, because the conversion to tokens would
destroy necessary information.)
This procedure doesn't allow semicolons or percent signs to be part of
file names, because of other conventions of \MP.
{\sl The {\logos METAFONT\/}book} doesn't
use semicolons or percents immediately after file names, but some users
no doubt will find it natural to do so; therefore system-dependent
changes to allow such characters in file names should probably
be made with reluctance, and only when an entire file name that
includes special characters is ``quoted'' somehow.
@^system dependencies@>
@c
static void mp_scan_file_name (MP mp) {
mp_begin_name (mp);
while (mp->buffer[loc] == ' ')
incr (loc);
while (1) {
if ((mp->buffer[loc] == ';') || (mp->buffer[loc] == '%'))
break;
if (!mp_more_name (mp, mp->buffer[loc]))
break;
incr (loc);
}
mp_end_name (mp);
}
@ Here is another version that takes its input from a string.
@<Declare subroutines for parsing file names@>=
void mp_str_scan_file (MP mp, mp_string s);
@ @c
void mp_str_scan_file (MP mp, mp_string s) {
size_t p, q; /* current position and stopping point */
mp_begin_name (mp);
p = 0;
q = s->len;
while (p < q) {
if (!mp_more_name (mp, *(s->str + p)))
break;
incr (p);
}
mp_end_name (mp);
}
@ And one that reads from a |char*|.
@<Declare subroutines for parsing file names@>=
extern void mp_ptr_scan_file (MP mp, char *s);
@ @c
void mp_ptr_scan_file (MP mp, char *s) {
char *p, *q; /* current position and stopping point */
mp_begin_name (mp);
p = s;
q = p + strlen (s);
while (p < q) {
if (!mp_more_name (mp, (ASCII_code) (*p)))
break;
p++;
}
mp_end_name (mp);
}
@ The option variable |job_name| contains the file name that was first
\&{input} by the user. This name is used to initialize the |job_name| global
as well as the |mp_job_name| internal, and is extended by `\.{.log}' and
`\.{ps}' and `\.{.mem}' and `\.{.tfm}' in order to make the names of \MP's
output files.
@<Glob...@>=
boolean log_opened; /* has the transcript file been opened? */
char *log_name; /* full name of the log file */
@ @<Option variables@>=
char *job_name; /* principal file name */
@ Initially |job_name=NULL|; it becomes nonzero as soon as the true name is known.
We have |job_name=NULL| if and only if the `\.{log}' file has not been opened,
except of course for a short time just after |job_name| has become nonzero.
@<Allocate or ...@>=
mp->job_name = mp_xstrdup (mp, opt->job_name);
/*|
if (mp->job_name != NULL) {
char *s = mp->job_name + strlen (mp->job_name);
while (s > mp->job_name) {
if (*s == '.') {
*s = '\0';
}
s--;
}
}
|*/
if (opt->noninteractive) {
if (mp->job_name == NULL)
mp->job_name = mp_xstrdup (mp, mp->mem_name);
}
mp->log_opened = false;
@ Cannot do this earlier because at the |<Allocate or ...>|, the string
pool is not yet initialized.
@<Fix up |mp->internal[mp_job_name]|@>=
if (mp->job_name != NULL) {
if (internal_string (mp_job_name) != 0)
delete_str_ref (internal_string (mp_job_name));
set_internal_string (mp_job_name, mp_rts (mp, mp->job_name));
}
@ @<Dealloc variables@>=
xfree (mp->job_name);
@ Here is a routine that manufactures the output file names, assuming that
|job_name<>0|. It ignores and changes the current settings of |cur_area|
and |cur_ext|.
@d pack_cur_name mp_pack_file_name(mp, mp->cur_name,mp->cur_area,mp->cur_ext)
@<Internal library ...@>=
void mp_pack_job_name (MP mp, const char *s);
@ @c
void mp_pack_job_name (MP mp, const char *s) { /* |s = ".log"|, |".mem"|, |".ps"|, or .\\{nnn} */
xfree (mp->cur_name);
mp->cur_name = xstrdup (mp->job_name);
xfree (mp->cur_area);
mp->cur_area = xstrdup ("");
xfree (mp->cur_ext);
mp->cur_ext = xstrdup (s);
pack_cur_name;
}
@ If some trouble arises when \MP\ tries to open a file, the following
routine calls upon the user to supply another file name. Parameter~|s|
is used in the error message to identify the type of file; parameter~|e|
is the default extension if none is given. Upon exit from the routine,
variables |cur_name|, |cur_area|, |cur_ext|, and |name_of_file| are
ready for another attempt at file opening.
@<Internal library ...@>=
void mp_prompt_file_name (MP mp, const char *s, const char *e);
@ @c
void mp_prompt_file_name (MP mp, const char *s, const char *e) {
size_t k; /* index into |buffer| */
char *saved_cur_name;
if (mp->interaction == mp_scroll_mode)
wake_up_terminal();
if (strcmp (s, "input file name") == 0) {
mp_print_err (mp, "I can\'t open file `");
@.I can't find file x@>
} else {
mp_print_err (mp, "I can\'t write on file `");
@.I can't write on file x@>
}
if (strcmp (s, "file name for output") == 0) {
mp_print (mp, mp->name_of_file);
} else {
mp_print_file_name (mp, mp->cur_name, mp->cur_area, mp->cur_ext);
}
mp_print (mp, "'.");
if (strcmp (e, "") == 0)
mp_show_context (mp);
mp_print_nl (mp, "Please type another ");
mp_print (mp, s);
@.Please type...@>;
if (mp->noninteractive || mp->interaction < mp_scroll_mode)
mp_fatal_error (mp, "*** (job aborted, file error in nonstop mode)");
@.job aborted, file error...@>;
saved_cur_name = xstrdup (mp->cur_name);
clear_terminal();
prompt_input (": ");
@<Scan file name in the buffer@>;
if (strcmp (mp->cur_ext, "") == 0)
mp->cur_ext = xstrdup (e);
if (strlen (mp->cur_name) == 0) {
mp->cur_name = saved_cur_name;
} else {
xfree (saved_cur_name);
}
pack_cur_name;
}
@ @<Scan file name in the buffer@>=
{
mp_begin_name (mp);
k = mp->first;
while ((mp->buffer[k] == ' ') && (k < mp->last))
incr (k);
while (1) {
if (k == mp->last)
break;
if (!mp_more_name (mp, mp->buffer[k]))
break;
incr (k);
}
mp_end_name (mp);
}
@ The |open_log_file| routine is used to open the transcript file and to help
it catch up to what has previously been printed on the terminal.
@c
void mp_open_log_file (MP mp) {
unsigned old_setting; /* previous |selector| setting */
int k; /* index into |months| and |buffer| */
int l; /* end of first input line */
integer m; /* the current month */
const char *months = "JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC";
/* abbreviations of month names */
if (mp->log_opened)
return;
old_setting = mp->selector;
if (mp->job_name == NULL) {
mp->job_name = xstrdup ("mpout");
@<Fix up |mp->internal[mp_job_name]|@>;
}
mp_pack_job_name (mp, ".log");
while (!mp_open_out (mp, &mp->log_file, mp_filetype_log)) {
@<Try to get a different log file name@>;
}
mp->log_name = xstrdup (mp->name_of_file);
mp->selector = log_only;
mp->log_opened = true;
@<Print the banner line, including the date and time@>;
mp->input_stack[mp->input_ptr] = mp->cur_input;
/* make sure bottom level is in memory */
if (!mp->noninteractive) {
mp_print_nl (mp, "**");
@.**@>;
l = mp->input_stack[0].limit_field - 1; /* last position of first line */
for (k = 0; k <= l; k++)
mp_print_char (mp, mp->buffer[k]);
mp_print_ln (mp); /* now the transcript file contains the first line of input */
}
mp->selector = old_setting + 2; /* |log_only| or |term_and_log| */
}
@ @<Dealloc variables@>=
xfree (mp->log_name);
@ Sometimes |open_log_file| is called at awkward moments when \MP\ is
unable to print error messages or even to |show_context|.
The |prompt_file_name| routine can result in a |fatal_error|, but the |error|
routine will not be invoked because |log_opened| will be false.
The normal idea of |mp_batch_mode| is that nothing at all should be written
on the terminal. However, in the unusual case that
no log file could be opened, we make an exception and allow
an explanatory message to be seen.
Incidentally, the program always refers to the log file as a `\.{transcript
file}', because some systems cannot use the extension `\.{.log}' for
this file.
@<Try to get a different log file name@>=
{
mp->selector = term_only;
mp_prompt_file_name (mp, "transcript file name", ".log");
}
@ @<Print the banner...@>=
{
wlog (mp->banner);
mp_print (mp, " ");
mp_print_int (mp, round_unscaled (internal_value (mp_day)));
mp_print_char (mp, xord (' '));
m = round_unscaled (internal_value (mp_month));
for (k = 3 * m - 3; k < 3 * m; k++) {
wlog_chr ((unsigned char) months[k]);
}
mp_print_char (mp, xord (' '));
mp_print_int (mp, round_unscaled (internal_value (mp_year)));
mp_print_char (mp, xord (' '));
mp_print_dd (mp, round_unscaled (internal_value (mp_hour)));
mp_print_char (mp, xord (':'));
mp_print_dd (mp, round_unscaled (internal_value (mp_minute)));
}
@ The |try_extension| function tries to open an input file determined by
|cur_name|, |cur_area|, and the argument |ext|. It returns |false| if it
can't find the file in |cur_area| or the appropriate system area.
@c
static boolean mp_try_extension (MP mp, const char *ext) {
mp_pack_file_name (mp, mp->cur_name, mp->cur_area, ext);
in_name = xstrdup (mp->cur_name);
in_area = xstrdup (mp->cur_area);
in_ext = xstrdup (ext);
if (mp_open_in (mp, &cur_file, mp_filetype_program)) {
return true;
} else {
mp_pack_file_name (mp, mp->cur_name, NULL, ext);
return mp_open_in (mp, &cur_file, mp_filetype_program);
}
}
@ Let's turn now to the procedure that is used to initiate file reading
when an `\.{input}' command is being processed.
@c
void mp_start_input (MP mp) { /* \MP\ will \.{input} something */
char *fname = NULL;
@<Put the desired file name in |(cur_name,cur_ext,cur_area)|@>;
while (1) {
mp_begin_file_reading (mp); /* set up |cur_file| and new level of input */
if (strlen (mp->cur_ext) == 0) {
if (mp_try_extension (mp, ".mp"))
break;
else if (mp_try_extension (mp, ""))
break;
else if (mp_try_extension (mp, ".mf"))
break;
} else if (mp_try_extension (mp, mp->cur_ext)) {
break;
}
mp_end_file_reading (mp); /* remove the level that didn't work */
mp_prompt_file_name (mp, "input file name", "");
}
name = mp_make_name_string (mp);
fname = xstrdup (mp->name_of_file);
if (mp->job_name == NULL) {
mp->job_name = xstrdup (mp->cur_name);
@<Fix up |mp->internal[mp_job_name]|@>;
}
if (!mp->log_opened) {
mp_open_log_file (mp);
} /* |open_log_file| doesn't |show_context|, so |limit|
and |loc| needn't be set to meaningful values yet */
if (((int) mp->term_offset + (int) strlen (fname)) > (mp->max_print_line - 2))
mp_print_ln (mp);
else if ((mp->term_offset > 0) || (mp->file_offset > 0))
mp_print_char (mp, xord (' '));
mp_print_char (mp, xord ('('));
incr (mp->open_parens);
mp_print (mp, fname);
xfree (fname);
update_terminal();
@<Flush |name| and replace it with |cur_name| if it won't be needed@>;
@<Read the first line of the new file@>;
}
@ This code should be omitted if |make_name_string| returns something other
than just a copy of its argument and the full file name is needed for opening
\.{MPX} files or implementing the switch-to-editor option.
@^system dependencies@>
@<Flush |name| and replace it with |cur_name| if it won't be needed@>=
mp_flush_string (mp, name);
name = mp_rts (mp, mp->cur_name);
xfree (mp->cur_name)
@ If the file is empty, it is considered to contain a single blank line,
so there is no need to test the return value.
@<Read the first line...@>=
{
line = 1;
(void) mp_input_ln (mp, cur_file);
mp_firm_up_the_line (mp);
mp->buffer[limit] = xord ('%');
mp->first = (size_t) (limit + 1);
loc = start;
}
@ @<Put the desired file name in |(cur_name,cur_ext,cur_area)|@>=
while (token_state && (nloc == NULL))
mp_end_token_list (mp);
if (token_state) {
const char *hlp[] = {
"Sorry...I've converted what follows to tokens,",
"possibly garbaging the name you gave.",
"Please delete the tokens and insert the name again.",
NULL };
mp_error (mp, "File names can't appear within macros", hlp, true);
@.File names can't...@>;
}
if (file_state) {
mp_scan_file_name (mp);
} else {
xfree (mp->cur_name);
mp->cur_name = xstrdup ("");
xfree (mp->cur_ext);
mp->cur_ext = xstrdup ("");
xfree (mp->cur_area);
mp->cur_area = xstrdup ("");
}
@ The following simple routine starts reading the \.{MPX} file associated
with the current input file.
@c
void mp_start_mpx_input (MP mp) {
char *origname = NULL; /* a copy of nameoffile */
mp_pack_file_name (mp, in_name, in_area, in_ext);
origname = xstrdup (mp->name_of_file);
mp_pack_file_name (mp, in_name, in_area, ".mpx");
if (!(mp->run_make_mpx) (mp, origname, mp->name_of_file))
goto NOT_FOUND;
mp_begin_file_reading (mp);
if (!mp_open_in (mp, &cur_file, mp_filetype_program)) {
mp_end_file_reading (mp);
goto NOT_FOUND;
}
name = mp_make_name_string (mp);
mp->mpx_name[iindex] = name;
add_str_ref (name);
@<Read the first line of the new file@>;
xfree (origname);
return;
NOT_FOUND:
@<Explain that the \.{MPX} file can't be read and |succumb|@>;
xfree (origname);
}
@ This should ideally be changed to do whatever is necessary to create the
\.{MPX} file given by |name_of_file| if it does not exist or if it is out
of date. This requires invoking \.{MPtoTeX} on the |origname| and passing
the results through \TeX\ and \.{DVItoMP}. (It is possible to use a
completely different typesetting program if suitable postprocessor is
available to perform the function of \.{DVItoMP}.)
@^system dependencies@>
@ @<Exported types@>=
typedef int (*mp_makempx_cmd) (MP mp, char *origname, char *mtxname);
@ @<Option variables@>=
mp_makempx_cmd run_make_mpx;
@ @<Allocate or initialize ...@>=
set_callback_option (run_make_mpx);
@ @<Declarations@>=
static int mp_run_make_mpx (MP mp, char *origname, char *mtxname);
@ The default does nothing.
@c
int mp_run_make_mpx (MP mp, char *origname, char *mtxname) {
(void) mp;
(void) origname;
(void) mtxname;
return false;
}
@ @<Explain that the \.{MPX} file can't be read and |succumb|@>=
{
const char *hlp[] = {
"The two files given above are one of your source files",
"and an auxiliary file I need to read to find out what your",
"btex..etex blocks mean. If you don't know why I had trouble,",
"try running it manually through MPtoTeX, TeX, and DVItoMP",
NULL };
if (mp->interaction == mp_error_stop_mode)
wake_up_terminal();
mp_print_nl (mp, ">> ");
mp_print (mp, origname);
mp_print_nl (mp, ">> ");
mp_print (mp, mp->name_of_file);
xfree (origname);
if ( mp->interaction==mp_error_stop_mode )
mp->interaction=mp_scroll_mode; /* no more interaction */
if ( mp->log_opened )
mp_error(mp, "! Unable to read mpx file", hlp, true);
mp->history=mp_fatal_error_stop;
mp_jump_out(mp); /* irrecoverable error */
}
@ The last file-opening commands are for files accessed via the \&{readfrom}
@:read_from_}{\&{readfrom} primitive@>
operator and the \&{write} command. Such files are stored in separate arrays.
@:write_}{\&{write} primitive@>
@<Types in the outer block@>=
typedef unsigned int readf_index; /* |0..max_read_files| */
typedef unsigned int write_index; /* |0..max_write_files| */
@ @<Glob...@>=
readf_index max_read_files; /* maximum number of simultaneously open \&{readfrom} files */
void **rd_file; /* \&{readfrom} files */
char **rd_fname; /* corresponding file name or 0 if file not open */
readf_index read_files; /* number of valid entries in the above arrays */
write_index max_write_files; /* maximum number of simultaneously open \&{write} */
void **wr_file; /* \&{write} files */
char **wr_fname; /* corresponding file name or 0 if file not open */
write_index write_files; /* number of valid entries in the above arrays */
@ @<Allocate or initialize ...@>=
mp->max_read_files = 8;
mp->rd_file = xmalloc ((mp->max_read_files + 1), sizeof (void *));
mp->rd_fname = xmalloc ((mp->max_read_files + 1), sizeof (char *));
memset (mp->rd_fname, 0, sizeof (char *) * (mp->max_read_files + 1));
mp->max_write_files = 8;
mp->wr_file = xmalloc ((mp->max_write_files + 1), sizeof (void *));
mp->wr_fname = xmalloc ((mp->max_write_files + 1), sizeof (char *));
memset (mp->wr_fname, 0, sizeof (char *) * (mp->max_write_files + 1));
@ This routine starts reading the file named by string~|s| without setting
|loc|, |limit|, or |name|. It returns |false| if the file is empty or cannot
be opened. Otherwise it updates |rd_file[n]| and |rd_fname[n]|.
@c
static boolean mp_start_read_input (MP mp, char *s, readf_index n) {
mp_ptr_scan_file (mp, s);
pack_cur_name;
mp_begin_file_reading (mp);
if (!mp_open_in (mp, &mp->rd_file[n], (int) (mp_filetype_text + n)))
goto NOT_FOUND;
if (!mp_input_ln (mp, mp->rd_file[n])) {
(mp->close_file) (mp, mp->rd_file[n]);
goto NOT_FOUND;
}
mp->rd_fname[n] = xstrdup (s);
return true;
NOT_FOUND:
mp_end_file_reading (mp);
return false;
}
@ Open |wr_file[n]| using file name~|s| and update |wr_fname[n]|.
@<Declarations@>=
static void mp_open_write_file (MP mp, char *s, readf_index n);
@ @c
void mp_open_write_file (MP mp, char *s, readf_index n) {
mp_ptr_scan_file (mp, s);
pack_cur_name;
while (!mp_open_out (mp, &mp->wr_file[n], (int) (mp_filetype_text + n)))
mp_prompt_file_name (mp, "file name for write output", "");
mp->wr_fname[n] = xstrdup (s);
}
@* Introduction to the parsing routines.
We come now to the central nervous system that sparks many of \MP's activities.
By evaluating expressions, from their primary constituents to ever larger
subexpressions, \MP\ builds the structures that ultimately define complete
pictures or fonts of type.
Four mutually recursive subroutines are involved in this process: We call them
$$\hbox{|scan_primary|, |scan_secondary|, |scan_tertiary|,
and |scan_expression|.}$$
@^recursion@>
Each of them is parameterless and begins with the first token to be scanned
already represented in |cur_cmd|, |cur_mod|, and |cur_sym|. After execution,
the value of the primary or secondary or tertiary or expression that was
found will appear in the global variables |cur_type| and |cur_exp|. The
token following the expression will be represented in |cur_cmd|, |cur_mod|,
and |cur_sym|.
Technically speaking, the parsing algorithms are ``LL(1),'' more or less;
backup mechanisms have been added in order to provide reasonable error
recovery.
@d cur_exp_value_boolean() number_to_int (mp->cur_exp.data.n)
@d cur_exp_value_number() mp->cur_exp.data.n
@d cur_exp_node() mp->cur_exp.data.node
@d cur_exp_str() mp->cur_exp.data.str
@d cur_exp_knot() mp->cur_exp.data.p
@d set_cur_exp_value_scaled(A) do {
if (cur_exp_str()) {
delete_str_ref(cur_exp_str());
}
set_number_from_scaled (mp->cur_exp.data.n, (A));
cur_exp_node() = NULL;
cur_exp_str() = NULL;
cur_exp_knot() = NULL;
} while (0)
@d set_cur_exp_value_boolean(A) do {
if (cur_exp_str()) {
delete_str_ref(cur_exp_str());
}
set_number_from_int (mp->cur_exp.data.n, (A));
cur_exp_node() = NULL;
cur_exp_str() = NULL;
cur_exp_knot() = NULL;
} while (0)
@d set_cur_exp_value_number(A) do {
if (cur_exp_str()) {
delete_str_ref(cur_exp_str());
}
number_clone (mp->cur_exp.data.n, (A));
cur_exp_node() = NULL;
cur_exp_str() = NULL;
cur_exp_knot() = NULL;
} while (0)
@d set_cur_exp_node(A) do {
if (cur_exp_str()) {
delete_str_ref(cur_exp_str());
}
cur_exp_node() = A;
cur_exp_str() = NULL;
cur_exp_knot() = NULL;
set_number_to_zero (mp->cur_exp.data.n);
} while (0)
@d set_cur_exp_str(A) do {
if (cur_exp_str()) {
delete_str_ref(cur_exp_str());
}
cur_exp_str() = A;
add_str_ref(cur_exp_str());
cur_exp_node() = NULL;
cur_exp_knot() = NULL;
set_number_to_zero (mp->cur_exp.data.n);
} while (0)
@d set_cur_exp_knot(A) do {
if (cur_exp_str()) {
delete_str_ref(cur_exp_str());
}
cur_exp_knot() = A;
cur_exp_node() = NULL;
cur_exp_str() = NULL;
set_number_to_zero (mp->cur_exp.data.n);
} while (0)
@ @<Glob...@>=
mp_value cur_exp; /* the value of the expression just found */
@ @<Set init...@>=
memset (&mp->cur_exp.data, 0, sizeof (mp_value));
new_number(mp->cur_exp.data.n);
@ @<Free table ...@>=
free_number(mp->cur_exp.data.n);
@ Many different kinds of expressions are possible, so it is wise to have
precise descriptions of what |cur_type| and |cur_exp| mean in all cases:
\smallskip\hang
|cur_type=mp_vacuous| means that this expression didn't turn out to have a
value at all, because it arose from a \&{begingroup}$\,\ldots\,$\&{endgroup}
construction in which there was no expression before the \&{endgroup}.
In this case |cur_exp| has some irrelevant value.
\smallskip\hang
|cur_type=mp_boolean_type| means that |cur_exp| is either |true_code|
or |false_code|.
\smallskip\hang
|cur_type=mp_unknown_boolean| means that |cur_exp| points to a capsule
node that is in
a ring of equivalent booleans whose value has not yet been defined.
\smallskip\hang
|cur_type=mp_string_type| means that |cur_exp| is a string number (i.e., an
integer in the range |0<=cur_exp<str_ptr|). That string's reference count
includes this particular reference.
\smallskip\hang
|cur_type=mp_unknown_string| means that |cur_exp| points to a capsule
node that is in
a ring of equivalent strings whose value has not yet been defined.
\smallskip\hang
|cur_type=mp_pen_type| means that |cur_exp| points to a node in a pen. Nobody
else points to any of the nodes in this pen. The pen may be polygonal or
elliptical.
\smallskip\hang
|cur_type=mp_unknown_pen| means that |cur_exp| points to a capsule
node that is in
a ring of equivalent pens whose value has not yet been defined.
\smallskip\hang
|cur_type=mp_path_type| means that |cur_exp| points to a the first node of
a path; nobody else points to this particular path. The control points of
the path will have been chosen.
\smallskip\hang
|cur_type=mp_unknown_path| means that |cur_exp| points to a capsule
node that is in
a ring of equivalent paths whose value has not yet been defined.
\smallskip\hang
|cur_type=mp_picture_type| means that |cur_exp| points to an edge header node.
There may be other pointers to this particular set of edges. The header node
contains a reference count that includes this particular reference.
\smallskip\hang
|cur_type=mp_unknown_picture| means that |cur_exp| points to a capsule
node that is in
a ring of equivalent pictures whose value has not yet been defined.
\smallskip\hang
|cur_type=mp_transform_type| means that |cur_exp| points to a |mp_transform_type|
capsule node. The |value| part of this capsule
points to a transform node that contains six numeric values,
each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
\smallskip\hang
|cur_type=mp_color_type| means that |cur_exp| points to a |color_type|
capsule node. The |value| part of this capsule
points to a color node that contains three numeric values,
each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
\smallskip\hang
|cur_type=mp_cmykcolor_type| means that |cur_exp| points to a |mp_cmykcolor_type|
capsule node. The |value| part of this capsule
points to a color node that contains four numeric values,
each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
\smallskip\hang
|cur_type=mp_pair_type| means that |cur_exp| points to a capsule
node whose type is |mp_pair_type|. The |value| part of this capsule
points to a pair node that contains two numeric values,
each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
\smallskip\hang
|cur_type=mp_known| means that |cur_exp| is a |scaled| value.
\smallskip\hang
|cur_type=mp_dependent| means that |cur_exp| points to a capsule node whose type
is |dependent|. The |dep_list| field in this capsule points to the associated
dependency list.
\smallskip\hang
|cur_type=mp_proto_dependent| means that |cur_exp| points to a |mp_proto_dependent|
capsule node. The |dep_list| field in this capsule
points to the associated dependency list.
\smallskip\hang
|cur_type=independent| means that |cur_exp| points to a capsule node
whose type is |independent|. This somewhat unusual case can arise, for
example, in the expression
`$x+\&{begingroup}\penalty0\,\&{string}\,x; 0\,\&{endgroup}$'.
\smallskip\hang
|cur_type=mp_token_list| means that |cur_exp| points to a linked list of
tokens.
\smallskip\noindent
The possible settings of |cur_type| have been listed here in increasing
numerical order. Notice that |cur_type| will never be |mp_numeric_type| or
|suffixed_macro| or |mp_unsuffixed_macro|, although variables of those types
are allowed. Conversely, \MP\ has no variables of type |mp_vacuous| or
|token_list|.
@ Capsules are non-symbolic nodes that have a similar meaning
to |cur_type| and |cur_exp|. Such nodes have |name_type=capsule|,
and their |type| field is one of the possibilities for |cur_type| listed above.
Also |link<=void| in capsules that aren't part of a token list.
The |value| field of a capsule is, in most cases, the value that
corresponds to its |type|, as |cur_exp| corresponds to |cur_type|.
However, when |cur_exp| would point to a capsule,
no extra layer of indirection is present; the |value|
field is what would have been called |value(cur_exp)| if it had not been
encapsulated. Furthermore, if the type is |dependent| or
|mp_proto_dependent|, the |value| field of a capsule is replaced by
|dep_list| and |prev_dep| fields, since dependency lists in capsules are
always part of the general |dep_list| structure.
The |get_x_next| routine is careful not to change the values of |cur_type|
and |cur_exp| when it gets an expanded token. However, |get_x_next| might
call a macro, which might parse an expression, which might execute lots of
commands in a group; hence it's possible that |cur_type| might change
from, say, |mp_unknown_boolean| to |mp_boolean_type|, or from |dependent| to
|known| or |independent|, during the time |get_x_next| is called. The
programs below are careful to stash sensitive intermediate results in
capsules, so that \MP's generality doesn't cause trouble.
Here's a procedure that illustrates these conventions. It takes
the contents of $(|cur_type|\kern-.3pt,|cur_exp|\kern-.3pt)$
and stashes them away in a
capsule. It is not used when |cur_type=mp_token_list|.
After the operation, |cur_type=mp_vacuous|; hence there is no need to
copy path lists or to update reference counts, etc.
The special link |MP_VOID| is put on the capsule returned by
|stash_cur_exp|, because this procedure is used to store macro parameters
that must be easily distinguishable from token lists.
@<Declare the stashing/unstashing routines@>=
static mp_node mp_stash_cur_exp (MP mp) {
mp_node p; /* the capsule that will be returned */
mp_variable_type exp_type = mp->cur_exp.type;
switch (exp_type) {
case unknown_types:
case mp_transform_type:
case mp_color_type:
case mp_pair_type:
case mp_dependent:
case mp_proto_dependent:
case mp_independent:
case mp_cmykcolor_type:
p = cur_exp_node ();
break;
/* |case mp_path_type: case mp_pen_type: case mp_string_type:| */
default:
p = mp_get_value_node (mp);
mp_name_type (p) = mp_capsule;
mp_type (p) = mp->cur_exp.type;
set_value_number (p, cur_exp_value_number ()); /* this also resets the rest to 0/NULL */
if (cur_exp_str ()) {
set_value_str (p, cur_exp_str ());
} else if (cur_exp_knot ()) {
set_value_knot (p, cur_exp_knot ());
} else if (cur_exp_node ()) {
set_value_node (p, cur_exp_node ());
}
break;
}
mp->cur_exp.type = mp_vacuous;
mp_link (p) = MP_VOID;
return p;
}
@ The inverse of |stash_cur_exp| is the following procedure, which
deletes an unnecessary capsule and puts its contents into |cur_type|
and |cur_exp|.
The program steps of \MP\ can be divided into two categories: those in
which |cur_type| and |cur_exp| are ``alive'' and those in which they are
``dead,'' in the sense that |cur_type| and |cur_exp| contain relevant
information or not. It's important not to ignore them when they're alive,
and it's important not to pay attention to them when they're dead.
There's also an intermediate category: If |cur_type=mp_vacuous|, then
|cur_exp| is irrelevant, hence we can proceed without caring if |cur_type|
and |cur_exp| are alive or dead. In such cases we say that |cur_type|
and |cur_exp| are {\sl dormant}. It is permissible to call |get_x_next|
only when they are alive or dormant.
The \\{stash} procedure above assumes that |cur_type| and |cur_exp|
are alive or dormant. The \\{unstash} procedure assumes that they are
dead or dormant; it resuscitates them.
@<Declare the stashing/unstashing...@>=
static void mp_unstash_cur_exp (MP mp, mp_node p);
@ @c
void mp_unstash_cur_exp (MP mp, mp_node p) {
mp->cur_exp.type = mp_type (p);
switch (mp->cur_exp.type) {
case unknown_types:
case mp_transform_type:
case mp_color_type:
case mp_pair_type:
case mp_dependent:
case mp_proto_dependent:
case mp_independent:
case mp_cmykcolor_type:
set_cur_exp_node (p);
break;
case mp_token_list: /* this is how symbols are stashed */
set_cur_exp_node (value_node(p));
mp_free_value_node (mp, p);
break;
case mp_path_type:
case mp_pen_type:
set_cur_exp_knot (value_knot (p));
mp_free_value_node (mp, p);
break;
case mp_string_type:
set_cur_exp_str (value_str (p));
mp_free_value_node (mp, p);
break;
case mp_picture_type:
set_cur_exp_node (value_node (p));
mp_free_value_node (mp, p);
break;
case mp_boolean_type:
case mp_known:
set_cur_exp_value_number (value_number (p));
mp_free_value_node (mp, p);
break;
default:
set_cur_exp_value_number (value_number (p));
if (value_knot(p)) {
set_cur_exp_knot (value_knot (p));
} else if (value_node(p)) {
set_cur_exp_node (value_node (p));
} else if (value_str(p)) {
set_cur_exp_str (value_str (p));
}
mp_free_value_node (mp, p);
break;
}
}
@ The following procedure prints the values of expressions in an
abbreviated format. If its first parameter |p| is NULL, the value of
|(cur_type,cur_exp)| is displayed; otherwise |p| should be a capsule
containing the desired value. The second parameter controls the amount of
output. If it is~0, dependency lists will be abbreviated to
`\.{linearform}' unless they consist of a single term. If it is greater
than~1, complicated structures (pens, pictures, and paths) will be displayed
in full.
@.linearform@>
@<Declarations@>=
@<Declare the procedure called |print_dp|@>;
@<Declare the stashing/unstashing routines@>;
static void mp_print_exp (MP mp, mp_node p, quarterword verbosity);
@ @c
void mp_print_exp (MP mp, mp_node p, quarterword verbosity) {
boolean restore_cur_exp; /* should |cur_exp| be restored? */
mp_variable_type t; /* the type of the expression */
mp_number vv; /* the value of the expression */
mp_node v = NULL;
new_number (vv);
if (p != NULL) {
restore_cur_exp = false;
} else {
p = mp_stash_cur_exp (mp);
restore_cur_exp = true;
}
t = mp_type (p);
if (t < mp_dependent) { /* no dep list, could be a capsule */
if (t != mp_vacuous && t != mp_known && value_node (p) != NULL)
v = value_node (p);
else
number_clone (vv, value_number (p));
} else if (t < mp_independent) {
v = (mp_node) dep_list ((mp_value_node) p);
}
@<Print an abbreviated value of |v| or |vv| with format depending on |t|@>;
if (restore_cur_exp)
mp_unstash_cur_exp (mp, p);
free_number (vv);
}
@ @<Print an abbreviated value of |v| or |vv| with format depending on |t|@>=
switch (t) {
case mp_vacuous:
mp_print (mp, "vacuous");
break;
case mp_boolean_type:
if (number_to_boolean (vv) == mp_true_code)
mp_print (mp, "true");
else
mp_print (mp, "false");
break;
case unknown_types:
case mp_numeric_type:
@<Display a variable that's been declared but not defined@>;
break;
case mp_string_type:
mp_print_char (mp, xord ('"'));
mp_print_str (mp, value_str (p));
mp_print_char (mp, xord ('"'));
break;
case mp_pen_type:
case mp_path_type:
case mp_picture_type:
@<Display a complex type@>;
break;
case mp_transform_type:
if (number_zero (vv) && v == NULL)
mp_print_type (mp, t);
else
@<Display a transform node@>;
break;
case mp_color_type:
if (number_zero (vv) && v == NULL)
mp_print_type (mp, t);
else
@<Display a color node@>;
break;
case mp_pair_type:
if (number_zero (vv) && v == NULL)
mp_print_type (mp, t);
else
@<Display a pair node@>;
break;
case mp_cmykcolor_type:
if (number_zero (vv) && v == NULL)
mp_print_type (mp, t);
else
@<Display a cmykcolor node@>;
break;
case mp_known:
print_number (vv);
break;
case mp_dependent:
case mp_proto_dependent:
mp_print_dp (mp, t, (mp_value_node) v, verbosity);
break;
case mp_independent:
mp_print_variable_name (mp, p);
break;
default:
mp_confusion (mp, "exp");
break;
@:this can't happen exp}{\quad exp@>
}
@ @<Display big node item |v|@>=
{
if (mp_type (v) == mp_known)
print_number (value_number (v));
else if (mp_type (v) == mp_independent)
mp_print_variable_name (mp, v);
else
mp_print_dp (mp, mp_type (v), (mp_value_node) dep_list ((mp_value_node) v),
verbosity);
}
@ In these cases, |v| starts as the big node.
@<Display a pair node@>=
{
mp_node vvv = v;
mp_print_char (mp, xord ('('));
/* clang: dereference of null pointer */ assert(vvv);
v = x_part (vvv);
@<Display big node item |v|@>;
mp_print_char (mp, xord (','));
v = y_part (vvv);
@<Display big node item |v|@>;
mp_print_char (mp, xord (')'));
}
@ @<Display a transform node@>=
{
mp_node vvv = v;
mp_print_char (mp, xord ('('));
/* clang: dereference of null pointer */ assert(vvv);
v = tx_part (vvv);
@<Display big node item |v|@>;
mp_print_char (mp, xord (','));
v = ty_part (vvv);
@<Display big node item |v|@>;
mp_print_char (mp, xord (','));
v = xx_part (vvv);
@<Display big node item |v|@>;
mp_print_char (mp, xord (','));
v = xy_part (vvv);
@<Display big node item |v|@>;
mp_print_char (mp, xord (','));
v = yx_part (vvv);
@<Display big node item |v|@>;
mp_print_char (mp, xord (','));
v = yy_part (vvv);
@<Display big node item |v|@>;
mp_print_char (mp, xord (')'));
}
@ @<Display a color node@>=
{
mp_node vvv = v;
mp_print_char (mp, xord ('('));
/* clang: dereference of null pointer */ assert(vvv);
v = red_part (vvv);
@<Display big node item |v|@>;
mp_print_char (mp, xord (','));
v = green_part (vvv);
@<Display big node item |v|@>;
mp_print_char (mp, xord (','));
v = blue_part (vvv);
@<Display big node item |v|@>;
mp_print_char (mp, xord (')'));
}
@ @<Display a cmykcolor node@>=
{
mp_node vvv = v;
mp_print_char (mp, xord ('('));
/* clang: dereference of null pointer */ assert(vvv);
v = cyan_part (vvv);
@<Display big node item |v|@>;
mp_print_char (mp, xord (','));
v = magenta_part (vvv);
@<Display big node item |v|@>;
mp_print_char (mp, xord (','));
v = yellow_part (vvv);
@<Display big node item |v|@>;
mp_print_char (mp, xord (','));
v = black_part (vvv);
@<Display big node item |v|@>;
mp_print_char (mp, xord (')'));
}
@ Values of type \&{picture}, \&{path}, and \&{pen} are displayed verbosely
in the log file only, unless the user has given a positive value to
\\{tracingonline}.
@<Display a complex type@>=
if (verbosity <= 1) {
mp_print_type (mp, t);
} else {
if (mp->selector == term_and_log)
if (number_nonpositive (internal_value (mp_tracing_online))) {
mp->selector = term_only;
mp_print_type (mp, t);
mp_print (mp, " (see the transcript file)");
mp->selector = term_and_log;
};
switch (t) {
case mp_pen_type:
mp_print_pen (mp, value_knot (p), "", false);
break;
case mp_path_type:
mp_print_path (mp, value_knot (p), "", false);
break;
case mp_picture_type:
mp_print_edges (mp, v, "", false);
break;
default:
break;
}
}
@ @<Declare the procedure called |print_dp|@>=
static void mp_print_dp (MP mp, quarterword t, mp_value_node p,
quarterword verbosity) {
mp_value_node q; /* the node following |p| */
q = (mp_value_node) mp_link (p);
if ((dep_info (q) == NULL) || (verbosity > 0))
mp_print_dependency (mp, p, t);
else
mp_print (mp, "linearform");
}
@ The displayed name of a variable in a ring will not be a capsule unless
the ring consists entirely of capsules.
@<Display a variable that's been declared but not defined@>=
{
mp_print_type (mp, t);
if (v != NULL) {
mp_print_char (mp, xord (' '));
while ((mp_name_type (v) == mp_capsule) && (v != p))
v = value_node (v);
mp_print_variable_name (mp, v);
};
}
@ When errors are detected during parsing, it is often helpful to
display an expression just above the error message, using |disp_err|
just before |mp_error|.
@<Declarations@>=
static void mp_disp_err (MP mp, mp_node p);
@ @c
void mp_disp_err (MP mp, mp_node p) {
if (mp->interaction == mp_error_stop_mode)
wake_up_terminal();
mp_print_nl (mp, ">> ");
@.>>@>;
mp_print_exp (mp, p, 1); /* ``medium verbose'' printing of the expression */
}
@ If |cur_type| and |cur_exp| contain relevant information that should
be recycled, we will use the following procedure, which changes |cur_type|
to |known| and stores a given value in |cur_exp|. We can think of |cur_type|
and |cur_exp| as either alive or dormant after this has been done,
because |cur_exp| will not contain a pointer value.
@ @c
void mp_flush_cur_exp (MP mp, mp_value v) {
if (is_number(mp->cur_exp.data.n)) {
free_number(mp->cur_exp.data.n);
}
switch (mp->cur_exp.type) {
case unknown_types:
case mp_transform_type:
case mp_color_type:
case mp_pair_type:
case mp_dependent:
case mp_proto_dependent:
case mp_independent:
case mp_cmykcolor_type:
mp_recycle_value (mp, cur_exp_node ());
mp_free_value_node (mp, cur_exp_node ());
break;
case mp_string_type:
delete_str_ref (cur_exp_str ());
break;
case mp_pen_type:
case mp_path_type:
mp_toss_knot_list (mp, cur_exp_knot ());
break;
case mp_picture_type:
delete_edge_ref (cur_exp_node ());
break;
default:
break;
}
mp->cur_exp = v;
mp->cur_exp.type = mp_known;
}
@ There's a much more general procedure that is capable of releasing
the storage associated with any non-symbolic value packet.
@<Declarations@>=
static void mp_recycle_value (MP mp, mp_node p);
@ @c
static void mp_recycle_value (MP mp, mp_node p) {
mp_variable_type t; /* a type code */
FUNCTION_TRACE2 ("mp_recycle_value(%p)\n", p);
if (p==NULL || p==MP_VOID)
return;
t = mp_type (p);
switch (t) {
case mp_vacuous:
case mp_boolean_type:
case mp_known:
case mp_numeric_type:
break;
case unknown_types:
mp_ring_delete (mp, p);
break;
case mp_string_type:
delete_str_ref (value_str (p));
break;
case mp_path_type:
case mp_pen_type:
mp_toss_knot_list (mp, value_knot (p));
break;
case mp_picture_type:
delete_edge_ref (value_node (p));
break;
case mp_cmykcolor_type:
if (value_node (p) != NULL) {
mp_recycle_value (mp, cyan_part (value_node (p)));
mp_recycle_value (mp, magenta_part (value_node (p)));
mp_recycle_value (mp, yellow_part (value_node (p)));
mp_recycle_value (mp, black_part (value_node (p)));
mp_free_value_node (mp, cyan_part (value_node (p)));
mp_free_value_node (mp, magenta_part (value_node (p)));
mp_free_value_node (mp, black_part (value_node (p)));
mp_free_value_node (mp, yellow_part (value_node (p)));
mp_free_node (mp, value_node (p), cmykcolor_node_size);
}
break;
case mp_pair_type:
if (value_node (p) != NULL) {
mp_recycle_value (mp, x_part (value_node (p)));
mp_recycle_value (mp, y_part (value_node (p)));
mp_free_value_node (mp, x_part (value_node (p)));
mp_free_value_node (mp, y_part (value_node (p)));
mp_free_pair_node (mp, value_node (p));
}
break;
case mp_color_type:
if (value_node (p) != NULL) {
mp_recycle_value (mp, red_part (value_node (p)));
mp_recycle_value (mp, green_part (value_node (p)));
mp_recycle_value (mp, blue_part (value_node (p)));
mp_free_value_node (mp, red_part (value_node (p)));
mp_free_value_node (mp, green_part (value_node (p)));
mp_free_value_node (mp, blue_part (value_node (p)));
mp_free_node (mp, value_node (p), color_node_size);
}
break;
case mp_transform_type:
if (value_node (p) != NULL) {
mp_recycle_value (mp, tx_part (value_node (p)));
mp_recycle_value (mp, ty_part (value_node (p)));
mp_recycle_value (mp, xx_part (value_node (p)));
mp_recycle_value (mp, xy_part (value_node (p)));
mp_recycle_value (mp, yx_part (value_node (p)));
mp_recycle_value (mp, yy_part (value_node (p)));
mp_free_value_node (mp, tx_part (value_node (p)));
mp_free_value_node (mp, ty_part (value_node (p)));
mp_free_value_node (mp, xx_part (value_node (p)));
mp_free_value_node (mp, xy_part (value_node (p)));
mp_free_value_node (mp, yx_part (value_node (p)));
mp_free_value_node (mp, yy_part (value_node (p)));
mp_free_node (mp, value_node (p), transform_node_size);
}
break;
case mp_dependent:
case mp_proto_dependent:
/* Recycle a dependency list */
{
mp_value_node qq = (mp_value_node) dep_list ((mp_value_node) p);
while (dep_info (qq) != NULL)
qq = (mp_value_node) mp_link (qq);
set_mp_link (prev_dep ((mp_value_node) p), mp_link (qq));
set_prev_dep (mp_link (qq), prev_dep ((mp_value_node) p));
set_mp_link (qq, NULL);
mp_flush_node_list (mp, (mp_node) dep_list ((mp_value_node) p));
}
break;
case mp_independent:
@<Recycle an independent variable@>;
break;
case mp_token_list:
case mp_structured:
mp_confusion (mp, "recycle");
break;
case mp_unsuffixed_macro:
case mp_suffixed_macro:
mp_delete_mac_ref (mp, value_node (p));
break;
default: /* there are no other valid cases, but please the compiler */
break;
}
mp_type (p) = mp_undefined;
}
@ When an independent variable disappears, it simply fades away, unless
something depends on it. In the latter case, a dependent variable whose
coefficient of dependence is maximal will take its place.
The relevant algorithm is due to Ignacio~A. Zabala, who implemented it
as part of his Ph.n->data. thesis (Stanford University, December 1982).
@^Zabala Salelles, Ignacio Andr\'es@>
For example, suppose that variable $x$ is being recycled, and that the
only variables depending on~$x$ are $y=2x+a$ and $z=x+b$. In this case
we want to make $y$ independent and $z=.5y-.5a+b$; no other variables
will depend on~$y$. If $\\{tracingequations}>0$ in this situation,
we will print `\.{\#\#\# -2x=-y+a}'.
There's a slight complication, however: An independent variable $x$
can occur both in dependency lists and in proto-dependency lists.
This makes it necessary to be careful when deciding which coefficient
is maximal.
Furthermore, this complication is not so slight when
a proto-dependent variable is chosen to become independent. For example,
suppose that $y=2x+100a$ is proto-dependent while $z=x+b$ is dependent;
then we must change $z=.5y-50a+b$ to a proto-dependency, because of the
large coefficient `50'.
In order to deal with these complications without wasting too much time,
we shall link together the occurrences of~$x$ among all the linear
dependencies, maintaining separate lists for the dependent and
proto-dependent cases.
@<Recycle an independent variable@>=
{
mp_value_node q, r, s;
mp_node pp; /* link manipulation register */
mp_number v ; /* a value */
mp_number test; /* a temporary value */
new_number (test);
new_number (v);
if (t < mp_dependent)
number_clone (v, value_number (p));
set_number_to_zero(mp->max_c[mp_dependent]);
set_number_to_zero(mp->max_c[mp_proto_dependent]);
mp->max_link[mp_dependent] = NULL;
mp->max_link[mp_proto_dependent] = NULL;
q = (mp_value_node) mp_link (mp->dep_head);
while (q != mp->dep_head) {
s = (mp_value_node) mp->temp_head;
set_mp_link (s, dep_list (q));
while (1) {
r = (mp_value_node) mp_link (s);
if (dep_info (r) == NULL)
break;
if (dep_info (r) != p) {
s = r;
} else {
t = mp_type (q);
if (mp_link (s) == dep_list (q)) { /* reset the |dep_list| */
set_dep_list (q, mp_link (r));
}
set_mp_link (s, mp_link (r));
set_dep_info (r, (mp_node) q);
number_clone (test, dep_value (r));
number_abs (test);
if (number_greater (test, mp->max_c[t])) {
/* Record a new maximum coefficient of type |t| */
if (number_positive(mp->max_c[t])) {
set_mp_link (mp->max_ptr[t], (mp_node) mp->max_link[t]);
mp->max_link[t] = mp->max_ptr[t];
}
number_clone (mp->max_c[t], test);
mp->max_ptr[t] = r;
} else {
set_mp_link (r, (mp_node) mp->max_link[t]);
mp->max_link[t] = r;
}
}
}
q = (mp_value_node) mp_link (r);
}
if (number_positive(mp->max_c[mp_dependent]) || number_positive(mp->max_c[mp_proto_dependent])) {
/* Choose a dependent variable to take the place of the disappearing
independent variable, and change all remaining dependencies
accordingly */
mp_number test, ret; /* temporary use */
new_number (ret);
new_number (test);
number_clone (test, mp->max_c[mp_dependent]);
number_divide_int (test, 4096);
if (number_greaterequal(test, mp->max_c[mp_proto_dependent]))
t = mp_dependent;
else
t = mp_proto_dependent;
/* Let |s=max_ptr[t]|. At this point we have $|value|(s)=\pm|max_c|[t]$,
and |dep_info(s)| points to the dependent variable~|pp| of type~|t| from
whose dependency list we have removed node~|s|. We must reinsert
node~|s| into the dependency list, with coefficient $-1.0$, and with
|pp| as the new independent variable. Since |pp| will have a larger serial
number than any other variable, we can put node |s| at the head of the
list. */
/* Determine the dependency list |s| to substitute for the independent
variable~|p| */
s = mp->max_ptr[t];
pp = (mp_node) dep_info (s);
number_clone (v, dep_value (s));
if (t == mp_dependent) {
set_dep_value (s, fraction_one_t);
} else {
set_dep_value (s, unity_t);
}
number_negate(dep_value(s));
r = (mp_value_node) dep_list ((mp_value_node) pp);
set_mp_link (s, (mp_node) r);
while (dep_info (r) != NULL)
r = (mp_value_node) mp_link (r);
q = (mp_value_node) mp_link (r);
set_mp_link (r, NULL);
set_prev_dep (q, prev_dep ((mp_value_node) pp));
set_mp_link (prev_dep ((mp_value_node) pp), (mp_node) q);
mp_new_indep (mp, pp);
if (cur_exp_node () == pp && mp->cur_exp.type == t)
mp->cur_exp.type = mp_independent;
if (number_positive (internal_value (mp_tracing_equations))) {
/* Show the transformed dependency */
if (mp_interesting (mp, p)) {
mp_begin_diagnostic (mp);
mp_show_transformed_dependency(mp, v, t, p);
mp_print_dependency (mp, s, t);
mp_end_diagnostic (mp, false);
}
}
t = (quarterword) (mp_dependent + mp_proto_dependent - t); /* complement |t| */
if (number_positive(mp->max_c[t])) {
/* we need to pick up an unchosen dependency */
set_mp_link (mp->max_ptr[t], (mp_node) mp->max_link[t]);
mp->max_link[t] = mp->max_ptr[t];
}
/* Finally, there are dependent and proto-dependent variables whose
dependency lists must be brought up to date. */
if (t != mp_dependent) {
/* Substitute new dependencies in place of |p| */
for (t = mp_dependent; t <= mp_proto_dependent; t=t+1) {
r = mp->max_link[t];
while (r != NULL) {
q = (mp_value_node) dep_info (r);
number_clone (test, v);
number_negate (test);
make_fraction (ret, dep_value (r), test);
set_dep_list (q, mp_p_plus_fq (mp, (mp_value_node) dep_list (q), ret, s, t, mp_dependent));
if (dep_list (q) == (mp_node) mp->dep_final)
mp_make_known (mp, q, mp->dep_final);
q = r;
r = (mp_value_node) mp_link (r);
mp_free_dep_node (mp, q);
}
}
} else {
/* Substitute new proto-dependencies in place of |p| */
for (t = mp_dependent; t <= mp_proto_dependent; t=t+1) {
r = mp->max_link[t];
while (r != NULL) {
q = (mp_value_node) dep_info (r);
if (t == mp_dependent) { /* for safety's sake, we change |q| to |mp_proto_dependent| */
if (cur_exp_node () == (mp_node) q && mp->cur_exp.type == mp_dependent)
mp->cur_exp.type = mp_proto_dependent;
set_dep_list (q, mp_p_over_v (mp, (mp_value_node) dep_list (q),
unity_t, mp_dependent,
mp_proto_dependent));
mp_type (q) = mp_proto_dependent;
fraction_to_round_scaled (dep_value (r));
}
number_clone (test, v);
number_negate (test);
make_scaled (ret, dep_value (r), test);
set_dep_list (q, mp_p_plus_fq (mp, (mp_value_node) dep_list (q),
ret, s,
mp_proto_dependent,
mp_proto_dependent));
if (dep_list (q) == (mp_node) mp->dep_final)
mp_make_known (mp, q, mp->dep_final);
q = r;
r = (mp_value_node) mp_link (r);
mp_free_dep_node (mp, q);
}
}
}
mp_flush_node_list (mp, (mp_node) s);
if (mp->fix_needed)
mp_fix_dependencies (mp);
check_arith();
free_number (ret);
}
free_number (v);
free_number(test);
}
@ @<Declarations@>=
static void mp_show_transformed_dependency(MP mp, mp_number v, mp_variable_type t, mp_node p);
@ @c
static void mp_show_transformed_dependency(MP mp, mp_number v, mp_variable_type t, mp_node p)
{
mp_number vv; /* for temp use */
new_number (vv);
mp_print_nl (mp, "### ");
if (number_positive(v))
mp_print_char (mp, xord ('-'));
if (t == mp_dependent) {
number_clone (vv, mp->max_c[mp_dependent]);
fraction_to_round_scaled (vv);
} else {
number_clone (vv, mp->max_c[mp_proto_dependent]);
}
if (!number_equal(vv, unity_t)) {
print_number (vv);
}
mp_print_variable_name (mp, p);
while (indep_scale (p) > 0) {
mp_print (mp, "*4");
set_indep_scale(p, indep_scale(p)-2);
}
if (t == mp_dependent)
mp_print_char (mp, xord ('='));
else
mp_print (mp, " = ");
free_number (vv);
}
@ The code for independency removal makes use of three non-symbolic arrays.
@<Glob...@>=
mp_number max_c[mp_proto_dependent + 1]; /* max coefficient magnitude */
mp_value_node max_ptr[mp_proto_dependent + 1]; /* where |p| occurs with |max_c| */
mp_value_node max_link[mp_proto_dependent + 1]; /* other occurrences of |p| */
@ @<Initialize table ... @>=
{
int i;
for (i=0;i<mp_proto_dependent + 1;i++) {
new_number (mp->max_c[i]);
}
}
@ @<Dealloc...@>=
{
int i;
for (i=0;i<mp_proto_dependent + 1;i++) {
free_number (mp->max_c[i]);
}
}
@ A global variable |var_flag| is set to a special command code
just before \MP\ calls |scan_expression|, if the expression should be
treated as a variable when this command code immediately follows. For
example, |var_flag| is set to |assignment| at the beginning of a
statement, because we want to know the {\sl location\/} of a variable at
the left of `\.{:=}', not the {\sl value\/} of that variable.
The |scan_expression| subroutine calls |scan_tertiary|,
which calls |scan_secondary|, which calls |scan_primary|, which sets
|var_flag:=0|. In this way each of the scanning routines ``knows''
when it has been called with a special |var_flag|, but |var_flag| is
usually zero.
A variable preceding a command that equals |var_flag| is converted to a
token list rather than a value. Furthermore, an `\.{=}' sign following an
expression with |var_flag=assignment| is not considered to be a relation
that produces boolean expressions.
@<Glob...@>=
int var_flag; /* command that wants a variable */
@ @<Set init...@>=
mp->var_flag = 0;
@* Parsing primary expressions.
The first parsing routine, |scan_primary|, is also the most complicated one,
since it involves so many different cases. But each case---with one
exception---is fairly simple by itself.
When |scan_primary| begins, the first token of the primary to be scanned
should already appear in |cur_cmd|, |cur_mod|, and |cur_sym|. The values
of |cur_type| and |cur_exp| should be either dead or dormant, as explained
earlier. If |cur_cmd| is not between |min_primary_command| and
|max_primary_command|, inclusive, a syntax error will be signaled.
Later we'll come to procedures that perform actual operations like
addition, square root, and so on; our purpose now is to do the parsing.
But we might as well mention those future procedures now, so that the
suspense won't be too bad:
\smallskip
|do_nullary(c)| does primitive operations that have no operands (e.g.,
`\&{true}' or `\&{pencircle}');
\smallskip
|do_unary(c)| applies a primitive operation to the current expression;
\smallskip
|do_binary(p,c)| applies a primitive operation to the capsule~|p|
and the current expression.
@<Declare the basic parsing subroutines@>=
static void check_for_mediation (MP mp);
void mp_scan_primary (MP mp) {
mp_command_code my_var_flag; /* initial value of |my_var_flag| */
my_var_flag = mp->var_flag;
mp->var_flag = 0;
RESTART:
check_arith();
/* Supply diagnostic information, if requested */
if (mp->interrupt != 0) {
if (mp->OK_to_interrupt) {
mp_back_input (mp);
check_interrupt;
mp_get_x_next (mp);
}
}
switch (cur_cmd()) {
case mp_left_delimiter:
{
/* Scan a delimited primary */
mp_node p, q, r; /* for list manipulation */
mp_sym l_delim, r_delim; /* hash addresses of a delimiter pair */
l_delim = cur_sym();
r_delim = equiv_sym (cur_sym());
mp_get_x_next (mp);
mp_scan_expression (mp);
if ((cur_cmd() == mp_comma) && (mp->cur_exp.type >= mp_known)) {
/* Scan the rest of a delimited set of numerics */
/* This code uses the fact that |red_part| and |green_part|
are synonymous with |x_part| and |y_part|. */
p = mp_stash_cur_exp (mp);
mp_get_x_next (mp);
mp_scan_expression (mp);
/* Make sure the second part of a pair or color has a numeric type */
if (mp->cur_exp.type < mp_known) {
const char *hlp[] = {
"I've started to scan a pair `(a,b)' or a color `(a,b,c)';",
"but after finding a nice `a' I found a `b' that isn't",
"of numeric type. So I've changed that part to zero.",
"(The b that I didn't like appears above the error message.)",
NULL };
mp_value new_expr;
memset(&new_expr,0,sizeof(mp_value));
mp_disp_err(mp, NULL);
new_number(new_expr.data.n);
set_number_to_zero(new_expr.data.n);
mp_back_error (mp,"Nonnumeric ypart has been replaced by 0", hlp, true);
mp_get_x_next (mp);
mp_flush_cur_exp (mp, new_expr);
}
q = mp_get_value_node (mp);
mp_name_type (q) = mp_capsule;
if (cur_cmd() == mp_comma) {
mp_init_color_node (mp, q);
r = value_node (q);
mp_stash_in (mp, y_part (r));
mp_unstash_cur_exp (mp, p);
mp_stash_in (mp, x_part (r));
/* Scan the last of a triplet of numerics */
mp_get_x_next (mp);
mp_scan_expression (mp);
if (mp->cur_exp.type < mp_known) {
mp_value new_expr;
const char *hlp[] = {
"I've just scanned a color `(a,b,c)' or cmykcolor(a,b,c,d); but the `c'",
"isn't of numeric type. So I've changed that part to zero.",
"(The c that I didn't like appears above the error message.)",
NULL };
memset(&new_expr,0,sizeof(mp_value));
mp_disp_err(mp, NULL);
new_number(new_expr.data.n);
set_number_to_zero(new_expr.data.n);
mp_back_error (mp,"Nonnumeric third part has been replaced by 0", hlp, true);
mp_get_x_next (mp);
mp_flush_cur_exp (mp, new_expr);
}
mp_stash_in (mp, blue_part (r));
if (cur_cmd() == mp_comma) {
mp_node t; /* a token */
mp_init_cmykcolor_node (mp, q);
t = value_node (q);
mp_type (cyan_part (t)) = mp_type (red_part (r));
set_value_number (cyan_part (t), value_number (red_part (r)));
mp_type (magenta_part (t)) = mp_type (green_part (r));
set_value_number (magenta_part (t), value_number (green_part (r)));
mp_type (yellow_part (t)) = mp_type (blue_part (r));
set_value_number (yellow_part (t), value_number (blue_part (r)));
/*see |mp_stash_in| */
if ( ((mp_type (cyan_part (t))) != mp_independent) && ((mp_type (cyan_part (t))) != mp_known) ) {
/* Copy the dep list */
set_dep_list (cyan_part(t),dep_list ((mp_value_node) red_part(r)));
set_prev_dep (cyan_part(t),prev_dep ((mp_value_node) red_part(r)));
set_mp_link (prev_dep (cyan_part(t)), (mp_node) cyan_part(t));
}
if ( ((mp_type (magenta_part (t))) != mp_independent) && ((mp_type (magenta_part (t))) != mp_known) ) {
/* Copy the dep list */
set_dep_list (magenta_part(t),dep_list ((mp_value_node) green_part(r)));
set_prev_dep (magenta_part(t),prev_dep ((mp_value_node) green_part(r)));
set_mp_link (prev_dep (magenta_part(t)), (mp_node) magenta_part(t));
}
if ( ((mp_type (yellow_part (t))) != mp_independent) && ((mp_type (yellow_part (t))) != mp_known)) {
/* Copy the dep list */
set_dep_list (yellow_part(t),dep_list ((mp_value_node) blue_part(r)));
set_prev_dep (yellow_part(t),prev_dep ((mp_value_node) blue_part(r)));
set_mp_link (prev_dep (yellow_part(t)), (mp_node) yellow_part(t));
}
mp_recycle_value (mp, r);
r = t;
/* Scan the last of a quartet of numerics */
mp_get_x_next (mp);
mp_scan_expression (mp);
if (mp->cur_exp.type < mp_known) {
const char *hlp[] = {
"I've just scanned a cmykcolor `(c,m,y,k)'; but the `k' isn't",
"of numeric type. So I've changed that part to zero.",
"(The k that I didn't like appears above the error message.)",
NULL };
mp_value new_expr;
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
mp_disp_err(mp, NULL);
set_number_to_zero(new_expr.data.n);
mp_back_error (mp,"Nonnumeric blackpart has been replaced by 0", hlp, true);
mp_get_x_next (mp);
mp_flush_cur_exp (mp, new_expr);
}
mp_stash_in (mp, black_part (r));
}
} else {
mp_init_pair_node (mp, q);
r = value_node (q);
mp_stash_in (mp, y_part (r));
mp_unstash_cur_exp (mp, p);
mp_stash_in (mp, x_part (r));
}
mp_check_delimiter (mp, l_delim, r_delim);
mp->cur_exp.type = mp_type (q);
set_cur_exp_node (q);
} else {
mp_check_delimiter (mp, l_delim, r_delim);
}
}
break;
case mp_begin_group:
/* Scan a grouped primary */
/* The local variable |group_line| keeps track of the line
where a \&{begingroup} command occurred; this will be useful
in an error message if the group doesn't actually end. */
{
integer group_line; /* where a group began */
group_line = mp_true_line (mp);
if (number_positive (internal_value (mp_tracing_commands)))
show_cur_cmd_mod;
mp_save_boundary (mp);
do {
mp_do_statement (mp); /* ends with |cur_cmd>=semicolon| */
} while (cur_cmd() == mp_semicolon);
if (cur_cmd() != mp_end_group) {
char msg[256];
const char *hlp[] = {
"I saw a `begingroup' back there that hasn't been matched",
"by `endgroup'. So I've inserted `endgroup' now.",
NULL };
mp_snprintf(msg, 256, "A group begun on line %d never ended", (int)group_line);
mp_back_error (mp, msg, hlp, true);
set_cur_cmd((mp_variable_type)mp_end_group);
}
mp_unsave (mp);
/* this might change |cur_type|, if independent variables are recycled */
if (number_positive (internal_value (mp_tracing_commands)))
show_cur_cmd_mod;
}
break;
case mp_string_token:
/* Scan a string constant */
mp->cur_exp.type = mp_string_type;
set_cur_exp_str (cur_mod_str());
break;
case mp_numeric_token:
{
/* Scan a primary that starts with a numeric token */
/* A numeric token might be a primary by itself, or it might be the
numerator of a fraction composed solely of numeric tokens, or it might
multiply the primary that follows (provided that the primary doesn't begin
with a plus sign or a minus sign). The code here uses the facts that
|max_primary_command=plus_or_minus| and
|max_primary_command-1=numeric_token|. If a fraction is found that is less
than unity, we try to retain higher precision when we use it in scalar
multiplication. */
mp_number num, denom; /* for primaries that are fractions, like `1/2' */
new_number (num);
new_number (denom);
set_cur_exp_value_number (cur_mod_number());
mp->cur_exp.type = mp_known;
mp_get_x_next (mp);
if (cur_cmd() != mp_slash) {
set_number_to_zero(num);
set_number_to_zero(denom);
} else {
mp_get_x_next (mp);
if (cur_cmd() != mp_numeric_token) {
mp_back_input (mp);
set_cur_cmd((mp_variable_type)mp_slash);
set_cur_mod(mp_over);
set_cur_sym(mp->frozen_slash);
free_number (num);
free_number (denom);
goto DONE;
}
number_clone (num, cur_exp_value_number ());
number_clone (denom, cur_mod_number());
if (number_zero(denom)) {
/* Protest division by zero */
const char *hlp[] = { "I'll pretend that you meant to divide by 1.", NULL };
mp_error (mp, "Division by zero", hlp, true);
} else {
mp_number ret;
new_number (ret);
make_scaled (ret, num, denom);
set_cur_exp_value_number (ret);
free_number (ret);
}
check_arith();
mp_get_x_next (mp);
}
if (cur_cmd() >= mp_min_primary_command) {
if (cur_cmd() < mp_numeric_token) { /* in particular, |cur_cmd<>plus_or_minus| */
mp_node p; /* for list manipulation */
mp_number absnum, absdenom;
new_number (absnum);
new_number (absdenom);
p = mp_stash_cur_exp (mp);
mp_scan_primary (mp);
number_clone (absnum, num);
number_abs (absnum);
number_clone (absdenom, denom);
number_abs (absdenom);
if (number_greaterequal(absnum, absdenom) || (mp->cur_exp.type < mp_color_type)) {
mp_do_binary (mp, p, mp_times);
} else {
mp_frac_mult (mp, num, denom);
mp_free_value_node (mp, p);
}
free_number (absnum);
free_number (absdenom);
}
}
free_number (num);
free_number (denom);
goto DONE;
}
break;
case mp_nullary:
/* Scan a nullary operation */
mp_do_nullary (mp, (quarterword) cur_mod());
break;
case mp_unary:
case mp_type_name:
case mp_cycle:
case mp_plus_or_minus:
{
/* Scan a unary operation */
quarterword c; /* a primitive operation code */
c = (quarterword) cur_mod();
mp_get_x_next (mp);
mp_scan_primary (mp);
mp_do_unary (mp, c);
goto DONE;
}
break;
case mp_primary_binary:
{
/* Scan a binary operation with `\&{of}' between its operands */
mp_node p; /* for list manipulation */
quarterword c; /* a primitive operation code */
c = (quarterword) cur_mod();
mp_get_x_next (mp);
mp_scan_expression (mp);
if (cur_cmd() != mp_of_token) {
char msg[256];
mp_string sname;
const char *hlp[] = {
"I've got the first argument; will look now for the other.",
NULL };
int old_setting = mp->selector;
mp->selector = new_string;
mp_print_cmd_mod (mp, mp_primary_binary, c);
mp->selector = old_setting;
sname = mp_make_string(mp);
mp_snprintf (msg, 256, "Missing `of' has been inserted for %s", mp_str(mp, sname));
delete_str_ref(sname);
mp_back_error (mp, msg, hlp, true);
}
p = mp_stash_cur_exp (mp);
mp_get_x_next (mp);
mp_scan_primary (mp);
mp_do_binary (mp, p, c);
goto DONE;
}
break;
case mp_str_op:
/* Convert a suffix to a string */
mp_get_x_next (mp);
mp_scan_suffix (mp);
mp->old_setting = mp->selector;
mp->selector = new_string;
mp_show_token_list (mp, cur_exp_node (), NULL, 100000, 0);
mp_flush_token_list (mp, cur_exp_node ());
set_cur_exp_str (mp_make_string (mp));
mp->selector = mp->old_setting;
mp->cur_exp.type = mp_string_type;
goto DONE;
break;
case mp_internal_quantity:
/* Scan an internal numeric quantity */
/* If an internal quantity appears all by itself on the left of an
assignment, we return a token list of length one, containing the address
of the internal quantity, with |name_type| equal to |mp_internal_sym|.
(This accords with the conventions of the save stack, as described earlier.) */
{
halfword qq = cur_mod();
if (my_var_flag == mp_assignment) {
mp_get_x_next (mp);
if (cur_cmd() == mp_assignment) {
set_cur_exp_node (mp_get_symbolic_node (mp));
set_mp_sym_info (cur_exp_node (), qq);
mp_name_type (cur_exp_node ()) = mp_internal_sym;
mp->cur_exp.type = mp_token_list;
goto DONE;
}
mp_back_input (mp);
}
if (internal_type (qq) == mp_string_type) {
set_cur_exp_str (internal_string (qq));
} else {
set_cur_exp_value_number (internal_value (qq));
}
mp->cur_exp.type = internal_type (qq);
}
break;
case mp_capsule_token:
mp_make_exp_copy (mp, cur_mod_node());
break;
case mp_tag_token:
@<Scan a variable primary; |goto restart| if it turns out to be a macro@>;
break;
default:
mp_bad_exp (mp, "A primary");
goto RESTART;
break;
}
mp_get_x_next (mp); /* the routines |goto done| if they don't want this */
DONE:
check_for_mediation (mp);
}
@ Expressions of the form `\.{a[b,c]}' are converted into
`\.{b+a*(c-b)}', without checking the types of \.b~or~\.c,
provided that \.a is numeric.
@<Declare the basic parsing subroutines@>=
static void check_for_mediation (MP mp) {
mp_node p, q, r; /* for list manipulation */
if (cur_cmd() == mp_left_bracket) {
if (mp->cur_exp.type >= mp_known) {
/* Scan a mediation construction */
p = mp_stash_cur_exp (mp);
mp_get_x_next (mp);
mp_scan_expression (mp);
if (cur_cmd() != mp_comma) {
/* Put the left bracket and the expression back to be rescanned */
/* The left bracket that we thought was introducing a subscript might have
actually been the left bracket in a mediation construction like `\.{x[a,b]}'.
So we don't issue an error message at this point; but we do want to back up
so as to avoid any embarrassment about our incorrect assumption. */
mp_back_input (mp); /* that was the token following the current expression */
mp_back_expr (mp);
set_cur_cmd((mp_variable_type)mp_left_bracket);
set_cur_mod_number(zero_t);
set_cur_sym(mp->frozen_left_bracket);
mp_unstash_cur_exp (mp, p);
} else {
q = mp_stash_cur_exp (mp);
mp_get_x_next (mp);
mp_scan_expression (mp);
if (cur_cmd() != mp_right_bracket) {
const char *hlp[] = {
"I've scanned an expression of the form `a[b,c',",
"so a right bracket should have come next.",
"I shall pretend that one was there.",
NULL };
mp_back_error (mp, "Missing `]' has been inserted", hlp, true);
}
r = mp_stash_cur_exp (mp);
mp_make_exp_copy (mp, q);
mp_do_binary (mp, r, mp_minus);
mp_do_binary (mp, p, mp_times);
mp_do_binary (mp, q, mp_plus);
mp_get_x_next (mp);
}
}
}
}
@ Errors at the beginning of expressions are flagged by |bad_exp|.
@c
static void mp_bad_exp (MP mp, const char *s) {
char msg[256];
int save_flag;
const char *hlp[] = {
"I'm afraid I need some sort of value in order to continue,",
"so I've tentatively inserted `0'. You may want to",
"delete this zero and insert something else;",
"see Chapter 27 of The METAFONTbook for an example.",
NULL };
@:METAFONTbook}{\sl The {\logos METAFONT\/}book@>;
{
mp_string cm;
int old_selector = mp->selector;
mp->selector = new_string;
mp_print_cmd_mod (mp, cur_cmd(), cur_mod());
mp->selector = old_selector;
cm = mp_make_string(mp);
mp_snprintf(msg, 256, "%s expression can't begin with `%s'", s, mp_str(mp, cm));
delete_str_ref(cm);
}
mp_back_input (mp);
set_cur_sym(NULL);
set_cur_cmd((mp_variable_type)mp_numeric_token);
set_cur_mod_number (zero_t);
mp_ins_error (mp, msg, hlp, true);
save_flag = mp->var_flag;
mp->var_flag = 0;
mp_get_x_next (mp);
mp->var_flag = save_flag;
}
@ The |stash_in| subroutine puts the current (numeric) expression into a field
within a ``big node.''
@c
static void mp_stash_in (MP mp, mp_node p) {
mp_value_node q; /* temporary register */
mp_type (p) = mp->cur_exp.type;
if (mp->cur_exp.type == mp_known) {
set_value_number (p, cur_exp_value_number ());
} else {
if (mp->cur_exp.type == mp_independent) {
/* Stash an independent |cur_exp| into a big node */
/* In rare cases the current expression can become |independent|. There
may be many dependency lists pointing to such an independent capsule,
so we can't simply move it into place within a big node. Instead,
we copy it, then recycle it. */
q = mp_single_dependency (mp, cur_exp_node ());
if (q == mp->dep_final) {
mp_type (p) = mp_known;
set_value_number (p, zero_t);
mp_free_dep_node (mp, q);
} else {
mp_new_dep (mp, p, mp_dependent, q);
}
mp_recycle_value (mp, cur_exp_node ());
mp_free_value_node (mp, cur_exp_node ());
} else {
set_dep_list ((mp_value_node) p,
dep_list ((mp_value_node) cur_exp_node ()));
set_prev_dep ((mp_value_node) p,
prev_dep ((mp_value_node) cur_exp_node ()));
set_mp_link (prev_dep ((mp_value_node) p), p);
mp_free_dep_node (mp, (mp_value_node) cur_exp_node ());
}
}
mp->cur_exp.type = mp_vacuous;
}
@ The most difficult part of |scan_primary| has been saved for last, since
it was necessary to build up some confidence first. We can now face the task
of scanning a variable.
As we scan a variable, we build a token list containing the relevant
names and subscript values, simultaneously following along in the
``collective'' structure to see if we are actually dealing with a macro
instead of a value.
The local variables |pre_head| and |post_head| will point to the beginning
of the prefix and suffix lists; |tail| will point to the end of the list
that is currently growing.
Another local variable, |tt|, contains partial information about the
declared type of the variable-so-far. If |tt>=mp_unsuffixed_macro|, the
relation |tt=mp_type(q)| will always hold. If |tt=undefined|, the routine
doesn't bother to update its information about type. And if
|undefined<tt<mp_unsuffixed_macro|, the precise value of |tt| isn't critical.
@ @<Scan a variable primary...@>=
{
mp_node p, q; /* for list manipulation */
mp_node t; /* a token */
mp_node pre_head, post_head, tail; /* prefix and suffix list variables */
quarterword tt; /* approximation to the type of the variable-so-far */
mp_node macro_ref = 0; /* reference count for a suffixed macro */
pre_head = mp_get_symbolic_node (mp);
tail = pre_head;
post_head = NULL;
tt = mp_vacuous;
while (1) {
t = mp_cur_tok (mp);
mp_link (tail) = t;
if (tt != mp_undefined) {
/* Find the approximate type |tt| and corresponding~|q| */
/* Every time we call |get_x_next|, there's a chance that the variable we've
been looking at will disappear. Thus, we cannot safely keep |q| pointing
into the variable structure; we need to start searching from the root each
time. */
mp_sym qq;
p = mp_link (pre_head);
qq = mp_sym_sym (p);
tt = mp_undefined;
if (eq_type (qq) % mp_outer_tag == mp_tag_token) {
q = equiv_node (qq);
if (q == NULL)
goto DONE2;
while (1) {
p = mp_link (p);
if (p == NULL) {
tt = mp_type (q);
goto DONE2;
}
if (mp_type (q) != mp_structured)
goto DONE2;
q = mp_link (attr_head (q)); /* the |collective_subscript| attribute */
if (mp_type (p) == mp_symbol_node) { /* it's not a subscript */
do {
q = mp_link (q);
} while (!(hashloc (q) >= mp_sym_sym (p)));
if (hashloc (q) > mp_sym_sym (p))
goto DONE2;
}
}
}
DONE2:
if (tt >= mp_unsuffixed_macro) {
/* Either begin an unsuffixed macro call or
prepare for a suffixed one */
mp_link (tail) = NULL;
if (tt > mp_unsuffixed_macro) { /* |tt=mp_suffixed_macro| */
post_head = mp_get_symbolic_node (mp);
tail = post_head;
mp_link (tail) = t;
tt = mp_undefined;
macro_ref = value_node (q);
add_mac_ref (macro_ref);
} else {
/* Set up unsuffixed macro call and |goto restart| */
/* The only complication associated with macro calling is that the prefix
and ``at'' parameters must be packaged in an appropriate list of lists. */
p = mp_get_symbolic_node (mp);
set_mp_sym_sym (pre_head, mp_link (pre_head));
mp_link (pre_head) = p;
set_mp_sym_sym (p, t);
mp_macro_call (mp, value_node (q), pre_head, NULL);
mp_get_x_next (mp);
goto RESTART;
}
}
}
mp_get_x_next (mp);
tail = t;
if (cur_cmd() == mp_left_bracket) {
/* Scan for a subscript; replace |cur_cmd| by |numeric_token| if found */
mp_get_x_next (mp);
mp_scan_expression (mp);
if (cur_cmd() != mp_right_bracket) {
/* Put the left bracket and the expression back to be rescanned */
/* The left bracket that we thought was introducing a subscript might have
actually been the left bracket in a mediation construction like `\.{x[a,b]}'.
So we don't issue an error message at this point; but we do want to back up
so as to avoid any embarrassment about our incorrect assumption. */
mp_back_input (mp); /* that was the token following the current expression */
mp_back_expr (mp);
set_cur_cmd((mp_variable_type)mp_left_bracket);
set_cur_mod_number(zero_t);
set_cur_sym(mp->frozen_left_bracket);
} else {
if (mp->cur_exp.type != mp_known)
mp_bad_subscript (mp);
set_cur_cmd((mp_variable_type)mp_numeric_token);
set_cur_mod_number(cur_exp_value_number ());
set_cur_sym(NULL);
}
}
if (cur_cmd() > mp_max_suffix_token)
break;
if (cur_cmd() < mp_min_suffix_token)
break;
} /* now |cur_cmd| is |internal_quantity|, |tag_token|, or |numeric_token| */
/* Handle unusual cases that masquerade as variables, and |goto restart| or
|goto done| if appropriate; otherwise make a copy of the variable and |goto done| */
/* If the variable does exist, we also need to check
for a few other special cases before deciding that a plain old ordinary
variable has, indeed, been scanned. */
if (post_head != NULL) {
/* Set up suffixed macro call and |goto restart| */
/* If the ``variable'' that turned out to be a suffixed macro no longer exists,
we don't care, because we have reserved a pointer (|macro_ref|) to its
token list. */
mp_back_input (mp);
p = mp_get_symbolic_node (mp);
q = mp_link (post_head);
set_mp_sym_sym (pre_head, mp_link (pre_head));
mp_link (pre_head) = post_head;
set_mp_sym_sym (post_head, q);
mp_link (post_head) = p;
set_mp_sym_sym (p, mp_link (q));
mp_link (q) = NULL;
mp_macro_call (mp, macro_ref, pre_head, NULL);
decr_mac_ref (macro_ref);
mp_get_x_next (mp);
goto RESTART;
}
q = mp_link (pre_head);
mp_free_symbolic_node (mp, pre_head);
if (cur_cmd() == my_var_flag) {
mp->cur_exp.type = mp_token_list;
set_cur_exp_node (q);
goto DONE;
}
p = mp_find_variable (mp, q);
if (p != NULL) {
mp_make_exp_copy (mp, p);
} else {
mp_value new_expr;
const char *hlp[] = {
"While I was evaluating the suffix of this variable,",
"something was redefined, and it's no longer a variable!",
"In order to get back on my feet, I've inserted `0' instead.",
NULL };
char *msg = mp_obliterated (mp, q);
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
set_number_to_zero(new_expr.data.n);
mp_back_error (mp, msg, hlp, true);
free(msg);
mp_get_x_next (mp);
mp_flush_cur_exp (mp, new_expr);
}
mp_flush_node_list (mp, q);
goto DONE;
}
@ Here's a routine that puts the current expression back to be read again.
@c
static void mp_back_expr (MP mp) {
mp_node p; /* capsule token */
p = mp_stash_cur_exp (mp);
mp_link (p) = NULL;
back_list (p);
}
@ Unknown subscripts lead to the following error message.
@c
static void mp_bad_subscript (MP mp) {
mp_value new_expr;
const char *hlp[] = {
"A bracketed subscript must have a known numeric value;",
"unfortunately, what I found was the value that appears just",
"above this error message. So I'll try a zero subscript.",
NULL };
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
mp_disp_err(mp, NULL);
mp_error (mp, "Improper subscript has been replaced by zero", hlp, true);
@.Improper subscript...@>;
mp_flush_cur_exp (mp, new_expr);
}
@ How do things stand now? Well, we have scanned an entire variable name,
including possible subscripts and/or attributes; |cur_cmd|, |cur_mod|, and
|cur_sym| represent the token that follows. If |post_head=NULL|, a
token list for this variable name starts at |mp_link(pre_head)|, with all
subscripts evaluated. But if |post_head<>NULL|, the variable turned out
to be a suffixed macro; |pre_head| is the head of the prefix list, while
|post_head| is the head of a token list containing both `\.{\AT!}' and
the suffix.
Our immediate problem is to see if this variable still exists. (Variable
structures can change drastically whenever we call |get_x_next|; users
aren't supposed to do this, but the fact that it is possible means that
we must be cautious.)
The following procedure creates an error message for when a variable
unexpectedly disappears.
@c
static char *mp_obliterated (MP mp, mp_node q) {
char msg[256];
mp_string sname;
int old_setting = mp->selector;
mp->selector = new_string;
mp_show_token_list (mp, q, NULL, 1000, 0);
sname = mp_make_string(mp);
mp->selector = old_setting;
mp_snprintf(msg, 256, "Variable %s has been obliterated", mp_str(mp, sname));
@.Variable...obliterated@>;
delete_str_ref(sname);
return xstrdup(msg);
}
@ Our remaining job is simply to make a copy of the value that has been
found. Some cases are harder than others, but complexity arises solely
because of the multiplicity of possible cases.
@<Declare the procedure called |make_exp_copy|@>=
@<Declare subroutines needed by |make_exp_copy|@>;
static void mp_make_exp_copy (MP mp, mp_node p) {
mp_node t; /* register(s) for list manipulation */
mp_value_node q;
RESTART:
mp->cur_exp.type = mp_type (p);
switch (mp->cur_exp.type) {
case mp_vacuous:
case mp_boolean_type:
case mp_known:
set_cur_exp_value_number (value_number (p));
break;
case unknown_types:
t = mp_new_ring_entry (mp, p);
set_cur_exp_node (t);
break;
case mp_string_type:
set_cur_exp_str (value_str (p));
break;
case mp_picture_type:
set_cur_exp_node (value_node (p));
add_edge_ref (cur_exp_node ());
break;
case mp_pen_type:
set_cur_exp_knot (copy_pen (value_knot (p)));
break;
case mp_path_type:
set_cur_exp_knot (mp_copy_path (mp, value_knot (p)));
break;
case mp_transform_type:
case mp_color_type:
case mp_cmykcolor_type:
case mp_pair_type:
/* Copy the big node |p| */
/* The most tedious case arises when the user refers to a
\&{pair}, \&{color}, or \&{transform} variable; we must copy several fields,
each of which can be |independent|, |dependent|, |mp_proto_dependent|,
or |known|. */
if (value_node (p) == NULL) {
switch (mp_type (p)) {
case mp_pair_type:
mp_init_pair_node (mp, p);
break;
case mp_color_type:
mp_init_color_node (mp, p);
break;
case mp_cmykcolor_type:
mp_init_cmykcolor_node (mp, p);
break;
case mp_transform_type:
mp_init_transform_node (mp, p);
break;
default: /* there are no other valid cases, but please the compiler */
break;
}
}
t = mp_get_value_node (mp);
mp_name_type (t) = mp_capsule;
q = (mp_value_node)value_node (p);
switch (mp->cur_exp.type) {
case mp_pair_type:
mp_init_pair_node (mp, t);
mp_install (mp, y_part (value_node (t)), y_part (q));
mp_install (mp, x_part (value_node (t)), x_part (q));
break;
case mp_color_type:
mp_init_color_node (mp, t);
mp_install (mp, blue_part (value_node (t)), blue_part (q));
mp_install (mp, green_part (value_node (t)), green_part (q));
mp_install (mp, red_part (value_node (t)), red_part (q));
break;
case mp_cmykcolor_type:
mp_init_cmykcolor_node (mp, t);
mp_install (mp, black_part (value_node (t)), black_part (q));
mp_install (mp, yellow_part (value_node (t)), yellow_part (q));
mp_install (mp, magenta_part (value_node (t)), magenta_part (q));
mp_install (mp, cyan_part (value_node (t)), cyan_part (q));
break;
case mp_transform_type:
mp_init_transform_node (mp, t);
mp_install (mp, yy_part (value_node (t)), yy_part (q));
mp_install (mp, yx_part (value_node (t)), yx_part (q));
mp_install (mp, xy_part (value_node (t)), xy_part (q));
mp_install (mp, xx_part (value_node (t)), xx_part (q));
mp_install (mp, ty_part (value_node (t)), ty_part (q));
mp_install (mp, tx_part (value_node (t)), tx_part (q));
break;
default: /* there are no other valid cases, but please the compiler */
break;
}
set_cur_exp_node (t);
break;
case mp_dependent:
case mp_proto_dependent:
mp_encapsulate (mp,
mp_copy_dep_list (mp,
(mp_value_node) dep_list ((mp_value_node)
p)));
break;
case mp_numeric_type:
mp_new_indep (mp, p);
goto RESTART;
break;
case mp_independent:
q = mp_single_dependency (mp, p);
if (q == mp->dep_final) {
mp->cur_exp.type = mp_known;
set_cur_exp_value_number (zero_t);
mp_free_dep_node (mp, q);
} else {
mp->cur_exp.type = mp_dependent;
mp_encapsulate (mp, q);
}
break;
default:
mp_confusion (mp, "copy");
@:this can't happen copy}{\quad copy@>;
break;
}
}
@ The |encapsulate| subroutine assumes that |dep_final| is the
tail of dependency list~|p|.
@<Declare subroutines needed by |make_exp_copy|@>=
static void mp_encapsulate (MP mp, mp_value_node p) {
mp_node q = mp_get_value_node (mp);
FUNCTION_TRACE2 ("mp_encapsulate(%p)\n", p);
mp_name_type (q) = mp_capsule;
mp_new_dep (mp, q, mp->cur_exp.type, p);
set_cur_exp_node (q);
}
@ The |install| procedure copies a numeric field~|q| into field~|r| of
a big node that will be part of a capsule.
@<Declare subroutines needed by |make_exp_copy|@>=
static void mp_install (MP mp, mp_node r, mp_node q) {
mp_value_node p; /* temporary register */
if (mp_type (q) == mp_known) {
mp_type (r) = mp_known;
set_value_number (r, value_number (q));
} else if (mp_type (q) == mp_independent) {
p = mp_single_dependency (mp, q);
if (p == mp->dep_final) {
mp_type (r) = mp_known;
set_value_number (r, zero_t);
mp_free_dep_node (mp, p);
} else {
mp_new_dep (mp, r, mp_dependent, p);
}
} else {
mp_new_dep (mp, r, mp_type (q),
mp_copy_dep_list (mp, (mp_value_node) dep_list ((mp_value_node)
q)));
}
}
@ Here is a comparatively simple routine that is used to scan the
\&{suffix} parameters of a macro.
@<Declare the basic parsing subroutines@>=
static void mp_scan_suffix (MP mp) {
mp_node h, t; /* head and tail of the list being built */
mp_node p; /* temporary register */
h = mp_get_symbolic_node (mp);
t = h;
while (1) {
if (cur_cmd() == mp_left_bracket) {
/* Scan a bracketed subscript and set |cur_cmd:=numeric_token| */
mp_get_x_next (mp);
mp_scan_expression (mp);
if (mp->cur_exp.type != mp_known)
mp_bad_subscript (mp);
if (cur_cmd() != mp_right_bracket) {
const char *hlp[] = {
"I've seen a `[' and a subscript value, in a suffix,",
"so a right bracket should have come next.",
"I shall pretend that one was there.",
NULL };
mp_back_error (mp, "Missing `]' has been inserted", hlp, true);
}
set_cur_cmd((mp_variable_type)mp_numeric_token);
set_cur_mod_number(cur_exp_value_number ());
}
if (cur_cmd() == mp_numeric_token) {
mp_number arg1;
new_number (arg1);
number_clone (arg1, cur_mod_number());
p = mp_new_num_tok (mp, arg1);
free_number (arg1);
} else if ((cur_cmd() == mp_tag_token) || (cur_cmd() == mp_internal_quantity)) {
p = mp_get_symbolic_node (mp);
set_mp_sym_sym (p, cur_sym());
mp_name_type (p) = cur_sym_mod();
} else {
break;
}
mp_link (t) = p;
t = p;
mp_get_x_next (mp);
}
set_cur_exp_node (mp_link (h));
mp_free_symbolic_node (mp, h);
mp->cur_exp.type = mp_token_list;
}
@* Parsing secondary and higher expressions.
After the intricacies of |scan_primary|\kern-1pt,
the |scan_secondary| routine is
refreshingly simple. It's not trivial, but the operations are relatively
straightforward; the main difficulty is, again, that expressions and data
structures might change drastically every time we call |get_x_next|, so a
cautious approach is mandatory. For example, a macro defined by
\&{primarydef} might have disappeared by the time its second argument has
been scanned; we solve this by increasing the reference count of its token
list, so that the macro can be called even after it has been clobbered.
@<Declare the basic parsing subroutines@>=
static void mp_scan_secondary (MP mp) {
mp_node p; /* for list manipulation */
halfword c, d; /* operation codes or modifiers */
mp_node cc = NULL;
mp_sym mac_name = NULL; /* token defined with \&{primarydef} */
RESTART:
if ((cur_cmd() < mp_min_primary_command) ||
(cur_cmd() > mp_max_primary_command))
mp_bad_exp (mp, "A secondary");
@.A secondary expression...@>;
mp_scan_primary (mp);
CONTINUE:
if (cur_cmd() <= mp_max_secondary_command &&
cur_cmd() >= mp_min_secondary_command) {
p = mp_stash_cur_exp (mp);
d = cur_cmd();
c = cur_mod();
if (d == mp_secondary_primary_macro) {
cc = cur_mod_node();
mac_name = cur_sym();
add_mac_ref (cc);
}
mp_get_x_next (mp);
mp_scan_primary (mp);
if (d != mp_secondary_primary_macro) {
mp_do_binary (mp, p, c);
} else {
mp_back_input (mp);
mp_binary_mac (mp, p, cc, mac_name);
decr_mac_ref (cc);
mp_get_x_next (mp);
goto RESTART;
}
goto CONTINUE;
}
}
@ The following procedure calls a macro that has two parameters,
|p| and |cur_exp|.
@c
static void mp_binary_mac (MP mp, mp_node p, mp_node c, mp_sym n) {
mp_node q, r; /* nodes in the parameter list */
q = mp_get_symbolic_node (mp);
r = mp_get_symbolic_node (mp);
mp_link (q) = r;
set_mp_sym_sym (q, p);
set_mp_sym_sym (r, mp_stash_cur_exp (mp));
mp_macro_call (mp, c, q, n);
}
@ The next procedure, |scan_tertiary|, is pretty much the same deal.
@<Declare the basic parsing subroutines@>=
static void mp_scan_tertiary (MP mp) {
mp_node p; /* for list manipulation */
halfword c, d; /* operation codes or modifiers */
mp_node cc = NULL;
mp_sym mac_name = NULL; /* token defined with \&{secondarydef} */
RESTART:
if ((cur_cmd() < mp_min_primary_command) ||
(cur_cmd() > mp_max_primary_command))
mp_bad_exp (mp, "A tertiary");
@.A tertiary expression...@>;
mp_scan_secondary (mp);
CONTINUE:
if (cur_cmd() <= mp_max_tertiary_command) {
if (cur_cmd() >= mp_min_tertiary_command) {
p = mp_stash_cur_exp (mp);
c = cur_mod();
d = cur_cmd();
if (d == mp_tertiary_secondary_macro) {
cc = cur_mod_node();
mac_name = cur_sym();
add_mac_ref (cc);
}
mp_get_x_next (mp);
mp_scan_secondary (mp);
if (d != mp_tertiary_secondary_macro) {
mp_do_binary (mp, p, c);
} else {
mp_back_input (mp);
mp_binary_mac (mp, p, cc, mac_name);
decr_mac_ref (cc);
mp_get_x_next (mp);
goto RESTART;
}
goto CONTINUE;
}
}
}
@ Finally we reach the deepest level in our quartet of parsing routines.
This one is much like the others; but it has an extra complication from
paths, which materialize here.
@<Declare the basic parsing subroutines@>=
static int mp_scan_path (MP mp);
static void mp_scan_expression (MP mp) {
int my_var_flag; /* initial value of |var_flag| */
my_var_flag = mp->var_flag;
check_expansion_depth();
RESTART:
if ((cur_cmd() < mp_min_primary_command) ||
(cur_cmd() > mp_max_primary_command))
mp_bad_exp (mp, "An");
@.An expression...@>;
mp_scan_tertiary (mp);
CONTINUE:
if (cur_cmd() <= mp_max_expression_command) {
if (cur_cmd() >= mp_min_expression_command) {
if ((cur_cmd() != mp_equals) || (my_var_flag != mp_assignment)) {
mp_node p; /* for list manipulation */
mp_node cc = NULL;
halfword c;
halfword d; /* operation codes or modifiers */
mp_sym mac_name; /* token defined with \&{tertiarydef} */
mac_name = NULL;
p = mp_stash_cur_exp (mp);
d = cur_cmd();
c = cur_mod();
if (d == mp_expression_tertiary_macro) {
cc = cur_mod_node();
mac_name = cur_sym();
add_mac_ref (cc);
}
if ((d < mp_ampersand) || ((d == mp_ampersand) &&
((mp_type (p) == mp_pair_type)
|| (mp_type (p) == mp_path_type)))) {
/* Scan a path construction operation; but |return| if |p| has the wrong type */
mp_unstash_cur_exp (mp, p);
if (!mp_scan_path(mp)) {
mp->expand_depth_count--;
return;
}
} else {
mp_get_x_next (mp);
mp_scan_tertiary (mp);
if (d != mp_expression_tertiary_macro) {
mp_do_binary (mp, p, c);
} else {
mp_back_input (mp);
mp_binary_mac (mp, p, cc, mac_name);
decr_mac_ref (cc);
mp_get_x_next (mp);
goto RESTART;
}
}
goto CONTINUE;
}
}
}
mp->expand_depth_count--;
}
@ The reader should review the data structure conventions for paths before
hoping to understand the next part of this code.
@d min_tension three_quarter_unit_t
@<Declare the basic parsing subroutines@>=
static void force_valid_tension_setting(MP mp) {
if ((mp->cur_exp.type != mp_known) || number_less(cur_exp_value_number (), min_tension)) {
mp_value new_expr;
const char *hlp[] = {
"The expression above should have been a number >=3/4.",
NULL };
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
mp_disp_err(mp, NULL);
number_clone(new_expr.data.n, unity_t);
mp_back_error (mp, "Improper tension has been set to 1", hlp, true);
mp_get_x_next (mp);
mp_flush_cur_exp (mp, new_expr);
}
}
static int mp_scan_path (MP mp) {
mp_knot path_p, path_q, r;
mp_knot pp, qq;
halfword d; /* operation code or modifier */
boolean cycle_hit; /* did a path expression just end with `\&{cycle}'? */
mp_number x, y; /* explicit coordinates or tension at a path join */
int t; /* knot type following a path join */
t = 0;
cycle_hit = false;
/* Convert the left operand, |p|, into a partial path ending at~|q|;
but |return| if |p| doesn't have a suitable type */
if (mp->cur_exp.type == mp_pair_type)
path_p = mp_pair_to_knot (mp);
else if (mp->cur_exp.type == mp_path_type)
path_p = cur_exp_knot ();
else
return 0;
path_q = path_p;
while (mp_next_knot (path_q) != path_p)
path_q = mp_next_knot (path_q);
if (mp_left_type (path_p) != mp_endpoint) { /* open up a cycle */
r = mp_copy_knot (mp, path_p);
mp_next_knot (path_q) = r;
path_q = r;
}
mp_left_type (path_p) = mp_open;
mp_right_type (path_q) = mp_open;
new_number (y);
new_number (x);
CONTINUE_PATH:
/* Determine the path join parameters;
but |goto finish_path| if there's only a direction specifier */
/* At this point |cur_cmd| is either |ampersand|, |left_brace|, or |path_join|. */
if (cur_cmd() == mp_left_brace) {
/* Put the pre-join direction information into node |q| */
/* At this point |mp_right_type(q)| is usually |open|, but it may have been
set to some other value by a previous operation. We must maintain
the value of |mp_right_type(q)| in cases such as
`\.{..\{curl2\}z\{0,0\}..}'. */
t = mp_scan_direction (mp);
if (t != mp_open) {
mp_right_type (path_q) = (unsigned short) t;
number_clone(path_q->right_given, cur_exp_value_number ());
if (mp_left_type (path_q) == mp_open) {
mp_left_type (path_q) = (unsigned short) t;
number_clone(path_q->left_given, cur_exp_value_number ());
} /* note that |left_given(q)=left_curl(q)| */
}
}
d = cur_cmd();
if (d == mp_path_join) {
/* Determine the tension and/or control points */
mp_get_x_next (mp);
if (cur_cmd() == mp_tension) {
/* Set explicit tensions */
mp_get_x_next (mp);
set_number_from_scaled (y, cur_cmd());
if (cur_cmd() == mp_at_least)
mp_get_x_next (mp);
mp_scan_primary (mp);
force_valid_tension_setting(mp);
if (number_to_scaled (y) == mp_at_least) {
if (is_number(cur_exp_value_number()))
number_negate (cur_exp_value_number());
}
number_clone(path_q->right_tension, cur_exp_value_number ());
if (cur_cmd() == mp_and_command) {
mp_get_x_next (mp);
set_number_from_scaled (y, cur_cmd());
if (cur_cmd() == mp_at_least)
mp_get_x_next (mp);
mp_scan_primary (mp);
force_valid_tension_setting(mp);
if (number_to_scaled (y) == mp_at_least) {
if (is_number(cur_exp_value_number()))
number_negate (cur_exp_value_number());
}
}
number_clone (y, cur_exp_value_number ());
} else if (cur_cmd() == mp_controls) {
/* Set explicit control points */
mp_right_type (path_q) = mp_explicit;
t = mp_explicit;
mp_get_x_next (mp);
mp_scan_primary (mp);
mp_known_pair (mp);
number_clone (path_q->right_x, mp->cur_x);
number_clone (path_q->right_y, mp->cur_y);
if (cur_cmd() != mp_and_command) {
number_clone (x, path_q->right_x);
number_clone (y, path_q->right_y);
} else {
mp_get_x_next (mp);
mp_scan_primary (mp);
mp_known_pair (mp);
number_clone (x, mp->cur_x);
number_clone (y, mp->cur_y);
}
} else {
set_number_to_unity(path_q->right_tension);
set_number_to_unity(y);
mp_back_input (mp); /* default tension */
goto DONE;
};
if (cur_cmd() != mp_path_join) {
const char *hlp[] = { "A path join command should end with two dots.", NULL};
mp_back_error (mp, "Missing `..' has been inserted", hlp, true);
}
DONE:
;
} else if (d != mp_ampersand) {
goto FINISH_PATH;
}
mp_get_x_next (mp);
if (cur_cmd() == mp_left_brace) {
/* Put the post-join direction information into |x| and |t| */
/* Since |left_tension| and |mp_left_y| share the same position in knot nodes,
and since |left_given| is similarly equivalent to |left_x|, we use
|x| and |y| to hold the given direction and tension information when
there are no explicit control points. */
t = mp_scan_direction (mp);
if (mp_right_type (path_q) != mp_explicit)
number_clone (x, cur_exp_value_number ());
else
t = mp_explicit; /* the direction information is superfluous */
} else if (mp_right_type (path_q) != mp_explicit) {
t = mp_open;
set_number_to_zero(x);
}
if (cur_cmd() == mp_cycle) {
/* Get ready to close a cycle */
/* If a person tries to define an entire path by saying `\.{(x,y)\&cycle}',
we silently change the specification to `\.{(x,y)..cycle}', since a cycle
shouldn't have length zero. */
cycle_hit = true;
mp_get_x_next (mp);
pp = path_p;
qq = path_p;
if (d == mp_ampersand) {
if (path_p == path_q) {
d = mp_path_join;
set_number_to_unity(path_q->right_tension);
set_number_to_unity(y);
}
}
} else {
mp_scan_tertiary (mp);
/* Convert the right operand, |cur_exp|,
into a partial path from |pp| to~|qq| */
if (mp->cur_exp.type != mp_path_type)
pp = mp_pair_to_knot (mp);
else
pp = cur_exp_knot ();
qq = pp;
while (mp_next_knot (qq) != pp)
qq = mp_next_knot (qq);
if (mp_left_type (pp) != mp_endpoint) { /* open up a cycle */
r = mp_copy_knot (mp, pp);
mp_next_knot (qq) = r;
qq = r;
}
mp_left_type (pp) = mp_open;
mp_right_type (qq) = mp_open;
}
/* Join the partial paths and reset |p| and |q| to the head and tail
of the result */
if (d == mp_ampersand) {
if (!(number_equal (path_q->x_coord, pp->x_coord)) ||
!(number_equal (path_q->y_coord, pp->y_coord))) {
const char *hlp[] = {
"When you join paths `p&q', the ending point of p",
"must be exactly equal to the starting point of q.",
"So I'm going to pretend that you said `p..q' instead.",
NULL };
mp_back_error (mp, "Paths don't touch; `&' will be changed to `..'", hlp, true);
@.Paths don't touch@>;
mp_get_x_next (mp);
d = mp_path_join;
set_number_to_unity (path_q->right_tension);
set_number_to_unity (y);
}
}
/* Plug an opening in |mp_right_type(pp)|, if possible */
if (mp_right_type (pp) == mp_open) {
if ((t == mp_curl) || (t == mp_given)) {
mp_right_type (pp) = (unsigned short) t;
number_clone (pp->right_given, x);
}
}
if (d == mp_ampersand) {
/* Splice independent paths together */
if (mp_left_type (path_q) == mp_open)
if (mp_right_type (path_q) == mp_open) {
mp_left_type (path_q) = mp_curl;
set_number_to_unity(path_q->left_curl);
}
if (mp_right_type (pp) == mp_open)
if (t == mp_open) {
mp_right_type (pp) = mp_curl;
set_number_to_unity(pp->right_curl);
}
mp_right_type (path_q) = mp_right_type (pp);
mp_next_knot (path_q) = mp_next_knot (pp);
number_clone (path_q->right_x, pp->right_x);
number_clone (path_q->right_y, pp->right_y);
mp_xfree (pp);
if (qq == pp)
qq = path_q;
} else {
/* Plug an opening in |mp_right_type(q)|, if possible */
if (mp_right_type (path_q) == mp_open) {
if ((mp_left_type (path_q) == mp_curl) || (mp_left_type (path_q) == mp_given)) {
mp_right_type (path_q) = mp_left_type (path_q);
number_clone(path_q->right_given, path_q->left_given);
}
}
mp_next_knot (path_q) = pp;
number_clone (pp->left_y, y);
if (t != mp_open) {
number_clone (pp->left_x, x);
mp_left_type (pp) = (unsigned short) t;
};
}
path_q = qq;
if (cur_cmd() >= mp_min_expression_command)
if (cur_cmd() <= mp_ampersand)
if (!cycle_hit)
goto CONTINUE_PATH;
FINISH_PATH:
/* Choose control points for the path and put the result into |cur_exp| */
if (cycle_hit) {
if (d == mp_ampersand)
path_p = path_q;
} else {
mp_left_type (path_p) = mp_endpoint;
if (mp_right_type (path_p) == mp_open) {
mp_right_type (path_p) = mp_curl;
set_number_to_unity(path_p->right_curl);
}
mp_right_type (path_q) = mp_endpoint;
if (mp_left_type (path_q) == mp_open) {
mp_left_type (path_q) = mp_curl;
set_number_to_unity(path_q->left_curl);
}
mp_next_knot (path_q) = path_p;
}
mp_make_choices (mp, path_p);
mp->cur_exp.type = mp_path_type;
set_cur_exp_knot (path_p);
free_number (x);
free_number (y);
return 1;
}
@ A pair of numeric values is changed into a knot node for a one-point path
when \MP\ discovers that the pair is part of a path.
@c
static mp_knot mp_pair_to_knot (MP mp) { /* convert a pair to a knot with two endpoints */
mp_knot q; /* the new node */
q = mp_new_knot(mp);
mp_left_type (q) = mp_endpoint;
mp_right_type (q) = mp_endpoint;
mp_originator (q) = mp_metapost_user;
mp_next_knot (q) = q;
mp_known_pair (mp);
number_clone (q->x_coord, mp->cur_x);
number_clone (q->y_coord, mp->cur_y);
return q;
}
@ The |known_pair| subroutine sets |cur_x| and |cur_y| to the components
of the current expression, assuming that the current expression is a
pair of known numerics. Unknown components are zeroed, and the
current expression is flushed.
@<Declarations@>=
static void mp_known_pair (MP mp);
@ @c
void mp_known_pair (MP mp) {
mp_value new_expr;
mp_node p; /* the pair node */
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
if (mp->cur_exp.type != mp_pair_type) {
const char *hlp[] = {
"I need x and y numbers for this part of the path.",
"The value I found (see above) was no good;",
"so I'll try to keep going by using zero instead.",
"(Chapter 27 of The METAFONTbook explains that",
"you might want to type `I ??" "?' now.)",
NULL };
mp_disp_err(mp, NULL);
mp_back_error (mp, "Undefined coordinates have been replaced by (0,0)", hlp, true);
mp_get_x_next (mp);
mp_flush_cur_exp (mp, new_expr);
set_number_to_zero(mp->cur_x);
set_number_to_zero(mp->cur_y);
} else {
p = value_node (cur_exp_node ());
/* Make sure that both |x| and |y| parts of |p| are known;
copy them into |cur_x| and |cur_y| */
if (mp_type (x_part (p)) == mp_known) {
number_clone(mp->cur_x, value_number (x_part (p)));
} else {
const char *hlp[] = {
"I need a `known' x value for this part of the path.",
"The value I found (see above) was no good;",
"so I'll try to keep going by using zero instead.",
"(Chapter 27 of The METAFONTbook explains that",
"you might want to type `I ??" "?' now.)",
NULL };
mp_disp_err (mp, x_part (p));
mp_back_error (mp, "Undefined x coordinate has been replaced by 0", hlp, true);
mp_get_x_next (mp);
mp_recycle_value (mp, x_part (p));
set_number_to_zero(mp->cur_x);
}
if (mp_type (y_part (p)) == mp_known) {
number_clone(mp->cur_y, value_number (y_part (p)));
} else {
const char *hlp[] = {
"I need a `known' y value for this part of the path.",
"The value I found (see above) was no good;",
"so I'll try to keep going by using zero instead.",
"(Chapter 27 of The METAFONTbook explains that",
"you might want to type `I ??" "?' now.)",
NULL };
mp_disp_err (mp, y_part (p));
mp_back_error (mp, "Undefined y coordinate has been replaced by 0", hlp, true);
mp_get_x_next (mp);
mp_recycle_value (mp, y_part (p));
set_number_to_zero(mp->cur_y);
}
mp_flush_cur_exp (mp, new_expr);
}
}
@ The |scan_direction| subroutine looks at the directional information
that is enclosed in braces, and also scans ahead to the following character.
A type code is returned, either |open| (if the direction was $(0,0)$),
or |curl| (if the direction was a curl of known value |cur_exp|), or
|given| (if the direction is given by the |angle| value that now
appears in |cur_exp|).
There's nothing difficult about this subroutine, but the program is rather
lengthy because a variety of potential errors need to be nipped in the bud.
@c
static quarterword mp_scan_direction (MP mp) {
int t; /* the type of information found */
mp_get_x_next (mp);
if (cur_cmd() == mp_curl_command) {
/* Scan a curl specification */
mp_get_x_next (mp);
mp_scan_expression (mp);
if ((mp->cur_exp.type != mp_known) || (number_negative(cur_exp_value_number ()))) {
mp_value new_expr;
const char *hlp[] = { "A curl must be a known, nonnegative number.", NULL };
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
set_number_to_unity(new_expr.data.n);
mp_disp_err(mp, NULL);
mp_back_error (mp, "Improper curl has been replaced by 1", hlp, true);
mp_get_x_next (mp);
mp_flush_cur_exp (mp, new_expr);
}
t = mp_curl;
} else {
/* Scan a given direction */
mp_scan_expression (mp);
if (mp->cur_exp.type > mp_pair_type) {
/* Get given directions separated by commas */
mp_number xx;
new_number(xx);
if (mp->cur_exp.type != mp_known) {
mp_value new_expr;
const char *hlp[] = {
"I need a `known' x value for this part of the path.",
"The value I found (see above) was no good;",
"so I'll try to keep going by using zero instead.",
"(Chapter 27 of The METAFONTbook explains that",
"you might want to type `I ??" "?' now.)",
NULL };
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
set_number_to_zero(new_expr.data.n);
mp_disp_err(mp, NULL);
mp_back_error (mp, "Undefined x coordinate has been replaced by 0", hlp, true);
mp_get_x_next (mp);
mp_flush_cur_exp (mp, new_expr);
}
number_clone(xx, cur_exp_value_number ());
if (cur_cmd() != mp_comma) {
const char *hlp[] = {
"I've got the x coordinate of a path direction;",
"will look for the y coordinate next.",
NULL };
mp_back_error (mp, "Missing `,' has been inserted", hlp, true);
}
mp_get_x_next (mp);
mp_scan_expression (mp);
if (mp->cur_exp.type != mp_known) {
mp_value new_expr;
const char *hlp[] = {
"I need a `known' y value for this part of the path.",
"The value I found (see above) was no good;",
"so I'll try to keep going by using zero instead.",
"(Chapter 27 of The METAFONTbook explains that",
"you might want to type `I ??" "?' now.)",
NULL };
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
set_number_to_zero(new_expr.data.n);
mp_disp_err(mp, NULL);
mp_back_error (mp, "Undefined y coordinate has been replaced by 0", hlp, true);
mp_get_x_next (mp);
mp_flush_cur_exp (mp, new_expr);
}
number_clone(mp->cur_y, cur_exp_value_number ());
number_clone(mp->cur_x, xx);
free_number(xx);
} else {
mp_known_pair (mp);
}
if (number_zero(mp->cur_x) && number_zero(mp->cur_y))
t = mp_open;
else {
mp_number narg;
new_angle (narg);
n_arg (narg, mp->cur_x, mp->cur_y);
t = mp_given;
set_cur_exp_value_number (narg);
free_number (narg);
}
}
if (cur_cmd() != mp_right_brace) {
const char *hlp[] = {
"I've scanned a direction spec for part of a path,",
"so a right brace should have come next.",
"I shall pretend that one was there.",
NULL };
mp_back_error (mp, "Missing `}' has been inserted", hlp, true);
}
mp_get_x_next (mp);
return (quarterword) t;
}
@ Finally, we sometimes need to scan an expression whose value is
supposed to be either |true_code| or |false_code|.
@d mp_get_boolean(mp) do {
mp_get_x_next (mp);
mp_scan_expression (mp);
if (mp->cur_exp.type != mp_boolean_type) {
do_boolean_error(mp);
}
} while (0)
@<Declare the basic parsing subroutines@>=
static void do_boolean_error (MP mp) {
mp_value new_expr;
const char *hlp[] = {
"The expression shown above should have had a definite",
"true-or-false value. I'm changing it to `false'.",
NULL };
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
mp_disp_err(mp, NULL);
set_number_from_boolean (new_expr.data.n, mp_false_code);
mp_back_error (mp, "Undefined condition will be treated as `false'", hlp, true);
mp_get_x_next (mp);
mp_flush_cur_exp (mp, new_expr);
mp->cur_exp.type = mp_boolean_type;
}
@ @<Declarations@>=
static void do_boolean_error (MP mp);
@* Doing the operations.
The purpose of parsing is primarily to permit people to avoid piles of
parentheses. But the real work is done after the structure of an expression
has been recognized; that's when new expressions are generated. We
turn now to the guts of \MP, which handles individual operators that
have come through the parsing mechanism.
We'll start with the easy ones that take no operands, then work our way
up to operators with one and ultimately two arguments. In other words,
we will write the three procedures |do_nullary|, |do_unary|, and |do_binary|
that are invoked periodically by the expression scanners.
First let's make sure that all of the primitive operators are in the
hash table. Although |scan_primary| and its relatives made use of the
\\{cmd} code for these operators, the \\{do} routines base everything
on the \\{mod} code. For example, |do_binary| doesn't care whether the
operation it performs is a |primary_binary| or |secondary_binary|, etc.
@<Put each...@>=
mp_primitive (mp, "true", mp_nullary, mp_true_code);
@:true_}{\&{true} primitive@>;
mp_primitive (mp, "false", mp_nullary, mp_false_code);
@:false_}{\&{false} primitive@>;
mp_primitive (mp, "nullpicture", mp_nullary, mp_null_picture_code);
@:null_picture_}{\&{nullpicture} primitive@>;
mp_primitive (mp, "nullpen", mp_nullary, mp_null_pen_code);
@:null_pen_}{\&{nullpen} primitive@>;
mp_primitive (mp, "readstring", mp_nullary, mp_read_string_op);
@:read_string_}{\&{readstring} primitive@>;
mp_primitive (mp, "pencircle", mp_nullary, mp_pen_circle);
@:pen_circle_}{\&{pencircle} primitive@>;
mp_primitive (mp, "normaldeviate", mp_nullary, mp_normal_deviate);
@:normal_deviate_}{\&{normaldeviate} primitive@>;
mp_primitive (mp, "readfrom", mp_unary, mp_read_from_op);
@:read_from_}{\&{readfrom} primitive@>;
mp_primitive (mp, "closefrom", mp_unary, mp_close_from_op);
@:close_from_}{\&{closefrom} primitive@>;
mp_primitive (mp, "odd", mp_unary, mp_odd_op);
@:odd_}{\&{odd} primitive@>;
mp_primitive (mp, "known", mp_unary, mp_known_op);
@:known_}{\&{known} primitive@>;
mp_primitive (mp, "unknown", mp_unary, mp_unknown_op);
@:unknown_}{\&{unknown} primitive@>;
mp_primitive (mp, "not", mp_unary, mp_not_op);
@:not_}{\&{not} primitive@>;
mp_primitive (mp, "decimal", mp_unary, mp_decimal);
@:decimal_}{\&{decimal} primitive@>;
mp_primitive (mp, "reverse", mp_unary, mp_reverse);
@:reverse_}{\&{reverse} primitive@>;
mp_primitive (mp, "makepath", mp_unary, mp_make_path_op);
@:make_path_}{\&{makepath} primitive@>;
mp_primitive (mp, "makepen", mp_unary, mp_make_pen_op);
@:make_pen_}{\&{makepen} primitive@>;
mp_primitive (mp, "oct", mp_unary, mp_oct_op);
@:oct_}{\&{oct} primitive@>;
mp_primitive (mp, "hex", mp_unary, mp_hex_op);
@:hex_}{\&{hex} primitive@>;
mp_primitive (mp, "ASCII", mp_unary, mp_ASCII_op);
@:ASCII_}{\&{ASCII} primitive@>;
mp_primitive (mp, "char", mp_unary, mp_char_op);
@:char_}{\&{char} primitive@>;
mp_primitive (mp, "length", mp_unary, mp_length_op);
@:length_}{\&{length} primitive@>;
mp_primitive (mp, "turningnumber", mp_unary, mp_turning_op);
@:turning_number_}{\&{turningnumber} primitive@>;
mp_primitive (mp, "xpart", mp_unary, mp_x_part);
@:x_part_}{\&{xpart} primitive@>;
mp_primitive (mp, "ypart", mp_unary, mp_y_part);
@:y_part_}{\&{ypart} primitive@>;
mp_primitive (mp, "xxpart", mp_unary, mp_xx_part);
@:xx_part_}{\&{xxpart} primitive@>;
mp_primitive (mp, "xypart", mp_unary, mp_xy_part);
@:xy_part_}{\&{xypart} primitive@>;
mp_primitive (mp, "yxpart", mp_unary, mp_yx_part);
@:yx_part_}{\&{yxpart} primitive@>;
mp_primitive (mp, "yypart", mp_unary, mp_yy_part);
@:yy_part_}{\&{yypart} primitive@>;
mp_primitive (mp, "redpart", mp_unary, mp_red_part);
@:red_part_}{\&{redpart} primitive@>;
mp_primitive (mp, "greenpart", mp_unary, mp_green_part);
@:green_part_}{\&{greenpart} primitive@>;
mp_primitive (mp, "bluepart", mp_unary, mp_blue_part);
@:blue_part_}{\&{bluepart} primitive@>;
mp_primitive (mp, "cyanpart", mp_unary, mp_cyan_part);
@:cyan_part_}{\&{cyanpart} primitive@>;
mp_primitive (mp, "magentapart", mp_unary, mp_magenta_part);
@:magenta_part_}{\&{magentapart} primitive@>;
mp_primitive (mp, "yellowpart", mp_unary, mp_yellow_part);
@:yellow_part_}{\&{yellowpart} primitive@>;
mp_primitive (mp, "blackpart", mp_unary, mp_black_part);
@:black_part_}{\&{blackpart} primitive@>;
mp_primitive (mp, "greypart", mp_unary, mp_grey_part);
@:grey_part_}{\&{greypart} primitive@>;
mp_primitive (mp, "colormodel", mp_unary, mp_color_model_part);
@:color_model_part_}{\&{colormodel} primitive@>;
mp_primitive (mp, "fontpart", mp_unary, mp_font_part);
@:font_part_}{\&{fontpart} primitive@>;
mp_primitive (mp, "textpart", mp_unary, mp_text_part);
@:text_part_}{\&{textpart} primitive@>;
mp_primitive (mp, "prescriptpart", mp_unary, mp_prescript_part);
@:prescript_part_}{\&{prescriptpart} primitive@>;
mp_primitive (mp, "postscriptpart", mp_unary, mp_postscript_part);
@:postscript_part_}{\&{postscriptpart} primitive@>;
mp_primitive (mp, "pathpart", mp_unary, mp_path_part);
@:path_part_}{\&{pathpart} primitive@>;
mp_primitive (mp, "penpart", mp_unary, mp_pen_part);
@:pen_part_}{\&{penpart} primitive@>;
mp_primitive (mp, "dashpart", mp_unary, mp_dash_part);
@:dash_part_}{\&{dashpart} primitive@>;
mp_primitive (mp, "sqrt", mp_unary, mp_sqrt_op);
@:sqrt_}{\&{sqrt} primitive@>;
mp_primitive (mp, "mexp", mp_unary, mp_m_exp_op);
@:m_exp_}{\&{mexp} primitive@>;
mp_primitive (mp, "mlog", mp_unary, mp_m_log_op);
@:m_log_}{\&{mlog} primitive@>;
mp_primitive (mp, "sind", mp_unary, mp_sin_d_op);
@:sin_d_}{\&{sind} primitive@>;
mp_primitive (mp, "cosd", mp_unary, mp_cos_d_op);
@:cos_d_}{\&{cosd} primitive@>;
mp_primitive (mp, "floor", mp_unary, mp_floor_op);
@:floor_}{\&{floor} primitive@>;
mp_primitive (mp, "uniformdeviate", mp_unary, mp_uniform_deviate);
@:uniform_deviate_}{\&{uniformdeviate} primitive@>;
mp_primitive (mp, "charexists", mp_unary, mp_char_exists_op);
@:char_exists_}{\&{charexists} primitive@>;
mp_primitive (mp, "fontsize", mp_unary, mp_font_size);
@:font_size_}{\&{fontsize} primitive@>;
mp_primitive (mp, "llcorner", mp_unary, mp_ll_corner_op);
@:ll_corner_}{\&{llcorner} primitive@>;
mp_primitive (mp, "lrcorner", mp_unary, mp_lr_corner_op);
@:lr_corner_}{\&{lrcorner} primitive@>;
mp_primitive (mp, "ulcorner", mp_unary, mp_ul_corner_op);
@:ul_corner_}{\&{ulcorner} primitive@>;
mp_primitive (mp, "urcorner", mp_unary, mp_ur_corner_op);
@:ur_corner_}{\&{urcorner} primitive@>;
mp_primitive (mp, "arclength", mp_unary, mp_arc_length);
@:arc_length_}{\&{arclength} primitive@>;
mp_primitive (mp, "angle", mp_unary, mp_angle_op);
@:angle_}{\&{angle} primitive@>;
mp_primitive (mp, "cycle", mp_cycle, mp_cycle_op);
@:cycle_}{\&{cycle} primitive@>;
mp_primitive (mp, "stroked", mp_unary, mp_stroked_op);
@:stroked_}{\&{stroked} primitive@>;
mp_primitive (mp, "filled", mp_unary, mp_filled_op);
@:filled_}{\&{filled} primitive@>;
mp_primitive (mp, "textual", mp_unary, mp_textual_op);
@:textual_}{\&{textual} primitive@>;
mp_primitive (mp, "clipped", mp_unary, mp_clipped_op);
@:clipped_}{\&{clipped} primitive@>;
mp_primitive (mp, "bounded", mp_unary, mp_bounded_op);
@:bounded_}{\&{bounded} primitive@>;
mp_primitive (mp, "+", mp_plus_or_minus, mp_plus);
@:+ }{\.{+} primitive@>;
mp_primitive (mp, "-", mp_plus_or_minus, mp_minus);
@:- }{\.{-} primitive@>;
mp_primitive (mp, "*", mp_secondary_binary, mp_times);
@:* }{\.{*} primitive@>;
mp_primitive (mp, "/", mp_slash, mp_over);
mp->frozen_slash = mp_frozen_primitive (mp, "/", mp_slash, mp_over);
@:/ }{\.{/} primitive@>;
mp_primitive (mp, "++", mp_tertiary_binary, mp_pythag_add);
@:++_}{\.{++} primitive@>;
mp_primitive (mp, "+-+", mp_tertiary_binary, mp_pythag_sub);
@:+-+_}{\.{+-+} primitive@>;
mp_primitive (mp, "or", mp_tertiary_binary, mp_or_op);
@:or_}{\&{or} primitive@>;
mp_primitive (mp, "and", mp_and_command, mp_and_op);
@:and_}{\&{and} primitive@>;
mp_primitive (mp, "<", mp_expression_binary, mp_less_than);
@:< }{\.{<} primitive@>;
mp_primitive (mp, "<=", mp_expression_binary, mp_less_or_equal);
@:<=_}{\.{<=} primitive@>;
mp_primitive (mp, ">", mp_expression_binary, mp_greater_than);
@:> }{\.{>} primitive@>;
mp_primitive (mp, ">=", mp_expression_binary, mp_greater_or_equal);
@:>=_}{\.{>=} primitive@>;
mp_primitive (mp, "=", mp_equals, mp_equal_to);
@:= }{\.{=} primitive@>;
mp_primitive (mp, "<>", mp_expression_binary, mp_unequal_to);
@:<>_}{\.{<>} primitive@>;
mp_primitive (mp, "substring", mp_primary_binary, mp_substring_of);
@:substring_}{\&{substring} primitive@>;
mp_primitive (mp, "subpath", mp_primary_binary, mp_subpath_of);
@:subpath_}{\&{subpath} primitive@>;
mp_primitive (mp, "directiontime", mp_primary_binary, mp_direction_time_of);
@:direction_time_}{\&{directiontime} primitive@>;
mp_primitive (mp, "point", mp_primary_binary, mp_point_of);
@:point_}{\&{point} primitive@>;
mp_primitive (mp, "precontrol", mp_primary_binary, mp_precontrol_of);
@:precontrol_}{\&{precontrol} primitive@>;
mp_primitive (mp, "postcontrol", mp_primary_binary, mp_postcontrol_of);
@:postcontrol_}{\&{postcontrol} primitive@>;
mp_primitive (mp, "penoffset", mp_primary_binary, mp_pen_offset_of);
@:pen_offset_}{\&{penoffset} primitive@>;
mp_primitive (mp, "arctime", mp_primary_binary, mp_arc_time_of);
@:arc_time_of_}{\&{arctime} primitive@>;
mp_primitive (mp, "mpversion", mp_nullary, mp_version);
@:mp_verison_}{\&{mpversion} primitive@>;
mp_primitive (mp, "&", mp_ampersand, mp_concatenate);
@:!!!}{\.{\&} primitive@>;
mp_primitive (mp, "rotated", mp_secondary_binary, mp_rotated_by);
@:rotated_}{\&{rotated} primitive@>;
mp_primitive (mp, "slanted", mp_secondary_binary, mp_slanted_by);
@:slanted_}{\&{slanted} primitive@>;
mp_primitive (mp, "scaled", mp_secondary_binary, mp_scaled_by);
@:scaled_}{\&{scaled} primitive@>;
mp_primitive (mp, "shifted", mp_secondary_binary, mp_shifted_by);
@:shifted_}{\&{shifted} primitive@>;
mp_primitive (mp, "transformed", mp_secondary_binary, mp_transformed_by);
@:transformed_}{\&{transformed} primitive@>;
mp_primitive (mp, "xscaled", mp_secondary_binary, mp_x_scaled);
@:x_scaled_}{\&{xscaled} primitive@>;
mp_primitive (mp, "yscaled", mp_secondary_binary, mp_y_scaled);
@:y_scaled_}{\&{yscaled} primitive@>;
mp_primitive (mp, "zscaled", mp_secondary_binary, mp_z_scaled);
@:z_scaled_}{\&{zscaled} primitive@>;
mp_primitive (mp, "infont", mp_secondary_binary, mp_in_font);
@:in_font_}{\&{infont} primitive@>;
mp_primitive (mp, "intersectiontimes", mp_tertiary_binary, mp_intersect);
@:intersection_times_}{\&{intersectiontimes} primitive@>;
mp_primitive (mp, "envelope", mp_primary_binary, mp_envelope_of);
@:envelope_}{\&{envelope} primitive@>;
mp_primitive (mp, "glyph", mp_primary_binary, mp_glyph_infont);
@:glyph_infont_}{\&{envelope} primitive@>
@ @<Cases of |print_cmd...@>=
case mp_nullary:
case mp_unary:
case mp_primary_binary:
case mp_secondary_binary:
case mp_tertiary_binary:
case mp_expression_binary:
case mp_cycle:
case mp_plus_or_minus:
case mp_slash:
case mp_ampersand:
case mp_equals:
case mp_and_command:
mp_print_op (mp, (quarterword) m);
break;
@ OK, let's look at the simplest \\{do} procedure first.
@c
@<Declare nullary action procedure@>;
static void mp_do_nullary (MP mp, quarterword c) {
check_arith();
if (number_greater (internal_value (mp_tracing_commands), two_t))
mp_show_cmd_mod (mp, mp_nullary, c);
switch (c) {
case mp_true_code:
case mp_false_code:
mp->cur_exp.type = mp_boolean_type;
set_cur_exp_value_boolean (c);
break;
case mp_null_picture_code:
mp->cur_exp.type = mp_picture_type;
set_cur_exp_node ((mp_node)mp_get_edge_header_node (mp));
mp_init_edges (mp, (mp_edge_header_node)cur_exp_node ());
break;
case mp_null_pen_code:
mp->cur_exp.type = mp_pen_type;
set_cur_exp_knot (mp_get_pen_circle (mp, zero_t));
break;
case mp_normal_deviate:
{
mp_number r;
new_number (r);
/*|mp_norm_rand (mp, &r)|;*/
m_norm_rand (r);
mp->cur_exp.type = mp_known;
set_cur_exp_value_number (r);
free_number (r);
}
break;
case mp_pen_circle:
mp->cur_exp.type = mp_pen_type;
set_cur_exp_knot (mp_get_pen_circle (mp, unity_t));
break;
case mp_version:
mp->cur_exp.type = mp_string_type;
set_cur_exp_str (mp_intern (mp, metapost_version));
break;
case mp_read_string_op:
/* Read a string from the terminal */
if (mp->noninteractive || mp->interaction <= mp_nonstop_mode)
mp_fatal_error (mp, "*** (cannot readstring in nonstop modes)");
mp_begin_file_reading (mp);
name = is_read;
limit = start;
prompt_input ("");
mp_finish_read (mp);
break;
} /* there are no other cases */
check_arith();
}
@ @<Declare nullary action procedure@>=
static void mp_finish_read (MP mp) { /* copy |buffer| line to |cur_exp| */
size_t k;
str_room (((int) mp->last - (int) start));
for (k = (size_t) start; k < mp->last; k++) {
append_char (mp->buffer[k]);
}
mp_end_file_reading (mp);
mp->cur_exp.type = mp_string_type;
set_cur_exp_str (mp_make_string (mp));
}
@ Things get a bit more interesting when there's an operand. The
operand to |do_unary| appears in |cur_type| and |cur_exp|.
This complicated if test makes sure that any |bounds| or |clip|
picture objects that get passed into \&{within} do not raise an
error when queried using the color part primitives (this is needed
for backward compatibility) .
@d cur_pic_item mp_link(edge_list(cur_exp_node()))
@d pict_color_type(A) ((cur_pic_item!=NULL) &&
((!has_color(cur_pic_item))
||
(((mp_color_model(cur_pic_item)==A)
||
((mp_color_model(cur_pic_item)==mp_uninitialized_model) &&
(number_to_scaled (internal_value(mp_default_color_model))/number_to_scaled (unity_t))==(A))))))
@d boolean_reset(A) if ( (A) ) set_cur_exp_value_boolean(mp_true_code); else set_cur_exp_value_boolean(mp_false_code)
@d type_range(A,B) {
if ( (mp->cur_exp.type>=(A)) && (mp->cur_exp.type<=(B)) )
set_number_from_boolean (new_expr.data.n, mp_true_code);
else
set_number_from_boolean (new_expr.data.n, mp_false_code);
mp_flush_cur_exp(mp, new_expr);
mp->cur_exp.type=mp_boolean_type;
}
@d type_test(A) {
if ( mp->cur_exp.type==(mp_variable_type)(A) )
set_number_from_boolean (new_expr.data.n, mp_true_code);
else
set_number_from_boolean (new_expr.data.n, mp_false_code);
mp_flush_cur_exp(mp, new_expr);
mp->cur_exp.type=mp_boolean_type;
}
@c
@<Declare unary action procedures@>;
static void mp_do_unary (MP mp, quarterword c) {
mp_node p; /* for list manipulation */
mp_value new_expr;
check_arith();
if (number_greater (internal_value (mp_tracing_commands), two_t)) {
/* Trace the current unary operation */
mp_begin_diagnostic (mp);
mp_print_nl (mp, "{");
mp_print_op (mp, c);
mp_print_char (mp, xord ('('));
mp_print_exp (mp, NULL, 0); /* show the operand, but not verbosely */
mp_print (mp, ")}");
mp_end_diagnostic (mp, false);
}
switch (c) {
case mp_plus:
if (mp->cur_exp.type < mp_color_type)
mp_bad_unary (mp, mp_plus);
break;
case mp_minus:
negate_cur_expr(mp);
break;
case mp_not_op:
if (mp->cur_exp.type != mp_boolean_type) {
mp_bad_unary (mp, mp_not_op);
} else {
halfword bb;
if (cur_exp_value_boolean () == mp_true_code)
bb = mp_false_code;
else
bb = mp_true_code;
set_cur_exp_value_boolean (bb);
}
break;
case mp_sqrt_op:
case mp_m_exp_op:
case mp_m_log_op:
case mp_sin_d_op:
case mp_cos_d_op:
case mp_floor_op:
case mp_uniform_deviate:
case mp_odd_op:
case mp_char_exists_op:
if (mp->cur_exp.type != mp_known) {
mp_bad_unary (mp, c);
} else {
switch (c) {
case mp_sqrt_op:
{
mp_number r1;
new_number (r1);
square_rt (r1, cur_exp_value_number ());
set_cur_exp_value_number (r1);
free_number (r1);
}
break;
case mp_m_exp_op:
{
mp_number r1;
new_number (r1);
m_exp (r1, cur_exp_value_number ());
set_cur_exp_value_number (r1);
free_number (r1);
}
break;
case mp_m_log_op:
{
mp_number r1;
new_number (r1);
m_log (r1, cur_exp_value_number ());
set_cur_exp_value_number (r1);
free_number (r1);
}
break;
case mp_sin_d_op:
case mp_cos_d_op:
{
mp_number n_sin, n_cos, arg1, arg2;
new_number (arg1);
new_number (arg2);
new_fraction (n_sin);
new_fraction (n_cos); /* results computed by |n_sin_cos| */
number_clone (arg1, cur_exp_value_number());
number_clone (arg2, unity_t);
number_multiply_int (arg2, 360);
number_modulo (arg1, arg2);
convert_scaled_to_angle (arg1);
n_sin_cos (arg1, n_cos, n_sin);
if (c == mp_sin_d_op) {
fraction_to_round_scaled (n_sin);
set_cur_exp_value_number (n_sin);
} else {
fraction_to_round_scaled (n_cos);
set_cur_exp_value_number (n_cos);
}
free_number (arg1);
free_number (arg2);
free_number (n_sin);
free_number (n_cos);
}
break;
case mp_floor_op:
{
mp_number vvx;
new_number (vvx);
number_clone (vvx, cur_exp_value_number ());
floor_scaled (vvx);
set_cur_exp_value_number (vvx);
free_number (vvx);
}
break;
case mp_uniform_deviate:
{
mp_number vvx;
new_number (vvx);
/*|mp_unif_rand (mp, &vvx, cur_exp_value_number ());|*/
m_unif_rand (vvx, cur_exp_value_number ());
set_cur_exp_value_number (vvx);
free_number (vvx);
}
break;
case mp_odd_op:
{
integer vvx = odd (round_unscaled (cur_exp_value_number ()));
boolean_reset (vvx);
mp->cur_exp.type = mp_boolean_type;
}
break;
case mp_char_exists_op:
/* Determine if a character has been shipped out */
set_cur_exp_value_scaled (round_unscaled (cur_exp_value_number ()) % 256);
if (number_negative(cur_exp_value_number ())) {
halfword vv = number_to_scaled(cur_exp_value_number ());
set_cur_exp_value_scaled (vv + 256);
}
boolean_reset (mp->char_exists[number_to_scaled(cur_exp_value_number ())]);
mp->cur_exp.type = mp_boolean_type;
break;
} /* there are no other cases */
}
break;
case mp_angle_op:
if (mp_nice_pair (mp, cur_exp_node (), mp->cur_exp.type)) {
mp_number narg;
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
new_angle (narg);
p = value_node (cur_exp_node ());
n_arg (narg, value_number (x_part (p)), value_number (y_part (p)));
number_clone (new_expr.data.n, narg);
convert_angle_to_scaled (new_expr.data.n);
free_number (narg);
mp_flush_cur_exp (mp, new_expr);
} else {
mp_bad_unary (mp, mp_angle_op);
}
break;
case mp_x_part:
case mp_y_part:
if ((mp->cur_exp.type == mp_pair_type)
|| (mp->cur_exp.type == mp_transform_type))
mp_take_part (mp, c);
else if (mp->cur_exp.type == mp_picture_type)
mp_take_pict_part (mp, c);
else
mp_bad_unary (mp, c);
break;
case mp_xx_part:
case mp_xy_part:
case mp_yx_part:
case mp_yy_part:
if (mp->cur_exp.type == mp_transform_type)
mp_take_part (mp, c);
else if (mp->cur_exp.type == mp_picture_type)
mp_take_pict_part (mp, c);
else
mp_bad_unary (mp, c);
break;
case mp_red_part:
case mp_green_part:
case mp_blue_part:
if (mp->cur_exp.type == mp_color_type)
mp_take_part (mp, c);
else if (mp->cur_exp.type == mp_picture_type) {
if pict_color_type
(mp_rgb_model) mp_take_pict_part (mp, c);
else
mp_bad_color_part (mp, c);
} else
mp_bad_unary (mp, c);
break;
case mp_cyan_part:
case mp_magenta_part:
case mp_yellow_part:
case mp_black_part:
if (mp->cur_exp.type == mp_cmykcolor_type)
mp_take_part (mp, c);
else if (mp->cur_exp.type == mp_picture_type) {
if pict_color_type
(mp_cmyk_model) mp_take_pict_part (mp, c);
else
mp_bad_color_part (mp, c);
} else
mp_bad_unary (mp, c);
break;
case mp_grey_part:
if (mp->cur_exp.type == mp_known);
else if (mp->cur_exp.type == mp_picture_type) {
if pict_color_type
(mp_grey_model) mp_take_pict_part (mp, c);
else
mp_bad_color_part (mp, c);
} else
mp_bad_unary (mp, c);
break;
case mp_color_model_part:
if (mp->cur_exp.type == mp_picture_type)
mp_take_pict_part (mp, c);
else
mp_bad_unary (mp, c);
break;
case mp_font_part:
case mp_text_part:
case mp_path_part:
case mp_pen_part:
case mp_dash_part:
case mp_prescript_part:
case mp_postscript_part:
if (mp->cur_exp.type == mp_picture_type)
mp_take_pict_part (mp, c);
else
mp_bad_unary (mp, c);
break;
case mp_char_op:
if (mp->cur_exp.type != mp_known) {
mp_bad_unary (mp, mp_char_op);
} else {
int vv = round_unscaled (cur_exp_value_number ()) % 256;
set_cur_exp_value_scaled (vv);
mp->cur_exp.type = mp_string_type;
if (number_negative(cur_exp_value_number ())) {
vv = number_to_scaled(cur_exp_value_number ()) + 256;
set_cur_exp_value_scaled (vv);
}
{
unsigned char ss[2];
ss[0] = (unsigned char) number_to_scaled(cur_exp_value_number ());
ss[1] = '\0';
set_cur_exp_str (mp_rtsl (mp, (char *) ss, 1));
}
}
break;
case mp_decimal:
if (mp->cur_exp.type != mp_known) {
mp_bad_unary (mp, mp_decimal);
} else {
mp->old_setting = mp->selector;
mp->selector = new_string;
print_number (cur_exp_value_number ());
set_cur_exp_str (mp_make_string (mp));
mp->selector = mp->old_setting;
mp->cur_exp.type = mp_string_type;
}
break;
case mp_oct_op:
case mp_hex_op:
case mp_ASCII_op:
if (mp->cur_exp.type != mp_string_type)
mp_bad_unary (mp, c);
else
mp_str_to_num (mp, c);
break;
case mp_font_size:
if (mp->cur_exp.type != mp_string_type) {
mp_bad_unary (mp, mp_font_size);
} else {
/* Find the design size of the font whose name is |cur_exp| */
/* One simple application of |find_font| is the implementation of the |font_size|
operator that gets the design size for a given font name. */
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
set_number_from_scaled (new_expr.data.n,
(mp->font_dsize[mp_find_font (mp, mp_str (mp, cur_exp_str ()))] + 8) / 16);
mp_flush_cur_exp (mp, new_expr);
}
break;
case mp_length_op:
/* The length operation is somewhat unusual in that it applies to a variety
of different types of operands. */
switch (mp->cur_exp.type) {
case mp_string_type:
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
number_clone (new_expr.data.n, unity_t);
number_multiply_int(new_expr.data.n, cur_exp_str ()->len);
mp_flush_cur_exp (mp, new_expr);
break;
case mp_path_type:
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
mp_path_length (mp, &new_expr.data.n);
mp_flush_cur_exp (mp, new_expr);
break;
case mp_known:
set_cur_exp_value_number (cur_exp_value_number ());
number_abs (cur_exp_value_number ());
break;
case mp_picture_type:
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
mp_pict_length (mp, &new_expr.data.n);
mp_flush_cur_exp (mp, new_expr);
break;
default:
if (mp_nice_pair (mp, cur_exp_node (), mp->cur_exp.type)) {
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
pyth_add (new_expr.data.n, value_number (x_part (value_node (cur_exp_node ()))),
value_number (y_part (value_node (cur_exp_node ()))));
mp_flush_cur_exp (mp, new_expr);
} else
mp_bad_unary (mp, c);
break;
}
break;
case mp_turning_op:
if (mp->cur_exp.type == mp_pair_type) {
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
set_number_to_zero(new_expr.data.n);
mp_flush_cur_exp (mp, new_expr);
} else if (mp->cur_exp.type != mp_path_type) {
mp_bad_unary (mp, mp_turning_op);
} else if (mp_left_type (cur_exp_knot ()) == mp_endpoint) {
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
new_expr.data.p = NULL;
mp_flush_cur_exp (mp, new_expr); /* not a cyclic path */
} else {
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
mp_turn_cycles_wrapper (mp, &new_expr.data.n, cur_exp_knot ());
mp_flush_cur_exp (mp, new_expr);
}
break;
case mp_boolean_type:
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
type_range (mp_boolean_type, mp_unknown_boolean);
break;
case mp_string_type:
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
type_range (mp_string_type, mp_unknown_string);
break;
case mp_pen_type:
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
type_range (mp_pen_type, mp_unknown_pen);
break;
case mp_path_type:
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
type_range (mp_path_type, mp_unknown_path);
break;
case mp_picture_type:
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
type_range (mp_picture_type, mp_unknown_picture);
break;
case mp_transform_type:
case mp_color_type:
case mp_cmykcolor_type:
case mp_pair_type:
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
type_test (c);
break;
case mp_numeric_type:
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
type_range (mp_known, mp_independent);
break;
case mp_known_op:
case mp_unknown_op:
mp_test_known (mp, c);
break;
case mp_cycle_op:
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
if (mp->cur_exp.type != mp_path_type)
set_number_from_boolean (new_expr.data.n, mp_false_code);
else if (mp_left_type (cur_exp_knot ()) != mp_endpoint)
set_number_from_boolean (new_expr.data.n, mp_true_code);
else
set_number_from_boolean (new_expr.data.n, mp_false_code);
mp_flush_cur_exp (mp, new_expr);
mp->cur_exp.type = mp_boolean_type;
break;
case mp_arc_length:
if (mp->cur_exp.type == mp_pair_type)
mp_pair_to_path (mp);
if (mp->cur_exp.type != mp_path_type) {
mp_bad_unary (mp, mp_arc_length);
} else {
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
mp_get_arc_length (mp, &new_expr.data.n, cur_exp_knot ());
mp_flush_cur_exp (mp, new_expr);
}
break;
case mp_filled_op:
case mp_stroked_op:
case mp_textual_op:
case mp_clipped_op:
case mp_bounded_op:
/* Here we use the fact that |c-filled_op+fill_code| is the desired graphical
object |type|. */
@^data structure assumptions@>
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
if (mp->cur_exp.type != mp_picture_type) {
set_number_from_boolean (new_expr.data.n, mp_false_code);
} else if (mp_link (edge_list (cur_exp_node ())) == NULL) {
set_number_from_boolean (new_expr.data.n, mp_false_code);
} else if (mp_type (mp_link (edge_list (cur_exp_node ()))) ==
(mp_variable_type) (c + mp_fill_node_type - mp_filled_op)) {
set_number_from_boolean (new_expr.data.n, mp_true_code);
} else {
set_number_from_boolean (new_expr.data.n, mp_false_code);
}
mp_flush_cur_exp (mp, new_expr);
mp->cur_exp.type = mp_boolean_type;
break;
case mp_make_pen_op:
if (mp->cur_exp.type == mp_pair_type)
mp_pair_to_path (mp);
if (mp->cur_exp.type != mp_path_type)
mp_bad_unary (mp, mp_make_pen_op);
else {
mp->cur_exp.type = mp_pen_type;
set_cur_exp_knot (mp_make_pen (mp, cur_exp_knot (), true));
}
break;
case mp_make_path_op:
if (mp->cur_exp.type != mp_pen_type) {
mp_bad_unary (mp, mp_make_path_op);
} else {
mp->cur_exp.type = mp_path_type;
mp_make_path (mp, cur_exp_knot ());
}
break;
case mp_reverse:
if (mp->cur_exp.type == mp_path_type) {
mp_knot pk = mp_htap_ypoc (mp, cur_exp_knot ());
if (mp_right_type (pk) == mp_endpoint)
pk = mp_next_knot (pk);
mp_toss_knot_list (mp, cur_exp_knot ());
set_cur_exp_knot (pk);
} else if (mp->cur_exp.type == mp_pair_type) {
mp_pair_to_path (mp);
} else {
mp_bad_unary (mp, mp_reverse);
}
break;
case mp_ll_corner_op:
if (!mp_get_cur_bbox (mp))
mp_bad_unary (mp, mp_ll_corner_op);
else
mp_pair_value (mp, mp_minx, mp_miny);
break;
case mp_lr_corner_op:
if (!mp_get_cur_bbox (mp))
mp_bad_unary (mp, mp_lr_corner_op);
else
mp_pair_value (mp, mp_maxx, mp_miny);
break;
case mp_ul_corner_op:
if (!mp_get_cur_bbox (mp))
mp_bad_unary (mp, mp_ul_corner_op);
else
mp_pair_value (mp, mp_minx, mp_maxy);
break;
case mp_ur_corner_op:
if (!mp_get_cur_bbox (mp))
mp_bad_unary (mp, mp_ur_corner_op);
else
mp_pair_value (mp, mp_maxx, mp_maxy);
break;
case mp_read_from_op:
case mp_close_from_op:
if (mp->cur_exp.type != mp_string_type)
mp_bad_unary (mp, c);
else
mp_do_read_or_close (mp, c);
break;
} /* there are no other cases */
check_arith();
}
@ The |nice_pair| function returns |true| if both components of a pair
are known.
@<Declare unary action procedures@>=
static boolean mp_nice_pair (MP mp, mp_node p, quarterword t) {
(void) mp;
if (t == mp_pair_type) {
p = value_node (p);
if (mp_type (x_part (p)) == mp_known)
if (mp_type (y_part (p)) == mp_known)
return true;
}
return false;
}
@ The |nice_color_or_pair| function is analogous except that it also accepts
fully known colors.
@<Declare unary action procedures@>=
static boolean mp_nice_color_or_pair (MP mp, mp_node p, quarterword t) {
mp_node q;
(void) mp;
switch (t) {
case mp_pair_type:
q = value_node (p);
if (mp_type (x_part (q)) == mp_known)
if (mp_type (y_part (q)) == mp_known)
return true;
break;
case mp_color_type:
q = value_node (p);
if (mp_type (red_part (q)) == mp_known)
if (mp_type (green_part (q)) == mp_known)
if (mp_type (blue_part (q)) == mp_known)
return true;
break;
case mp_cmykcolor_type:
q = value_node (p);
if (mp_type (cyan_part (q)) == mp_known)
if (mp_type (magenta_part (q)) == mp_known)
if (mp_type (yellow_part (q)) == mp_known)
if (mp_type (black_part (q)) == mp_known)
return true;
break;
}
return false;
}
@ @<Declare unary action...@>=
static void mp_print_known_or_unknown_type (MP mp, quarterword t, mp_node v) {
mp_print_char (mp, xord ('('));
if (t > mp_known)
mp_print (mp, "unknown numeric");
else {
if ((t == mp_pair_type) || (t == mp_color_type) || (t == mp_cmykcolor_type))
if (!mp_nice_color_or_pair (mp, v, t))
mp_print (mp, "unknown ");
mp_print_type (mp, t);
}
mp_print_char (mp, xord (')'));
}
@ @<Declare unary action...@>=
static void mp_bad_unary (MP mp, quarterword c) {
char msg[256];
mp_string sname;
int old_setting = mp->selector;
const char *hlp[] = {
"I'm afraid I don't know how to apply that operation to that",
"particular type. Continue, and I'll simply return the",
"argument (shown above) as the result of the operation.",
NULL };
mp->selector = new_string;
mp_print_op (mp, c);
mp_print_known_or_unknown_type (mp, mp->cur_exp.type, cur_exp_node ());
sname = mp_make_string(mp);
mp->selector = old_setting;
mp_snprintf (msg, 256, "Not implemented: %s", mp_str(mp, sname));
delete_str_ref(sname);
mp_disp_err(mp, NULL);
mp_back_error (mp, msg, hlp, true);
@.Not implemented...@>;
mp_get_x_next (mp);
}
@ Negation is easy except when the current expression
is of type |independent|, or when it is a pair with one or more
|independent| components.
@<Declare unary action...@>=
static void mp_negate_dep_list (MP mp, mp_value_node p) {
(void) mp;
while (1) {
number_negate (dep_value (p));
if (dep_info (p) == NULL)
return;
p = (mp_value_node) mp_link (p);
}
}
@ It is tempting to argue that the negative of an independent variable
is an independent variable, hence we don't have to do anything when
negating it. The fallacy is that other dependent variables pointing
to the current expression must change the sign of their
coefficients if we make no change to the current expression.
Instead, we work around the problem by copying the current expression
and recycling it afterwards (cf.~the |stash_in| routine).
@d negate_value(A) if (mp_type (A) == mp_known) {
set_value_number(A, (value_number (A))); /* to clear the rest */
number_negate (value_number (A));
} else {
mp_negate_dep_list (mp, (mp_value_node) dep_list ((mp_value_node) A));
}
@<Declare unary action...@>=
static void negate_cur_expr(MP mp) {
mp_node p, q, r; /* for list manipulation */
switch (mp->cur_exp.type) {
case mp_color_type:
case mp_cmykcolor_type:
case mp_pair_type:
case mp_independent:
q = cur_exp_node ();
mp_make_exp_copy (mp, q);
if (mp->cur_exp.type == mp_dependent) {
mp_negate_dep_list (mp, (mp_value_node) dep_list ((mp_value_node)
cur_exp_node ()));
} else if (mp->cur_exp.type <= mp_pair_type) {
/* |mp_color_type| |mp_cmykcolor_type|, or |mp_pair_type| */
p = value_node (cur_exp_node ());
switch (mp->cur_exp.type) {
case mp_pair_type:
r = x_part (p);
negate_value (r);
r = y_part (p);
negate_value (r);
break;
case mp_color_type:
r = red_part (p);
negate_value (r);
r = green_part (p);
negate_value (r);
r = blue_part (p);
negate_value (r);
break;
case mp_cmykcolor_type:
r = cyan_part (p);
negate_value (r);
r = magenta_part (p);
negate_value (r);
r = yellow_part (p);
negate_value (r);
r = black_part (p);
negate_value (r);
break;
default: /* there are no other valid cases, but please the compiler */
break;
}
} /* if |cur_type=mp_known| then |cur_exp=0| */
mp_recycle_value (mp, q);
mp_free_value_node (mp, q);
break;
case mp_dependent:
case mp_proto_dependent:
mp_negate_dep_list (mp, (mp_value_node) dep_list ((mp_value_node)
cur_exp_node ()));
break;
case mp_known:
if (is_number(cur_exp_value_number()))
number_negate (cur_exp_value_number());
break;
default:
mp_bad_unary (mp, mp_minus);
break;
}
}
@ If the current expression is a pair, but the context wants it to
be a path, we call |pair_to_path|.
@<Declare unary action...@>=
static void mp_pair_to_path (MP mp) {
set_cur_exp_knot (mp_pair_to_knot (mp));
mp->cur_exp.type = mp_path_type;
}
@ @<Declarations@>=
static void mp_bad_color_part (MP mp, quarterword c);
@ @c
static void mp_bad_color_part (MP mp, quarterword c) {
mp_node p; /* the big node */
mp_value new_expr;
char msg[256];
int old_setting;
mp_string sname;
const char *hlp[] = {
"You can only ask for the redpart, greenpart, bluepart of a rgb object,",
"the cyanpart, magentapart, yellowpart or blackpart of a cmyk object, ",
"or the greypart of a grey object. No mixing and matching, please.",
NULL };
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
p = mp_link (edge_list (cur_exp_node ()));
mp_disp_err(mp, NULL);
old_setting = mp->selector;
mp->selector = new_string;
mp_print_op (mp, c);
sname = mp_make_string(mp);
mp->selector = old_setting;
@.Wrong picture color model...@>;
if (mp_color_model (p) == mp_grey_model)
mp_snprintf (msg, 256, "Wrong picture color model: %s of grey object", mp_str(mp, sname));
else if (mp_color_model (p) == mp_cmyk_model)
mp_snprintf (msg, 256, "Wrong picture color model: %s of cmyk object", mp_str(mp, sname));
else if (mp_color_model (p) == mp_rgb_model)
mp_snprintf (msg, 256, "Wrong picture color model: %s of rgb object", mp_str(mp, sname));
else if (mp_color_model (p) == mp_no_model)
mp_snprintf (msg, 256, "Wrong picture color model: %s of marking object", mp_str(mp, sname));
else
mp_snprintf (msg, 256, "Wrong picture color model: %s of defaulted object", mp_str(mp, sname));
delete_str_ref(sname);
mp_error (mp, msg, hlp, true);
if (c == mp_black_part)
number_clone (new_expr.data.n, unity_t);
else
set_number_to_zero(new_expr.data.n);
mp_flush_cur_exp (mp, new_expr);
}
@ In the following procedure, |cur_exp| points to a capsule, which points to
a big node. We want to delete all but one part of the big node.
@<Declare unary action...@>=
static void mp_take_part (MP mp, quarterword c) {
mp_node p; /* the big node */
p = value_node (cur_exp_node ());
set_value_node (mp->temp_val, p);
mp_type (mp->temp_val) = mp->cur_exp.type;
mp_link (p) = mp->temp_val;
mp_free_value_node (mp, cur_exp_node ());
switch (c) {
case mp_x_part:
if (mp->cur_exp.type == mp_pair_type)
mp_make_exp_copy (mp, x_part (p));
else
mp_make_exp_copy (mp, tx_part (p));
break;
case mp_y_part:
if (mp->cur_exp.type == mp_pair_type)
mp_make_exp_copy (mp, y_part (p));
else
mp_make_exp_copy (mp, ty_part (p));
break;
case mp_xx_part:
mp_make_exp_copy (mp, xx_part (p));
break;
case mp_xy_part:
mp_make_exp_copy (mp, xy_part (p));
break;
case mp_yx_part:
mp_make_exp_copy (mp, yx_part (p));
break;
case mp_yy_part:
mp_make_exp_copy (mp, yy_part (p));
break;
case mp_red_part:
mp_make_exp_copy (mp, red_part (p));
break;
case mp_green_part:
mp_make_exp_copy (mp, green_part (p));
break;
case mp_blue_part:
mp_make_exp_copy (mp, blue_part (p));
break;
case mp_cyan_part:
mp_make_exp_copy (mp, cyan_part (p));
break;
case mp_magenta_part:
mp_make_exp_copy (mp, magenta_part (p));
break;
case mp_yellow_part:
mp_make_exp_copy (mp, yellow_part (p));
break;
case mp_black_part:
mp_make_exp_copy (mp, black_part (p));
break;
}
mp_recycle_value (mp, mp->temp_val);
}
@ @<Initialize table entries@>=
mp->temp_val = mp_get_value_node (mp);
mp_name_type (mp->temp_val) = mp_capsule;
@ @<Free table entries@>=
mp_free_value_node (mp, mp->temp_val);
@ @<Declarations@>=
static mp_edge_header_node mp_scale_edges (MP mp, mp_number se_sf, mp_edge_header_node se_pic);
@ @<Declare unary action...@>=
static void mp_take_pict_part (MP mp, quarterword c) {
mp_node p; /* first graphical object in |cur_exp| */
mp_value new_expr;
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
p = mp_link (edge_list (cur_exp_node ()));
if (p != NULL) {
switch (c) {
case mp_x_part:
case mp_y_part:
case mp_xx_part:
case mp_xy_part:
case mp_yx_part:
case mp_yy_part:
if (mp_type (p) == mp_text_node_type) {
mp_text_node p0 = (mp_text_node)p;
switch (c) {
case mp_x_part:
number_clone(new_expr.data.n, p0->tx);
break;
case mp_y_part:
number_clone(new_expr.data.n, p0->ty);
break;
case mp_xx_part:
number_clone(new_expr.data.n, p0->txx);
break;
case mp_xy_part:
number_clone(new_expr.data.n, p0->txy);
break;
case mp_yx_part:
number_clone(new_expr.data.n, p0->tyx);
break;
case mp_yy_part:
number_clone(new_expr.data.n, p0->tyy);
break;
}
mp_flush_cur_exp (mp, new_expr);
} else
goto NOT_FOUND;
break;
case mp_red_part:
case mp_green_part:
case mp_blue_part:
if (has_color (p)) {
switch (c) {
case mp_red_part:
number_clone(new_expr.data.n,((mp_stroked_node)p)->red);
break;
case mp_green_part:
number_clone(new_expr.data.n,((mp_stroked_node)p)->green);
break;
case mp_blue_part:
number_clone(new_expr.data.n,((mp_stroked_node)p)->blue);
break;
}
mp_flush_cur_exp (mp, new_expr);
} else
goto NOT_FOUND;
break;
case mp_cyan_part:
case mp_magenta_part:
case mp_yellow_part:
case mp_black_part:
if (has_color (p)) {
if (mp_color_model (p) == mp_uninitialized_model && c == mp_black_part) {
set_number_to_unity(new_expr.data.n);
} else {
switch (c) {
case mp_cyan_part:
number_clone(new_expr.data.n,((mp_stroked_node)p)->cyan);
break;
case mp_magenta_part:
number_clone(new_expr.data.n,((mp_stroked_node)p)->magenta);
break;
case mp_yellow_part:
number_clone(new_expr.data.n,((mp_stroked_node)p)->yellow);
break;
case mp_black_part:
number_clone(new_expr.data.n,((mp_stroked_node)p)->black);
break;
}
}
mp_flush_cur_exp (mp, new_expr);
} else
goto NOT_FOUND;
break;
case mp_grey_part:
if (has_color (p)) {
number_clone(new_expr.data.n,((mp_stroked_node)p)->grey);
mp_flush_cur_exp (mp, new_expr);
} else
goto NOT_FOUND;
break;
case mp_color_model_part:
if (has_color (p)) {
if (mp_color_model (p) == mp_uninitialized_model) {
number_clone (new_expr.data.n, internal_value (mp_default_color_model));
} else {
number_clone (new_expr.data.n, unity_t);
number_multiply_int (new_expr.data.n, mp_color_model (p));
}
mp_flush_cur_exp (mp, new_expr);
} else
goto NOT_FOUND;
break;
case mp_text_part:
if (mp_type (p) != mp_text_node_type)
goto NOT_FOUND;
else {
new_expr.data.str = mp_text_p (p);
add_str_ref (new_expr.data.str);
mp_flush_cur_exp (mp, new_expr);
mp->cur_exp.type = mp_string_type;
};
break;
case mp_prescript_part:
if (!has_color (p)) {
goto NOT_FOUND;
} else {
if (mp_pre_script(p)) {
new_expr.data.str = mp_pre_script(p);
add_str_ref (new_expr.data.str);
} else {
new_expr.data.str = mp_rts(mp,"");
}
mp_flush_cur_exp (mp, new_expr);
mp->cur_exp.type = mp_string_type;
};
break;
case mp_postscript_part:
if (!has_color (p)) {
goto NOT_FOUND;
} else {
if (mp_post_script(p)) {
new_expr.data.str = mp_post_script(p);
add_str_ref (new_expr.data.str);
} else {
new_expr.data.str = mp_rts(mp,"");
}
mp_flush_cur_exp (mp, new_expr);
mp->cur_exp.type = mp_string_type;
};
break;
case mp_font_part:
if (mp_type (p) != mp_text_node_type)
goto NOT_FOUND;
else {
new_expr.data.str = mp_rts (mp, mp->font_name[mp_font_n (p)]);
add_str_ref (new_expr.data.str);
mp_flush_cur_exp (mp, new_expr);
mp->cur_exp.type = mp_string_type;
};
break;
case mp_path_part:
if (mp_type (p) == mp_text_node_type) {
goto NOT_FOUND;
} else if (is_stop (p)) {
mp_confusion (mp, "pict");
} else {
new_expr.data.node = NULL;
switch (mp_type (p)) {
case mp_fill_node_type:
new_expr.data.p = mp_copy_path (mp, mp_path_p ((mp_fill_node) p));
break;
case mp_stroked_node_type:
new_expr.data.p = mp_copy_path (mp, mp_path_p ((mp_stroked_node) p));
break;
case mp_start_bounds_node_type:
new_expr.data.p = mp_copy_path (mp, mp_path_p ((mp_start_bounds_node) p));
break;
case mp_start_clip_node_type:
new_expr.data.p = mp_copy_path (mp, mp_path_p ((mp_start_clip_node) p));
break;
default:
assert (0);
break;
}
mp_flush_cur_exp (mp, new_expr);
mp->cur_exp.type = mp_path_type;
}
break;
case mp_pen_part:
if (!has_pen (p)) {
goto NOT_FOUND;
} else {
switch (mp_type (p)) {
case mp_fill_node_type:
if (mp_pen_p ((mp_fill_node) p) == NULL)
goto NOT_FOUND;
else {
new_expr.data.p = copy_pen (mp_pen_p ((mp_fill_node) p));
mp_flush_cur_exp (mp, new_expr);
mp->cur_exp.type = mp_pen_type;
}
break;
case mp_stroked_node_type:
if (mp_pen_p ((mp_stroked_node) p) == NULL)
goto NOT_FOUND;
else {
new_expr.data.p = copy_pen (mp_pen_p ((mp_stroked_node) p));
mp_flush_cur_exp (mp, new_expr);
mp->cur_exp.type = mp_pen_type;
}
break;
default:
assert (0);
break;
}
}
break;
case mp_dash_part:
if (mp_type (p) != mp_stroked_node_type) {
goto NOT_FOUND;
} else {
if (mp_dash_p (p) == NULL) {
goto NOT_FOUND;
} else {
add_edge_ref (mp_dash_p (p));
new_expr.data.node = (mp_node)mp_scale_edges (mp, ((mp_stroked_node)p)->dash_scale,
(mp_edge_header_node)mp_dash_p (p));
mp_flush_cur_exp (mp, new_expr);
mp->cur_exp.type = mp_picture_type;
}
}
break;
} /* all cases have been enumerated */
return;
};
NOT_FOUND:
/* Convert the current expression to a NULL value appropriate for |c| */
switch (c) {
case mp_text_part:
case mp_font_part:
case mp_prescript_part:
case mp_postscript_part:
new_expr.data.str = mp_rts(mp,"");
mp_flush_cur_exp (mp, new_expr);
mp->cur_exp.type = mp_string_type;
break;
case mp_path_part:
new_expr.data.p = mp_new_knot (mp);
mp_flush_cur_exp (mp, new_expr);
mp_left_type (cur_exp_knot ()) = mp_endpoint;
mp_right_type (cur_exp_knot ()) = mp_endpoint;
mp_next_knot (cur_exp_knot ()) = cur_exp_knot ();
set_number_to_zero(cur_exp_knot ()->x_coord);
set_number_to_zero(cur_exp_knot ()->y_coord);
mp_originator (cur_exp_knot ()) = mp_metapost_user;
mp->cur_exp.type = mp_path_type;
break;
case mp_pen_part:
new_expr.data.p = mp_get_pen_circle (mp, zero_t);
mp_flush_cur_exp (mp, new_expr);
mp->cur_exp.type = mp_pen_type;
break;
case mp_dash_part:
new_expr.data.node = (mp_node)mp_get_edge_header_node (mp);
mp_flush_cur_exp (mp, new_expr);
mp_init_edges (mp, (mp_edge_header_node)cur_exp_node ());
mp->cur_exp.type = mp_picture_type;
break;
default:
set_number_to_zero(new_expr.data.n);
mp_flush_cur_exp (mp, new_expr);
break;
}
}
@ @<Declare unary action...@>=
static void mp_str_to_num (MP mp, quarterword c) { /* converts a string to a number */
integer n; /* accumulator */
ASCII_code m; /* current character */
unsigned k; /* index into |str_pool| */
int b; /* radix of conversion */
boolean bad_char; /* did the string contain an invalid digit? */
mp_value new_expr;
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
if (c == mp_ASCII_op) {
if (cur_exp_str ()->len == 0)
n = -1;
else
n = cur_exp_str ()->str[0];
} else {
if (c == mp_oct_op)
b = 8;
else
b = 16;
n = 0;
bad_char = false;
for (k = 0; k < cur_exp_str ()->len; k++) {
m = (ASCII_code) (*(cur_exp_str ()->str + k));
if ((m >= '0') && (m <= '9'))
m = (ASCII_code) (m - '0');
else if ((m >= 'A') && (m <= 'F'))
m = (ASCII_code) (m - 'A' + 10);
else if ((m >= 'a') && (m <= 'f'))
m = (ASCII_code) (m - 'a' + 10);
else {
bad_char = true;
m = 0;
};
if ((int) m >= b) {
bad_char = true;
m = 0;
};
if (n < 32768 / b)
n = n * b + m;
else
n = 32767;
}
/* Give error messages if |bad_char| or |n>=4096| */
if (bad_char) {
const char *hlp[] = {"I zeroed out characters that weren't hex digits.", NULL};
if (c == mp_oct_op) {
hlp[0] = "I zeroed out characters that weren't in the range 0..7.";
}
mp_disp_err(mp, NULL);
mp_back_error (mp, "String contains illegal digits", hlp, true);
mp_get_x_next (mp);
}
if ((n > 4095)) { /* todo, this is scaled specific */
if (number_positive (internal_value (mp_warning_check))) {
char msg[256];
const char *hlp[] = {
"I have trouble with numbers greater than 4095; watch out.",
"(Set warningcheck:=0 to suppress this message.)",
NULL };
mp_snprintf (msg, 256,"Number too large (%d)", (int)n);
mp_back_error (mp, msg, hlp, true);
mp_get_x_next (mp);
}
}
}
number_clone (new_expr.data.n, unity_t);
number_multiply_int(new_expr.data.n, n);
mp_flush_cur_exp (mp, new_expr);
}
@ @<Declare unary action...@>=
static void mp_path_length (MP mp, mp_number *n) { /* computes the length of the current path */
mp_knot p; /* traverser */
set_number_to_zero (*n);
p = cur_exp_knot ();
if (mp_left_type (p) == mp_endpoint) {
number_substract(*n, unity_t); /* -unity */
}
do {
p = mp_next_knot (p);
number_add(*n, unity_t);
} while (p != cur_exp_knot ());
}
@ @<Declare unary action...@>=
static void mp_pict_length (MP mp, mp_number *n) {
/* counts interior components in picture |cur_exp| */
mp_node p; /* traverser */
set_number_to_zero (*n);
p = mp_link (edge_list (cur_exp_node ()));
if (p != NULL) {
if (is_start_or_stop (p))
if (mp_skip_1component (mp, p) == NULL)
p = mp_link (p);
while (p != NULL) {
if ( ! is_start_or_stop(p) )
p = mp_link(p);
else if ( ! is_stop(p))
p = mp_skip_1component(mp, p);
else
return;
number_add(*n, unity_t);
}
}
}
@ The function |an_angle| returns the value of the |angle| primitive, or $0$ if the
argument is |origin|.
@<Declare unary action...@>=
static void mp_an_angle (MP mp, mp_number *ret, mp_number xpar, mp_number ypar) {
set_number_to_zero (*ret);
if ((!(number_zero(xpar) && number_zero(ypar)))) {
n_arg (*ret, xpar, ypar);
}
}
@ The actual turning number is (for the moment) computed in a C function
that receives eight integers corresponding to the four controlling points,
and returns a single angle. Besides those, we have to account for discrete
moves at the actual points.
@d mp_floor(a) ((a)>=0 ? (int)(a) : -(int)(-(a)))
@d bezier_error (720*(256*256*16))+1
@d mp_sign(v) ((v)>0 ? 1 : ((v)<0 ? -1 : 0 ))
@d mp_out(A) (double)((A)/16)
@<Declare unary action...@>=
static void mp_bezier_slope (MP mp, mp_number *ret, mp_number AX, mp_number AY, mp_number BX,
mp_number BY, mp_number CX, mp_number CY, mp_number DX,
mp_number DY);
@ @c
static void mp_bezier_slope (MP mp, mp_number *ret, mp_number AX, mp_number AY, mp_number BX,
mp_number BY, mp_number CX, mp_number CY, mp_number DX,
mp_number DY) {
double a, b, c;
mp_number deltax, deltay;
double ax, ay, bx, by, cx, cy, dx, dy;
mp_number xi, xo, xm;
double res = 0;
ax = number_to_double (AX);
ay = number_to_double (AY);
bx = number_to_double (BX);
by = number_to_double (BY);
cx = number_to_double (CX);
cy = number_to_double (CY);
dx = number_to_double (DX);
dy = number_to_double (DY);
new_number (deltax);
new_number (deltay);
set_number_from_substraction(deltax, BX, AX);
set_number_from_substraction(deltay, BY, AY);
if (number_zero(deltax) && number_zero(deltay)) {
set_number_from_substraction(deltax, CX, AX);
set_number_from_substraction(deltay, CY, AY);
}
if (number_zero(deltax) && number_zero(deltay)) {
set_number_from_substraction(deltax, DX, AX);
set_number_from_substraction(deltay, DY, AY);
}
new_number (xi);
new_number (xm);
new_number (xo);
mp_an_angle (mp, &xi, deltax, deltay);
set_number_from_substraction(deltax, CX, BX);
set_number_from_substraction(deltay, CY, BY);
mp_an_angle (mp, &xm, deltax, deltay); /* !!! never used? */
set_number_from_substraction(deltax, DX, CX);
set_number_from_substraction(deltay, DY, CY);
if (number_zero(deltax) && number_zero(deltay)) {
set_number_from_substraction(deltax, DX, BX);
set_number_from_substraction(deltay, DY, BY);
}
if (number_zero(deltax) && number_zero(deltay)) {
set_number_from_substraction(deltax, DX, AX);
set_number_from_substraction(deltay, DY, AY);
}
mp_an_angle (mp, &xo, deltax, deltay);
a = (bx - ax) * (cy - by) - (cx - bx) * (by - ay); /* a = (bp-ap)x(cp-bp); */
b = (bx - ax) * (dy - cy) - (by - ay) * (dx - cx);; /* b = (bp-ap)x(dp-cp); */
c = (cx - bx) * (dy - cy) - (dx - cx) * (cy - by); /* c = (cp-bp)x(dp-cp); */
if ((a == 0) && (c == 0)) {
res = (b == 0 ? 0 : (mp_out (number_to_double(xo)) - mp_out (number_to_double(xi))));
} else if ((a == 0) || (c == 0)) {
if ((mp_sign (b) == mp_sign (a)) || (mp_sign (b) == mp_sign (c))) {
res = mp_out (number_to_double(xo)) - mp_out (number_to_double(xi)); /* ? */
if (res < -180.0)
res += 360.0;
else if (res > 180.0)
res -= 360.0;
} else {
res = mp_out (number_to_double(xo)) - mp_out (number_to_double(xi)); /* ? */
}
} else if ((mp_sign (a) * mp_sign (c)) < 0) {
res = mp_out (number_to_double(xo)) - mp_out (number_to_double(xi)); /* ? */
if (res < -180.0)
res += 360.0;
else if (res > 180.0)
res -= 360.0;
} else {
if (mp_sign (a) == mp_sign (b)) {
res = mp_out (number_to_double(xo)) - mp_out (number_to_double(xi)); /* ? */
if (res < -180.0)
res += 360.0;
else if (res > 180.0)
res -= 360.0;
} else {
if ((b * b) == (4 * a * c)) {
res = (double) bezier_error;
} else if ((b * b) < (4 * a * c)) {
res = mp_out (number_to_double(xo)) - mp_out (number_to_double(xi)); /* ? */
if (res <= 0.0 && res > -180.0)
res += 360.0;
else if (res >= 0.0 && res < 180.0)
res -= 360.0;
} else {
res = mp_out (number_to_double(xo)) - mp_out (number_to_double(xi));
if (res < -180.0)
res += 360.0;
else if (res > 180.0)
res -= 360.0;
}
}
}
free_number (deltax);
free_number (deltay);
free_number (xi);
free_number (xo);
free_number (xm);
set_number_from_double(*ret, res);
convert_scaled_to_angle (*ret);
}
@
@d p_nextnext mp_next_knot(mp_next_knot(p))
@d p_next mp_next_knot(p)
@<Declare unary action...@>=
static void mp_turn_cycles (MP mp, mp_number *turns, mp_knot c) {
mp_angle res, ang; /* the angles of intermediate results */
mp_knot p; /* for running around the path */
mp_number xp, yp; /* coordinates of next point */
mp_number x, y; /* helper coordinates */
mp_number arg1, arg2;
mp_angle in_angle, out_angle; /* helper angles */
mp_angle seven_twenty_deg_t, neg_one_eighty_deg_t;
unsigned old_setting; /* saved |selector| setting */
set_number_to_zero(*turns);
new_number(arg1);
new_number(arg2);
new_number(xp);
new_number(yp);
new_number(x);
new_number(y);
new_angle(in_angle);
new_angle(out_angle);
new_angle(ang);
new_angle(res);
new_angle(seven_twenty_deg_t);
new_angle(neg_one_eighty_deg_t);
number_clone(seven_twenty_deg_t, three_sixty_deg_t);
number_double(seven_twenty_deg_t);
number_clone(neg_one_eighty_deg_t, one_eighty_deg_t);
number_negate(neg_one_eighty_deg_t);
p = c;
old_setting = mp->selector;
mp->selector = term_only;
if (number_greater (internal_value (mp_tracing_commands), unity_t)) {
mp_begin_diagnostic (mp);
mp_print_nl (mp, "");
mp_end_diagnostic (mp, false);
}
do {
number_clone (xp, p_next->x_coord);
number_clone (yp, p_next->y_coord);
mp_bezier_slope (mp, &ang, p->x_coord, p->y_coord, p->right_x, p->right_y,
p_next->left_x, p_next->left_y, xp, yp);
if (number_greater(ang, seven_twenty_deg_t)) {
mp_error (mp, "Strange path", NULL, true);
mp->selector = old_setting;
set_number_to_zero(*turns);
goto DONE;
}
number_add(res, ang);
if (number_greater(res, one_eighty_deg_t)) {
number_substract(res, three_sixty_deg_t);
number_add(*turns, unity_t);
}
if (number_lessequal(res, neg_one_eighty_deg_t)) {
number_add(res, three_sixty_deg_t);
number_substract(*turns, unity_t);
}
/* incoming angle at next point */
number_clone (x, p_next->left_x);
number_clone (y, p_next->left_y);
if (number_equal(xp, x) && number_equal(yp, y)) {
number_clone (x, p->right_x);
number_clone (y, p->right_y);
}
if (number_equal(xp, x) && number_equal(yp, y)) {
number_clone (x, p->x_coord);
number_clone (y, p->y_coord);
}
set_number_from_substraction(arg1, xp, x);
set_number_from_substraction(arg2, yp, y);
mp_an_angle (mp, &in_angle, arg1, arg2);
/* outgoing angle at next point */
number_clone (x, p_next->right_x);
number_clone (y, p_next->right_y);
if (number_equal(xp, x) && number_equal(yp, y)) {
number_clone (x, p_nextnext->left_x);
number_clone (y, p_nextnext->left_y);
}
if (number_equal(xp, x) && number_equal(yp, y)) {
number_clone (x, p_nextnext->x_coord);
number_clone (y, p_nextnext->y_coord);
}
set_number_from_substraction(arg1, x, xp);
set_number_from_substraction(arg2, y, yp);
mp_an_angle (mp, &out_angle, arg1, arg2);
set_number_from_substraction(ang, out_angle, in_angle);
mp_reduce_angle (mp, &ang);
if (number_nonzero(ang)) {
number_add(res, ang);
if (number_greaterequal(res, one_eighty_deg_t)) {
number_substract(res, three_sixty_deg_t);
number_add(*turns, unity_t);
}
if (number_lessequal(res, neg_one_eighty_deg_t)) {
number_add(res, three_sixty_deg_t);
number_substract(*turns, unity_t);
}
}
p = mp_next_knot (p);
} while (p != c);
mp->selector = old_setting;
DONE:
free_number(xp);
free_number(yp);
free_number(x);
free_number(y);
free_number(seven_twenty_deg_t);
free_number(neg_one_eighty_deg_t);
free_number(in_angle);
free_number(out_angle);
free_number(ang);
free_number(res);
free_number(arg1);
free_number(arg2);
}
@ @<Declare unary action...@>=
static void mp_turn_cycles_wrapper (MP mp, mp_number *ret, mp_knot c) {
if (mp_next_knot (c) == c) {
/* one-knot paths always have a turning number of 1 */
set_number_to_unity(*ret);
} else {
mp_turn_cycles (mp, ret, c);
}
}
@ @<Declare unary action procedures@>=
static void mp_test_known (MP mp, quarterword c) {
int b; /* is the current expression known? */
mp_node p; /* location in a big node */
mp_value new_expr;
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
b = mp_false_code;
switch (mp->cur_exp.type) {
case mp_vacuous:
case mp_boolean_type:
case mp_string_type:
case mp_pen_type:
case mp_path_type:
case mp_picture_type:
case mp_known:
b = mp_true_code;
break;
case mp_transform_type:
p = value_node (cur_exp_node ());
if (mp_type (tx_part (p)) != mp_known)
break;
if (mp_type (ty_part (p)) != mp_known)
break;
if (mp_type (xx_part (p)) != mp_known)
break;
if (mp_type (xy_part (p)) != mp_known)
break;
if (mp_type (yx_part (p)) != mp_known)
break;
if (mp_type (yy_part (p)) != mp_known)
break;
b = mp_true_code;
break;
case mp_color_type:
p = value_node (cur_exp_node ());
if (mp_type (red_part (p)) != mp_known)
break;
if (mp_type (green_part (p)) != mp_known)
break;
if (mp_type (blue_part (p)) != mp_known)
break;
b = mp_true_code;
break;
case mp_cmykcolor_type:
p = value_node (cur_exp_node ());
if (mp_type (cyan_part (p)) != mp_known)
break;
if (mp_type (magenta_part (p)) != mp_known)
break;
if (mp_type (yellow_part (p)) != mp_known)
break;
if (mp_type (black_part (p)) != mp_known)
break;
b = mp_true_code;
break;
case mp_pair_type:
p = value_node (cur_exp_node ());
if (mp_type (x_part (p)) != mp_known)
break;
if (mp_type (y_part (p)) != mp_known)
break;
b = mp_true_code;
break;
default:
break;
}
if (c == mp_known_op) {
set_number_from_boolean (new_expr.data.n, b);
} else {
if (b==mp_true_code) {
set_number_from_boolean (new_expr.data.n, mp_false_code);
} else {
set_number_from_boolean (new_expr.data.n, mp_true_code);
}
}
mp_flush_cur_exp (mp, new_expr);
cur_exp_node() = NULL; /* !! do not replace with |set_cur_exp_node()| !! */
mp->cur_exp.type = mp_boolean_type;
}
@ The |pair_value| routine changes the current expression to a
given ordered pair of values.
@<Declare unary action procedures@>=
static void mp_pair_value (MP mp, mp_number x, mp_number y) {
mp_node p; /* a pair node */
mp_value new_expr;
mp_number x1, y1;
new_number(x1);
new_number(y1);
number_clone (x1, x);
number_clone (y1, y);
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
p = mp_get_value_node (mp);
new_expr.type = mp_type (p);
new_expr.data.node = p;
mp_flush_cur_exp (mp, new_expr);
mp->cur_exp.type = mp_pair_type;
mp_name_type (p) = mp_capsule;
mp_init_pair_node (mp, p);
p = value_node (p);
mp_type (x_part (p)) = mp_known;
set_value_number (x_part (p), x1);
mp_type (y_part (p)) = mp_known;
set_value_number (y_part (p), y1);
free_number(x1);
free_number(y1);
}
@ Here is a function that sets |minx|, |maxx|, |miny|, |maxy| to the bounding
box of the current expression. The boolean result is |false| if the expression
has the wrong type.
@<Declare unary action procedures@>=
static boolean mp_get_cur_bbox (MP mp) {
switch (mp->cur_exp.type) {
case mp_picture_type:
{
mp_edge_header_node p0 = (mp_edge_header_node)cur_exp_node ();
mp_set_bbox (mp, p0, true);
if (number_greater(p0->minx, p0->maxx)) {
set_number_to_zero(mp_minx);
set_number_to_zero(mp_maxx);
set_number_to_zero(mp_miny);
set_number_to_zero(mp_maxy);
} else {
number_clone (mp_minx, p0->minx);
number_clone (mp_maxx, p0->maxx);
number_clone (mp_miny, p0->miny);
number_clone (mp_maxy, p0->maxy);
}
}
break;
case mp_path_type:
mp_path_bbox (mp, cur_exp_knot ());
break;
case mp_pen_type:
mp_pen_bbox (mp, cur_exp_knot ());
break;
default:
return false;
}
return true;
}
@ Here is a routine that interprets |cur_exp| as a file name and tries to read
a line from the file or to close the file.
@<Declare unary action procedures@>=
static void mp_do_read_or_close (MP mp, quarterword c) {
mp_value new_expr;
readf_index n, n0; /* indices for searching |rd_fname| */
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
/* Find the |n| where |rd_fname[n]=cur_exp|; if |cur_exp| must be inserted,
call |start_read_input| and |goto found| or |not_found| */
/* Free slots in the |rd_file| and |rd_fname| arrays are marked with NULL's in
|rd_fname|. */
{
char *fn;
n = mp->read_files;
n0 = mp->read_files;
fn = mp_xstrdup (mp, mp_str (mp, cur_exp_str ()));
while (mp_xstrcmp (fn, mp->rd_fname[n]) != 0) {
if (n > 0) {
decr (n);
} else if (c == mp_close_from_op) {
goto CLOSE_FILE;
} else {
if (n0 == mp->read_files) {
if (mp->read_files < mp->max_read_files) {
incr (mp->read_files);
} else {
void **rd_file;
char **rd_fname;
readf_index l, k;
l = mp->max_read_files + (mp->max_read_files / 4);
rd_file = xmalloc ((l + 1), sizeof (void *));
rd_fname = xmalloc ((l + 1), sizeof (char *));
for (k = 0; k <= l; k++) {
if (k <= mp->max_read_files) {
rd_file[k] = mp->rd_file[k];
rd_fname[k] = mp->rd_fname[k];
} else {
rd_file[k] = 0;
rd_fname[k] = NULL;
}
}
xfree (mp->rd_file);
xfree (mp->rd_fname);
mp->max_read_files = l;
mp->rd_file = rd_file;
mp->rd_fname = rd_fname;
}
}
n = n0;
if (mp_start_read_input (mp, fn, n))
goto FOUND;
else
goto NOT_FOUND;
}
if (mp->rd_fname[n] == NULL) {
n0 = n;
}
}
if (c == mp_close_from_op) {
(mp->close_file) (mp, mp->rd_file[n]);
goto NOT_FOUND;
}
}
mp_begin_file_reading (mp);
name = is_read;
if (mp_input_ln (mp, mp->rd_file[n]))
goto FOUND;
mp_end_file_reading (mp);
NOT_FOUND:
/* Record the end of file and set |cur_exp| to a dummy value */
xfree (mp->rd_fname[n]);
mp->rd_fname[n] = NULL;
if (n == mp->read_files - 1)
mp->read_files = n;
if (c == mp_close_from_op)
goto CLOSE_FILE;
new_expr.data.str = mp->eof_line;
add_str_ref (new_expr.data.str);
mp_flush_cur_exp (mp, new_expr);
mp->cur_exp.type = mp_string_type;
return;
CLOSE_FILE:
mp_flush_cur_exp (mp, new_expr);
mp->cur_exp.type = mp_vacuous;
return;
FOUND:
mp_flush_cur_exp (mp, new_expr);
mp_finish_read (mp);
}
@ The string denoting end-of-file is a one-byte string at position zero, by definition.
I have to cheat a little here because
@<Glob...@>=
mp_string eof_line;
@ @<Set init...@>=
mp->eof_line = mp_rtsl (mp, "\0", 1);
mp->eof_line->refs = MAX_STR_REF;
@ Finally, we have the operations that combine a capsule~|p|
with the current expression.
Several of the binary operations are potentially complicated by the
fact that |independent| values can sneak into capsules. For example,
we've seen an instance of this difficulty in the unary operation
of negation. In order to reduce the number of cases that need to be
handled, we first change the two operands (if necessary)
to rid them of |independent| components. The original operands are
put into capsules called |old_p| and |old_exp|, which will be
recycled after the binary operation has been safely carried out.
@d binary_return { mp_finish_binary(mp, old_p, old_exp); return; }
@c
@<Declare binary action procedures@>;
static void mp_finish_binary (MP mp, mp_node old_p, mp_node old_exp) {
check_arith();
/* Recycle any sidestepped |independent| capsules */
if (old_p != NULL) {
mp_recycle_value (mp, old_p);
mp_free_value_node (mp, old_p);
}
if (old_exp != NULL) {
mp_recycle_value (mp, old_exp);
mp_free_value_node (mp, old_exp);
}
}
static void mp_do_binary (MP mp, mp_node p, integer c) {
mp_node q, r, rr; /* for list manipulation */
mp_node old_p, old_exp; /* capsules to recycle */
mp_value new_expr;
check_arith();
if (number_greater (internal_value (mp_tracing_commands), two_t)) {
/* Trace the current binary operation */
mp_begin_diagnostic (mp);
mp_print_nl (mp, "{(");
mp_print_exp (mp, p, 0); /* show the operand, but not verbosely */
mp_print_char (mp, xord (')'));
mp_print_op (mp, (quarterword) c);
mp_print_char (mp, xord ('('));
mp_print_exp (mp, NULL, 0);
mp_print (mp, ")}");
mp_end_diagnostic (mp, false);
}
/* Sidestep |independent| cases in capsule |p| */
/* A big node is considered to be ``tarnished'' if it contains at least one
independent component. We will define a simple function called `|tarnished|'
that returns |NULL| if and only if its argument is not tarnished. */
switch (mp_type (p)) {
case mp_transform_type:
case mp_color_type:
case mp_cmykcolor_type:
case mp_pair_type:
old_p = mp_tarnished (mp, p);
break;
case mp_independent:
old_p = MP_VOID;
break;
default:
old_p = NULL;
break;
}
if (old_p != NULL) {
q = mp_stash_cur_exp (mp);
old_p = p;
mp_make_exp_copy (mp, old_p);
p = mp_stash_cur_exp (mp);
mp_unstash_cur_exp (mp, q);
}
/* Sidestep |independent| cases in the current expression */
switch (mp->cur_exp.type) {
case mp_transform_type:
case mp_color_type:
case mp_cmykcolor_type:
case mp_pair_type:
old_exp = mp_tarnished (mp, cur_exp_node ());
break;
case mp_independent:
old_exp = MP_VOID;
break;
default:
old_exp = NULL;
break;
}
if (old_exp != NULL) {
old_exp = cur_exp_node ();
mp_make_exp_copy (mp, old_exp);
}
switch (c) {
case mp_plus:
case mp_minus:
/* Add or subtract the current expression from |p| */
if ((mp->cur_exp.type < mp_color_type) || (mp_type (p) < mp_color_type)) {
mp_bad_binary (mp, p, (quarterword) c);
} else {
quarterword cc = (quarterword)c;
if ((mp->cur_exp.type > mp_pair_type) && (mp_type (p) > mp_pair_type)) {
mp_add_or_subtract (mp, p, NULL, cc);
} else {
if (mp->cur_exp.type != mp_type (p)) {
mp_bad_binary (mp, p, cc);
} else {
q = value_node (p);
r = value_node (cur_exp_node ());
switch (mp->cur_exp.type) {
case mp_pair_type:
mp_add_or_subtract (mp, x_part (q), x_part (r),cc);
mp_add_or_subtract (mp, y_part (q), y_part (r),cc);
break;
case mp_color_type:
mp_add_or_subtract (mp, red_part (q), red_part (r),cc);
mp_add_or_subtract (mp, green_part (q), green_part (r),cc);
mp_add_or_subtract (mp, blue_part (q), blue_part (r),cc);
break;
case mp_cmykcolor_type:
mp_add_or_subtract (mp, cyan_part (q), cyan_part (r),cc);
mp_add_or_subtract (mp, magenta_part (q), magenta_part (r),cc);
mp_add_or_subtract (mp, yellow_part (q), yellow_part (r),cc);
mp_add_or_subtract (mp, black_part (q), black_part (r),cc);
break;
case mp_transform_type:
mp_add_or_subtract (mp, tx_part (q), tx_part (r),cc);
mp_add_or_subtract (mp, ty_part (q), ty_part (r),cc);
mp_add_or_subtract (mp, xx_part (q), xx_part (r),cc);
mp_add_or_subtract (mp, xy_part (q), xy_part (r),cc);
mp_add_or_subtract (mp, yx_part (q), yx_part (r),cc);
mp_add_or_subtract (mp, yy_part (q), yy_part (r),cc);
break;
default: /* there are no other valid cases, but please the compiler */
break;
}
}
}
}
break;
case mp_less_than:
case mp_less_or_equal:
case mp_greater_than:
case mp_greater_or_equal:
case mp_equal_to:
case mp_unequal_to:
check_arith(); /* at this point |arith_error| should be |false|? */
if ((mp->cur_exp.type > mp_pair_type) && (mp_type (p) > mp_pair_type)) {
mp_add_or_subtract (mp, p, NULL, mp_minus); /* |cur_exp:=(p)-cur_exp| */
} else if (mp->cur_exp.type != mp_type (p)) {
mp_bad_binary (mp, p, (quarterword) c);
goto DONE;
} else if (mp->cur_exp.type == mp_string_type) {
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
set_number_from_scaled (new_expr.data.n, mp_str_vs_str (mp, value_str (p), cur_exp_str ()));
mp_flush_cur_exp (mp, new_expr);
} else if ((mp->cur_exp.type == mp_unknown_string) ||
(mp->cur_exp.type == mp_unknown_boolean)) {
/* Check if unknowns have been equated */
/* When two unknown strings are in the same ring, we know that they are
equal. Otherwise, we don't know whether they are equal or not, so we
make no change. */
q = value_node (cur_exp_node ());
while ((q != cur_exp_node ()) && (q != p))
q = value_node (q);
if (q == p) {
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
set_cur_exp_node (NULL);
mp_flush_cur_exp (mp, new_expr);
}
} else if ((mp->cur_exp.type <= mp_pair_type)
&& (mp->cur_exp.type >= mp_transform_type)) {
/* Reduce comparison of big nodes to comparison of scalars */
/* In the following, the |while| loops exist just so that |break| can be used,
each loop runs exactly once. */
quarterword part_type;
q = value_node (p);
r = value_node (cur_exp_node ());
part_type = 0;
switch (mp->cur_exp.type) {
case mp_pair_type:
while (part_type==0) {
rr = x_part (r);
part_type = mp_x_part;
mp_add_or_subtract (mp, x_part (q), rr, mp_minus);
if (mp_type (rr) != mp_known || ! number_zero(value_number (rr)))
break;
rr = y_part (r);
part_type = mp_y_part;
mp_add_or_subtract (mp, y_part (q), rr, mp_minus);
if (mp_type (rr) != mp_known || !number_zero(value_number (rr)))
break;
}
mp_take_part (mp, part_type);
break;
case mp_color_type:
while (part_type==0) {
rr = red_part (r);
part_type = mp_red_part;
mp_add_or_subtract (mp, red_part (q), rr, mp_minus);
if (mp_type (rr) != mp_known || ! number_zero(value_number (rr)))
break;
rr = green_part (r);
part_type = mp_green_part;
mp_add_or_subtract (mp, green_part (q), rr, mp_minus);
if (mp_type (rr) != mp_known || !number_zero(value_number (rr)))
break;
rr = blue_part (r);
part_type = mp_blue_part;
mp_add_or_subtract (mp, blue_part (q), rr, mp_minus);
if (mp_type (rr) != mp_known || !number_zero(value_number (rr)))
break;
}
mp_take_part (mp, part_type);
break;
case mp_cmykcolor_type:
while (part_type==0) {
rr = cyan_part (r);
part_type = mp_cyan_part;
mp_add_or_subtract (mp, cyan_part (q), rr, mp_minus);
if (mp_type (rr) != mp_known || !number_zero(value_number (rr)))
break;
rr = magenta_part (r);
part_type = mp_magenta_part;
mp_add_or_subtract (mp, magenta_part (q), rr, mp_minus);
if (mp_type (rr) != mp_known || !number_zero(value_number (rr)))
break;
rr = yellow_part (r);
part_type = mp_yellow_part;
mp_add_or_subtract (mp, yellow_part (q), rr, mp_minus);
if (mp_type (rr) != mp_known || !number_zero(value_number (rr)))
break;
rr = black_part (r);
part_type = mp_black_part;
mp_add_or_subtract (mp, black_part (q), rr, mp_minus);
if (mp_type (rr) != mp_known || !number_zero(value_number (rr)))
break;
}
mp_take_part (mp, part_type);
break;
case mp_transform_type:
while (part_type==0) {
rr = tx_part (r);
part_type = mp_x_part;
mp_add_or_subtract (mp, tx_part (q), rr, mp_minus);
if (mp_type (rr) != mp_known || !number_zero(value_number (rr)))
break;
rr = ty_part (r);
part_type = mp_y_part;
mp_add_or_subtract (mp, ty_part (q), rr, mp_minus);
if (mp_type (rr) != mp_known || !number_zero(value_number (rr)))
break;
rr = xx_part (r);
part_type = mp_xx_part;
mp_add_or_subtract (mp, xx_part (q), rr, mp_minus);
if (mp_type (rr) != mp_known || !number_zero(value_number (rr)))
break;
rr = xy_part (r);
part_type = mp_xy_part;
mp_add_or_subtract (mp, xy_part (q), rr, mp_minus);
if (mp_type (rr) != mp_known || !number_zero(value_number (rr)))
break;
rr = yx_part (r);
part_type = mp_yx_part;
mp_add_or_subtract (mp, yx_part (q), rr, mp_minus);
if (mp_type (rr) != mp_known || !number_zero(value_number (rr)))
break;
rr = yy_part (r);
part_type = mp_yy_part;
mp_add_or_subtract (mp, yy_part (q), rr, mp_minus);
if (mp_type (rr) != mp_known || !number_zero(value_number (rr)))
break;
}
mp_take_part (mp, part_type);
break;
default:
assert (0); /* todo: |mp->cur_exp.type>mp_transform_node_type| ? */
break;
}
} else if (mp->cur_exp.type == mp_boolean_type) {
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
set_number_from_boolean (new_expr.data.n, number_to_scaled(cur_exp_value_number ()) -
number_to_scaled (value_number (p)));
mp_flush_cur_exp (mp, new_expr);
} else {
mp_bad_binary (mp, p, (quarterword) c);
goto DONE;
}
/* Compare the current expression with zero */
if (mp->cur_exp.type != mp_known) {
const char *hlp[] = {
"Oh dear. I can\'t decide if the expression above is positive,",
"negative, or zero. So this comparison test won't be `true'.",
NULL };
if (mp->cur_exp.type < mp_known) {
mp_disp_err (mp, p);
hlp[0] = "The quantities shown above have not been equated.";
hlp[1] = NULL;
}
mp_disp_err(mp, NULL);
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
set_number_from_boolean (new_expr.data.n, mp_false_code);
mp_back_error (mp,"Unknown relation will be considered false", hlp, true);
@.Unknown relation...@>;
mp_get_x_next (mp);
mp_flush_cur_exp (mp, new_expr);
} else {
switch (c) {
case mp_less_than:
boolean_reset (number_negative(cur_exp_value_number ()));
break;
case mp_less_or_equal:
boolean_reset (number_nonpositive(cur_exp_value_number ()));
break;
case mp_greater_than:
boolean_reset (number_positive(cur_exp_value_number ()));
break;
case mp_greater_or_equal:
boolean_reset (number_nonnegative(cur_exp_value_number ()));
break;
case mp_equal_to:
boolean_reset (number_zero(cur_exp_value_number ()));
break;
case mp_unequal_to:
boolean_reset (number_nonzero(cur_exp_value_number ()));
break;
}; /* there are no other cases */
}
mp->cur_exp.type = mp_boolean_type;
DONE:
mp->arith_error = false; /* ignore overflow in comparisons */
break;
case mp_and_op:
case mp_or_op:
/* Here we use the sneaky fact that |and_op-false_code=or_op-true_code| */
if ((mp_type (p) != mp_boolean_type) || (mp->cur_exp.type != mp_boolean_type))
mp_bad_binary (mp, p, (quarterword) c);
else if (number_to_boolean (p->data.n) == c + mp_false_code - mp_and_op) {
set_cur_exp_value_boolean (number_to_boolean (p->data.n));
}
break;
case mp_times:
if ((mp->cur_exp.type < mp_color_type) || (mp_type (p) < mp_color_type)) {
mp_bad_binary (mp, p, mp_times);
} else if ((mp->cur_exp.type == mp_known) || (mp_type (p) == mp_known)) {
/* Multiply when at least one operand is known */
mp_number vv;
new_fraction (vv);
if (mp_type (p) == mp_known) {
number_clone(vv, value_number (p));
mp_free_value_node (mp, p);
} else {
number_clone(vv, cur_exp_value_number ());
mp_unstash_cur_exp (mp, p);
}
if (mp->cur_exp.type == mp_known) {
mp_number ret;
new_number (ret);
take_scaled (ret, cur_exp_value_number (), vv);
set_cur_exp_value_number (ret);
free_number (ret);
} else if (mp->cur_exp.type == mp_pair_type) {
mp_dep_mult (mp, (mp_value_node) x_part (value_node (cur_exp_node ())), vv, true);
mp_dep_mult (mp, (mp_value_node) y_part (value_node (cur_exp_node ())), vv, true);
} else if (mp->cur_exp.type == mp_color_type) {
mp_dep_mult (mp, (mp_value_node) red_part (value_node (cur_exp_node ())), vv, true);
mp_dep_mult (mp, (mp_value_node) green_part (value_node (cur_exp_node ())), vv, true);
mp_dep_mult (mp, (mp_value_node) blue_part (value_node (cur_exp_node ())), vv, true);
} else if (mp->cur_exp.type == mp_cmykcolor_type) {
mp_dep_mult (mp, (mp_value_node) cyan_part (value_node (cur_exp_node ())), vv, true);
mp_dep_mult (mp, (mp_value_node) magenta_part (value_node (cur_exp_node ())), vv, true);
mp_dep_mult (mp, (mp_value_node) yellow_part (value_node (cur_exp_node ())), vv, true);
mp_dep_mult (mp, (mp_value_node) black_part (value_node (cur_exp_node ())), vv, true);
} else {
mp_dep_mult (mp, NULL, vv, true);
}
free_number (vv);
binary_return;
} else if ((mp_nice_color_or_pair (mp, p, mp_type (p))
&& (mp->cur_exp.type > mp_pair_type))
|| (mp_nice_color_or_pair (mp, cur_exp_node (), mp->cur_exp.type)
&& (mp_type (p) > mp_pair_type))) {
mp_hard_times (mp, p);
binary_return;
} else {
mp_bad_binary (mp, p, mp_times);
}
break;
case mp_over:
if ((mp->cur_exp.type != mp_known) || (mp_type (p) < mp_color_type)) {
mp_bad_binary (mp, p, mp_over);
} else {
mp_number v_n;
new_number (v_n);
number_clone (v_n, cur_exp_value_number ());
mp_unstash_cur_exp (mp, p);
if (number_zero(v_n)) {
/* Squeal about division by zero */
const char *hlp[] = {
"You're trying to divide the quantity shown above the error",
"message by zero. I'm going to divide it by one instead.",
NULL };
mp_disp_err(mp, NULL);
mp_back_error (mp, "Division by zero", hlp, true);
mp_get_x_next (mp);
} else {
if (mp->cur_exp.type == mp_known) {
mp_number ret;
new_number (ret);
make_scaled (ret, cur_exp_value_number (), v_n);
set_cur_exp_value_number (ret);
free_number (ret);
} else if (mp->cur_exp.type == mp_pair_type) {
mp_dep_div (mp, (mp_value_node) x_part (value_node (cur_exp_node ())),
v_n);
mp_dep_div (mp, (mp_value_node) y_part (value_node (cur_exp_node ())),
v_n);
} else if (mp->cur_exp.type == mp_color_type) {
mp_dep_div (mp,
(mp_value_node) red_part (value_node (cur_exp_node ())),
v_n);
mp_dep_div (mp,
(mp_value_node) green_part (value_node (cur_exp_node ())),
v_n);
mp_dep_div (mp,
(mp_value_node) blue_part (value_node (cur_exp_node ())),
v_n);
} else if (mp->cur_exp.type == mp_cmykcolor_type) {
mp_dep_div (mp,
(mp_value_node) cyan_part (value_node (cur_exp_node ())),
v_n);
mp_dep_div (mp, (mp_value_node)
magenta_part (value_node (cur_exp_node ())), v_n);
mp_dep_div (mp, (mp_value_node)
yellow_part (value_node (cur_exp_node ())), v_n);
mp_dep_div (mp,
(mp_value_node) black_part (value_node (cur_exp_node ())),
v_n);
} else {
mp_dep_div (mp, NULL, v_n);
}
}
free_number(v_n);
binary_return;
}
break;
case mp_pythag_add:
case mp_pythag_sub:
if ((mp->cur_exp.type == mp_known) && (mp_type (p) == mp_known)) {
mp_number r;
new_number (r);
if (c == mp_pythag_add) {
pyth_add (r, value_number (p), cur_exp_value_number ());
} else {
pyth_sub (r, value_number (p), cur_exp_value_number ());
}
set_cur_exp_value_number (r);
free_number (r);
} else
mp_bad_binary (mp, p, (quarterword) c);
break;
case mp_rotated_by:
case mp_slanted_by:
case mp_scaled_by:
case mp_shifted_by:
case mp_transformed_by:
case mp_x_scaled:
case mp_y_scaled:
case mp_z_scaled:
/* The next few sections of the program deal with affine transformations
of coordinate data. */
if (mp_type (p) == mp_path_type) {
path_trans ((quarterword) c, p);
binary_return;
} else if (mp_type (p) == mp_pen_type) {
pen_trans ((quarterword) c, p);
set_cur_exp_knot (mp_convex_hull (mp, cur_exp_knot ()));
/* rounding error could destroy convexity */
binary_return;
} else if ((mp_type (p) == mp_pair_type) || (mp_type (p) == mp_transform_type)) {
mp_big_trans (mp, p, (quarterword) c);
} else if (mp_type (p) == mp_picture_type) {
mp_do_edges_trans (mp, p, (quarterword) c);
binary_return;
} else {
mp_bad_binary (mp, p, (quarterword) c);
}
break;
case mp_concatenate:
if ((mp->cur_exp.type == mp_string_type) && (mp_type (p) == mp_string_type)) {
mp_string str = mp_cat (mp, value_str (p), cur_exp_str());
delete_str_ref (cur_exp_str ()) ;
set_cur_exp_str (str);
} else
mp_bad_binary (mp, p, mp_concatenate);
break;
case mp_substring_of:
if (mp_nice_pair (mp, p, mp_type (p)) && (mp->cur_exp.type == mp_string_type)) {
mp_string str = mp_chop_string (mp,
cur_exp_str (),
round_unscaled (value_number (x_part (value_node(p)))),
round_unscaled (value_number (y_part (value_node(p)))));
delete_str_ref (cur_exp_str ()) ;
set_cur_exp_str (str);
} else
mp_bad_binary (mp, p, mp_substring_of);
break;
case mp_subpath_of:
if (mp->cur_exp.type == mp_pair_type)
mp_pair_to_path (mp);
if (mp_nice_pair (mp, p, mp_type (p)) && (mp->cur_exp.type == mp_path_type))
mp_chop_path (mp, value_node (p));
else
mp_bad_binary (mp, p, mp_subpath_of);
break;
case mp_point_of:
case mp_precontrol_of:
case mp_postcontrol_of:
if (mp->cur_exp.type == mp_pair_type)
mp_pair_to_path (mp);
if ((mp->cur_exp.type == mp_path_type) && (mp_type (p) == mp_known))
mp_find_point (mp, value_number (p), (quarterword) c);
else
mp_bad_binary (mp, p, (quarterword) c);
break;
case mp_pen_offset_of:
if ((mp->cur_exp.type == mp_pen_type) && mp_nice_pair (mp, p, mp_type (p)))
mp_set_up_offset (mp, value_node (p));
else
mp_bad_binary (mp, p, mp_pen_offset_of);
break;
case mp_direction_time_of:
if (mp->cur_exp.type == mp_pair_type)
mp_pair_to_path (mp);
if ((mp->cur_exp.type == mp_path_type) && mp_nice_pair (mp, p, mp_type (p)))
mp_set_up_direction_time (mp, value_node (p));
else
mp_bad_binary (mp, p, mp_direction_time_of);
break;
case mp_envelope_of:
if ((mp_type (p) != mp_pen_type) || (mp->cur_exp.type != mp_path_type))
mp_bad_binary (mp, p, mp_envelope_of);
else
mp_set_up_envelope (mp, p);
break;
case mp_glyph_infont:
if ((mp_type (p) != mp_string_type &&
mp_type (p) != mp_known) || (mp->cur_exp.type != mp_string_type))
mp_bad_binary (mp, p, mp_glyph_infont);
else
mp_set_up_glyph_infont (mp, p);
break;
case mp_arc_time_of:
if (mp->cur_exp.type == mp_pair_type)
mp_pair_to_path (mp);
if ((mp->cur_exp.type == mp_path_type) && (mp_type (p) == mp_known)) {
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
mp_get_arc_time (mp, &new_expr.data.n, cur_exp_knot (), value_number (p));
mp_flush_cur_exp (mp, new_expr);
} else {
mp_bad_binary (mp, p, (quarterword) c);
}
break;
case mp_intersect:
if (mp_type (p) == mp_pair_type) {
q = mp_stash_cur_exp (mp);
mp_unstash_cur_exp (mp, p);
mp_pair_to_path (mp);
p = mp_stash_cur_exp (mp);
mp_unstash_cur_exp (mp, q);
}
if (mp->cur_exp.type == mp_pair_type)
mp_pair_to_path (mp);
if ((mp->cur_exp.type == mp_path_type) && (mp_type (p) == mp_path_type)) {
mp_number arg1, arg2;
new_number (arg1);
new_number (arg2);
mp_path_intersection (mp, value_knot (p), cur_exp_knot ());
number_clone (arg1, mp->cur_t);
number_clone (arg2, mp->cur_tt);
mp_pair_value (mp, arg1, arg2);
free_number (arg1);
free_number (arg2);
} else {
mp_bad_binary (mp, p, mp_intersect);
}
break;
case mp_in_font:
if ((mp->cur_exp.type != mp_string_type) || mp_type (p) != mp_string_type) {
mp_bad_binary (mp, p, mp_in_font);
} else {
mp_do_infont (mp, p);
binary_return;
}
break;
} /* there are no other cases */
mp_recycle_value (mp, p);
mp_free_value_node (mp, p); /* |return| to avoid this */
mp_finish_binary (mp, old_p, old_exp);
}
@ @<Declare binary action...@>=
static void mp_bad_binary (MP mp, mp_node p, quarterword c) {
char msg[256];
mp_string sname;
int old_setting = mp->selector;
const char *hlp[] = {
"I'm afraid I don't know how to apply that operation to that",
"combination of types. Continue, and I'll return the second",
"argument (see above) as the result of the operation.",
NULL };
mp->selector = new_string;
if (c >= mp_min_of)
mp_print_op (mp, c);
mp_print_known_or_unknown_type (mp, mp_type (p), p);
if (c >= mp_min_of)
mp_print (mp, "of");
else
mp_print_op (mp, c);
mp_print_known_or_unknown_type (mp, mp->cur_exp.type, cur_exp_node ());
sname = mp_make_string(mp);
mp->selector = old_setting;
mp_snprintf (msg, 256, "Not implemented: %s", mp_str(mp, sname));
@.Not implemented...@>;
delete_str_ref(sname);
mp_disp_err (mp, p);
mp_disp_err (mp, NULL);
mp_back_error (mp, msg, hlp, true);
mp_get_x_next (mp);
}
static void mp_bad_envelope_pen (MP mp) {
const char *hlp[] = {
"I'm afraid I don't know how to apply that operation to that",
"combination of types. Continue, and I'll return the second",
"argument (see above) as the result of the operation.",
NULL };
mp_disp_err (mp, NULL);
mp_disp_err (mp, NULL);
mp_back_error (mp, "Not implemented: envelope(elliptical pen)of(path)", hlp, true);
@.Not implemented...@>;
mp_get_x_next (mp);
}
@ @<Declare binary action...@>=
static mp_node mp_tarnished (MP mp, mp_node p) {
mp_node q; /* beginning of the big node */
mp_node r; /* moving value node pointer */
(void) mp;
q = value_node (p);
switch (mp_type (p)) {
case mp_pair_type:
r = x_part (q);
if (mp_type (r) == mp_independent)
return MP_VOID;
r = y_part (q);
if (mp_type (r) == mp_independent)
return MP_VOID;
break;
case mp_color_type:
r = red_part (q);
if (mp_type (r) == mp_independent)
return MP_VOID;
r = green_part (q);
if (mp_type (r) == mp_independent)
return MP_VOID;
r = blue_part (q);
if (mp_type (r) == mp_independent)
return MP_VOID;
break;
case mp_cmykcolor_type:
r = cyan_part (q);
if (mp_type (r) == mp_independent)
return MP_VOID;
r = magenta_part (q);
if (mp_type (r) == mp_independent)
return MP_VOID;
r = yellow_part (q);
if (mp_type (r) == mp_independent)
return MP_VOID;
r = black_part (q);
if (mp_type (r) == mp_independent)
return MP_VOID;
break;
case mp_transform_type:
r = tx_part (q);
if (mp_type (r) == mp_independent)
return MP_VOID;
r = ty_part (q);
if (mp_type (r) == mp_independent)
return MP_VOID;
r = xx_part (q);
if (mp_type (r) == mp_independent)
return MP_VOID;
r = xy_part (q);
if (mp_type (r) == mp_independent)
return MP_VOID;
r = yx_part (q);
if (mp_type (r) == mp_independent)
return MP_VOID;
r = yy_part (q);
if (mp_type (r) == mp_independent)
return MP_VOID;
break;
default: /* there are no other valid cases, but please the compiler */
break;
}
return NULL;
}
@ The first argument to |add_or_subtract| is the location of a value node
in a capsule or pair node that will soon be recycled. The second argument
is either a location within a pair or transform node of |cur_exp|,
or it is NULL (which means that |cur_exp| itself should be the second
argument). The third argument is either |plus| or |minus|.
The sum or difference of the numeric quantities will replace the second
operand. Arithmetic overflow may go undetected; users aren't supposed to
be monkeying around with really big values.
@^overflow in arithmetic@>
@<Declare binary action...@>=
@<Declare the procedure called |dep_finish|@>;
static void mp_add_or_subtract (MP mp, mp_node p, mp_node q, quarterword c) {
mp_variable_type s, t; /* operand types */
mp_value_node r; /* dependency list traverser */
mp_value_node v = NULL; /* second operand value for dep lists */
mp_number vv; /* second operand value for known values */
new_number (vv);
if (q == NULL) {
t = mp->cur_exp.type;
if (t < mp_dependent)
number_clone (vv, cur_exp_value_number ());
else
v = (mp_value_node) dep_list ((mp_value_node) cur_exp_node ());
} else {
t = mp_type (q);
if (t < mp_dependent)
number_clone (vv, value_number (q));
else
v = (mp_value_node) dep_list ((mp_value_node) q);
}
if (t == mp_known) {
mp_value_node qq = (mp_value_node) q;
if (c == mp_minus)
number_negate (vv);
if (mp_type (p) == mp_known) {
slow_add (vv, value_number (p), vv);
if (q == NULL)
set_cur_exp_value_number (vv);
else
set_value_number (q, vv);
free_number (vv);
return;
}
/* Add a known value to the constant term of |dep_list(p)| */
r = (mp_value_node) dep_list ((mp_value_node) p);
while (dep_info (r) != NULL)
r = (mp_value_node) mp_link (r);
slow_add (vv, dep_value (r), vv);
set_dep_value (r, vv);
if (qq == NULL) {
qq = mp_get_dep_node (mp);
set_cur_exp_node ((mp_node) qq);
mp->cur_exp.type = mp_type (p);
mp_name_type (qq) = mp_capsule;
/* clang: never read: |q = (mp_node) qq;| */
}
set_dep_list (qq, dep_list ((mp_value_node) p));
mp_type (qq) = mp_type (p);
set_prev_dep (qq, prev_dep ((mp_value_node) p));
mp_link (prev_dep ((mp_value_node) p)) = (mp_node) qq;
mp_type (p) = mp_known; /* this will keep the recycler from collecting non-garbage */
} else {
if (c == mp_minus)
mp_negate_dep_list (mp, v);
/* Add operand |p| to the dependency list |v| */
/* We prefer |dependent| lists to |mp_proto_dependent| ones, because it is
nice to retain the extra accuracy of |fraction| coefficients.
But we have to handle both kinds, and mixtures too. */
if (mp_type (p) == mp_known) {
/* Add the known |value(p)| to the constant term of |v| */
while (dep_info (v) != NULL) {
v = (mp_value_node) mp_link (v);
}
slow_add (vv, value_number (p), dep_value (v));
set_dep_value (v, vv);
} else {
s = mp_type (p);
r = (mp_value_node) dep_list ((mp_value_node) p);
if (t == mp_dependent) {
if (s == mp_dependent) {
mp_number ret1, ret2;
new_fraction (ret1);
new_fraction (ret2);
mp_max_coef (mp, &ret1, r);
mp_max_coef (mp, &ret2, v);
number_add (ret1, ret2);
free_number (ret2);
if (number_less (ret1, coef_bound_k)) {
v = mp_p_plus_q (mp, v, r, mp_dependent);
free_number (ret1);
goto DONE;
}
free_number (ret1);
} /* |fix_needed| will necessarily be false */
t = mp_proto_dependent;
v = mp_p_over_v (mp, v, unity_t, mp_dependent, mp_proto_dependent);
}
if (s == mp_proto_dependent)
v = mp_p_plus_q (mp, v, r, mp_proto_dependent);
else
v = mp_p_plus_fq (mp, v, unity_t, r, mp_proto_dependent, mp_dependent);
DONE:
/* Output the answer, |v| (which might have become |known|) */
if (q != NULL) {
mp_dep_finish (mp, v, (mp_value_node) q, t);
} else {
mp->cur_exp.type = t;
mp_dep_finish (mp, v, NULL, t);
}
}
}
free_number (vv);
}
@ Here's the current situation: The dependency list |v| of type |t|
should either be put into the current expression (if |q=NULL|) or
into location |q| within a pair node (otherwise). The destination (|cur_exp|
or |q|) formerly held a dependency list with the same
final pointer as the list |v|.
@<Declare the procedure called |dep_finish|@>=
static void mp_dep_finish (MP mp, mp_value_node v, mp_value_node q,
quarterword t) {
mp_value_node p; /* the destination */
if (q == NULL)
p = (mp_value_node) cur_exp_node ();
else
p = q;
set_dep_list (p, v);
mp_type (p) = t;
if (dep_info (v) == NULL) {
mp_number vv; /* the value, if it is |known| */
new_number (vv);
number_clone (vv, value_number (v));
if (q == NULL) {
mp_value new_expr;
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
number_clone (new_expr.data.n, vv);
mp_flush_cur_exp (mp, new_expr);
} else {
mp_recycle_value (mp, (mp_node) p);
mp_type (q) = mp_known;
set_value_number (q, vv);
}
free_number (vv);
} else if (q == NULL) {
mp->cur_exp.type = t;
}
if (mp->fix_needed)
mp_fix_dependencies (mp);
}
@ @<Declare binary action...@>=
static void mp_dep_mult (MP mp, mp_value_node p, mp_number v, boolean v_is_scaled) {
mp_value_node q; /* the dependency list being multiplied by |v| */
quarterword s, t; /* its type, before and after */
if (p == NULL) {
q = (mp_value_node) cur_exp_node ();
} else if (mp_type (p) != mp_known) {
q = p;
} else {
{
mp_number r1, arg1;
new_number (arg1);
number_clone (arg1, dep_value (p));
if (v_is_scaled) {
new_number (r1);
take_scaled (r1, arg1, v);
} else {
new_fraction (r1);
take_fraction (r1, arg1, v);
}
set_dep_value (p, r1);
free_number (r1);
free_number (arg1);
}
return;
}
t = mp_type (q);
q = (mp_value_node) dep_list (q);
s = t;
if (t == mp_dependent) {
if (v_is_scaled) {
mp_number ab_vs_cd;
mp_number arg1, arg2;
new_number (ab_vs_cd);
new_number (arg2);
new_fraction (arg1);
mp_max_coef (mp, &arg1, q);
number_clone (arg2, v);
number_abs (arg2);
ab_vs_cd (ab_vs_cd, arg1, arg2, coef_bound_minus_1, unity_t);
free_number (arg1);
free_number (arg2);
if (number_nonnegative(ab_vs_cd)) {
t = mp_proto_dependent;
}
free_number (ab_vs_cd);
}
}
q = mp_p_times_v (mp, q, v, s, t, v_is_scaled);
mp_dep_finish (mp, q, p, t);
}
@ Here is a routine that is similar to |times|; but it is invoked only
internally, when |v| is a |fraction| whose magnitude is at most~1,
and when |cur_type>=mp_color_type|.
@c
static void mp_frac_mult (MP mp, mp_number n, mp_number d) {
/* multiplies |cur_exp| by |n/d| */
mp_node old_exp; /* a capsule to recycle */
mp_number v; /* |n/d| */
new_fraction (v);
if (number_greater (internal_value (mp_tracing_commands), two_t)) {
@<Trace the fraction multiplication@>;
}
switch (mp->cur_exp.type) {
case mp_transform_type:
case mp_color_type:
case mp_cmykcolor_type:
case mp_pair_type:
old_exp = mp_tarnished (mp, cur_exp_node ());
break;
case mp_independent:
old_exp = MP_VOID;
break;
default:
old_exp = NULL;
break;
}
if (old_exp != NULL) {
old_exp = cur_exp_node ();
mp_make_exp_copy (mp, old_exp);
}
make_fraction (v, n, d);
if (mp->cur_exp.type == mp_known) {
mp_number r1, arg1;
new_fraction (r1);
new_number (arg1);
number_clone (arg1, cur_exp_value_number ());
take_fraction (r1, arg1, v);
set_cur_exp_value_number (r1);
free_number (r1);
free_number (arg1);
} else if (mp->cur_exp.type == mp_pair_type) {
mp_dep_mult (mp, (mp_value_node) x_part (value_node (cur_exp_node ())), v, false);
mp_dep_mult (mp, (mp_value_node) y_part (value_node (cur_exp_node ())), v, false);
} else if (mp->cur_exp.type == mp_color_type) {
mp_dep_mult (mp, (mp_value_node) red_part (value_node (cur_exp_node ())), v, false);
mp_dep_mult (mp, (mp_value_node) green_part (value_node (cur_exp_node ())), v, false);
mp_dep_mult (mp, (mp_value_node) blue_part (value_node (cur_exp_node ())), v, false);
} else if (mp->cur_exp.type == mp_cmykcolor_type) {
mp_dep_mult (mp, (mp_value_node) cyan_part (value_node (cur_exp_node ())), v, false);
mp_dep_mult (mp, (mp_value_node) magenta_part (value_node (cur_exp_node ())), v, false);
mp_dep_mult (mp, (mp_value_node) yellow_part (value_node (cur_exp_node ())), v, false);
mp_dep_mult (mp, (mp_value_node) black_part (value_node (cur_exp_node ())), v, false);
} else {
mp_dep_mult (mp, NULL, v, false);
}
if (old_exp != NULL) {
mp_recycle_value (mp, old_exp);
mp_free_value_node (mp, old_exp);
}
free_number (v);
}
@ @<Trace the fraction multiplication@>=
{
mp_begin_diagnostic (mp);
mp_print_nl (mp, "{(");
print_number (n);
mp_print_char (mp, xord ('/'));
print_number (d);
mp_print (mp, ")*(");
mp_print_exp (mp, NULL, 0);
mp_print (mp, ")}");
mp_end_diagnostic (mp, false);
}
@ The |hard_times| routine multiplies a nice color or pair by a dependency list.
@<Declare binary action procedures@>=
static void mp_hard_times (MP mp, mp_node p) {
mp_value_node q; /* a copy of the dependent variable |p| */
mp_value_node pp; /* for typecasting p */
mp_node r; /* a component of the big node for the nice color or pair */
mp_number v; /* the known value for |r| */
new_number (v);
if (mp_type (p) <= mp_pair_type) {
q = (mp_value_node) mp_stash_cur_exp (mp);
mp_unstash_cur_exp (mp, p);
p = (mp_node) q;
} /* now |cur_type=mp_pair_type| or |cur_type=mp_color_type| or |cur_type=mp_cmykcolor_type| */
pp = (mp_value_node) p;
if (mp->cur_exp.type == mp_pair_type) {
r = x_part (value_node (cur_exp_node ()));
number_clone(v, value_number (r));
mp_new_dep (mp, r, mp_type (pp),
mp_copy_dep_list (mp, (mp_value_node) dep_list (pp)));
mp_dep_mult (mp, (mp_value_node) r, v, true);
r = y_part (value_node (cur_exp_node ()));
number_clone(v, value_number (r));
mp_new_dep (mp, r, mp_type (pp),
mp_copy_dep_list (mp, (mp_value_node) dep_list (pp)));
mp_dep_mult (mp, (mp_value_node) r, v, true);
} else if (mp->cur_exp.type == mp_color_type) {
r = red_part (value_node (cur_exp_node ()));
number_clone(v, value_number (r));
mp_new_dep (mp, r, mp_type (pp),
mp_copy_dep_list (mp, (mp_value_node) dep_list (pp)));
mp_dep_mult (mp, (mp_value_node) r, v, true);
r = green_part (value_node (cur_exp_node ()));
number_clone(v, value_number (r));
mp_new_dep (mp, r, mp_type (pp),
mp_copy_dep_list (mp, (mp_value_node) dep_list (pp)));
mp_dep_mult (mp, (mp_value_node) r, v, true);
r = blue_part (value_node (cur_exp_node ()));
number_clone(v, value_number (r));
mp_new_dep (mp, r, mp_type (pp),
mp_copy_dep_list (mp, (mp_value_node) dep_list (pp)));
mp_dep_mult (mp, (mp_value_node) r, v, true);
} else if (mp->cur_exp.type == mp_cmykcolor_type) {
r = cyan_part (value_node (cur_exp_node ()));
number_clone(v, value_number (r));
mp_new_dep (mp, r, mp_type (pp),
mp_copy_dep_list (mp, (mp_value_node) dep_list (pp)));
mp_dep_mult (mp, (mp_value_node) r, v, true);
r = yellow_part (value_node (cur_exp_node ()));
number_clone(v, value_number (r));
mp_new_dep (mp, r, mp_type (pp),
mp_copy_dep_list (mp, (mp_value_node) dep_list (pp)));
mp_dep_mult (mp, (mp_value_node) r, v, true);
r = magenta_part (value_node (cur_exp_node ()));
number_clone(v, value_number (r));
mp_new_dep (mp, r, mp_type (pp),
mp_copy_dep_list (mp, (mp_value_node) dep_list (pp)));
mp_dep_mult (mp, (mp_value_node) r, v, true);
r = black_part (value_node (cur_exp_node ()));
number_clone(v, value_number (r));
mp_new_dep (mp, r, mp_type (pp),
mp_copy_dep_list (mp, (mp_value_node) dep_list (pp)));
mp_dep_mult (mp, (mp_value_node) r, v, true);
}
free_number (v);
}
@ @<Declare binary action...@>=
static void mp_dep_div (MP mp, mp_value_node p, mp_number v) {
mp_value_node q; /* the dependency list being divided by |v| */
quarterword s, t; /* its type, before and after */
if (p == NULL)
q = (mp_value_node) cur_exp_node ();
else if (mp_type (p) != mp_known)
q = p;
else {
mp_number ret;
new_number (ret);
make_scaled (ret, value_number (p), v);
set_value_number (p, ret);
free_number (ret);
return;
}
t = mp_type (q);
q = (mp_value_node) dep_list (q);
s = t;
if (t == mp_dependent) {
mp_number ab_vs_cd;
mp_number arg1, arg2;
new_number (ab_vs_cd);
new_number (arg2);
new_fraction (arg1);
mp_max_coef (mp, &arg1, q);
number_clone (arg2, v);
number_abs (arg2);
ab_vs_cd (ab_vs_cd, arg1, unity_t, coef_bound_minus_1, arg2);
free_number (arg1);
free_number (arg2);
if (number_nonnegative(ab_vs_cd)) {
t = mp_proto_dependent;
}
free_number (ab_vs_cd);
}
q = mp_p_over_v (mp, q, v, s, t);
mp_dep_finish (mp, q, p, t);
}
@ Let |c| be one of the eight transform operators. The procedure call
|set_up_trans(c)| first changes |cur_exp| to a transform that corresponds to
|c| and the original value of |cur_exp|. (In particular, |cur_exp| doesn't
change at all if |c=transformed_by|.)
Then, if all components of the resulting transform are |known|, they are
moved to the global variables |txx|, |txy|, |tyx|, |tyy|, |tx|, |ty|;
and |cur_exp| is changed to the known value zero.
@<Declare binary action...@>=
static void mp_set_up_trans (MP mp, quarterword c) {
mp_node p, q, r; /* list manipulation registers */
mp_value new_expr;
memset(&new_expr,0,sizeof(mp_value));
if ((c != mp_transformed_by) || (mp->cur_exp.type != mp_transform_type)) {
/* Put the current transform into |cur_exp| */
const char *hlp[] = {
"The expression shown above has the wrong type,",
"so I can\'t transform anything using it.",
"Proceed, and I'll omit the transformation.",
NULL };
p = mp_stash_cur_exp (mp);
set_cur_exp_node (mp_id_transform (mp));
mp->cur_exp.type = mp_transform_type;
q = value_node (cur_exp_node ());
switch (c) {
@<For each of the eight cases, change the relevant fields of |cur_exp|
and |goto done|;
but do nothing if capsule |p| doesn't have the appropriate type@>;
}; /* there are no other cases */
mp_disp_err (mp, p);
mp_back_error (mp, "Improper transformation argument", hlp, true);
mp_get_x_next (mp);
DONE:
mp_recycle_value (mp, p);
mp_free_value_node (mp, p);
}
/* If the current transform is entirely known, stash it in global variables;
otherwise |return| */
q = value_node (cur_exp_node ());
if (mp_type (tx_part (q)) != mp_known)
return;
if (mp_type (ty_part (q)) != mp_known)
return;
if (mp_type (xx_part (q)) != mp_known)
return;
if (mp_type (xy_part (q)) != mp_known)
return;
if (mp_type (yx_part (q)) != mp_known)
return;
if (mp_type (yy_part (q)) != mp_known)
return;
number_clone(mp->txx, value_number (xx_part (q)));
number_clone(mp->txy, value_number (xy_part (q)));
number_clone(mp->tyx, value_number (yx_part (q)));
number_clone(mp->tyy, value_number (yy_part (q)));
number_clone(mp->tx, value_number (tx_part (q)));
number_clone(mp->ty, value_number (ty_part (q)));
new_number(new_expr.data.n);
set_number_to_zero (new_expr.data.n);
mp_flush_cur_exp (mp, new_expr);
}
@ @<Glob...@>=
mp_number txx;
mp_number txy;
mp_number tyx;
mp_number tyy;
mp_number tx;
mp_number ty; /* current transform coefficients */
@ @<Initialize table...@>=
new_number(mp->txx);
new_number(mp->txy);
new_number(mp->tyx);
new_number(mp->tyy);
new_number(mp->tx);
new_number(mp->ty);
@ @<Free table...@>=
free_number(mp->txx);
free_number(mp->txy);
free_number(mp->tyx);
free_number(mp->tyy);
free_number(mp->tx);
free_number(mp->ty);
@ @<For each of the eight cases...@>=
case mp_rotated_by:
if (mp_type (p) == mp_known)
@<Install sines and cosines, then |goto done|@>;
break;
case mp_slanted_by:
if (mp_type (p) > mp_pair_type) {
mp_install (mp, xy_part (q), p);
goto DONE;
}
break;
case mp_scaled_by:
if (mp_type (p) > mp_pair_type) {
mp_install (mp, xx_part (q), p);
mp_install (mp, yy_part (q), p);
goto DONE;
}
break;
case mp_shifted_by:
if (mp_type (p) == mp_pair_type) {
r = value_node (p);
mp_install (mp, tx_part (q), x_part (r));
mp_install (mp, ty_part (q), y_part (r));
goto DONE;
}
break;
case mp_x_scaled:
if (mp_type (p) > mp_pair_type) {
mp_install (mp, xx_part (q), p);
goto DONE;
}
break;
case mp_y_scaled:
if (mp_type (p) > mp_pair_type) {
mp_install (mp, yy_part (q), p);
goto DONE;
}
break;
case mp_z_scaled:
if (mp_type (p) == mp_pair_type)
@<Install a complex multiplier, then |goto done|@>;
break;
case mp_transformed_by:
break;
@ @<Install sines and cosines, then |goto done|@>=
{
mp_number n_sin, n_cos, arg1, arg2;
new_number (arg1);
new_number (arg2);
new_fraction (n_sin);
new_fraction (n_cos); /* results computed by |n_sin_cos| */
number_clone (arg2, unity_t);
number_clone (arg1, value_number (p));
number_multiply_int (arg2, 360);
number_modulo (arg1, arg2);
convert_scaled_to_angle (arg1);
n_sin_cos (arg1, n_cos, n_sin);
fraction_to_round_scaled (n_sin);
fraction_to_round_scaled (n_cos);
set_value_number (xx_part (q), n_cos);
set_value_number (yx_part (q), n_sin);
set_value_number (xy_part (q), value_number (yx_part (q)));
number_negate (value_number (xy_part (q)));
set_value_number (yy_part (q), value_number (xx_part (q)));
free_number (arg1);
free_number (arg2);
free_number (n_sin);
free_number (n_cos);
goto DONE;
}
@ @<Install a complex multiplier, then |goto done|@>=
{
r = value_node (p);
mp_install (mp, xx_part (q), x_part (r));
mp_install (mp, yy_part (q), x_part (r));
mp_install (mp, yx_part (q), y_part (r));
if (mp_type (y_part (r)) == mp_known) {
set_value_number (y_part (r), value_number (y_part (r)));
number_negate (value_number (y_part (r)));
} else {
mp_negate_dep_list (mp, (mp_value_node) dep_list ((mp_value_node)
y_part (r)));
}
mp_install (mp, xy_part (q), y_part (r));
goto DONE;
}
@ Procedure |set_up_known_trans| is like |set_up_trans|, but it
insists that the transformation be entirely known.
@<Declare binary action...@>=
static void mp_set_up_known_trans (MP mp, quarterword c) {
mp_set_up_trans (mp, c);
if (mp->cur_exp.type != mp_known) {
mp_value new_expr;
const char *hlp[] = {
"I'm unable to apply a partially specified transformation",
"except to a fully known pair or transform.",
"Proceed, and I'll omit the transformation.",
NULL };
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
mp_disp_err(mp, NULL);
set_number_to_zero (new_expr.data.n);
mp_back_error (mp,"Transform components aren't all known", hlp, true);
mp_get_x_next (mp);
mp_flush_cur_exp (mp, new_expr);
set_number_to_unity(mp->txx);
set_number_to_zero(mp->txy);
set_number_to_zero(mp->tyx);
set_number_to_unity(mp->tyy);
set_number_to_zero(mp->tx);
set_number_to_zero(mp->ty);
}
}
@ Here's a procedure that applies the transform |txx..ty| to a pair of
coordinates in locations |p| and~|q|.
@<Declare binary action...@>=
static void mp_number_trans (MP mp, mp_number *p, mp_number *q) {
mp_number r1, r2, v;
new_number (r1);
new_number (r2);
new_number (v);
take_scaled (r1, *p, mp->txx);
take_scaled (r2, *q, mp->txy);
number_add (r1, r2);
set_number_from_addition(v, r1, mp->tx);
take_scaled (r1, *p, mp->tyx);
take_scaled (r2, *q, mp->tyy);
number_add (r1, r2);
set_number_from_addition(*q, r1, mp->ty);
number_clone(*p,v);
free_number (r1);
free_number (r2);
free_number(v);
}
@ The simplest transformation procedure applies a transform to all
coordinates of a path. The |path_trans(c)(p)| macro applies
a transformation defined by |cur_exp| and the transform operator |c|
to the path~|p|.
@d path_trans(A,B) { mp_set_up_known_trans(mp, (A));
mp_unstash_cur_exp(mp, (B));
mp_do_path_trans(mp, cur_exp_knot()); }
@<Declare binary action...@>=
static void mp_do_path_trans (MP mp, mp_knot p) {
mp_knot q; /* list traverser */
q = p;
do {
if (mp_left_type (q) != mp_endpoint)
mp_number_trans (mp, &q->left_x, &q->left_y);
mp_number_trans (mp, &q->x_coord, &q->y_coord);
if (mp_right_type (q) != mp_endpoint)
mp_number_trans (mp, &q->right_x, &q->right_y);
q = mp_next_knot (q);
} while (q != p);
}
@ Transforming a pen is very similar, except that there are no |mp_left_type|
and |mp_right_type| fields.
@d pen_trans(A,B) { mp_set_up_known_trans(mp, (A));
mp_unstash_cur_exp(mp, (B));
mp_do_pen_trans(mp, cur_exp_knot()); }
@<Declare binary action...@>=
static void mp_do_pen_trans (MP mp, mp_knot p) {
mp_knot q; /* list traverser */
if (pen_is_elliptical (p)) {
mp_number_trans (mp, &p->left_x, &p->left_y);
mp_number_trans (mp, &p->right_x, &p->right_y);
}
q = p;
do {
mp_number_trans (mp, &q->x_coord, &q->y_coord);
q = mp_next_knot (q);
} while (q != p);
}
@ The next transformation procedure applies to edge structures. It will do
any transformation, but the results may be substandard if the picture contains
text that uses downloaded bitmap fonts. The binary action procedure is
|do_edges_trans|, but we also need a function that just scales a picture.
That routine is |scale_edges|. Both it and the underlying routine |edges_trans|
should be thought of as procedures that update an edge structure |h|, except
that they have to return a (possibly new) structure because of the need to call
|private_edges|.
@<Declare binary action...@>=
static mp_edge_header_node mp_edges_trans (MP mp, mp_edge_header_node h) {
mp_node q; /* the object being transformed */
mp_dash_node r, s; /* for list manipulation */
mp_number sx, sy; /* saved transformation parameters */
mp_number sqdet; /* square root of determinant for |dash_scale| */
mp_number sgndet; /* sign of the determinant */
h = mp_private_edges (mp, h);
new_number(sx);
new_number(sy);
new_number(sqdet);
new_number(sgndet);
mp_sqrt_det (mp, &sqdet, mp->txx, mp->txy, mp->tyx, mp->tyy);
ab_vs_cd (sgndet, mp->txx, mp->tyy, mp->txy, mp->tyx);
if (dash_list (h) != mp->null_dash) {
@<Try to transform the dash list of |h|@>;
}
@<Make the bounding box of |h| unknown if it can't be updated properly
without scanning the whole structure@>;
q = mp_link (edge_list (h));
while (q != NULL) {
@<Transform graphical object |q|@>;
q = mp_link (q);
}
free_number (sx);
free_number (sy);
free_number (sqdet);
free_number(sgndet);
return h;
}
static void mp_do_edges_trans (MP mp, mp_node p, quarterword c) {
mp_set_up_known_trans (mp, c);
set_value_node (p, (mp_node)mp_edges_trans (mp, (mp_edge_header_node)value_node (p)));
mp_unstash_cur_exp (mp, p);
}
static mp_edge_header_node mp_scale_edges (MP mp, mp_number se_sf, mp_edge_header_node se_pic) {
number_clone(mp->txx, se_sf);
number_clone(mp->tyy, se_sf);
set_number_to_zero(mp->txy);
set_number_to_zero(mp->tyx);
set_number_to_zero(mp->tx);
set_number_to_zero(mp->ty);
return mp_edges_trans (mp, se_pic);
}
@ @<Try to transform the dash list of |h|@>=
if (number_nonzero(mp->txy) || number_nonzero(mp->tyx) ||
number_nonzero(mp->ty) || number_nonequalabs (mp->txx, mp->tyy)) {
mp_flush_dash_list (mp, h);
} else {
mp_number abs_tyy, ret;
new_number (abs_tyy);
if (number_negative(mp->txx)) {
@<Reverse the dash list of |h|@>;
}
@<Scale the dash list by |txx| and shift it by |tx|@>;
number_clone(abs_tyy, mp->tyy);
number_abs (abs_tyy);
new_number (ret);
take_scaled (ret, h->dash_y, abs_tyy);
number_clone(h->dash_y, ret);
free_number (ret);
free_number (abs_tyy);
}
@ @<Reverse the dash list of |h|@>=
{
r = dash_list (h);
set_dash_list (h, mp->null_dash);
while (r != mp->null_dash) {
s = r;
r = (mp_dash_node)mp_link (r);
number_swap(s->start_x, s->stop_x );
mp_link (s) = (mp_node)dash_list (h);
set_dash_list (h, s);
}
}
@ @<Scale the dash list by |txx| and shift it by |tx|@>=
r = dash_list (h);
{
mp_number arg1;
new_number (arg1);
while (r != mp->null_dash) {
take_scaled (arg1, r->start_x, mp->txx);
set_number_from_addition(r->start_x, arg1, mp->tx);
take_scaled (arg1, r->stop_x, mp->txx);
set_number_from_addition(r->stop_x, arg1, mp->tx);
r = (mp_dash_node)mp_link (r);
}
free_number (arg1);
}
@ @<Make the bounding box of |h| unknown if it can't be updated properly...@>=
if (number_zero(mp->txx) && number_zero(mp->tyy)) {
@<Swap the $x$ and $y$ parameters in the bounding box of |h|@>;
} else if (number_nonzero(mp->txy) || number_nonzero(mp->tyx)) {
mp_init_bbox (mp, h);
goto DONE1;
}
if (number_lessequal (h->minx, h->maxx)) {
@<Scale the bounding box by |txx+txy| and |tyx+tyy|; then shift by
|(tx,ty)|@>;
}
DONE1:
@ @<Swap the $x$ and $y$ parameters in the bounding box of |h|@>=
{
number_swap(h->minx, h->miny);
number_swap(h->maxx, h->maxy);
}
@ The sum ``|txx+txy|'' is whichever of |txx| or |txy| is nonzero. The other
sum is similar.
@<Scale the bounding box by |txx+txy| and |tyx+tyy|; then shift...@>=
{
mp_number tot, ret;
new_number(tot);
new_number (ret);
set_number_from_addition(tot,mp->txx,mp->txy);
take_scaled (ret, h->minx, tot);
set_number_from_addition(h->minx,ret, mp->tx);
take_scaled (ret, h->maxx, tot);
set_number_from_addition(h->maxx,ret, mp->tx);
set_number_from_addition(tot,mp->tyx,mp->tyy);
take_scaled (ret, h->miny, tot);
set_number_from_addition(h->miny, ret, mp->ty);
take_scaled (ret, h->maxy, tot);
set_number_from_addition(h->maxy, ret, mp->ty);
set_number_from_addition(tot, mp->txx, mp->txy);
if (number_negative(tot)) {
number_swap(h->minx, h->maxx);
}
set_number_from_addition(tot, mp->tyx, mp->tyy);
if (number_negative(tot)) {
number_swap(h->miny, h->maxy);
}
free_number (ret);
free_number (tot);
}
@ Now we ready for the main task of transforming the graphical objects in edge
structure~|h|.
@<Transform graphical object |q|@>=
switch (mp_type (q)) {
case mp_fill_node_type:
{
mp_fill_node qq = (mp_fill_node) q;
mp_do_path_trans (mp, mp_path_p (qq));
@<Transform |mp_pen_p(qq)|, making sure polygonal pens stay counter-clockwise@>;
}
break;
case mp_stroked_node_type:
{
mp_stroked_node qq = (mp_stroked_node) q;
mp_do_path_trans (mp, mp_path_p (qq));
@<Transform |mp_pen_p(qq)|, making sure polygonal pens stay counter-clockwise@>;
}
break;
case mp_start_clip_node_type:
mp_do_path_trans (mp, mp_path_p ((mp_start_clip_node) q));
break;
case mp_start_bounds_node_type:
mp_do_path_trans (mp, mp_path_p ((mp_start_bounds_node) q));
break;
case mp_text_node_type:
@<Transform the compact transformation@>;
break;
case mp_stop_clip_node_type:
case mp_stop_bounds_node_type:
break;
default: /* there are no other valid cases, but please the compiler */
break;
}
@ Note that the shift parameters |(tx,ty)| apply only to the path being stroked.
The |dash_scale| has to be adjusted to scale the dash lengths in |mp_dash_p(q)|
since the \ps\ output procedures will try to compensate for the transformation
we are applying to |mp_pen_p(q)|. Since this compensation is based on the square
root of the determinant, |sqdet| is the appropriate factor.
We pass the mptrap test only if |dash_scale| is not adjusted, nowadays
(backend is changed?)
@<Transform |mp_pen_p(qq)|, making sure...@>=
if (mp_pen_p (qq) != NULL) {
number_clone(sx, mp->tx);
number_clone(sy, mp->ty);
set_number_to_zero(mp->tx);
set_number_to_zero(mp->ty);
mp_do_pen_trans (mp, mp_pen_p (qq));
if (number_nonzero(sqdet)
&& ((mp_type (q) == mp_stroked_node_type) && (mp_dash_p (q) != NULL))) {
mp_number ret;
new_number (ret);
take_scaled (ret, ((mp_stroked_node)q)->dash_scale, sqdet);
number_clone(((mp_stroked_node)q)->dash_scale, ret);
free_number (ret);
}
if (!pen_is_elliptical (mp_pen_p (qq)))
if (number_negative(sgndet))
mp_pen_p (qq) = mp_make_pen (mp, mp_copy_path (mp, mp_pen_p (qq)), true);
/* this unreverses the pen */
number_clone(mp->tx, sx);
number_clone(mp->ty, sy);
}
@ @<Transform the compact transformation@>=
mp_number_trans (mp, &((mp_text_node)q)->tx, &((mp_text_node)q)->ty);
number_clone(sx, mp->tx);
number_clone(sy, mp->ty);
set_number_to_zero(mp->tx);
set_number_to_zero(mp->ty);
mp_number_trans (mp, &((mp_text_node)q)->txx, &((mp_text_node)q)->tyx);
mp_number_trans (mp, &((mp_text_node)q)->txy, &((mp_text_node)q)->tyy);
number_clone(mp->tx, sx);
number_clone(mp->ty, sy)
@ The hard cases of transformation occur when big nodes are involved,
and when some of their components are unknown.
@<Declare binary action...@>=
@<Declare subroutines needed by |big_trans|@>;
static void mp_big_trans (MP mp, mp_node p, quarterword c) {
mp_node q, r, pp, qq; /* list manipulation registers */
q = value_node (p);
if (mp_type (q) == mp_pair_node_type) {
if (mp_type (x_part (q)) != mp_known ||
mp_type (y_part (q)) != mp_known) {
@<Transform an unknown big node and |return|@>;
}
} else { /* |mp_transform_type| */
if (mp_type (tx_part (q)) != mp_known ||
mp_type (ty_part (q)) != mp_known ||
mp_type (xx_part (q)) != mp_known ||
mp_type (xy_part (q)) != mp_known ||
mp_type (yx_part (q)) != mp_known ||
mp_type (yy_part (q)) != mp_known) {
@<Transform an unknown big node and |return|@>;
}
}
@<Transform a known big node@>;
} /* node |p| will now be recycled by |do_binary| */
@ @<Transform an unknown big node and |return|@>=
{
mp_set_up_known_trans (mp, c);
mp_make_exp_copy (mp, p);
r = value_node (cur_exp_node ());
if (mp->cur_exp.type == mp_transform_type) {
mp_bilin1 (mp, yy_part (r), mp->tyy, xy_part (q), mp->tyx, zero_t);
mp_bilin1 (mp, yx_part (r), mp->tyy, xx_part (q), mp->tyx, zero_t);
mp_bilin1 (mp, xy_part (r), mp->txx, yy_part (q), mp->txy, zero_t);
mp_bilin1 (mp, xx_part (r), mp->txx, yx_part (q), mp->txy, zero_t);
}
mp_bilin1 (mp, y_part (r), mp->tyy, x_part (q), mp->tyx, mp->ty);
mp_bilin1 (mp, x_part (r), mp->txx, y_part (q), mp->txy, mp->tx);
return;
}
@ Let |p| point to a value field inside a big node of |cur_exp|,
and let |q| point to a another value field. The |bilin1| procedure
replaces |p| by $p\cdot t+q\cdot u+\delta$.
@<Declare subroutines needed by |big_trans|@>=
static void mp_bilin1 (MP mp, mp_node p, mp_number t, mp_node q,
mp_number u, mp_number delta_orig) {
mp_number delta;
new_number (delta);
number_clone (delta, delta_orig);
if (!number_equal(t, unity_t)) {
mp_dep_mult (mp, (mp_value_node) p, t, true);
}
if (number_nonzero(u)) {
if (mp_type (q) == mp_known) {
mp_number tmp;
new_number (tmp);
take_scaled (tmp, value_number (q), u);
number_add (delta, tmp);
free_number (tmp);
} else {
/* Ensure that |type(p)=mp_proto_dependent| */
if (mp_type (p) != mp_proto_dependent) {
if (mp_type (p) == mp_known) {
mp_new_dep (mp, p, mp_type (p), mp_const_dependency (mp, value_number (p)));
} else {
set_dep_list ((mp_value_node) p,
mp_p_times_v (mp,
(mp_value_node) dep_list ((mp_value_node)
p), unity_t,
mp_dependent, mp_proto_dependent, true));
}
mp_type (p) = mp_proto_dependent;
}
set_dep_list ((mp_value_node) p,
mp_p_plus_fq (mp,
(mp_value_node) dep_list ((mp_value_node) p), u,
(mp_value_node) dep_list ((mp_value_node) q),
mp_proto_dependent, mp_type (q)));
}
}
if (mp_type (p) == mp_known) {
set_value_number (p, value_number (p));
number_add (value_number (p), delta);
} else {
mp_number tmp;
mp_value_node r; /* list traverser */
new_number (tmp);
r = (mp_value_node) dep_list ((mp_value_node) p);
while (dep_info (r) != NULL)
r = (mp_value_node) mp_link (r);
number_clone (tmp, value_number(r));
number_add (delta, tmp);
if (r != (mp_value_node) dep_list ((mp_value_node) p))
set_value_number (r, delta);
else {
mp_recycle_value (mp, p);
mp_type (p) = mp_known;
set_value_number (p, delta);
}
free_number (tmp);
}
if (mp->fix_needed)
mp_fix_dependencies (mp);
free_number (delta);
}
@ @<Transform a known big node@>=
mp_set_up_trans (mp, c);
if (mp->cur_exp.type == mp_known) {
@<Transform known by known@>;
} else {
pp = mp_stash_cur_exp (mp);
qq = value_node (pp);
mp_make_exp_copy (mp, p);
r = value_node (cur_exp_node ());
if (mp->cur_exp.type == mp_transform_type) {
mp_bilin2 (mp, yy_part (r), yy_part (qq), value_number (xy_part (q)),
yx_part (qq), NULL);
mp_bilin2 (mp, yx_part (r), yy_part (qq), value_number (xx_part (q)),
yx_part (qq), NULL);
mp_bilin2 (mp, xy_part (r), xx_part (qq), value_number (yy_part (q)),
xy_part (qq), NULL);
mp_bilin2 (mp, xx_part (r), xx_part (qq), value_number (yx_part (q)),
xy_part (qq), NULL);
}
mp_bilin2 (mp, y_part (r), yy_part (qq), value_number (x_part (q)),
yx_part (qq), y_part (qq));
mp_bilin2 (mp, x_part (r), xx_part (qq), value_number (y_part (q)),
xy_part (qq), x_part (qq));
mp_recycle_value (mp, pp);
mp_free_value_node (mp, pp);
}
@ Let |p| be a |mp_proto_dependent| value whose dependency list ends
at |dep_final|. The following procedure adds |v| times another
numeric quantity to~|p|.
@<Declare subroutines needed by |big_trans|@>=
static void mp_add_mult_dep (MP mp, mp_value_node p, mp_number v, mp_node r) {
if (mp_type (r) == mp_known) {
mp_number ret;
new_number (ret);
take_scaled (ret, value_number (r), v);
set_dep_value (mp->dep_final, dep_value (mp->dep_final));
number_add (dep_value (mp->dep_final), ret);
free_number (ret);
} else {
set_dep_list (p,
mp_p_plus_fq (mp, (mp_value_node) dep_list (p), v,
(mp_value_node) dep_list ((mp_value_node) r),
mp_proto_dependent, mp_type (r)));
if (mp->fix_needed)
mp_fix_dependencies (mp);
}
}
@ The |bilin2| procedure is something like |bilin1|, but with known
and unknown quantities reversed. Parameter |p| points to a value field
within the big node for |cur_exp|; and |type(p)=mp_known|. Parameters
|t| and~|u| point to value fields elsewhere; so does parameter~|q|,
unless it is |NULL| (which stands for zero). Location~|p| will be
replaced by $p\cdot t+v\cdot u+q$.
@<Declare subroutines needed by |big_trans|@>=
static void mp_bilin2 (MP mp, mp_node p, mp_node t, mp_number v,
mp_node u, mp_node q) {
mp_number vv; /* temporary storage for |value(p)| */
new_number (vv);
number_clone (vv, value_number (p));
mp_new_dep (mp, p, mp_proto_dependent, mp_const_dependency (mp, zero_t)); /* this sets |dep_final| */
if (number_nonzero(vv)) {
mp_add_mult_dep (mp, (mp_value_node) p, vv, t); /* |dep_final| doesn't change */
}
if (number_nonzero(v)) {
mp_number arg1;
new_number (arg1);
number_clone (arg1, v);
mp_add_mult_dep (mp, (mp_value_node) p, arg1, u);
free_number (arg1);
}
if (q != NULL)
mp_add_mult_dep (mp, (mp_value_node) p, unity_t, q);
if (dep_list ((mp_value_node) p) == (mp_node) mp->dep_final) {
number_clone (vv, dep_value (mp->dep_final));
mp_recycle_value (mp, p);
mp_type (p) = mp_known;
set_value_number (p, vv);
}
free_number (vv);
}
@ @<Transform known by known@>=
{
mp_make_exp_copy (mp, p);
r = value_node (cur_exp_node ());
if (mp->cur_exp.type == mp_transform_type) {
mp_bilin3 (mp, yy_part (r), mp->tyy, value_number (xy_part (q)), mp->tyx, zero_t);
mp_bilin3 (mp, yx_part (r), mp->tyy, value_number (xx_part (q)), mp->tyx, zero_t);
mp_bilin3 (mp, xy_part (r), mp->txx, value_number (yy_part (q)), mp->txy, zero_t);
mp_bilin3 (mp, xx_part (r), mp->txx, value_number (yx_part (q)), mp->txy, zero_t);
}
mp_bilin3 (mp, y_part (r), mp->tyy, value_number (x_part (q)), mp->tyx, mp->ty);
mp_bilin3 (mp, x_part (r), mp->txx, value_number (y_part (q)), mp->txy, mp->tx);
}
@ Finally, in |bilin3| everything is |known|.
@<Declare subroutines needed by |big_trans|@>=
static void mp_bilin3 (MP mp, mp_node p, mp_number t,
mp_number v, mp_number u, mp_number delta_orig) {
mp_number delta;
mp_number tmp;
new_number (tmp);
new_number (delta);
number_clone (delta, delta_orig);
if (!number_equal(t, unity_t)) {
take_scaled (tmp, value_number (p), t);
} else {
number_clone (tmp, value_number (p));
}
number_add (delta, tmp);
if (number_nonzero(u)) {
mp_number ret;
new_number (ret);
take_scaled (ret, v, u);
set_value_number (p, delta);
number_add (value_number (p), ret);
free_number (ret);
} else
set_value_number (p, delta);
free_number (tmp);
free_number (delta);
}
@ @<Declare binary action...@>=
static void mp_chop_path (MP mp, mp_node p) {
mp_knot q; /* a knot in the original path */
mp_knot pp, qq, rr, ss; /* link variables for copies of path nodes */
mp_number a, b; /* indices for chopping */
mp_number l;
boolean reversed; /* was |a>b|? */
new_number (a);
new_number (b);
new_number (l);
mp_path_length (mp, &l);
number_clone (a, value_number (x_part (p)));
number_clone (b, value_number (y_part (p)));
if (number_lessequal(a, b)) {
reversed = false;
} else {
reversed = true;
number_swap (a, b);
}
/* Dispense with the cases |a<0| and/or |b>l| */
if (number_negative(a)) {
if (mp_left_type (cur_exp_knot ()) == mp_endpoint) {
set_number_to_zero(a);
if (number_negative(b))
set_number_to_zero(b);
} else {
do {
number_add (a, l);
number_add (b, l);
} while (number_negative(a)); /* a cycle always has length |l>0| */
}
}
if (number_greater (b, l)) {
if (mp_left_type (cur_exp_knot ()) == mp_endpoint) {
number_clone (b, l);
if (number_greater (a, l))
number_clone(a, l);
} else {
while (number_greaterequal (a, l)) {
number_substract (a, l);
number_substract (b, l);
}
}
}
q = cur_exp_knot ();
while (number_greaterequal(a, unity_t)) {
q = mp_next_knot (q);
number_substract(a, unity_t);
number_substract(b, unity_t);
}
if (number_equal(b, a)) {
/* Construct a path from |pp| to |qq| of length zero */
if (number_positive (a)) {
mp_number arg1;
new_number (arg1);
number_clone (arg1, a);
convert_scaled_to_fraction (arg1);
mp_split_cubic (mp, q, arg1);
free_number (arg1);
q = mp_next_knot (q);
}
pp = mp_copy_knot (mp, q);
qq = pp;
} else {
/* Construct a path from |pp| to |qq| of length $\lceil b\rceil$ */
pp = mp_copy_knot (mp, q);
qq = pp;
do {
q = mp_next_knot (q);
rr = qq;
qq = mp_copy_knot (mp, q);
mp_next_knot (rr) = qq;
number_substract (b, unity_t);
} while (number_positive (b));
if (number_positive (a)) {
mp_number arg1;
new_number (arg1);
ss = pp;
number_clone (arg1, a);
convert_scaled_to_fraction (arg1);
mp_split_cubic (mp, ss, arg1);
free_number (arg1);
pp = mp_next_knot (ss);
mp_toss_knot (mp, ss);
if (rr == ss) {
mp_number arg1, arg2;
new_number (arg1);
new_number (arg2);
set_number_from_substraction (arg1, unity_t, a);
number_clone (arg2, b);
make_scaled (b, arg2, arg1);
free_number (arg1);
free_number (arg2);
rr = pp;
}
}
if (number_negative (b)) {
mp_number arg1;
new_number (arg1);
set_number_from_addition (arg1, b, unity_t);
convert_scaled_to_fraction (arg1);
mp_split_cubic (mp, rr, arg1);
free_number (arg1);
mp_toss_knot (mp, qq);
qq = mp_next_knot (rr);
}
}
mp_left_type (pp) = mp_endpoint;
mp_right_type (qq) = mp_endpoint;
mp_next_knot (qq) = pp;
mp_toss_knot_list (mp, cur_exp_knot ());
if (reversed) {
set_cur_exp_knot (mp_next_knot (mp_htap_ypoc (mp, pp)));
mp_toss_knot_list (mp, pp);
} else {
set_cur_exp_knot (pp);
}
free_number (l);
free_number (a);
free_number (b);
}
@ @<Declare binary action...@>=
static void mp_set_up_offset (MP mp, mp_node p) {
mp_find_offset (mp, value_number (x_part (p)), value_number (y_part (p)),
cur_exp_knot ());
mp_pair_value (mp, mp->cur_x, mp->cur_y);
}
static void mp_set_up_direction_time (MP mp, mp_node p) {
mp_value new_expr;
memset(&new_expr,0,sizeof(mp_value));
new_number (new_expr.data.n);
mp_find_direction_time (mp, &new_expr.data.n, value_number (x_part (p)),
value_number (y_part (p)),
cur_exp_knot ());
mp_flush_cur_exp (mp, new_expr);
}
static void mp_set_up_envelope (MP mp, mp_node p) {
unsigned char ljoin, lcap;
mp_number miterlim;
mp_knot q = mp_copy_path (mp, cur_exp_knot ()); /* the original path */
new_number(miterlim);
/* TODO: accept elliptical pens for straight paths */
if (pen_is_elliptical (value_knot (p))) {
mp_bad_envelope_pen (mp);
set_cur_exp_knot (q);
mp->cur_exp.type = mp_path_type;
return;
}
if (number_greater (internal_value (mp_linejoin), unity_t))
ljoin = 2;
else if (number_positive (internal_value (mp_linejoin)))
ljoin = 1;
else
ljoin = 0;
if (number_greater (internal_value (mp_linecap), unity_t))
lcap = 2;
else if (number_positive (internal_value (mp_linecap)))
lcap = 1;
else
lcap = 0;
if (number_less (internal_value (mp_miterlimit), unity_t))
set_number_to_unity(miterlim);
else
number_clone(miterlim, internal_value (mp_miterlimit));
set_cur_exp_knot (mp_make_envelope
(mp, q, value_knot (p), ljoin, lcap, miterlim));
mp->cur_exp.type = mp_path_type;
}
@ This is pretty straightfoward. The one silly thing is that
the output of |mp_ps_do_font_charstring| has to be un-exported.
@<Declare binary action...@>=
static void mp_set_up_glyph_infont (MP mp, mp_node p) {
mp_edge_object *h = NULL;
mp_ps_font *f = NULL;
char *n = mp_str (mp, cur_exp_str ());
f = mp_ps_font_parse (mp, (int) mp_find_font (mp, n));
if (f != NULL) {
if (mp_type (p) == mp_known) {
int v = round_unscaled (value_number (p));
if (v < 0 || v > 255) {
char msg[256];
mp_snprintf (msg, 256, "glyph index too high (%d)", v);
mp_error (mp, msg, NULL, true);
} else {
h = mp_ps_font_charstring (mp, f, v);
}
} else {
n = mp_str (mp, value_str (p));
h = mp_ps_do_font_charstring (mp, f, n);
}
mp_ps_font_free (mp, f);
}
if (h != NULL) {
set_cur_exp_node ((mp_node)mp_gr_import (mp, h));
} else {
set_cur_exp_node ((mp_node)mp_get_edge_header_node (mp));
mp_init_edges (mp, (mp_edge_header_node)cur_exp_node ());
}
mp->cur_exp.type = mp_picture_type;
}
@ @<Declare binary action...@>=
static void mp_find_point (MP mp, mp_number v_orig, quarterword c) {
mp_knot p; /* the path */
mp_number n; /* its length */
mp_number v;
new_number (v);
new_number (n);
number_clone (v, v_orig);
p = cur_exp_knot ();
if (mp_left_type (p) == mp_endpoint) {
set_number_to_unity (n);
number_negate (n);
} else {
set_number_to_zero (n);
}
do {
p = mp_next_knot (p);
number_add (n, unity_t);
} while (p != cur_exp_knot ());
if (number_zero (n)) {
set_number_to_zero(v);
} else if (number_negative(v)) {
if (mp_left_type (p) == mp_endpoint) {
set_number_to_zero(v);
} else {
/* |v = n - 1 - ((-v - 1) % n)
== - ((-v - 1) % n) - 1 + n| */
number_negate (v);
number_add_scaled (v, -1);
number_modulo (v, n);
number_negate (v);
number_add_scaled (v, -1);
number_add (v, n);
}
} else if (number_greater(v, n)) {
if (mp_left_type (p) == mp_endpoint)
number_clone (v, n);
else
number_modulo (v, n);
}
p = cur_exp_knot ();
while (number_greaterequal(v, unity_t)) {
p = mp_next_knot (p);
number_substract (v, unity_t);
}
if (number_nonzero(v)) {
/* Insert a fractional node by splitting the cubic */
convert_scaled_to_fraction (v);
mp_split_cubic (mp, p, v);
p = mp_next_knot (p);
}
/* Set the current expression to the desired path coordinates */
switch (c) {
case mp_point_of:
mp_pair_value (mp, p->x_coord, p->y_coord);
break;
case mp_precontrol_of:
if (mp_left_type (p) == mp_endpoint)
mp_pair_value (mp, p->x_coord, p->y_coord);
else
mp_pair_value (mp, p->left_x, p->left_y);
break;
case mp_postcontrol_of:
if (mp_right_type (p) == mp_endpoint)
mp_pair_value (mp, p->x_coord, p->y_coord);
else
mp_pair_value (mp, p->right_x, p->right_y);
break;
} /* there are no other cases */
free_number (v);
free_number (n);
}
@ Function |new_text_node| owns the reference count for its second argument
(the text string) but not its first (the font name).
@<Declare binary action...@>=
static void mp_do_infont (MP mp, mp_node p) {
mp_edge_header_node q;
mp_value new_expr;
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
q = mp_get_edge_header_node (mp);
mp_init_edges (mp, q);
add_str_ref (cur_exp_str());
mp_link (obj_tail (q)) =
mp_new_text_node (mp, mp_str (mp, cur_exp_str ()), value_str (p));
obj_tail (q) = mp_link (obj_tail (q));
mp_free_value_node (mp, p);
new_expr.data.node = (mp_node)q;
mp_flush_cur_exp (mp, new_expr);
mp->cur_exp.type = mp_picture_type;
}
@* Statements and commands.
The chief executive of \MP\ is the |do_statement| routine, which
contains the master switch that causes all the various pieces of \MP\
to do their things, in the right order.
In a sense, this is the grand climax of the program: It applies all the
tools that we have worked so hard to construct. In another sense, this is
the messiest part of the program: It necessarily refers to other pieces
of code all over the place, so that a person can't fully understand what is
going on without paging back and forth to be reminded of conventions that
are defined elsewhere. We are now at the hub of the web.
The structure of |do_statement| itself is quite simple. The first token
of the statement is fetched using |get_x_next|. If it can be the first
token of an expression, we look for an equation, an assignment, or a
title. Otherwise we use a \&{case} construction to branch at high speed to
the appropriate routine for various and sundry other types of commands,
each of which has an ``action procedure'' that does the necessary work.
The program uses the fact that
$$\hbox{|min_primary_command=max_statement_command=type_name|}$$
to interpret a statement that starts with, e.g., `\&{string}',
as a type declaration rather than a boolean expression.
@c
static void worry_about_bad_statement (MP mp);
static void flush_unparsable_junk_after_statement (MP mp);
void mp_do_statement (MP mp) { /* governs \MP's activities */
mp->cur_exp.type = mp_vacuous;
mp_get_x_next (mp);
if (cur_cmd() > mp_max_primary_command) {
worry_about_bad_statement (mp);
} else if (cur_cmd() > mp_max_statement_command) {
/* Do an equation, assignment, title, or
`$\langle\,$expression$\,\rangle\,$\&{endgroup}'; */
/* The most important statements begin with expressions */
mp_value new_expr;
mp->var_flag = mp_assignment;
mp_scan_expression (mp);
if (cur_cmd() < mp_end_group) {
if (cur_cmd() == mp_equals)
mp_do_equation (mp);
else if (cur_cmd() == mp_assignment)
mp_do_assignment (mp);
else if (mp->cur_exp.type == mp_string_type) {
/* Do a title */
if (number_positive (internal_value (mp_tracing_titles))) {
mp_print_nl (mp, "");
mp_print_str (mp, cur_exp_str ());
update_terminal();
}
} else if (mp->cur_exp.type != mp_vacuous) {
const char *hlp[] = {
"I couldn't find an `=' or `:=' after the",
"expression that is shown above this error message,",
"so I guess I'll just ignore it and carry on.",
NULL };
mp_disp_err(mp, NULL);
mp_back_error (mp, "Isolated expression", hlp, true);
mp_get_x_next (mp);
}
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
set_number_to_zero (new_expr.data.n);
mp_flush_cur_exp (mp, new_expr);
mp->cur_exp.type = mp_vacuous;
}
} else {
/* Do a statement that doesn't begin with an expression */
/* If |do_statement| ends with |cur_cmd=end_group|, we should have
|cur_type=mp_vacuous| unless the statement was simply an expression;
in the latter case, |cur_type| and |cur_exp| should represent that
expression. */
if (number_positive (internal_value (mp_tracing_commands)))
show_cur_cmd_mod;
switch (cur_cmd()) {
case mp_type_name:
mp_do_type_declaration (mp);
break;
case mp_macro_def:
if (cur_mod() > var_def)
mp_make_op_def (mp);
else if (cur_mod() > end_def)
mp_scan_def (mp);
break;
case mp_random_seed:
mp_do_random_seed (mp);
break;
case mp_mode_command:
mp_print_ln (mp);
mp->interaction = cur_mod();
initialize_print_selector();
if (mp->log_opened)
mp->selector = mp->selector + 2;
mp_get_x_next (mp);
break;
case mp_protection_command:
mp_do_protection (mp);
break;
case mp_delimiters:
mp_def_delims (mp);
break;
case mp_save_command:
do {
mp_get_symbol (mp);
mp_save_variable (mp, cur_sym());
mp_get_x_next (mp);
} while (cur_cmd() == mp_comma);
break;
case mp_interim_command:
mp_do_interim (mp);
break;
case mp_let_command:
mp_do_let (mp);
break;
case mp_new_internal:
mp_do_new_internal (mp);
break;
case mp_show_command:
mp_do_show_whatever (mp);
break;
case mp_add_to_command:
mp_do_add_to (mp);
break;
case mp_bounds_command:
mp_do_bounds (mp);
break;
case mp_ship_out_command:
mp_do_ship_out (mp);
break;
case mp_every_job_command:
mp_get_symbol (mp);
mp->start_sym = cur_sym();
mp_get_x_next (mp);
break;
case mp_message_command:
mp_do_message (mp);
break;
case mp_write_command:
mp_do_write (mp);
break;
case mp_tfm_command:
mp_do_tfm_command (mp);
break;
case mp_special_command:
if (cur_mod() == 0)
mp_do_special (mp);
else if (cur_mod() == 1)
mp_do_mapfile (mp);
else
mp_do_mapline (mp);
break;
default:
break; /* make the compiler happy */
}
mp->cur_exp.type = mp_vacuous;
}
if (cur_cmd() < mp_semicolon)
flush_unparsable_junk_after_statement(mp);
mp->error_count = 0;
}
@ @<Declarations@>=
@<Declare action procedures for use by |do_statement|@>
@ The only command codes |>max_primary_command| that can be present
at the beginning of a statement are |semicolon| and higher; these
occur when the statement is null.
@c
static void worry_about_bad_statement (MP mp) {
if (cur_cmd() < mp_semicolon) {
char msg[256];
mp_string sname;
int old_setting = mp->selector;
const char *hlp[] = {
"I was looking for the beginning of a new statement.",
"If you just proceed without changing anything, I'll ignore",
"everything up to the next `;'. Please insert a semicolon",
"now in front of anything that you don't want me to delete.",
"(See Chapter 27 of The METAFONTbook for an example.)",
NULL };
mp->selector = new_string;
mp_print_cmd_mod (mp, cur_cmd(), cur_mod());
sname = mp_make_string(mp);
mp->selector = old_setting;
mp_snprintf (msg, 256, "A statement can't begin with `%s'", mp_str(mp, sname));
delete_str_ref(sname);
mp_back_error (mp, msg, hlp, true);
mp_get_x_next (mp);
}
}
@ The help message printed here says that everything is flushed up to
a semicolon, but actually the commands |end_group| and |stop| will
also terminate a statement.
@c
static void flush_unparsable_junk_after_statement (MP mp)
{
const char *hlp[] = {
"I've just read as much of that statement as I could fathom,",
"so a semicolon should have been next. It's very puzzling...",
"but I'll try to get myself back together, by ignoring",
"everything up to the next `;'. Please insert a semicolon",
"now in front of anything that you don't want me to delete.",
"(See Chapter 27 of The METAFONTbook for an example.)",
NULL };
mp_back_error (mp, "Extra tokens will be flushed", hlp, true);
mp->scanner_status = flushing;
do {
get_t_next (mp);
if (cur_cmd() == mp_string_token) {
delete_str_ref (cur_mod_str());
}
} while (!mp_end_of_statement); /* |cur_cmd=semicolon|, |end_group|, or |stop| */
mp->scanner_status = normal;
}
@ Equations and assignments are performed by the pair of mutually recursive
@^recursion@>
routines |do_equation| and |do_assignment|. These routines are called when
|cur_cmd=equals| and when |cur_cmd=assignment|, respectively; the left-hand
side is in |cur_type| and |cur_exp|, while the right-hand side is yet
to be scanned. After the routines are finished, |cur_type| and |cur_exp|
will be equal to the right-hand side (which will normally be equal
to the left-hand side).
@<Declarations@>=
@<Declare the procedure called |make_eq|@>;
static void mp_do_equation (MP mp);
@ @c
static void trace_equation (MP mp, mp_node lhs) {
mp_begin_diagnostic (mp);
mp_print_nl (mp, "{(");
mp_print_exp (mp, lhs, 0);
mp_print (mp, ")=(");
mp_print_exp (mp, NULL, 0);
mp_print (mp, ")}");
mp_end_diagnostic (mp, false);
}
void mp_do_equation (MP mp) {
mp_node lhs; /* capsule for the left-hand side */
lhs = mp_stash_cur_exp (mp);
mp_get_x_next (mp);
mp->var_flag = mp_assignment;
mp_scan_expression (mp);
if (cur_cmd() == mp_equals)
mp_do_equation (mp);
else if (cur_cmd() == mp_assignment)
mp_do_assignment (mp);
if (number_greater (internal_value (mp_tracing_commands), two_t)) {
trace_equation(mp, lhs);
}
if (mp->cur_exp.type == mp_unknown_path) {
if (mp_type (lhs) == mp_pair_type) {
mp_node p; /* temporary register */
p = mp_stash_cur_exp (mp);
mp_unstash_cur_exp (mp, lhs);
lhs = p;
} /* in this case |make_eq| will change the pair to a path */
}
mp_make_eq (mp, lhs); /* equate |lhs| to |(cur_type,cur_exp)| */
}
@ And |do_assignment| is similar to |do_equation|:
@<Declarations@>=
static void mp_do_assignment (MP mp);
@ @c
static void bad_lhs (MP mp) {
const char *hlp[] = {
"I didn't find a variable name at the left of the `:=',",
"so I'm going to pretend that you said `=' instead.",
NULL };
mp_disp_err(mp, NULL);
mp_error (mp, "Improper `:=' will be changed to `='", hlp, true);
mp_do_equation (mp);
}
static void bad_internal_assignment (MP mp, mp_node lhs) {
char msg[256];
const char *hlp[] = {
"I can\'t set this internal quantity to anything but a known",
"numeric value, so I'll have to ignore this assignment.",
NULL };
mp_disp_err(mp, NULL);
if (internal_type (mp_sym_info (lhs)) == mp_known) {
mp_snprintf (msg, 256, "Internal quantity `%s' must receive a known numeric value",
internal_name (mp_sym_info (lhs)));
} else {
mp_snprintf (msg, 256, "Internal quantity `%s' must receive a known string",
internal_name (mp_sym_info (lhs)));
hlp[1] = "string, so I'll have to ignore this assignment.";
}
mp_back_error (mp, msg, hlp, true);
mp_get_x_next (mp);
}
static void forbidden_internal_assignment (MP mp, mp_node lhs) {
char msg[256];
const char *hlp[] = {
"I can\'t set this internal quantity to anything just yet",
"(it is read-only), so I'll have to ignore this assignment.",
NULL };
mp_snprintf (msg, 256, "Internal quantity `%s' is read-only",
internal_name (mp_sym_info (lhs)));
mp_back_error (mp, msg, hlp, true);
mp_get_x_next (mp);
}
static void bad_internal_assignment_precision (MP mp, mp_node lhs, mp_number min, mp_number max) {
char msg[256];
char s[256];
const char *hlp[] = {
"Precision values are limited by the current numbersystem.",
NULL,
NULL } ;
mp_snprintf (msg, 256, "Bad '%s' has been ignored", internal_name (mp_sym_info (lhs)));
mp_snprintf (s, 256, "Currently I am using '%s'; the allowed precision range is [%s,%s].",
mp_str (mp, internal_string (mp_number_system)), number_tostring(min), number_tostring(max));
hlp[1] = s;
mp_back_error (mp, msg, hlp, true);
mp_get_x_next (mp);
}
static void bad_expression_assignment (MP mp, mp_node lhs) {
const char *hlp[] = {
"It seems you did a nasty thing---probably by accident,",
"but nevertheless you nearly hornswoggled me...",
"While I was evaluating the right-hand side of this",
"command, something happened, and the left-hand side",
"is no longer a variable! So I won't change anything.",
NULL };
char *msg = mp_obliterated (mp, lhs);
mp_back_error (mp, msg, hlp, true);
free(msg);
mp_get_x_next (mp);
}
static void trace_assignment (MP mp, mp_node lhs) {
mp_begin_diagnostic (mp);
mp_print_nl (mp, "{");
if (mp_name_type (lhs) == mp_internal_sym)
mp_print (mp, internal_name (mp_sym_info (lhs)));
else
mp_show_token_list (mp, lhs, NULL, 1000, 0);
mp_print (mp, ":=");
mp_print_exp (mp, NULL, 0);
mp_print_char (mp, xord ('}'));
mp_end_diagnostic (mp, false);
}
void mp_do_assignment (MP mp) {
if (mp->cur_exp.type != mp_token_list) {
bad_lhs(mp);
} else {
mp_node lhs; /* token list for the left-hand side */
lhs = cur_exp_node ();
mp->cur_exp.type = mp_vacuous;
mp_get_x_next (mp);
mp->var_flag = mp_assignment;
mp_scan_expression (mp);
if (cur_cmd() == mp_equals)
mp_do_equation (mp);
else if (cur_cmd() == mp_assignment)
mp_do_assignment (mp);
if (number_greater (internal_value (mp_tracing_commands), two_t)) {
trace_assignment (mp, lhs);
}
if (mp_name_type (lhs) == mp_internal_sym) {
/* Assign the current expression to an internal variable */
if ((mp->cur_exp.type == mp_known || mp->cur_exp.type == mp_string_type)
&& (internal_type (mp_sym_info (lhs)) == mp->cur_exp.type)) {
if(mp_sym_info (lhs) == mp_number_system) {
forbidden_internal_assignment (mp, lhs);
} else if (mp_sym_info (lhs) == mp_number_precision) {
if (!(mp->cur_exp.type == mp_known &&
(!number_less(cur_exp_value_number(), precision_min)) &&
(!number_greater(cur_exp_value_number(), precision_max))
)) {
bad_internal_assignment_precision(mp, lhs, precision_min, precision_max);
} else {
set_internal_from_cur_exp(mp_sym_info (lhs));
set_precision();
}
} else {
set_internal_from_cur_exp(mp_sym_info (lhs));
}
} else {
bad_internal_assignment (mp, lhs);
}
} else {
/* Assign the current expression to the variable |lhs| */
mp_node p; /* where the left-hand value is stored */
mp_node q; /* temporary capsule for the right-hand value */
p = mp_find_variable (mp, lhs);
if (p != NULL) {
q = mp_stash_cur_exp (mp);
mp->cur_exp.type = mp_und_type (mp, p);
mp_recycle_value (mp, p);
mp_type (p) = mp->cur_exp.type;
set_value_number (p, zero_t);
mp_make_exp_copy (mp, p);
p = mp_stash_cur_exp (mp);
mp_unstash_cur_exp (mp, q);
mp_make_eq (mp, p);
} else {
bad_expression_assignment(mp, lhs);
}
}
mp_flush_node_list (mp, lhs);
}
}
@ And now we get to the nitty-gritty. The |make_eq| procedure is given
a pointer to a capsule that is to be equated to the current expression.
@<Declare the procedure called |make_eq|@>=
static void mp_make_eq (MP mp, mp_node lhs);
@
@c
static void announce_bad_equation (MP mp, mp_node lhs) {
char msg[256];
const char *hlp[] = {
"I'm sorry, but I don't know how to make such things equal.",
"(See the two expressions just above the error message.)",
NULL };
mp_snprintf(msg, 256, "Equation cannot be performed (%s=%s)",
(mp_type (lhs) <= mp_pair_type ? mp_type_string (mp_type (lhs)) : "numeric"),
(mp->cur_exp.type <= mp_pair_type ? mp_type_string (mp->cur_exp.type) : "numeric"));
mp_disp_err (mp, lhs);
mp_disp_err(mp, NULL);
mp_back_error (mp, msg, hlp, true);
mp_get_x_next (mp);
}
static void exclaim_inconsistent_equation (MP mp) {
const char *hlp[] = {
"The equation I just read contradicts what was said before.",
"But don't worry; continue and I'll just ignore it.",
NULL };
mp_back_error (mp,"Inconsistent equation", hlp, true);
mp_get_x_next (mp);
}
static void exclaim_redundant_or_inconsistent_equation (MP mp) {
const char *hlp[] = {
"An equation between already-known quantities can't help.",
"But don't worry; continue and I'll just ignore it.",
NULL };
mp_back_error (mp, "Redundant or inconsistent equation", hlp, true);
mp_get_x_next (mp);
}
static void report_redundant_or_inconsistent_equation (MP mp, mp_node lhs, mp_number v) {
if (mp->cur_exp.type <= mp_string_type) {
if (mp->cur_exp.type == mp_string_type) {
if (mp_str_vs_str (mp, value_str (lhs), cur_exp_str ()) != 0) {
exclaim_inconsistent_equation(mp);
} else {
exclaim_redundant_equation(mp);
}
} else if (!number_equal (v, cur_exp_value_number ())) {
exclaim_inconsistent_equation(mp);
} else {
exclaim_redundant_equation(mp);
}
} else {
exclaim_redundant_or_inconsistent_equation (mp);
}
}
void mp_make_eq (MP mp, mp_node lhs) {
mp_value new_expr;
mp_variable_type t; /* type of the left-hand side */
mp_number v; /* value of the left-hand side */
memset(&new_expr,0,sizeof(mp_value));
new_number (v);
RESTART:
t = mp_type (lhs);
if (t <= mp_pair_type)
number_clone (v, value_number (lhs));
/* For each type |t|, make an equation or complain if |cur_type|
is incompatible with~|t| */
switch (t) {
case mp_boolean_type:
case mp_string_type:
case mp_pen_type:
case mp_path_type:
case mp_picture_type:
if (mp->cur_exp.type == t + unknown_tag) {
new_number(new_expr.data.n);
if (t==mp_boolean_type) {
number_clone (new_expr.data.n, v);
} else if (t==mp_string_type) {
new_expr.data.str = value_str(lhs);
} else if (t==mp_picture_type) {
new_expr.data.node = value_node(lhs);
} else { /* pen or path */
new_expr.data.p = value_knot(lhs);
}
mp_nonlinear_eq (mp, new_expr, cur_exp_node (), false);
mp_unstash_cur_exp (mp, cur_exp_node ());
} else if (mp->cur_exp.type == t) {
report_redundant_or_inconsistent_equation(mp, lhs, v);
} else {
announce_bad_equation(mp, lhs);
}
break;
case unknown_types:
if (mp->cur_exp.type == t - unknown_tag) {
mp_nonlinear_eq (mp, mp->cur_exp, lhs, true);
} else if (mp->cur_exp.type == t) {
mp_ring_merge (mp, lhs, cur_exp_node ());
} else if (mp->cur_exp.type == mp_pair_type) {
if (t == mp_unknown_path) {
mp_pair_to_path (mp);
goto RESTART;
}
} else {
announce_bad_equation(mp, lhs);
}
break;
case mp_transform_type:
case mp_color_type:
case mp_cmykcolor_type:
case mp_pair_type:
if (mp->cur_exp.type == t) {
/* Do multiple equations */
mp_node q = value_node (cur_exp_node ());
mp_node p = value_node (lhs);
switch (t) {
case mp_transform_type:
mp_try_eq (mp, yy_part (p), yy_part (q));
mp_try_eq (mp, yx_part (p), yx_part (q));
mp_try_eq (mp, xy_part (p), xy_part (q));
mp_try_eq (mp, xx_part (p), xx_part (q));
mp_try_eq (mp, ty_part (p), ty_part (q));
mp_try_eq (mp, tx_part (p), tx_part (q));
break;
case mp_color_type:
mp_try_eq (mp, blue_part (p), blue_part (q));
mp_try_eq (mp, green_part (p), green_part (q));
mp_try_eq (mp, red_part (p), red_part (q));
break;
case mp_cmykcolor_type:
mp_try_eq (mp, black_part (p), black_part (q));
mp_try_eq (mp, yellow_part (p), yellow_part (q));
mp_try_eq (mp, magenta_part (p), magenta_part (q));
mp_try_eq (mp, cyan_part (p), cyan_part (q));
break;
case mp_pair_type:
mp_try_eq (mp, y_part (p), y_part (q));
mp_try_eq (mp, x_part (p), x_part (q));
break;
default: /* there are no other valid cases, but please the compiler */
break;
}
} else {
announce_bad_equation(mp, lhs);
}
break;
case mp_known:
case mp_dependent:
case mp_proto_dependent:
case mp_independent:
if (mp->cur_exp.type >= mp_known) {
mp_try_eq (mp, lhs, NULL);
} else {
announce_bad_equation(mp, lhs);
}
break;
case mp_vacuous:
announce_bad_equation(mp, lhs);
break;
default: /* there are no other valid cases, but please the compiler */
announce_bad_equation(mp, lhs);
break;
}
check_arith();
mp_recycle_value (mp, lhs);
free_number (v);
mp_free_value_node (mp, lhs);
}
@ The first argument to |try_eq| is the location of a value node
in a capsule that will soon be recycled. The second argument is
either a location within a pair or transform node pointed to by
|cur_exp|, or it is |NULL| (which means that |cur_exp| itself
serves as the second argument). The idea is to leave |cur_exp| unchanged,
but to equate the two operands.
@<Declarations@>=
static void mp_try_eq (MP mp, mp_node l, mp_node r);
@
@d equation_threshold_k ((math_data *)mp->math)->equation_threshold_t
@c
static void deal_with_redundant_or_inconsistent_equation(MP mp, mp_value_node p, mp_node r) {
mp_number absp;
new_number (absp);
number_clone (absp, value_number (p));
number_abs (absp);
if (number_greater (absp, equation_threshold_k)) { /* off by .001 or more */
char msg[256];
const char *hlp[] = {
"The equation I just read contradicts what was said before.",
"But don't worry; continue and I'll just ignore it.",
NULL };
mp_snprintf (msg, 256, "Inconsistent equation (off by %s)", number_tostring (value_number (p)));
mp_back_error (mp, msg, hlp, true);
mp_get_x_next (mp);
} else if (r == NULL) {
exclaim_redundant_equation(mp);
}
free_number (absp);
mp_free_dep_node (mp, p);
}
void mp_try_eq (MP mp, mp_node l, mp_node r) {
mp_value_node p; /* dependency list for right operand minus left operand */
mp_variable_type t; /* the type of list |p| */
mp_value_node q; /* the constant term of |p| is here */
mp_value_node pp; /* dependency list for right operand */
mp_variable_type tt; /* the type of list |pp| */
boolean copied; /* have we copied a list that ought to be recycled? */
/* Remove the left operand from its container, negate it, and
put it into dependency list~|p| with constant term~|q| */
t = mp_type (l);
if (t == mp_known) {
mp_number arg1;
new_number (arg1);
number_clone (arg1, value_number(l));
number_negate (arg1);
t = mp_dependent;
p = mp_const_dependency (mp, arg1);
q = p;
free_number (arg1);
} else if (t == mp_independent) {
t = mp_dependent;
p = mp_single_dependency (mp, l);
number_negate(dep_value (p));
q = mp->dep_final;
} else {
mp_value_node ll = (mp_value_node) l;
p = (mp_value_node) dep_list (ll);
q = p;
while (1) {
number_negate(dep_value (q));
if (dep_info (q) == NULL)
break;
q = (mp_value_node) mp_link (q);
}
mp_link (prev_dep (ll)) = mp_link (q);
set_prev_dep ((mp_value_node) mp_link (q), prev_dep (ll));
mp_type (ll) = mp_known;
}
/* Add the right operand to list |p| */
if (r == NULL) {
if (mp->cur_exp.type == mp_known) {
number_add (value_number (q), cur_exp_value_number ());
goto DONE1;
} else {
tt = mp->cur_exp.type;
if (tt == mp_independent)
pp = mp_single_dependency (mp, cur_exp_node ());
else
pp = (mp_value_node) dep_list ((mp_value_node) cur_exp_node ());
}
} else {
if (mp_type (r) == mp_known) {
number_add (dep_value (q), value_number (r));
goto DONE1;
} else {
tt = mp_type (r);
if (tt == mp_independent)
pp = mp_single_dependency (mp, r);
else
pp = (mp_value_node) dep_list ((mp_value_node) r);
}
}
if (tt != mp_independent) {
copied = false;
} else {
copied = true;
tt = mp_dependent;
}
/* Add dependency list |pp| of type |tt| to dependency list~|p| of type~|t| */
mp->watch_coefs = false;
if (t == tt) {
p = mp_p_plus_q (mp, p, pp, (quarterword) t);
} else if (t == mp_proto_dependent) {
p = mp_p_plus_fq (mp, p, unity_t, pp, mp_proto_dependent, mp_dependent);
} else {
mp_number x;
new_number (x);
q = p;
while (dep_info (q) != NULL) {
number_clone (x, dep_value (q));
fraction_to_round_scaled (x);
set_dep_value (q, x);
q = (mp_value_node) mp_link (q);
}
free_number (x);
t = mp_proto_dependent;
p = mp_p_plus_q (mp, p, pp, (quarterword) t);
}
mp->watch_coefs = true;
if (copied)
mp_flush_node_list (mp, (mp_node) pp);
DONE1:
if (dep_info (p) == NULL) {
deal_with_redundant_or_inconsistent_equation(mp, p, r);
} else {
mp_linear_eq (mp, p, (quarterword) t);
if (r == NULL && mp->cur_exp.type != mp_known) {
if (mp_type (cur_exp_node ()) == mp_known) {
mp_node pp = cur_exp_node ();
set_cur_exp_value_number (value_number (pp));
mp->cur_exp.type = mp_known;
mp_free_value_node (mp, pp);
}
}
}
}
@ Our next goal is to process type declarations. For this purpose it's
convenient to have a procedure that scans a $\langle\,$declared
variable$\,\rangle$ and returns the corresponding token list. After the
following procedure has acted, the token after the declared variable
will have been scanned, so it will appear in |cur_cmd|, |cur_mod|,
and~|cur_sym|.
@<Declarations@>=
static mp_node mp_scan_declared_variable (MP mp);
@ @c
mp_node mp_scan_declared_variable (MP mp) {
mp_sym x; /* hash address of the variable's root */
mp_node h, t; /* head and tail of the token list to be returned */
mp_get_symbol (mp);
x = cur_sym();
if (cur_cmd() != mp_tag_token)
mp_clear_symbol (mp, x, false);
h = mp_get_symbolic_node (mp);
set_mp_sym_sym (h, x);
t = h;
while (1) {
mp_get_x_next (mp);
if (cur_sym() == NULL)
break;
if (cur_cmd() != mp_tag_token) {
if (cur_cmd() != mp_internal_quantity) {
if (cur_cmd() == mp_left_bracket) {
/* Descend past a collective subscript */
/* If the subscript isn't collective, we don't accept it as part of the
declared variable. */
mp_sym ll = cur_sym(); /* hash address of left bracket */
mp_get_x_next (mp);
if (cur_cmd() == mp_right_bracket) {
set_cur_sym(collective_subscript);
} else {
mp_back_input (mp);
set_cur_sym(ll);
set_cur_cmd((mp_variable_type)mp_left_bracket);
break;
}
} else {
break;
}
}
}
mp_link (t) = mp_get_symbolic_node (mp);
t = mp_link (t);
set_mp_sym_sym (t, cur_sym());
mp_name_type (t) = cur_sym_mod();
}
if ((eq_type (x) % mp_outer_tag) != mp_tag_token)
mp_clear_symbol (mp, x, false);
if (equiv_node (x) == NULL)
mp_new_root (mp, x);
return h;
}
@ Type declarations are introduced by the following primitive operations.
@<Put each...@>=
mp_primitive (mp, "numeric", mp_type_name, mp_numeric_type);
@:numeric_}{\&{numeric} primitive@>;
mp_primitive (mp, "string", mp_type_name, mp_string_type);
@:string_}{\&{string} primitive@>;
mp_primitive (mp, "boolean", mp_type_name, mp_boolean_type);
@:boolean_}{\&{boolean} primitive@>;
mp_primitive (mp, "path", mp_type_name, mp_path_type);
@:path_}{\&{path} primitive@>;
mp_primitive (mp, "pen", mp_type_name, mp_pen_type);
@:pen_}{\&{pen} primitive@>;
mp_primitive (mp, "picture", mp_type_name, mp_picture_type);
@:picture_}{\&{picture} primitive@>;
mp_primitive (mp, "transform", mp_type_name, mp_transform_type);
@:transform_}{\&{transform} primitive@>;
mp_primitive (mp, "color", mp_type_name, mp_color_type);
@:color_}{\&{color} primitive@>;
mp_primitive (mp, "rgbcolor", mp_type_name, mp_color_type);
@:color_}{\&{rgbcolor} primitive@>;
mp_primitive (mp, "cmykcolor", mp_type_name, mp_cmykcolor_type);
@:color_}{\&{cmykcolor} primitive@>;
mp_primitive (mp, "pair", mp_type_name, mp_pair_type);
@:pair_}{\&{pair} primitive@>
@ @<Cases of |print_cmd...@>=
case mp_type_name:
mp_print_type (mp, (quarterword) m);
break;
@ Now we are ready to handle type declarations, assuming that a
|type_name| has just been scanned.
@<Declare action procedures for use by |do_statement|@>=
static void mp_do_type_declaration (MP mp);
@ @c
static void flush_spurious_symbols_after_declared_variable(MP mp);
void mp_do_type_declaration (MP mp) {
integer t; /* the type being declared */
mp_node p; /* token list for a declared variable */
mp_node q; /* value node for the variable */
if (cur_mod() >= mp_transform_type)
t = (quarterword) cur_mod();
else
t = (quarterword) (cur_mod() + unknown_tag);
do {
p = mp_scan_declared_variable (mp);
mp_flush_variable (mp, equiv_node (mp_sym_sym (p)), mp_link (p), false);
q = mp_find_variable (mp, p);
if (q != NULL) {
mp_type (q) = t;
set_value_number (q, zero_t); /* todo: this was |null| */
} else {
const char *hlp[] = {
"You can't use, e.g., `numeric foo[]' after `vardef foo'.",
"Proceed, and I'll ignore the illegal redeclaration.",
NULL };
mp_back_error (mp, "Declared variable conflicts with previous vardef", hlp, true);
mp_get_x_next (mp);
}
mp_flush_node_list (mp, p);
if (cur_cmd() < mp_comma) {
flush_spurious_symbols_after_declared_variable(mp);
}
} while (!mp_end_of_statement);
}
@
@c
static void flush_spurious_symbols_after_declared_variable (MP mp)
{
const char *hlp[] = {
"Variables in declarations must consist entirely of",
"names and collective subscripts, e.g., `x[]a'.",
"Are you trying to use a reserved word in a variable name?",
"I'm going to discard the junk I found here,",
"up to the next comma or the end of the declaration.",
NULL };
if (cur_cmd() == mp_numeric_token)
hlp[2] = "Explicit subscripts like `x15a' aren't permitted.";
mp_back_error (mp, "Illegal suffix of declared variable will be flushed", hlp, true);
mp_get_x_next (mp);
mp->scanner_status = flushing;
do {
get_t_next (mp);
@<Decrease the string reference count...@>;
} while (cur_cmd() < mp_comma); /* break on either |end_of_statement| or |comma| */
mp->scanner_status = normal;
}
@ \MP's |main_control| procedure just calls |do_statement| repeatedly
until coming to the end of the user's program.
Each execution of |do_statement| concludes with
|cur_cmd=semicolon|, |end_group|, or |stop|.
@c
static void mp_main_control (MP mp) {
do {
mp_do_statement (mp);
if (cur_cmd() == mp_end_group) {
mp_value new_expr;
const char *hlp[] = {
"I'm not currently working on a `begingroup',",
"so I had better not try to end anything.",
NULL };
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
mp_error (mp, "Extra `endgroup'", hlp, true);
mp_flush_cur_exp (mp, new_expr);
}
} while (cur_cmd() != mp_stop);
}
int mp_run (MP mp) {
if (mp->history < mp_fatal_error_stop) {
xfree (mp->jump_buf);
mp->jump_buf = malloc (sizeof (jmp_buf));
if (mp->jump_buf == NULL || setjmp (*(mp->jump_buf)) != 0)
return mp->history;
mp_main_control (mp); /* come to life */
mp_final_cleanup (mp); /* prepare for death */
mp_close_files_and_terminate (mp);
}
return mp->history;
}
@ This function allows setting of internals from an external
source (like the command line or a controlling application).
It accepts two |char *|'s, even for numeric assignments when
it calls |atoi| to get an integer from the start of the string.
@c
void mp_set_internal (MP mp, char *n, char *v, int isstring) {
size_t l = strlen (n);
char err[256];
const char *errid = NULL;
if (l > 0) {
mp_sym p = mp_id_lookup (mp, n, l, false);
if (p == NULL) {
errid = "variable does not exist";
} else {
if (eq_type (p) == mp_internal_quantity) {
if ((internal_type (equiv (p)) == mp_string_type) && (isstring)) {
set_internal_string (equiv (p), mp_rts (mp, v));
} else if ((internal_type (equiv (p)) == mp_known) && (!isstring)) {
int test = atoi (v);
if (test > 16383 && mp->math_mode==mp_math_scaled_mode) {
errid = "value is too large";
} else if (test < -16383 && mp->math_mode==mp_math_scaled_mode) {
errid = "value is too small";
} else {
set_internal_from_number (equiv (p), unity_t);
number_multiply_int (internal_value(equiv (p)), test);
}
} else {
errid = "value has the wrong type";
}
} else {
errid = "variable is not an internal";
}
}
}
if (errid != NULL) {
if (isstring) {
mp_snprintf (err, 256, "%s=\"%s\": %s, assignment ignored.", n, v, errid);
} else {
mp_snprintf (err, 256, "%s=%d: %s, assignment ignored.", n, atoi (v),
errid);
}
mp_warn (mp, err);
}
}
@ @<Exported function headers@>=
void mp_set_internal (MP mp, char *n, char *v, int isstring);
@ For |mp_execute|, we need to define a structure to store the
redirected input and output. This structure holds the five relevant
streams: the three informational output streams, the PostScript
generation stream, and the input stream. These streams have many
things in common, so it makes sense to give them their own structure
definition.
\item{fptr} is a virtual file pointer
\item{data} is the data this stream holds
\item{cur} is a cursor pointing into |data|
\item{size} is the allocated length of the data stream
\item{used} is the actual length of the data stream
There are small differences between input and output: |term_in| never
uses |used|, whereas the other four never use |cur|.
The file |luatexdir/tex/texfileio.h| defines |term_in| as |stdin| and
|term_out| as |stdout|. Moreover |stdio.h| for MinGW defines |stdin| as
|(&_iob[0])| and |stdout| as |(&_iob[1])|. We must avoid all that.
@<Exported types@>=
#undef term_in
#undef term_out
typedef struct {
void *fptr;
char *data;
char *cur;
size_t size;
size_t used;
} mp_stream;
typedef struct {
mp_stream term_out;
mp_stream error_out;
mp_stream log_out;
mp_stream ship_out;
mp_stream term_in;
struct mp_edge_object *edges;
} mp_run_data;
@ We need a function to clear an output stream, this is called at the
beginning of |mp_execute|. We also need one for destroying an output
stream, this is called just before a stream is (re)opened.
@c
static void mp_reset_stream (mp_stream * str) {
xfree (str->data);
str->cur = NULL;
str->size = 0;
str->used = 0;
}
static void mp_free_stream (mp_stream * str) {
xfree (str->fptr);
mp_reset_stream (str);
}
@ @<Declarations@>=
static void mp_reset_stream (mp_stream * str);
static void mp_free_stream (mp_stream * str);
@ The global instance contains a pointer instead of the actual structure
even though it is essentially static, because that makes it is easier to move
the object around.
@<Global ...@>=
mp_run_data run_data;
@ Another type is needed: the indirection will overload some of the
file pointer objects in the instance (but not all). For clarity, an
indirect object is used that wraps a |FILE *|.
@<Types ... @>=
typedef struct File {
FILE *f;
} File;
@ Here are all of the functions that need to be overloaded for |mp_execute|.
@<Declarations@>=
static void *mplib_open_file (MP mp, const char *fname, const char *fmode,
int ftype);
static int mplib_get_char (void *f, mp_run_data * mplib_data);
static void mplib_unget_char (void *f, mp_run_data * mplib_data, int c);
static char *mplib_read_ascii_file (MP mp, void *ff, size_t * size);
static void mplib_write_ascii_file (MP mp, void *ff, const char *s);
static void mplib_read_binary_file (MP mp, void *ff, void **data,
size_t * size);
static void mplib_write_binary_file (MP mp, void *ff, void *s, size_t size);
static void mplib_close_file (MP mp, void *ff);
static int mplib_eof_file (MP mp, void *ff);
static void mplib_flush_file (MP mp, void *ff);
static void mplib_shipout_backend (MP mp, void *h);
@ The |xmalloc(1,1)| calls make sure the stored indirection values are unique.
@d reset_stream(a) do {
mp_reset_stream(&(a));
if (!ff->f) {
ff->f = xmalloc(1,1);
(a).fptr = ff->f;
} } while (0)
@c
static void *mplib_open_file (MP mp, const char *fname, const char *fmode,
int ftype) {
File *ff = xmalloc (1, sizeof (File));
mp_run_data *run = mp_rundata (mp);
ff->f = NULL;
if (ftype == mp_filetype_terminal) {
if (fmode[0] == 'r') {
if (!ff->f) {
ff->f = xmalloc (1, 1);
run->term_in.fptr = ff->f;
}
} else {
reset_stream (run->term_out);
}
} else if (ftype == mp_filetype_error) {
reset_stream (run->error_out);
} else if (ftype == mp_filetype_log) {
reset_stream (run->log_out);
} else if (ftype == mp_filetype_postscript) {
mp_free_stream (&(run->ship_out));
ff->f = xmalloc (1, 1);
run->ship_out.fptr = ff->f;
} else if (ftype == mp_filetype_bitmap) {
mp_free_stream (&(run->ship_out));
ff->f = xmalloc (1, 1);
run->ship_out.fptr = ff->f;
} else {
char realmode[3];
char *f = (mp->find_file) (mp, fname, fmode, ftype);
if (f == NULL)
return NULL;
realmode[0] = *fmode;
realmode[1] = 'b';
realmode[2] = 0;
ff->f = fopen (f, realmode);
free (f);
if ((fmode[0] == 'r') && (ff->f == NULL)) {
free (ff);
return NULL;
}
}
return ff;
}
static int mplib_get_char (void *f, mp_run_data * run) {
int c;
if (f == run->term_in.fptr && run->term_in.data != NULL) {
if (run->term_in.size == 0) {
if (run->term_in.cur != NULL) {
run->term_in.cur = NULL;
} else {
xfree (run->term_in.data);
}
c = EOF;
} else {
run->term_in.size--;
c = *(run->term_in.cur)++;
}
} else {
c = fgetc (f);
}
return c;
}
static void mplib_unget_char (void *f, mp_run_data * run, int c) {
if (f == run->term_in.fptr && run->term_in.cur != NULL) {
run->term_in.size++;
run->term_in.cur--;
} else {
ungetc (c, f);
}
}
static char *mplib_read_ascii_file (MP mp, void *ff, size_t * size) {
char *s = NULL;
if (ff != NULL) {
int c;
size_t len = 0, lim = 128;
mp_run_data *run = mp_rundata (mp);
FILE *f = ((File *) ff)->f;
if (f == NULL)
return NULL;
*size = 0;
c = mplib_get_char (f, run);
if (c == EOF)
return NULL;
s = malloc (lim);
if (s == NULL)
return NULL;
while (c != EOF && c != '\n' && c != '\r') {
if (len >= (lim - 1)) {
s = xrealloc (s, (lim + (lim >> 2)), 1);
if (s == NULL)
return NULL;
lim += (lim >> 2);
}
s[len++] = (char) c;
c = mplib_get_char (f, run);
}
if (c == '\r') {
c = mplib_get_char (f, run);
if (c != EOF && c != '\n')
mplib_unget_char (f, run, c);
}
s[len] = 0;
*size = len;
}
return s;
}
static void mp_append_string (MP mp, mp_stream * a, const char *b) {
size_t l = strlen (b) + 1; /* don't forget the trailing |'\0'| */
if ((a->used + l) >= a->size) {
a->size += 256 + (a->size) / 5 + l;
a->data = xrealloc (a->data, a->size, 1);
}
memcpy (a->data + a->used, b, l);
a->used += (l-1);
}
static void mp_append_data (MP mp, mp_stream * a, void *b, size_t l) {
if ((a->used + l) >= a->size) {
a->size += 256 + (a->size) / 5 + l;
a->data = xrealloc (a->data, a->size, 1);
}
memcpy (a->data + a->used, b, l);
a->used += l;
}
static void mplib_write_ascii_file (MP mp, void *ff, const char *s) {
if (ff != NULL) {
void *f = ((File *) ff)->f;
mp_run_data *run = mp_rundata (mp);
if (f != NULL) {
if (f == run->term_out.fptr) {
mp_append_string (mp, &(run->term_out), s);
} else if (f == run->error_out.fptr) {
mp_append_string (mp, &(run->error_out), s);
} else if (f == run->log_out.fptr) {
mp_append_string (mp, &(run->log_out), s);
} else if (f == run->ship_out.fptr) {
mp_append_string (mp, &(run->ship_out), s);
} else {
fprintf ((FILE *) f, "%s", s);
}
}
}
}
static void mplib_read_binary_file (MP mp, void *ff, void **data, size_t * size) {
(void) mp;
if (ff != NULL) {
size_t len = 0;
FILE *f = ((File *) ff)->f;
if (f != NULL)
len = fread (*data, 1, *size, f);
*size = len;
}
}
static void mplib_write_binary_file (MP mp, void *ff, void *s, size_t size) {
(void) mp;
if (ff != NULL) {
void *f = ((File *) ff)->f;
mp_run_data *run = mp_rundata (mp);
if (f != NULL) {
if (f == run->ship_out.fptr) {
mp_append_data (mp, &(run->ship_out), s, size);
} else {
(void) fwrite (s, size, 1, f);
}
}
}
}
static void mplib_close_file (MP mp, void *ff) {
if (ff != NULL) {
mp_run_data *run = mp_rundata (mp);
void *f = ((File *) ff)->f;
if (f != NULL) {
if (f != run->term_out.fptr
&& f != run->error_out.fptr
&& f != run->log_out.fptr
&& f != run->ship_out.fptr && f != run->term_in.fptr) {
fclose (f);
}
}
free (ff);
}
}
static int mplib_eof_file (MP mp, void *ff) {
if (ff != NULL) {
mp_run_data *run = mp_rundata (mp);
FILE *f = ((File *) ff)->f;
if (f == NULL)
return 1;
if (f == run->term_in.fptr && run->term_in.data != NULL) {
return (run->term_in.size == 0);
}
return feof (f);
}
return 1;
}
static void mplib_flush_file (MP mp, void *ff) {
(void) mp;
(void) ff;
return;
}
static void mplib_shipout_backend (MP mp, void *voidh) {
mp_edge_header_node h = (mp_edge_header_node) voidh;
mp_edge_object *hh = mp_gr_export (mp, h);
if (hh) {
mp_run_data *run = mp_rundata (mp);
if (run->edges == NULL) {
run->edges = hh;
} else {
mp_edge_object *p = run->edges;
while (p->next != NULL) {
p = p->next;
}
p->next = hh;
}
}
}
@ This is where we fill them all in.
@<Prepare function pointers for non-interactive use@>=
{
mp->open_file = mplib_open_file;
mp->close_file = mplib_close_file;
mp->eof_file = mplib_eof_file;
mp->flush_file = mplib_flush_file;
mp->write_ascii_file = mplib_write_ascii_file;
mp->read_ascii_file = mplib_read_ascii_file;
mp->write_binary_file = mplib_write_binary_file;
mp->read_binary_file = mplib_read_binary_file;
mp->shipout_backend = mplib_shipout_backend;
}
@ Perhaps this is the most important API function in the library.
@<Exported function ...@>=
extern mp_run_data *mp_rundata (MP mp);
@ @c
mp_run_data *mp_rundata (MP mp) {
return &(mp->run_data);
}
@ @<Dealloc ...@>=
mp_free_stream (&(mp->run_data.term_in));
mp_free_stream (&(mp->run_data.term_out));
mp_free_stream (&(mp->run_data.log_out));
mp_free_stream (&(mp->run_data.error_out));
mp_free_stream (&(mp->run_data.ship_out));
@ @<Finish non-interactive use@>=
xfree (mp->term_out);
xfree (mp->term_in);
xfree (mp->err_out);
@ @<Start non-interactive work@>=
@<Initialize the output routines@>;
mp->input_ptr = 0;
mp->max_in_stack = file_bottom;
mp->in_open = file_bottom;
mp->open_parens = 0;
mp->max_buf_stack = 0;
mp->param_ptr = 0;
mp->max_param_stack = 0;
start = loc = 0;
iindex = file_bottom;
nloc = nstart = NULL;
mp->first = 0;
line = 0;
name = is_term;
mp->mpx_name[file_bottom] = absent;
mp->force_eof = false;
t_open_in();
mp->scanner_status = normal;
if (!mp->ini_version) {
if (!mp_load_preload_file (mp)) {
mp->history = mp_fatal_error_stop;
return mp->history;
}
}
mp_fix_date_and_time (mp);
if (mp->random_seed == 0)
mp->random_seed =
(number_to_scaled (internal_value (mp_time)) / number_to_scaled (unity_t)) + number_to_scaled (internal_value (mp_day));
init_randoms (mp->random_seed);
initialize_print_selector();
mp_open_log_file (mp);
mp_set_job_id (mp);
mp_init_map_file (mp, mp->troff_mode);
mp->history = mp_spotless; /* ready to go! */
if (mp->troff_mode) {
number_clone (internal_value(mp_gtroffmode), unity_t);
number_clone (internal_value(mp_prologues), unity_t);
}
@<Fix up |mp->internal[mp_job_name]|@>;
if (mp->start_sym != NULL) { /* insert the `\&{everyjob}' symbol */
set_cur_sym(mp->start_sym);
mp_back_input (mp);
}
@ @c
int mp_execute (MP mp, char *s, size_t l) {
mp_reset_stream (&(mp->run_data.term_out));
mp_reset_stream (&(mp->run_data.log_out));
mp_reset_stream (&(mp->run_data.error_out));
mp_reset_stream (&(mp->run_data.ship_out));
if (mp->finished) {
return mp->history;
} else if (!mp->noninteractive) {
mp->history = mp_fatal_error_stop;
return mp->history;
}
if (mp->history < mp_fatal_error_stop) {
xfree (mp->jump_buf);
mp->jump_buf = malloc (sizeof (jmp_buf));
if (mp->jump_buf == NULL || setjmp (*(mp->jump_buf)) != 0) {
return mp->history;
}
if (s == NULL) { /* this signals EOF */
mp_final_cleanup (mp); /* prepare for death */
mp_close_files_and_terminate (mp);
return mp->history;
}
mp->tally = 0;
mp->term_offset = 0;
mp->file_offset = 0;
/* Perhaps some sort of warning here when |data| is not
* yet exhausted would be nice ... this happens after errors
*/
if (mp->run_data.term_in.data)
xfree (mp->run_data.term_in.data);
mp->run_data.term_in.data = xstrdup (s);
mp->run_data.term_in.cur = mp->run_data.term_in.data;
mp->run_data.term_in.size = l;
if (mp->run_state == 0) {
mp->selector = term_only;
@<Start non-interactive work@>;
}
mp->run_state = 1;
(void) mp_input_ln (mp, mp->term_in);
mp_firm_up_the_line (mp);
mp->buffer[limit] = xord ('%');
mp->first = (size_t) (limit + 1);
loc = start;
do {
mp_do_statement (mp);
} while (cur_cmd() != mp_stop);
mp_final_cleanup (mp);
mp_close_files_and_terminate (mp);
}
return mp->history;
}
@ This function cleans up
@c
int mp_finish (MP mp) {
int history = 0;
if (mp->finished || mp->history >= mp_fatal_error_stop) {
history = mp->history;
mp_free (mp);
return history;
}
xfree (mp->jump_buf);
mp->jump_buf = malloc (sizeof (jmp_buf));
if (mp->jump_buf == NULL || setjmp (*(mp->jump_buf)) != 0) {
history = mp->history;
} else {
history = mp->history;
mp_final_cleanup (mp); /* prepare for death */
}
mp_close_files_and_terminate (mp);
mp_free (mp);
return history;
}
@ People may want to know the library version
@c
char *mp_metapost_version (void) {
return mp_strdup (metapost_version);
}
void mp_show_library_versions (void) {
fprintf(stdout, "Compiled with cairo %s; using %s\n", CAIRO_VERSION_STRING, cairo_version_string());
fprintf(stdout, "Compiled with pixman %s; using %s\n", PIXMAN_VERSION_STRING, pixman_version_string());
fprintf(stdout, "Compiled with libpng %s; using %s\n", PNG_LIBPNG_VER_STRING, png_libpng_ver);
fprintf(stdout, "Compiled with zlib %s; using %s\n", ZLIB_VERSION, zlibVersion());
fprintf(stdout, "Compiled with mpfr %s; using %s\n", MPFR_VERSION_STRING, mpfr_get_version());
fprintf(stdout, "Compiled with gmp %d.%d.%d; using %s\n\n", __GNU_MP_VERSION, __GNU_MP_VERSION_MINOR, __GNU_MP_VERSION_PATCHLEVEL, gmp_version);
}
@ @<Exported function headers@>=
int mp_run (MP mp);
int mp_execute (MP mp, char *s, size_t l);
int mp_finish (MP mp);
char *mp_metapost_version (void);void mp_show_library_versions (void);
@ @<Put each...@>=
mp_primitive (mp, "end", mp_stop, 0);
@:end_}{\&{end} primitive@>;
mp_primitive (mp, "dump", mp_stop, 1);
mp->frozen_dump = mp_frozen_primitive (mp, "dump", mp_stop, 1);
@:dump_}{\&{dump} primitive@>
@ @<Cases of |print_cmd...@>=
case mp_stop:
if (cur_mod() == 0)
mp_print (mp, "end");
else
mp_print (mp, "dump");
break;
@* Commands.
Let's turn now to statements that are classified as ``commands'' because
of their imperative nature. We'll begin with simple ones, so that it
will be clear how to hook command processing into the |do_statement| routine;
then we'll tackle the tougher commands.
Here's one of the simplest:
@ @<Declare action procedures for use by |do_statement|@>=
static void mp_do_random_seed (MP mp);
@ @c
void mp_do_random_seed (MP mp) {
mp_value new_expr;
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
mp_get_x_next (mp);
if (cur_cmd() != mp_assignment) {
const char *hlp[] = { "Always say `randomseed:=<numeric expression>'.", NULL };
mp_back_error (mp, "Missing `:=' has been inserted", hlp, true);
@.Missing `:='@>;
};
mp_get_x_next (mp);
mp_scan_expression (mp);
if (mp->cur_exp.type != mp_known) {
const char *hlp[] = {
"Your expression was too random for me to handle,",
"so I won't change the random seed just now.",
NULL };
mp_disp_err(mp, NULL);
mp_back_error (mp, "Unknown value will be ignored", hlp, true);
@.Unknown value...ignored@>;
mp_get_x_next (mp);
mp_flush_cur_exp (mp, new_expr);
} else {
@<Initialize the random seed to |cur_exp|@>;
}
}
@ @<Initialize the random seed to |cur_exp|@>=
{
init_randoms (number_to_scaled(cur_exp_value_number ()));
if (mp->selector >= log_only && mp->selector < write_file) {
mp->old_setting = mp->selector;
mp->selector = log_only;
mp_print_nl (mp, "{randomseed:=");
print_number (cur_exp_value_number ());
mp_print_char (mp, xord ('}'));
mp_print_nl (mp, "");
mp->selector = mp->old_setting;
}
}
@ And here's another simple one (somewhat different in flavor):
@ @<Put each...@>=
mp_primitive (mp, "batchmode", mp_mode_command, mp_batch_mode);
@:mp_batch_mode_}{\&{batchmode} primitive@>;
mp_primitive (mp, "nonstopmode", mp_mode_command, mp_nonstop_mode);
@:mp_nonstop_mode_}{\&{nonstopmode} primitive@>;
mp_primitive (mp, "scrollmode", mp_mode_command, mp_scroll_mode);
@:mp_scroll_mode_}{\&{scrollmode} primitive@>;
mp_primitive (mp, "errorstopmode", mp_mode_command, mp_error_stop_mode);
@:mp_error_stop_mode_}{\&{errorstopmode} primitive@>
@ @<Cases of |print_cmd_mod|...@>=
case mp_mode_command:
switch (m) {
case mp_batch_mode:
mp_print (mp, "batchmode");
break;
case mp_nonstop_mode:
mp_print (mp, "nonstopmode");
break;
case mp_scroll_mode:
mp_print (mp, "scrollmode");
break;
default:
mp_print (mp, "errorstopmode");
break;
}
break;
@ The `\&{inner}' and `\&{outer}' commands are only slightly harder.
@ @<Put each...@>=
mp_primitive (mp, "inner", mp_protection_command, 0);
@:inner_}{\&{inner} primitive@>;
mp_primitive (mp, "outer", mp_protection_command, 1);
@:outer_}{\&{outer} primitive@>
@ @<Cases of |print_cmd...@>=
case mp_protection_command:
if (m == 0)
mp_print (mp, "inner");
else
mp_print (mp, "outer");
break;
@ @<Declare action procedures for use by |do_statement|@>=
static void mp_do_protection (MP mp);
@ @c
void mp_do_protection (MP mp) {
int m; /* 0 to unprotect, 1 to protect */
halfword t; /* the |eq_type| before we change it */
m = cur_mod();
do {
mp_get_symbol (mp);
t = eq_type (cur_sym());
if (m == 0) {
if (t >= mp_outer_tag)
set_eq_type (cur_sym(), (t - mp_outer_tag));
} else if (t < mp_outer_tag) {
set_eq_type (cur_sym(), (t + mp_outer_tag));
}
mp_get_x_next (mp);
} while (cur_cmd() == mp_comma);
}
@ \MP\ never defines the tokens `\.(' and `\.)' to be primitives, but
plain \MP\ begins with the declaration `\&{delimiters} \.{()}'. Such a
declaration assigns the command code |left_delimiter| to `\.{(}' and
|right_delimiter| to `\.{)}'; the |equiv| of each delimiter is the
hash address of its mate.
@ @<Declare action procedures for use by |do_statement|@>=
static void mp_def_delims (MP mp);
@ @c
void mp_def_delims (MP mp) {
mp_sym l_delim, r_delim; /* the new delimiter pair */
mp_get_clear_symbol (mp);
l_delim = cur_sym();
mp_get_clear_symbol (mp);
r_delim = cur_sym();
set_eq_type (l_delim, mp_left_delimiter);
set_equiv_sym (l_delim, r_delim);
set_eq_type (r_delim, mp_right_delimiter);
set_equiv_sym (r_delim, l_delim);
mp_get_x_next (mp);
}
@ Here is a procedure that is called when \MP\ has reached a point
where some right delimiter is mandatory.
@<Declarations@>=
static void mp_check_delimiter (MP mp, mp_sym l_delim, mp_sym r_delim);
@ @c
void mp_check_delimiter (MP mp, mp_sym l_delim, mp_sym r_delim) {
if (cur_cmd() == mp_right_delimiter)
if (equiv_sym (cur_sym()) == l_delim)
return;
if (cur_sym() != r_delim) {
char msg[256];
const char *hlp[] = {
"I found no right delimiter to match a left one. So I've",
"put one in, behind the scenes; this may fix the problem.",
NULL };
mp_snprintf(msg, 256, "Missing `%s' has been inserted", mp_str (mp, text (r_delim)));
@.Missing `)'@>;
mp_back_error (mp, msg, hlp, true);
} else {
char msg[256];
const char *hlp[] = {
"Strange: This token has lost its former meaning!",
"I'll read it as a right delimiter this time;",
"but watch out, I'll probably miss it later.",
NULL };
mp_snprintf(msg, 256, "The token `%s' is no longer a right delimiter", mp_str(mp, text (r_delim)));
@.The token...delimiter@>;
mp_error (mp, msg, hlp, true);
}
}
@ The next four commands save or change the values associated with tokens.
@ @<Declare action procedures for use by |do_statement|@>=
static void mp_do_statement (MP mp);
static void mp_do_interim (MP mp);
@ @c
void mp_do_interim (MP mp) {
mp_get_x_next (mp);
if (cur_cmd() != mp_internal_quantity) {
char msg[256];
const char *hlp[] = {
"Something like `tracingonline' should follow `interim'.",
NULL };
mp_snprintf(msg, 256, "The token `%s' isn't an internal quantity",
(cur_sym() == NULL ? "(%CAPSULE)" : mp_str(mp, text (cur_sym()))));
@.The token...quantity@>;
mp_back_error (mp, msg, hlp, true);
} else {
mp_save_internal (mp, cur_mod());
mp_back_input (mp);
}
mp_do_statement (mp);
}
@ The following procedure is careful not to undefine the left-hand symbol
too soon, lest commands like `{\tt let x=x}' have a surprising effect.
@<Declare action procedures for use by |do_statement|@>=
static void mp_do_let (MP mp);
@ @c
void mp_do_let (MP mp) {
mp_sym l; /* hash location of the left-hand symbol */
mp_get_symbol (mp);
l = cur_sym();
mp_get_x_next (mp);
if (cur_cmd() != mp_equals && cur_cmd() != mp_assignment) {
const char *hlp[] = {
"You should have said `let symbol = something'.",
"But don't worry; I'll pretend that an equals sign",
"was present. The next token I read will be `something'.",
NULL };
mp_back_error (mp, "Missing `=' has been inserted", hlp, true);
@.Missing `='@>;
}
mp_get_symbol (mp);
switch (cur_cmd()) {
case mp_defined_macro:
case mp_secondary_primary_macro:
case mp_tertiary_secondary_macro:
case mp_expression_tertiary_macro:
add_mac_ref (cur_mod_node());
break;
default:
break;
}
mp_clear_symbol (mp, l, false);
set_eq_type (l, cur_cmd());
if (cur_cmd() == mp_tag_token)
set_equiv (l, 0); /* todo: this was |null| */
else if (cur_cmd() == mp_defined_macro ||
cur_cmd() == mp_secondary_primary_macro ||
cur_cmd() == mp_tertiary_secondary_macro ||
cur_cmd() == mp_expression_tertiary_macro)
set_equiv_node (l, cur_mod_node());
else if (cur_cmd() == mp_left_delimiter ||
cur_cmd() == mp_right_delimiter)
set_equiv_sym (l, equiv_sym (cur_sym()));
else
set_equiv (l, cur_mod());
mp_get_x_next (mp);
}
@ @<Declarations@>=
static void mp_do_new_internal (MP mp);
@ @<Internal library ...@>=
void mp_grow_internals (MP mp, int l);
@ @c
void mp_grow_internals (MP mp, int l) {
mp_internal *internal;
int k;
if (l > max_halfword) {
mp_confusion (mp, "out of memory space"); /* can't be reached */
}
internal = xmalloc ((l + 1), sizeof (mp_internal));
for (k = 0; k <= l; k++) {
if (k <= mp->max_internal) {
memcpy (internal + k, mp->internal + k, sizeof (mp_internal));
} else {
memset (internal + k, 0, sizeof (mp_internal));
new_number(((mp_internal *)(internal + k))->v.data.n);
}
}
xfree (mp->internal);
mp->internal = internal;
mp->max_internal = l;
}
void mp_do_new_internal (MP mp) {
int the_type = mp_known;
mp_get_x_next (mp);
if (cur_cmd() == mp_type_name && cur_mod() == mp_string_type) {
the_type = mp_string_type;
} else {
if (!(cur_cmd() == mp_type_name && cur_mod() == mp_numeric_type)) {
mp_back_input (mp);
}
}
do {
if (mp->int_ptr == mp->max_internal) {
mp_grow_internals (mp, (mp->max_internal + (mp->max_internal / 4)));
}
mp_get_clear_symbol (mp);
incr (mp->int_ptr);
set_eq_type (cur_sym(), mp_internal_quantity);
set_equiv (cur_sym(), mp->int_ptr);
if (internal_name (mp->int_ptr) != NULL)
xfree (internal_name (mp->int_ptr));
set_internal_name (mp->int_ptr,
mp_xstrdup (mp, mp_str (mp, text (cur_sym()))));
if (the_type == mp_string_type) {
set_internal_string (mp->int_ptr, mp_rts(mp,""));
} else {
set_number_to_zero (internal_value (mp->int_ptr));
}
set_internal_type (mp->int_ptr, the_type);
mp_get_x_next (mp);
} while (cur_cmd() == mp_comma);
}
@ @<Dealloc variables@>=
for (k = 0; k <= mp->max_internal; k++) {
free_number(mp->internal[k].v.data.n);
xfree (internal_name (k));
}
xfree (mp->internal);
@ The various `\&{show}' commands are distinguished by modifier fields
in the usual way.
@d show_token_code 0 /* show the meaning of a single token */
@d show_stats_code 1 /* show current memory and string usage */
@d show_code 2 /* show a list of expressions */
@d show_var_code 3 /* show a variable and its descendents */
@d show_dependencies_code 4 /* show dependent variables in terms of independents */
@<Put each...@>=
mp_primitive (mp, "showtoken", mp_show_command, show_token_code);
@:show_token_}{\&{showtoken} primitive@>;
mp_primitive (mp, "showstats", mp_show_command, show_stats_code);
@:show_stats_}{\&{showstats} primitive@>;
mp_primitive (mp, "show", mp_show_command, show_code);
@:show_}{\&{show} primitive@>;
mp_primitive (mp, "showvariable", mp_show_command, show_var_code);
@:show_var_}{\&{showvariable} primitive@>;
mp_primitive (mp, "showdependencies", mp_show_command, show_dependencies_code);
@:show_dependencies_}{\&{showdependencies} primitive@>
@ @<Cases of |print_cmd...@>=
case mp_show_command:
switch (m) {
case show_token_code:
mp_print (mp, "showtoken");
break;
case show_stats_code:
mp_print (mp, "showstats");
break;
case show_code:
mp_print (mp, "show");
break;
case show_var_code:
mp_print (mp, "showvariable");
break;
default:
mp_print (mp, "showdependencies");
break;
}
break;
@ The value of |cur_mod| controls the |verbosity| in the |print_exp| routine:
if it's |show_code|, complicated structures are abbreviated, otherwise
they aren't.
@<Declare action procedures for use by |do_statement|@>=
static void mp_do_show (MP mp);
@ @c
void mp_do_show (MP mp) {
mp_value new_expr;
do {
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
mp_get_x_next (mp);
mp_scan_expression (mp);
mp_print_nl (mp, ">> ");
@.>>@>;
mp_print_exp (mp, NULL, 2);
mp_flush_cur_exp (mp, new_expr);
} while (cur_cmd() == mp_comma);
}
@ @<Declare action procedures for use by |do_statement|@>=
static void mp_disp_token (MP mp);
@ @c
void mp_disp_token (MP mp) {
mp_print_nl (mp, "> ");
@.>\relax@>;
if (cur_sym() == NULL) {
@<Show a numeric or string or capsule token@>;
} else {
mp_print_text (cur_sym());
mp_print_char (mp, xord ('='));
if (eq_type (cur_sym()) >= mp_outer_tag)
mp_print (mp, "(outer) ");
mp_print_cmd_mod (mp, cur_cmd(), cur_mod());
if (cur_cmd() == mp_defined_macro) {
mp_print_ln (mp);
mp_show_macro (mp, cur_mod_node(), NULL, 100000);
} /* this avoids recursion between |show_macro| and |print_cmd_mod| */
@^recursion@>
}
}
@ @<Show a numeric or string or capsule token@>=
{
if (cur_cmd() == mp_numeric_token) {
print_number (cur_mod_number());
} else if (cur_cmd() == mp_capsule_token) {
mp_print_capsule (mp, cur_mod_node());
} else {
mp_print_char (mp, xord ('"'));
mp_print_str (mp, cur_mod_str());
mp_print_char (mp, xord ('"'));
delete_str_ref (cur_mod_str());
}
}
@ The following cases of |print_cmd_mod| might arise in connection
with |disp_token|, although they don't necessarily correspond to
primitive tokens.
@<Cases of |print_cmd_...@>=
case mp_left_delimiter:
case mp_right_delimiter:
if (c == mp_left_delimiter)
mp_print (mp, "left");
else
mp_print (mp, "right");
#if 0
mp_print (mp, " delimiter that matches ");
mp_print_text (m);
#else
mp_print (mp, " delimiter");
#endif
break;
case mp_tag_token:
if (m == 0) /* todo: this was |null| */
mp_print (mp, "tag");
else
mp_print (mp, "variable");
break;
case mp_defined_macro:
mp_print (mp, "macro:");
break;
case mp_secondary_primary_macro:
case mp_tertiary_secondary_macro:
case mp_expression_tertiary_macro:
mp_print_cmd_mod(mp, mp_macro_def,c);
mp_print(mp, "'d macro:");
mp_print_ln(mp);
mp_show_token_list(mp, mp_link(mp_link(cur_mod_node())),0,1000,0);
break;
case mp_repeat_loop:
mp_print (mp, "[repeat the loop]");
break;
case mp_internal_quantity:
mp_print (mp, internal_name (m));
break;
@ @<Declare action procedures for use by |do_statement|@>=
static void mp_do_show_token (MP mp);
@ @c
void mp_do_show_token (MP mp) {
do {
get_t_next (mp);
mp_disp_token (mp);
mp_get_x_next (mp);
} while (cur_cmd() == mp_comma);
}
@ @<Declare action procedures for use by |do_statement|@>=
static void mp_do_show_stats (MP mp);
@ @c
void mp_do_show_stats (MP mp) {
mp_print_nl (mp, "Memory usage ");
@.Memory usage...@>;
mp_print_int (mp, (integer) mp->var_used);
mp_print_ln (mp);
mp_print_nl (mp, "String usage ");
mp_print_int (mp, (int) mp->strs_in_use);
mp_print_char (mp, xord ('&'));
mp_print_int (mp, (int) mp->pool_in_use);
mp_print_ln (mp);
mp_get_x_next (mp);
}
@ Here's a recursive procedure that gives an abbreviated account
of a variable, for use by |do_show_var|.
@<Declare action procedures for use by |do_statement|@>=
static void mp_disp_var (MP mp, mp_node p);
@ @c
void mp_disp_var (MP mp, mp_node p) {
mp_node q; /* traverses attributes and subscripts */
int n; /* amount of macro text to show */
if (mp_type (p) == mp_structured) {
@<Descend the structure@>;
} else if (mp_type (p) >= mp_unsuffixed_macro) {
@<Display a variable macro@>;
} else if (mp_type (p) != mp_undefined) {
mp_print_nl (mp, "");
mp_print_variable_name (mp, p);
mp_print_char (mp, xord ('='));
mp_print_exp (mp, p, 0);
}
}
@ @<Descend the structure@>=
{
q = attr_head (p);
do {
mp_disp_var (mp, q);
q = mp_link (q);
} while (q != mp->end_attr);
q = subscr_head (p);
while (mp_name_type (q) == mp_subscr) {
mp_disp_var (mp, q);
q = mp_link (q);
}
}
@ @<Display a variable macro@>=
{
mp_print_nl (mp, "");
mp_print_variable_name (mp, p);
if (mp_type (p) > mp_unsuffixed_macro)
mp_print (mp, "@@#"); /* |suffixed_macro| */
mp_print (mp, "=macro:");
if ((int) mp->file_offset >= mp->max_print_line - 20)
n = 5;
else
n = mp->max_print_line - (int) mp->file_offset - 15;
mp_show_macro (mp, value_node (p), NULL, n);
}
@ @<Declare action procedures for use by |do_statement|@>=
static void mp_do_show_var (MP mp);
@ @c
void mp_do_show_var (MP mp) {
do {
get_t_next (mp);
if (cur_sym() != NULL)
if (cur_sym_mod() == 0)
if (cur_cmd() == mp_tag_token)
if (cur_mod() != 0 || cur_mod_node()!=NULL) {
mp_disp_var (mp, cur_mod_node());
goto DONE;
}
mp_disp_token (mp);
DONE:
mp_get_x_next (mp);
} while (cur_cmd() == mp_comma);
}
@ @<Declare action procedures for use by |do_statement|@>=
static void mp_do_show_dependencies (MP mp);
@ @c
void mp_do_show_dependencies (MP mp) {
mp_value_node p; /* link that runs through all dependencies */
p = (mp_value_node) mp_link (mp->dep_head);
while (p != mp->dep_head) {
if (mp_interesting (mp, (mp_node) p)) {
mp_print_nl (mp, "");
mp_print_variable_name (mp, (mp_node) p);
if (mp_type (p) == mp_dependent)
mp_print_char (mp, xord ('='));
else
mp_print (mp, " = "); /* extra spaces imply proto-dependency */
mp_print_dependency (mp, (mp_value_node) dep_list (p), mp_type (p));
}
p = (mp_value_node) dep_list (p);
while (dep_info (p) != NULL)
p = (mp_value_node) mp_link (p);
p = (mp_value_node) mp_link (p);
}
mp_get_x_next (mp);
}
@ Finally we are ready for the procedure that governs all of the
show commands.
@<Declare action procedures for use by |do_statement|@>=
static void mp_do_show_whatever (MP mp);
@ @c
void mp_do_show_whatever (MP mp) {
if (mp->interaction == mp_error_stop_mode)
wake_up_terminal();
switch (cur_mod()) {
case show_token_code:
mp_do_show_token (mp);
break;
case show_stats_code:
mp_do_show_stats (mp);
break;
case show_code:
mp_do_show (mp);
break;
case show_var_code:
mp_do_show_var (mp);
break;
case show_dependencies_code:
mp_do_show_dependencies (mp);
break;
} /* there are no other cases */
if (number_positive (internal_value (mp_showstopping))) {
const char *hlp[] = {
"This isn't an error message; I'm just showing something.",
NULL };
if (mp->interaction < mp_error_stop_mode) {
hlp[0] = NULL;
decr (mp->error_count);
}
if (cur_cmd() == mp_semicolon) {
mp_error (mp, "OK", hlp, true);
} else {
mp_back_error (mp, "OK", hlp, true);
mp_get_x_next (mp);
}
@.OK@>;
}
}
@ The `\&{addto}' command needs the following additional primitives:
@d double_path_code 0 /* command modifier for `\&{doublepath}' */
@d contour_code 1 /* command modifier for `\&{contour}' */
@d also_code 2 /* command modifier for `\&{also}' */
@ Pre and postscripts need two new identifiers:
@d with_mp_pre_script 11
@d with_mp_post_script 13
@<Put each...@>=
mp_primitive (mp, "doublepath", mp_thing_to_add, double_path_code);
@:double_path_}{\&{doublepath} primitive@>;
mp_primitive (mp, "contour", mp_thing_to_add, contour_code);
@:contour_}{\&{contour} primitive@>;
mp_primitive (mp, "also", mp_thing_to_add, also_code);
@:also_}{\&{also} primitive@>;
mp_primitive (mp, "withpen", mp_with_option, mp_pen_type);
@:with_pen_}{\&{withpen} primitive@>;
mp_primitive (mp, "dashed", mp_with_option, mp_picture_type);
@:dashed_}{\&{dashed} primitive@>;
mp_primitive (mp, "withprescript", mp_with_option, with_mp_pre_script);
@:with_mp_pre_script_}{\&{withprescript} primitive@>;
mp_primitive (mp, "withpostscript", mp_with_option, with_mp_post_script);
@:with_mp_post_script_}{\&{withpostscript} primitive@>;
mp_primitive (mp, "withoutcolor", mp_with_option, mp_no_model);
@:with_color_}{\&{withoutcolor} primitive@>;
mp_primitive (mp, "withgreyscale", mp_with_option, mp_grey_model);
@:with_color_}{\&{withgreyscale} primitive@>;
mp_primitive (mp, "withcolor", mp_with_option, mp_uninitialized_model);
@:with_color_}{\&{withcolor} primitive@>
/* \&{withrgbcolor} is an alias for \&{withcolor} */
mp_primitive (mp, "withrgbcolor", mp_with_option, mp_rgb_model);
@:with_color_}{\&{withrgbcolor} primitive@>;
mp_primitive (mp, "withcmykcolor", mp_with_option, mp_cmyk_model);
@:with_color_}{\&{withcmykcolor} primitive@>
@ @<Cases of |print_cmd...@>=
case mp_thing_to_add:
if (m == contour_code)
mp_print (mp, "contour");
else if (m == double_path_code)
mp_print (mp, "doublepath");
else
mp_print (mp, "also");
break;
case mp_with_option:
if (m == mp_pen_type)
mp_print (mp, "withpen");
else if (m == with_mp_pre_script)
mp_print (mp, "withprescript");
else if (m == with_mp_post_script)
mp_print (mp, "withpostscript");
else if (m == mp_no_model)
mp_print (mp, "withoutcolor");
else if (m == mp_rgb_model)
mp_print (mp, "withrgbcolor");
else if (m == mp_uninitialized_model)
mp_print (mp, "withcolor");
else if (m == mp_cmyk_model)
mp_print (mp, "withcmykcolor");
else if (m == mp_grey_model)
mp_print (mp, "withgreyscale");
else
mp_print (mp, "dashed");
break;
@ The |scan_with_list| procedure parses a $\langle$with list$\rangle$ and
updates the list of graphical objects starting at |p|. Each $\langle$with
clause$\rangle$ updates all graphical objects whose |type| is compatible.
Other objects are ignored.
@<Declare action procedures for use by |do_statement|@>=
static void mp_scan_with_list (MP mp, mp_node p);
@ Forcing the color to be between |0| and |unity| here guarantees that no
picture will ever contain a color outside the legal range for \ps\ graphics.
@d make_cp_a_colored_object() do {
cp = p;
while (cp != NULL) {
if (has_color (cp))
break;
cp = mp_link (cp);
}
} while (0)
@d clear_color(A) do {
set_number_to_zero(((mp_stroked_node)(A))->cyan);
set_number_to_zero(((mp_stroked_node)(A))->magenta);
set_number_to_zero(((mp_stroked_node)(A))->yellow);
set_number_to_zero(((mp_stroked_node)(A))->black);
mp_color_model ((A)) = mp_uninitialized_model;
} while (0)
@d set_color_val(A,B) do {
number_clone(A, (B));
if (number_negative(A))
set_number_to_zero(A);
if (number_greater(A,unity_t))
set_number_to_unity(A);
} while (0)
@c
static int is_invalid_with_list (MP mp, mp_variable_type t) {
return ((t == with_mp_pre_script) && (mp->cur_exp.type != mp_string_type)) ||
((t == with_mp_post_script) && (mp->cur_exp.type != mp_string_type)) ||
((t == (mp_variable_type) mp_uninitialized_model) &&
((mp->cur_exp.type != mp_cmykcolor_type)
&& (mp->cur_exp.type != mp_color_type)
&& (mp->cur_exp.type != mp_known)
&& (mp->cur_exp.type != mp_boolean_type))) || ((t == (mp_variable_type) mp_cmyk_model)
&& (mp->cur_exp.type !=
mp_cmykcolor_type))
|| ((t == (mp_variable_type) mp_rgb_model) && (mp->cur_exp.type != mp_color_type))
|| ((t == (mp_variable_type) mp_grey_model) && (mp->cur_exp.type != mp_known))
|| ((t == (mp_variable_type) mp_pen_type) && (mp->cur_exp.type != t))
|| ((t == (mp_variable_type) mp_picture_type) && (mp->cur_exp.type != t));
}
static void complain_invalid_with_list (MP mp, mp_variable_type t) {
/* Complain about improper type */
mp_value new_expr;
const char *hlp[] = {
"Next time say `withpen <known pen expression>';",
"I'll ignore the bad `with' clause and look for another.",
NULL };
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
mp_disp_err(mp, NULL);
if (t == with_mp_pre_script)
hlp[0] = "Next time say `withprescript <known string expression>';";
else if (t == with_mp_post_script)
hlp[0] = "Next time say `withpostscript <known string expression>';";
else if (t == mp_picture_type)
hlp[0] = "Next time say `dashed <known picture expression>';";
else if (t == (mp_variable_type) mp_uninitialized_model)
hlp[0] = "Next time say `withcolor <known color expression>';";
else if (t == (mp_variable_type) mp_rgb_model)
hlp[0] = "Next time say `withrgbcolor <known color expression>';";
else if (t == (mp_variable_type) mp_cmyk_model)
hlp[0] = "Next time say `withcmykcolor <known cmykcolor expression>';";
else if (t == (mp_variable_type) mp_grey_model)
hlp[0] = "Next time say `withgreyscale <known numeric expression>';";;
mp_back_error (mp, "Improper type", hlp, true);
mp_get_x_next (mp);
mp_flush_cur_exp (mp, new_expr);
}
void mp_scan_with_list (MP mp, mp_node p) {
mp_variable_type t; /* |cur_mod| of the |with_option| (should match |cur_type|) */
mp_node q; /* for list manipulation */
mp_node cp, pp, dp, ap, bp;
/* objects being updated; |void| initially; |NULL| to suppress update */
cp = MP_VOID;
pp = MP_VOID;
dp = MP_VOID;
ap = MP_VOID;
bp = MP_VOID;
while (cur_cmd() == mp_with_option) {
/* todo this is not very nice: the color models have their own enumeration */
t = (mp_variable_type) cur_mod();
mp_get_x_next (mp);
if (t != (mp_variable_type) mp_no_model)
mp_scan_expression (mp);
if (is_invalid_with_list(mp, t)) {
complain_invalid_with_list (mp, t);
continue;
}
if (t == (mp_variable_type) mp_uninitialized_model) {
mp_value new_expr;
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
if (cp == MP_VOID)
make_cp_a_colored_object();
if (cp != NULL) {
/* Transfer a color from the current expression to object~|cp| */
if (mp->cur_exp.type == mp_color_type) {
/* Transfer a rgbcolor from the current expression to object~|cp| */
mp_stroked_node cp0 = (mp_stroked_node)cp;
q = value_node (cur_exp_node ());
clear_color(cp0);
mp_color_model (cp) = mp_rgb_model;
set_color_val (cp0->red, value_number (red_part (q)));
set_color_val (cp0->green, value_number (green_part (q)));
set_color_val (cp0->blue, value_number (blue_part (q)));
} else if (mp->cur_exp.type == mp_cmykcolor_type) {
/* Transfer a cmykcolor from the current expression to object~|cp| */
mp_stroked_node cp0 = (mp_stroked_node)cp;
q = value_node (cur_exp_node ());
set_color_val (cp0->cyan, value_number (cyan_part (q)));
set_color_val (cp0->magenta, value_number (magenta_part (q)));
set_color_val (cp0->yellow, value_number (yellow_part (q)));
set_color_val (cp0->black, value_number (black_part (q)));
mp_color_model (cp) = mp_cmyk_model;
} else if (mp->cur_exp.type == mp_known) {
/* Transfer a greyscale from the current expression to object~|cp| */
mp_number qq;
mp_stroked_node cp0 = (mp_stroked_node)cp;
new_number (qq);
number_clone (qq, cur_exp_value_number ());
clear_color (cp);
mp_color_model (cp) = mp_grey_model;
set_color_val (cp0->grey, qq);
free_number (qq);
} else if (cur_exp_value_boolean () == mp_false_code) {
/* Transfer a noncolor from the current expression to object~|cp| */
clear_color (cp);
mp_color_model (cp) = mp_no_model;
} else if (cur_exp_value_boolean () == mp_true_code) {
/* Transfer no color from the current expression to object~|cp| */
clear_color (cp);
mp_color_model (cp) = mp_uninitialized_model;
}
}
mp_flush_cur_exp (mp, new_expr);
} else if (t == (mp_variable_type) mp_rgb_model) {
mp_value new_expr;
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
if (cp == MP_VOID)
make_cp_a_colored_object();
if (cp != NULL) {
/* Transfer a rgbcolor from the current expression to object~|cp| */
mp_stroked_node cp0 = (mp_stroked_node)cp;
q = value_node (cur_exp_node ());
clear_color(cp0);
mp_color_model (cp) = mp_rgb_model;
set_color_val (cp0->red, value_number (red_part (q)));
set_color_val (cp0->green, value_number (green_part (q)));
set_color_val (cp0->blue, value_number (blue_part (q)));
}
mp_flush_cur_exp (mp, new_expr);
} else if (t == (mp_variable_type) mp_cmyk_model) {
mp_value new_expr;
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
if (cp == MP_VOID)
make_cp_a_colored_object();
if (cp != NULL) {
/* Transfer a cmykcolor from the current expression to object~|cp| */
mp_stroked_node cp0 = (mp_stroked_node)cp;
q = value_node (cur_exp_node ());
set_color_val (cp0->cyan, value_number (cyan_part (q)));
set_color_val (cp0->magenta, value_number (magenta_part (q)));
set_color_val (cp0->yellow, value_number (yellow_part (q)));
set_color_val (cp0->black, value_number (black_part (q)));
mp_color_model (cp) = mp_cmyk_model;
}
mp_flush_cur_exp (mp, new_expr);
} else if (t == (mp_variable_type) mp_grey_model) {
mp_value new_expr;
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
if (cp == MP_VOID)
make_cp_a_colored_object();
if (cp != NULL) {
/* Transfer a greyscale from the current expression to object~|cp| */
mp_number qq;
mp_stroked_node cp0 = (mp_stroked_node)cp;
new_number (qq);
number_clone (qq, cur_exp_value_number ());
clear_color (cp);
mp_color_model (cp) = mp_grey_model;
set_color_val (cp0->grey, qq);
free_number (qq);
}
mp_flush_cur_exp (mp, new_expr);
} else if (t == (mp_variable_type) mp_no_model) {
if (cp == MP_VOID)
make_cp_a_colored_object();
if (cp != NULL) {
/* Transfer a noncolor from the current expression to object~|cp| */
clear_color (cp);
mp_color_model (cp) = mp_no_model;
}
} else if (t == mp_pen_type) {
if (pp == MP_VOID) {
/* Make |pp| an object in list~|p| that needs a pen */
pp = p;
while (pp != NULL) {
if (has_pen (pp))
break;
pp = mp_link (pp);
}
}
if (pp != NULL) {
switch (mp_type (pp)) {
case mp_fill_node_type:
if (mp_pen_p ((mp_fill_node) pp) != NULL)
mp_toss_knot_list (mp, mp_pen_p ((mp_fill_node) pp));
mp_pen_p ((mp_fill_node) pp) = cur_exp_knot ();
break;
case mp_stroked_node_type:
if (mp_pen_p ((mp_stroked_node) pp) != NULL)
mp_toss_knot_list (mp, mp_pen_p ((mp_stroked_node) pp));
mp_pen_p ((mp_stroked_node) pp) = cur_exp_knot ();
break;
default:
assert (0);
break;
}
mp->cur_exp.type = mp_vacuous;
}
} else if (t == with_mp_pre_script) {
if (cur_exp_str ()->len) {
if (ap == MP_VOID)
ap = p;
while ((ap != NULL) && (!has_color (ap)))
ap = mp_link (ap);
if (ap != NULL) {
if (mp_pre_script (ap) != NULL) { /* build a new,combined string */
unsigned old_setting; /* saved |selector| setting */
mp_string s; /* for string cleanup after combining */
s = mp_pre_script (ap);
old_setting = mp->selector;
mp->selector = new_string;
str_room (mp_pre_script (ap)->len + cur_exp_str ()->len + 2);
mp_print_str (mp, cur_exp_str ());
append_char (13); /* a forced \ps\ newline */
mp_print_str (mp, mp_pre_script (ap));
mp_pre_script (ap) = mp_make_string (mp);
delete_str_ref (s);
mp->selector = old_setting;
} else {
mp_pre_script (ap) = cur_exp_str ();
}
add_str_ref (mp_pre_script (ap));
mp->cur_exp.type = mp_vacuous;
}
}
} else if (t == with_mp_post_script) {
if (cur_exp_str ()->len) {
if (bp == MP_VOID)
bp = p;
while ((bp != NULL) && (!has_color (bp)))
bp = mp_link (bp);
if (bp != NULL) {
if (mp_post_script (bp) != NULL) {
unsigned old_setting; /* saved |selector| setting */
mp_string s; /* for string cleanup after combining */
s = mp_post_script (bp);
old_setting = mp->selector;
mp->selector = new_string;
str_room (mp_post_script (bp)->len + cur_exp_str ()->len + 2);
mp_print_str (mp, mp_post_script (bp));
append_char (13); /* a forced \ps\ newline */
mp_print_str (mp, cur_exp_str ());
mp_post_script (bp) = mp_make_string (mp);
delete_str_ref (s);
mp->selector = old_setting;
} else {
mp_post_script (bp) = cur_exp_str ();
}
add_str_ref (mp_post_script (bp));
mp->cur_exp.type = mp_vacuous;
}
}
} else {
if (dp == MP_VOID) {
/* Make |dp| a stroked node in list~|p| */
dp = p;
while (dp != NULL) {
if (mp_type (dp) == mp_stroked_node_type)
break;
dp = mp_link (dp);
}
}
if (dp != NULL) {
if (mp_dash_p (dp) != NULL)
delete_edge_ref (mp_dash_p (dp));
mp_dash_p (dp) = (mp_node)mp_make_dashes (mp, (mp_edge_header_node)cur_exp_node ());
set_number_to_unity(((mp_stroked_node)dp)->dash_scale);
mp->cur_exp.type = mp_vacuous;
}
}
}
/* Copy the information from objects |cp|, |pp|, and |dp| into the rest
of the list */
if (cp > MP_VOID) {
/* Copy |cp|'s color into the colored objects linked to~|cp| */
q = mp_link (cp);
while (q != NULL) {
if (has_color (q)) {
mp_stroked_node q0 = (mp_stroked_node)q;
mp_stroked_node cp0 = (mp_stroked_node)cp;
number_clone(q0->red, cp0->red);
number_clone(q0->green, cp0->green);
number_clone(q0->blue, cp0->blue);
number_clone(q0->black, cp0->black);
mp_color_model (q) = mp_color_model (cp);
}
q = mp_link (q);
}
}
if (pp > MP_VOID) {
/* Copy |mp_pen_p(pp)| into stroked and filled nodes linked to |pp| */
q = mp_link (pp);
while (q != NULL) {
if (has_pen (q)) {
switch (mp_type (q)) {
case mp_fill_node_type:
if (mp_pen_p ((mp_fill_node) q) != NULL)
mp_toss_knot_list (mp, mp_pen_p ((mp_fill_node) q));
mp_pen_p ((mp_fill_node) q) = copy_pen (mp_pen_p ((mp_fill_node) pp));
break;
case mp_stroked_node_type:
if (mp_pen_p ((mp_stroked_node) q) != NULL)
mp_toss_knot_list (mp, mp_pen_p ((mp_stroked_node) q));
mp_pen_p ((mp_stroked_node) q) =
copy_pen (mp_pen_p ((mp_stroked_node) pp));
break;
default:
assert (0);
break;
}
}
q = mp_link (q);
}
}
if (dp > MP_VOID) {
/* Make stroked nodes linked to |dp| refer to |mp_dash_p(dp)| */
q = mp_link (dp);
while (q != NULL) {
if (mp_type (q) == mp_stroked_node_type) {
if (mp_dash_p (q) != NULL)
delete_edge_ref (mp_dash_p (q));
mp_dash_p (q) = mp_dash_p (dp);
set_number_to_unity(((mp_stroked_node)q)->dash_scale);
if (mp_dash_p (q) != NULL)
add_edge_ref (mp_dash_p (q));
}
q = mp_link (q);
}
}
}
@ One of the things we need to do when we've parsed an \&{addto} or
similar command is find the header of a supposed \&{picture} variable, given
a token list for that variable. Since the edge structure is about to be
updated, we use |private_edges| to make sure that this is possible.
@<Declare action procedures for use by |do_statement|@>=
static mp_edge_header_node mp_find_edges_var (MP mp, mp_node t);
@ @c
mp_edge_header_node mp_find_edges_var (MP mp, mp_node t) {
mp_node p;
mp_edge_header_node cur_edges; /* the return value */
p = mp_find_variable (mp, t);
cur_edges = NULL;
if (p == NULL) {
const char *hlp[] = {
"It seems you did a nasty thing---probably by accident,",
"but nevertheless you nearly hornswoggled me...",
"While I was evaluating the right-hand side of this",
"command, something happened, and the left-hand side",
"is no longer a variable! So I won't change anything.",
NULL };
char *msg = mp_obliterated (mp, t);
mp_back_error (mp, msg, hlp, true);
free(msg);
mp_get_x_next (mp);
} else if (mp_type (p) != mp_picture_type) {
char msg[256];
mp_string sname;
int old_setting = mp->selector;
const char *hlp[] = {
"I was looking for a \"known\" picture variable.",
"So I'll not change anything just now.",
NULL };
mp->selector = new_string;
mp_show_token_list (mp, t, NULL, 1000, 0);
sname = mp_make_string(mp);
mp->selector = old_setting;
mp_snprintf (msg, 256, "Variable %s is the wrong type(%s)",
mp_str(mp, sname), mp_type_string(mp_type (p)));
@.Variable x is the wrong type@>;
delete_str_ref(sname);
mp_back_error (mp, msg, hlp, true);
mp_get_x_next (mp);
} else {
set_value_node (p, (mp_node)mp_private_edges (mp, (mp_edge_header_node)value_node (p)));
cur_edges = (mp_edge_header_node)value_node (p);
}
mp_flush_node_list (mp, t);
return cur_edges;
}
@ @<Put each...@>=
mp_primitive (mp, "clip", mp_bounds_command, mp_start_clip_node_type);
@:clip_}{\&{clip} primitive@>;
mp_primitive (mp, "setbounds", mp_bounds_command, mp_start_bounds_node_type);
@:set_bounds_}{\&{setbounds} primitive@>
@ @<Cases of |print_cmd...@>=
case mp_bounds_command:
if (m == mp_start_clip_node_type)
mp_print (mp, "clip");
else
mp_print (mp, "setbounds");
break;
@ The following function parses the beginning of an \&{addto} or \&{clip}
command: it expects a variable name followed by a token with |cur_cmd=sep|
and then an expression. The function returns the token list for the variable
and stores the command modifier for the separator token in the global variable
|last_add_type|. We must be careful because this variable might get overwritten
any time we call |get_x_next|.
@<Glob...@>=
quarterword last_add_type;
/* command modifier that identifies the last \&{addto} command */
@ @<Declare action procedures for use by |do_statement|@>=
static mp_node mp_start_draw_cmd (MP mp, quarterword sep);
@ @c
mp_node mp_start_draw_cmd (MP mp, quarterword sep) {
mp_node lhv; /* variable to add to left */
quarterword add_type = 0; /* value to be returned in |last_add_type| */
lhv = NULL;
mp_get_x_next (mp);
mp->var_flag = sep;
mp_scan_primary (mp);
if (mp->cur_exp.type != mp_token_list) {
/* Abandon edges command because there's no variable */
mp_value new_expr;
const char *hlp[] = {
"At this point I needed to see the name of a picture variable.",
"(Or perhaps you have indeed presented me with one; I might",
"have missed it, if it wasn't followed by the proper token.)",
"So I'll not change anything just now.",
NULL };
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
mp_disp_err(mp, NULL);
set_number_to_zero (new_expr.data.n);
mp_back_error (mp, "Not a suitable variable", hlp, true);
mp_get_x_next (mp);
mp_flush_cur_exp (mp, new_expr);
} else {
lhv = cur_exp_node ();
add_type = (quarterword) cur_mod();
mp->cur_exp.type = mp_vacuous;
mp_get_x_next (mp);
mp_scan_expression (mp);
}
mp->last_add_type = add_type;
return lhv;
}
@ Here is an example of how to use |start_draw_cmd|.
@<Declare action procedures for use by |do_statement|@>=
static void mp_do_bounds (MP mp);
@ @c
void mp_do_bounds (MP mp) {
mp_node lhv; /* variable on left, the corresponding edge structure */
mp_edge_header_node lhe;
mp_node p; /* for list manipulation */
integer m; /* initial value of |cur_mod| */
m = cur_mod();
lhv = mp_start_draw_cmd (mp, mp_to_token);
if (lhv != NULL) {
mp_value new_expr;
memset(&new_expr,0,sizeof(mp_value));
lhe = mp_find_edges_var (mp, lhv);
if (lhe == NULL) {
new_number(new_expr.data.n);
set_number_to_zero (new_expr.data.n);
mp_flush_cur_exp (mp, new_expr);
} else if (mp->cur_exp.type != mp_path_type) {
const char *hlp[] ={
"This expression should have specified a known path.",
"So I'll not change anything just now.",
NULL };
mp_disp_err(mp, NULL);
new_number(new_expr.data.n);
set_number_to_zero (new_expr.data.n);
mp_back_error (mp, "Improper `clip'", hlp, true);
mp_get_x_next (mp);
mp_flush_cur_exp (mp, new_expr);
} else if (mp_left_type (cur_exp_knot ()) == mp_endpoint) {
/* Complain about a non-cycle */
const char *hlp[] = {
"That contour should have ended with `..cycle' or `&cycle'.",
"So I'll not change anything just now.",
NULL };
mp_back_error (mp, "Not a cycle" , hlp, true);
mp_get_x_next (mp);
} else {
/* Make |cur_exp| into a \&{setbounds} or clipping path and add it to |lhe| */
p = mp_new_bounds_node (mp, cur_exp_knot (), (quarterword) m);
mp_link (p) = mp_link (edge_list (lhe));
mp_link (edge_list (lhe)) = p;
if (obj_tail (lhe) == edge_list (lhe))
obj_tail (lhe) = p;
if (m == mp_start_clip_node_type) {
p = mp_new_bounds_node (mp, NULL, mp_stop_clip_node_type);
} else if (m == mp_start_bounds_node_type) {
p = mp_new_bounds_node (mp, NULL, mp_stop_bounds_node_type);
}
mp_link (obj_tail (lhe)) = p;
obj_tail (lhe) = p;
mp_init_bbox (mp, lhe);
}
}
}
@ The |do_add_to| procedure is a little like |do_clip| but there are a lot more
cases to deal with.
@<Declare action procedures for use by |do_statement|@>=
static void mp_do_add_to (MP mp);
@ @c
void mp_do_add_to (MP mp) {
mp_node lhv;
mp_edge_header_node lhe; /* variable on left, the corresponding edge structure */
mp_node p; /* the graphical object or list for |scan_with_list| to update */
mp_edge_header_node e; /* an edge structure to be merged */
quarterword add_type; /* |also_code|, |contour_code|, or |double_path_code| */
lhv = mp_start_draw_cmd (mp, mp_thing_to_add);
add_type = mp->last_add_type;
if (lhv != NULL) {
if (add_type == also_code) {
/* Make sure the current expression is a suitable picture and set |e| and |p|
appropriately */
/* Setting |p:=NULL| causes the $\langle$with list$\rangle$ to be ignored;
setting |e:=NULL| prevents anything from being added to |lhe|. */
p = NULL;
e = NULL;
if (mp->cur_exp.type != mp_picture_type) {
mp_value new_expr;
const char *hlp[]= {
"This expression should have specified a known picture.",
"So I'll not change anything just now.",
NULL };
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
mp_disp_err(mp, NULL);
set_number_to_zero (new_expr.data.n);
mp_back_error (mp, "Improper `addto'", hlp, true);
mp_get_x_next (mp);
mp_flush_cur_exp (mp, new_expr);
} else {
e = mp_private_edges (mp, (mp_edge_header_node)cur_exp_node ());
mp->cur_exp.type = mp_vacuous;
p = mp_link (edge_list (e));
}
} else {
/* Create a graphical object |p| based on |add_type| and the current
expression */
/* In this case |add_type<>also_code| so setting |p:=NULL| suppresses future
attempts to add to the edge structure. */
e = NULL;
p = NULL;
if (mp->cur_exp.type == mp_pair_type)
mp_pair_to_path (mp);
if (mp->cur_exp.type != mp_path_type) {
mp_value new_expr;
const char *hlp[] = {
"This expression should have specified a known path.",
"So I'll not change anything just now.",
NULL };
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
mp_disp_err(mp, NULL);
set_number_to_zero (new_expr.data.n);
mp_back_error (mp, "Improper `addto'", hlp, true);
mp_get_x_next (mp);
mp_flush_cur_exp (mp, new_expr);
} else if (add_type == contour_code) {
if (mp_left_type (cur_exp_knot ()) == mp_endpoint) {
/* Complain about a non-cycle */
const char *hlp[] = {
"That contour should have ended with `..cycle' or `&cycle'.",
"So I'll not change anything just now.",
NULL };
mp_back_error (mp, "Not a cycle" , hlp, true);
mp_get_x_next (mp);
} else {
p = mp_new_fill_node (mp, cur_exp_knot ());
mp->cur_exp.type = mp_vacuous;
}
} else {
p = mp_new_stroked_node (mp, cur_exp_knot ());
mp->cur_exp.type = mp_vacuous;
}
}
mp_scan_with_list (mp, p);
/* Use |p|, |e|, and |add_type| to augment |lhv| as requested */
lhe = mp_find_edges_var (mp, lhv);
if (lhe == NULL) {
if ((e == NULL) && (p != NULL))
e = mp_toss_gr_object (mp, p);
if (e != NULL)
delete_edge_ref (e);
} else if (add_type == also_code) {
if (e != NULL) {
/* Merge |e| into |lhe| and delete |e| */
if (mp_link (edge_list (e)) != NULL) {
mp_link (obj_tail (lhe)) = mp_link (edge_list (e));
obj_tail (lhe) = obj_tail (e);
obj_tail (e) = edge_list (e);
mp_link (edge_list (e)) = NULL;
mp_flush_dash_list (mp, lhe);
}
mp_toss_edges (mp, e);
}
} else if (p != NULL) {
mp_link (obj_tail (lhe)) = p;
obj_tail (lhe) = p;
if (add_type == double_path_code) {
if (mp_pen_p ((mp_stroked_node) p) == NULL) {
mp_pen_p ((mp_stroked_node) p) = mp_get_pen_circle (mp, zero_t);
}
}
}
}
}
@ @<Declare action procedures for use by |do_statement|@>=
@<Declare the \ps\ output procedures@>;
static void mp_do_ship_out (MP mp);
@ @c
void mp_do_ship_out (MP mp) {
integer c; /* the character code */
mp_value new_expr;
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
mp_get_x_next (mp);
mp_scan_expression (mp);
if (mp->cur_exp.type != mp_picture_type) {
@<Complain that it's not a known picture@>;
} else {
c = round_unscaled (internal_value (mp_char_code)) % 256;
if (c < 0)
c = c + 256;
@<Store the width information for character code~|c|@>;
mp_ship_out (mp, cur_exp_node ());
set_number_to_zero (new_expr.data.n);
mp_flush_cur_exp (mp, new_expr);
}
}
@ @<Complain that it's not a known picture@>=
{
const char *hlp[] = { "I can only output known pictures.", NULL };
mp_disp_err(mp, NULL);
set_number_to_zero (new_expr.data.n);
mp_back_error (mp, "Not a known picture", hlp, true);
mp_get_x_next (mp);
mp_flush_cur_exp (mp, new_expr);
}
@ The \&{everyjob} command simply assigns a nonzero value to the global variable
|start_sym|.
@ @<Glob...@>=
mp_sym start_sym; /* a symbolic token to insert at beginning of job */
@ @<Set init...@>=
mp->start_sym = NULL;
@ Finally, we have only the ``message'' commands remaining.
@d message_code 0
@d err_message_code 1
@d err_help_code 2
@d filename_template_code 3
@d print_with_leading_zeroes(A,B) do {
size_t g = mp->cur_length;
size_t f = (size_t)(B);
mp_print_int(mp, (A));
g = mp->cur_length - g;
if ( f>g ) {
mp->cur_length = mp->cur_length - g;
while ( f>g ) {
mp_print_char(mp, xord('0'));
decr(f);
};
mp_print_int(mp, (A));
};
f = 0;
} while (0)
@<Put each...@>=
mp_primitive (mp, "message", mp_message_command, message_code);
@:message_}{\&{message} primitive@>;
mp_primitive (mp, "errmessage", mp_message_command, err_message_code);
@:err_message_}{\&{errmessage} primitive@>;
mp_primitive (mp, "errhelp", mp_message_command, err_help_code);
@:err_help_}{\&{errhelp} primitive@>;
mp_primitive (mp, "filenametemplate", mp_message_command, filename_template_code);
@:filename_template_}{\&{filenametemplate} primitive@>
@ @<Cases of |print_cmd...@>=
case mp_message_command:
if (m < err_message_code)
mp_print (mp, "message");
else if (m == err_message_code)
mp_print (mp, "errmessage");
else if (m == filename_template_code)
mp_print (mp, "filenametemplate");
else
mp_print (mp, "errhelp");
break;
@ @<Declare action procedures for use by |do_statement|@>=
@<Declare a procedure called |no_string_err|@>;
static void mp_do_message (MP mp);
@
@c
void mp_do_message (MP mp) {
int m; /* the type of message */
mp_value new_expr;
m = cur_mod();
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
mp_get_x_next (mp);
mp_scan_expression (mp);
if (mp->cur_exp.type != mp_string_type)
mp_no_string_err (mp, "A message should be a known string expression.");
else {
switch (m) {
case message_code:
mp_print_nl (mp, "");
mp_print_str (mp, cur_exp_str ());
break;
case err_message_code:
@<Print string |cur_exp| as an error message@>;
break;
case err_help_code:
@<Save string |cur_exp| as the |err_help|@>;
break;
case filename_template_code:
@<Save the filename template@>;
break;
} /* there are no other cases */
}
set_number_to_zero (new_expr.data.n);
mp_flush_cur_exp (mp, new_expr);
}
@ @<Save the filename template@>=
{
delete_str_ref (internal_string (mp_output_template));
if (cur_exp_str ()->len == 0) {
set_internal_string (mp_output_template, mp_rts (mp, "%j.%c"));
} else {
set_internal_string (mp_output_template, cur_exp_str ());
add_str_ref (internal_string (mp_output_template));
}
}
@ @<Declare a procedure called |no_string_err|@>=
static void mp_no_string_err (MP mp, const char *s) {
const char *hlp[] = {s, NULL};
mp_disp_err(mp, NULL);
mp_back_error (mp, "Not a string", hlp, true);
@.Not a string@>;
mp_get_x_next (mp);
}
@ The global variable |err_help| is zero when the user has most recently
given an empty help string, or if none has ever been given.
@<Save string |cur_exp| as the |err_help|@>=
{
if (mp->err_help != NULL)
delete_str_ref (mp->err_help);
if (cur_exp_str ()->len == 0)
mp->err_help = NULL;
else {
mp->err_help = cur_exp_str ();
add_str_ref (mp->err_help);
}
}
@ If \&{errmessage} occurs often in |mp_scroll_mode|, without user-defined
\&{errhelp}, we don't want to give a long help message each time. So we
give a verbose explanation only once.
@<Glob...@>=
boolean long_help_seen; /* has the long \.{\\errmessage} help been used? */
@ @<Set init...@>=
mp->long_help_seen = false;
@ @<Print string |cur_exp| as an error message@>=
{
char msg[256];
mp_snprintf(msg, 256, "%s", mp_str(mp, cur_exp_str ()));
if (mp->err_help != NULL) {
mp->use_err_help = true;
mp_back_error (mp, msg, NULL, true);
} else if (mp->long_help_seen) {
const char *hlp[] = { "(That was another `errmessage'.)", NULL };
mp_back_error (mp, msg, hlp, true);
} else {
const char *hlp[] = {
"This error message was generated by an `errmessage'",
"command, so I can\'t give any explicit help.",
"Pretend that you're Miss Marple: Examine all clues,",
"and deduce the truth by inspired guesses.",
NULL };
@^Marple, Jane@>
if (mp->interaction < mp_error_stop_mode)
mp->long_help_seen = true;
mp_back_error (mp, msg, hlp, true);
}
mp_get_x_next (mp);
mp->use_err_help = false;
}
@ @<Declare action procedures for use by |do_statement|@>=
static void mp_do_write (MP mp);
@ @c
void mp_do_write (MP mp) {
mp_string t; /* the line of text to be written */
write_index n, n0; /* for searching |wr_fname| and |wr_file| arrays */
unsigned old_setting; /* for saving |selector| during output */
mp_value new_expr;
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
mp_get_x_next (mp);
mp_scan_expression (mp);
if (mp->cur_exp.type != mp_string_type) {
mp_no_string_err (mp,
"The text to be written should be a known string expression");
} else if (cur_cmd() != mp_to_token) {
const char *hlp[] = { "A write command should end with `to <filename>'", NULL };
mp_back_error (mp, "Missing `to' clause", hlp, true);
mp_get_x_next (mp);
} else {
t = cur_exp_str ();
mp->cur_exp.type = mp_vacuous;
mp_get_x_next (mp);
mp_scan_expression (mp);
if (mp->cur_exp.type != mp_string_type)
mp_no_string_err (mp,
"I can\'t write to that file name. It isn't a known string");
else {
@<Write |t| to the file named by |cur_exp|@>;
}
/* |delete_str_ref(t);| *//* todo: is this right? */
}
set_number_to_zero (new_expr.data.n);
mp_flush_cur_exp (mp, new_expr);
}
@ @<Write |t| to the file named by |cur_exp|@>=
{
@<Find |n| where |wr_fname[n]=cur_exp| and call |open_write_file| if
|cur_exp| must be inserted@>;
if (mp_str_vs_str (mp, t, mp->eof_line) == 0) {
@<Record the end of file on |wr_file[n]|@>;
} else {
old_setting = mp->selector;
mp->selector = n + write_file;
mp_print_str (mp, t);
mp_print_ln (mp);
mp->selector = old_setting;
}
}
@ @<Find |n| where |wr_fname[n]=cur_exp| and call |open_write_file| if...@>=
{
char *fn = mp_str (mp, cur_exp_str ());
n = mp->write_files;
n0 = mp->write_files;
while (mp_xstrcmp (fn, mp->wr_fname[n]) != 0) {
if (n == 0) { /* bottom reached */
if (n0 == mp->write_files) {
if (mp->write_files < mp->max_write_files) {
incr (mp->write_files);
} else {
void **wr_file;
char **wr_fname;
write_index l, k;
l = mp->max_write_files + (mp->max_write_files / 4);
wr_file = xmalloc ((l + 1), sizeof (void *));
wr_fname = xmalloc ((l + 1), sizeof (char *));
for (k = 0; k <= l; k++) {
if (k <= mp->max_write_files) {
wr_file[k] = mp->wr_file[k];
wr_fname[k] = mp->wr_fname[k];
} else {
wr_file[k] = 0;
wr_fname[k] = NULL;
}
}
xfree (mp->wr_file);
xfree (mp->wr_fname);
mp->max_write_files = l;
mp->wr_file = wr_file;
mp->wr_fname = wr_fname;
}
}
n = n0;
mp_open_write_file (mp, fn, n);
} else {
decr (n);
if (mp->wr_fname[n] == NULL)
n0 = n;
}
}
}
@ @<Record the end of file on |wr_file[n]|@>=
{
(mp->close_file) (mp, mp->wr_file[n]);
xfree (mp->wr_fname[n]);
if (n == mp->write_files - 1)
mp->write_files = n;
}
@* Writing font metric data.
\TeX\ gets its knowledge about fonts from font metric files, also called
\.{TFM} files; the `\.T' in `\.{TFM}' stands for \TeX,
but other programs know about them too. One of \MP's duties is to
write \.{TFM} files so that the user's fonts can readily be
applied to typesetting.
@:TFM files}{\.{TFM} files@>
@^font metric files@>
The information in a \.{TFM} file appears in a sequence of 8-bit bytes.
Since the number of bytes is always a multiple of~4, we could
also regard the file as a sequence of 32-bit words, but \MP\ uses the
byte interpretation. The format of \.{TFM} files was designed by
Lyle Ramshaw in 1980. The intent is to convey a lot of different kinds
@^Ramshaw, Lyle Harold@>
of information in a compact but useful form.
@<Glob...@>=
void *tfm_file; /* the font metric output goes here */
char *metric_file_name; /* full name of the font metric file */
@ The first 24 bytes (6 words) of a \.{TFM} file contain twelve 16-bit
integers that give the lengths of the various subsequent portions
of the file. These twelve integers are, in order:
$$\vbox{\halign{\hfil#&$\null=\null$#\hfil\cr
|lf|&length of the entire file, in words;\cr
|lh|&length of the header data, in words;\cr
|bc|&smallest character code in the font;\cr
|ec|&largest character code in the font;\cr
|nw|&number of words in the width table;\cr
|nh|&number of words in the height table;\cr
|nd|&number of words in the depth table;\cr
|ni|&number of words in the italic correction table;\cr
|nl|&number of words in the lig/kern table;\cr
|nk|&number of words in the kern table;\cr
|ne|&number of words in the extensible character table;\cr
|np|&number of font parameter words.\cr}}$$
They are all nonnegative and less than $2^{15}$. We must have |bc-1<=ec<=255|,
|ne<=256|, and
$$\hbox{|lf=6+lh+(ec-bc+1)+nw+nh+nd+ni+nl+nk+ne+np|.}$$
Note that a font may contain as many as 256 characters (if |bc=0| and |ec=255|),
and as few as 0 characters (if |bc=ec+1|).
Incidentally, when two or more 8-bit bytes are combined to form an integer of
16 or more bits, the most significant bytes appear first in the file.
This is called BigEndian order.
@^BigEndian order@>
@ The rest of the \.{TFM} file may be regarded as a sequence of ten data
arrays.
The most important data type used here is a |fix_word|, which is
a 32-bit representation of a binary fraction. A |fix_word| is a signed
quantity, with the two's complement of the entire word used to represent
negation. Of the 32 bits in a |fix_word|, exactly 12 are to the left of the
binary point; thus, the largest |fix_word| value is $2048-2^{-20}$, and
the smallest is $-2048$. We will see below, however, that all but two of
the |fix_word| values must lie between $-16$ and $+16$.
@ The first data array is a block of header information, which contains
general facts about the font. The header must contain at least two words,
|header[0]| and |header[1]|, whose meaning is explained below. Additional
header information of use to other software routines might also be
included, and \MP\ will generate it if the \.{headerbyte} command occurs.
For example, 16 more words of header information are in use at the Xerox
Palo Alto Research Center; the first ten specify the character coding
scheme used (e.g., `\.{XEROX TEXT}' or `\.{TEX MATHSY}'), the next five
give the font family name (e.g., `\.{HELVETICA}' or `\.{CMSY}'), and the
last gives the ``face byte.''
\yskip\hang|header[0]| is a 32-bit check sum that \MP\ will copy into
the \.{GF} output file. This helps ensure consistency between files,
since \TeX\ records the check sums from the \.{TFM}'s it reads, and these
should match the check sums on actual fonts that are used. The actual
relation between this check sum and the rest of the \.{TFM} file is not
important; the check sum is simply an identification number with the
property that incompatible fonts almost always have distinct check sums.
@^check sum@>
\yskip\hang|header[1]| is a |fix_word| containing the design size of the
font, in units of \TeX\ points. This number must be at least 1.0; it is
fairly arbitrary, but usually the design size is 10.0 for a ``10 point''
font, i.e., a font that was designed to look best at a 10-point size,
whatever that really means. When a \TeX\ user asks for a font `\.{at}
$\delta$ \.{pt}', the effect is to override the design size and replace it
by $\delta$, and to multiply the $x$ and~$y$ coordinates of the points in
the font image by a factor of $\delta$ divided by the design size. {\sl
All other dimensions in the\/ \.{TFM} file are |fix_word|\kern-1pt\
numbers in design-size units.} Thus, for example, the value of |param[6]|,
which defines the \.{em} unit, is often the |fix_word| value $2^{20}=1.0$,
since many fonts have a design size equal to one em. The other dimensions
must be less than 16 design-size units in absolute value; thus,
|header[1]| and |param[1]| are the only |fix_word| entries in the whole
\.{TFM} file whose first byte might be something besides 0 or 255.
@^design size@>
@ Next comes the |char_info| array, which contains one |char_info_word|
per character. Each word in this part of the file contains six fields
packed into four bytes as follows.
\yskip\hang first byte: |width_index| (8 bits)\par
\hang second byte: |height_index| (4 bits) times 16, plus |depth_index|
(4~bits)\par
\hang third byte: |italic_index| (6 bits) times 4, plus |tag|
(2~bits)\par
\hang fourth byte: |remainder| (8 bits)\par
\yskip\noindent
The actual width of a character is \\{width}|[width_index]|, in design-size
units; this is a device for compressing information, since many characters
have the same width. Since it is quite common for many characters
to have the same height, depth, or italic correction, the \.{TFM} format
imposes a limit of 16 different heights, 16 different depths, and
64 different italic corrections.
Incidentally, the relation $\\{width}[0]=\\{height}[0]=\\{depth}[0]=
\\{italic}[0]=0$ should always hold, so that an index of zero implies a
value of zero. The |width_index| should never be zero unless the
character does not exist in the font, since a character is valid if and
only if it lies between |bc| and |ec| and has a nonzero |width_index|.
@ The |tag| field in a |char_info_word| has four values that explain how to
interpret the |remainder| field.
\yskip\hang|tag=0| (|no_tag|) means that |remainder| is unused.\par
\hang|tag=1| (|lig_tag|) means that this character has a ligature/kerning
program starting at location |remainder| in the |lig_kern| array.\par
\hang|tag=2| (|list_tag|) means that this character is part of a chain of
characters of ascending sizes, and not the largest in the chain. The
|remainder| field gives the character code of the next larger character.\par
\hang|tag=3| (|ext_tag|) means that this character code represents an
extensible character, i.e., a character that is built up of smaller pieces
so that it can be made arbitrarily large. The pieces are specified in
|exten[remainder]|.\par
\yskip\noindent
Characters with |tag=2| and |tag=3| are treated as characters with |tag=0|
unless they are used in special circumstances in math formulas. For example,
\TeX's \.{\\sum} operation looks for a |list_tag|, and the \.{\\left}
operation looks for both |list_tag| and |ext_tag|.
@d no_tag 0 /* vanilla character */
@d lig_tag 1 /* character has a ligature/kerning program */
@d list_tag 2 /* character has a successor in a charlist */
@d ext_tag 3 /* character is extensible */
@ The |lig_kern| array contains instructions in a simple programming language
that explains what to do for special letter pairs. Each word in this array is a
|lig_kern_command| of four bytes.
\yskip\hang first byte: |skip_byte|, indicates that this is the final program
step if the byte is 128 or more, otherwise the next step is obtained by
skipping this number of intervening steps.\par
\hang second byte: |next_char|, ``if |next_char| follows the current character,
then perform the operation and stop, otherwise continue.''\par
\hang third byte: |op_byte|, indicates a ligature step if less than~128,
a kern step otherwise.\par
\hang fourth byte: |remainder|.\par
\yskip\noindent
In a kern step, an
additional space equal to |kern[256*(op_byte-128)+remainder]| is inserted
between the current character and |next_char|. This amount is
often negative, so that the characters are brought closer together
by kerning; but it might be positive.
There are eight kinds of ligature steps, having |op_byte| codes $4a+2b+c$ where
$0\le a\le b+c$ and $0\le b,c\le1$. The character whose code is
|remainder| is inserted between the current character and |next_char|;
then the current character is deleted if $b=0$, and |next_char| is
deleted if $c=0$; then we pass over $a$~characters to reach the next
current character (which may have a ligature/kerning program of its own).
If the very first instruction of the |lig_kern| array has |skip_byte=255|,
the |next_char| byte is the so-called right boundary character of this font;
the value of |next_char| need not lie between |bc| and~|ec|.
If the very last instruction of the |lig_kern| array has |skip_byte=255|,
there is a special ligature/kerning program for a left boundary character,
beginning at location |256*op_byte+remainder|.
The interpretation is that \TeX\ puts implicit boundary characters
before and after each consecutive string of characters from the same font.
These implicit characters do not appear in the output, but they can affect
ligatures and kerning.
If the very first instruction of a character's |lig_kern| program has
|skip_byte>128|, the program actually begins in location
|256*op_byte+remainder|. This feature allows access to large |lig_kern|
arrays, because the first instruction must otherwise
appear in a location |<=255|.
Any instruction with |skip_byte>128| in the |lig_kern| array must satisfy
the condition
$$\hbox{|256*op_byte+remainder<nl|.}$$
If such an instruction is encountered during
normal program execution, it denotes an unconditional halt; no ligature
command is performed.
@d stop_flag (128)
/* value indicating `\.{STOP}' in a lig/kern program */
@d kern_flag (128) /* op code for a kern step */
@d skip_byte(A) mp->lig_kern[(A)].b0
@d next_char(A) mp->lig_kern[(A)].b1
@d op_byte(A) mp->lig_kern[(A)].b2
@d rem_byte(A) mp->lig_kern[(A)].b3
@ Extensible characters are specified by an |extensible_recipe|, which
consists of four bytes called |top|, |mid|, |bot|, and |rep| (in this
order). These bytes are the character codes of individual pieces used to
build up a large symbol. If |top|, |mid|, or |bot| are zero, they are not
present in the built-up result. For example, an extensible vertical line is
like an extensible bracket, except that the top and bottom pieces are missing.
Let $T$, $M$, $B$, and $R$ denote the respective pieces, or an empty box
if the piece isn't present. Then the extensible characters have the form
$TR^kMR^kB$ from top to bottom, for some |k>=0|, unless $M$ is absent;
in the latter case we can have $TR^kB$ for both even and odd values of~|k|.
The width of the extensible character is the width of $R$; and the
height-plus-depth is the sum of the individual height-plus-depths of the
components used, since the pieces are butted together in a vertical list.
@d ext_top(A) mp->exten[(A)].b0 /* |top| piece in a recipe */
@d ext_mid(A) mp->exten[(A)].b1 /* |mid| piece in a recipe */
@d ext_bot(A) mp->exten[(A)].b2 /* |bot| piece in a recipe */
@d ext_rep(A) mp->exten[(A)].b3 /* |rep| piece in a recipe */
@ The final portion of a \.{TFM} file is the |param| array, which is another
sequence of |fix_word| values.
\yskip\hang|param[1]=slant| is the amount of italic slant, which is used
to help position accents. For example, |slant=.25| means that when you go
up one unit, you also go .25 units to the right. The |slant| is a pure
number; it is the only |fix_word| other than the design size itself that is
not scaled by the design size.
@^design size@>
\hang|param[2]=space| is the normal spacing between words in text.
Note that character 040 in the font need not have anything to do with
blank spaces.
\hang|param[3]=space_stretch| is the amount of glue stretching between words.
\hang|param[4]=space_shrink| is the amount of glue shrinking between words.
\hang|param[5]=x_height| is the size of one ex in the font; it is also
the height of letters for which accents don't have to be raised or lowered.
\hang|param[6]=quad| is the size of one em in the font.
\hang|param[7]=extra_space| is the amount added to |param[2]| at the
ends of sentences.
\yskip\noindent
If fewer than seven parameters are present, \TeX\ sets the missing parameters
to zero.
@d slant_code 1
@d space_code 2
@d space_stretch_code 3
@d space_shrink_code 4
@d x_height_code 5
@d quad_code 6
@d extra_space_code 7
@ So that is what \.{TFM} files hold. One of \MP's duties is to output such
information, and it does this all at once at the end of a job.
In order to prepare for such frenetic activity, it squirrels away the
necessary facts in various arrays as information becomes available.
Character dimensions (\&{charwd}, \&{charht}, \&{chardp}, and \&{charic})
are stored respectively in |tfm_width|, |tfm_height|, |tfm_depth|, and
|tfm_ital_corr|. Other information about a character (e.g., about
its ligatures or successors) is accessible via the |char_tag| and
|char_remainder| arrays. Other information about the font as a whole
is kept in additional arrays called |header_byte|, |lig_kern|,
|kern|, |exten|, and |param|.
@d max_tfm_int 32510
@d undefined_label max_tfm_int /* an undefined local label */
@<Glob...@>=
#define TFM_ITEMS 257
eight_bits bc;
eight_bits ec; /* smallest and largest character codes shipped out */
mp_node tfm_width[TFM_ITEMS]; /* \&{charwd} values */
mp_node tfm_height[TFM_ITEMS]; /* \&{charht} values */
mp_node tfm_depth[TFM_ITEMS]; /* \&{chardp} values */
mp_node tfm_ital_corr[TFM_ITEMS]; /* \&{charic} values */
boolean char_exists[TFM_ITEMS]; /* has this code been shipped out? */
int char_tag[TFM_ITEMS]; /* |remainder| category */
int char_remainder[TFM_ITEMS]; /* the |remainder| byte */
char *header_byte; /* bytes of the \.{TFM} header */
int header_last; /* last initialized \.{TFM} header byte */
int header_size; /* size of the \.{TFM} header */
four_quarters *lig_kern; /* the ligature/kern table */
short nl; /* the number of ligature/kern steps so far */
mp_number *kern; /* distinct kerning amounts */
short nk; /* the number of distinct kerns so far */
four_quarters exten[TFM_ITEMS]; /* extensible character recipes */
short ne; /* the number of extensible characters so far */
mp_number *param; /* \&{fontinfo} parameters */
short np; /* the largest \&{fontinfo} parameter specified so far */
short nw;
short nh;
short nd;
short ni; /* sizes of \.{TFM} subtables */
short skip_table[TFM_ITEMS]; /* local label status */
boolean lk_started; /* has there been a lig/kern step in this command yet? */
integer bchar; /* right boundary character */
short bch_label; /* left boundary starting location */
short ll;
short lll; /* registers used for lig/kern processing */
short label_loc[257]; /* lig/kern starting addresses */
eight_bits label_char[257]; /* characters for |label_loc| */
short label_ptr; /* highest position occupied in |label_loc| */
@ @<Allocate or initialize ...@>=
mp->header_last = 7;
mp->header_size = 128; /* just for init */
mp->header_byte = xmalloc (mp->header_size, sizeof (char));
@ @<Dealloc variables@>=
xfree (mp->header_byte);
xfree (mp->lig_kern);
if (mp->kern) {
int i;
for (i=0;i<(max_tfm_int + 1);i++) {
free_number(mp->kern[i]);
}
xfree (mp->kern);
}
if (mp->param) {
int i;
for (i=0;i<(max_tfm_int + 1);i++) {
free_number(mp->param[i]);
}
xfree (mp->param);
}
@ @<Set init...@>=
for (k = 0; k <= 255; k++) {
mp->tfm_width[k] = 0;
mp->tfm_height[k] = 0;
mp->tfm_depth[k] = 0;
mp->tfm_ital_corr[k] = 0;
mp->char_exists[k] = false;
mp->char_tag[k] = no_tag;
mp->char_remainder[k] = 0;
mp->skip_table[k] = undefined_label;
}
memset (mp->header_byte, 0, (size_t) mp->header_size);
mp->bc = 255;
mp->ec = 0;
mp->nl = 0;
mp->nk = 0;
mp->ne = 0;
mp->np = 0;
set_internal_from_number (mp_boundary_char, unity_t);
number_negate (internal_value (mp_boundary_char));
mp->bch_label = undefined_label;
mp->label_loc[0] = -1;
mp->label_ptr = 0;
@ @<Declarations@>=
static mp_node mp_tfm_check (MP mp, quarterword m);
@ @c
static mp_node mp_tfm_check (MP mp, quarterword m) {
mp_number absm;
mp_node p = mp_get_value_node (mp);
new_number (absm);
number_clone (absm, internal_value (m));
number_abs (absm);
if (number_greaterequal (absm, fraction_half_t)) {
char msg[256];
const char *hlp[] = {
"Font metric dimensions must be less than 2048pt.",
NULL } ;
mp_snprintf (msg, 256, "Enormous %s has been reduced", internal_name (m));
@.Enormous charwd...@>
@.Enormous chardp...@>
@.Enormous charht...@>
@.Enormous charic...@>
@.Enormous designsize...@>;
mp_back_error (mp, msg, hlp, true);
mp_get_x_next (mp);
if (number_positive (internal_value (m))) {
set_value_number (p, fraction_half_t);
number_add_scaled (value_number (p), -1);
} else {
set_value_number (p, fraction_half_t);
number_negate (value_number (p));
number_add_scaled (value_number (p), 1);
}
} else {
set_value_number (p, internal_value (m));
}
free_number (absm);
return p;
}
@ @<Store the width information for character code~|c|@>=
if (c < mp->bc)
mp->bc = (eight_bits) c;
if (c > mp->ec)
mp->ec = (eight_bits) c;
mp->char_exists[c] = true;
mp_free_value_node (mp, mp->tfm_width[c]);
mp->tfm_width[c] = mp_tfm_check (mp, mp_char_wd);
mp_free_value_node (mp, mp->tfm_height[c]);
mp->tfm_height[c] = mp_tfm_check (mp, mp_char_ht);
mp_free_value_node (mp, mp->tfm_depth[c]);
mp->tfm_depth[c] = mp_tfm_check (mp, mp_char_dp);
mp_free_value_node (mp, mp->tfm_ital_corr[c]);
mp->tfm_ital_corr[c] = mp_tfm_check (mp, mp_char_ic)
@ Now let's consider \MP's special \.{TFM}-oriented commands.
@ @d char_list_code 0
@d lig_table_code 1
@d extensible_code 2
@d header_byte_code 3
@d font_dimen_code 4
@<Put each...@>=
mp_primitive (mp, "charlist", mp_tfm_command, char_list_code);
@:char_list_}{\&{charlist} primitive@>;
mp_primitive (mp, "ligtable", mp_tfm_command, lig_table_code);
@:lig_table_}{\&{ligtable} primitive@>;
mp_primitive (mp, "extensible", mp_tfm_command, extensible_code);
@:extensible_}{\&{extensible} primitive@>;
mp_primitive (mp, "headerbyte", mp_tfm_command, header_byte_code);
@:header_byte_}{\&{headerbyte} primitive@>;
mp_primitive (mp, "fontdimen", mp_tfm_command, font_dimen_code);
@:font_dimen_}{\&{fontdimen} primitive@>
@ @<Cases of |print_cmd...@>=
case mp_tfm_command:
switch (m) {
case char_list_code:
mp_print (mp, "charlist");
break;
case lig_table_code:
mp_print (mp, "ligtable");
break;
case extensible_code:
mp_print (mp, "extensible");
break;
case header_byte_code:
mp_print (mp, "headerbyte");
break;
default:
mp_print (mp, "fontdimen");
break;
}
break;
@ @<Declare action procedures for use by |do_statement|@>=
static eight_bits mp_get_code (MP mp);
@ @c
eight_bits mp_get_code (MP mp) { /* scans a character code value */
integer c; /* the code value found */
mp_value new_expr;
const char *hlp[] = {
"I was looking for a number between 0 and 255, or for a",
"string of length 1. Didn't find it; will use 0 instead.",
NULL };
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
mp_get_x_next (mp);
mp_scan_expression (mp);
if (mp->cur_exp.type == mp_known) {
c = round_unscaled (cur_exp_value_number ());
if (c >= 0)
if (c < 256)
return (eight_bits) c;
} else if (mp->cur_exp.type == mp_string_type) {
if (cur_exp_str ()->len == 1) {
c = (integer) (*(cur_exp_str ()->str));
return (eight_bits) c;
}
}
mp_disp_err(mp, NULL);
set_number_to_zero (new_expr.data.n);
mp_back_error (mp, "Invalid code has been replaced by 0", hlp, true);
@.Invalid code...@>;
mp_get_x_next (mp);
mp_flush_cur_exp (mp, new_expr);
c = 0;
return (eight_bits) c;
}
@ @<Declare action procedures for use by |do_statement|@>=
static void mp_set_tag (MP mp, halfword c, quarterword t, halfword r);
@ @c
void mp_set_tag (MP mp, halfword c, quarterword t, halfword r) {
if (mp->char_tag[c] == no_tag) {
mp->char_tag[c] = t;
mp->char_remainder[c] = r;
if (t == lig_tag) {
mp->label_ptr++;
mp->label_loc[mp->label_ptr] = (short) r;
mp->label_char[mp->label_ptr] = (eight_bits) c;
}
} else {
@<Complain about a character tag conflict@>;
}
}
@ @<Complain about a character tag conflict@>=
{
const char *xtra = NULL;
char msg[256];
const char *hlp[] = {
"It's not legal to label a character more than once.",
"So I'll not change anything just now.",
NULL };
switch (mp->char_tag[c]) {
case lig_tag: xtra = "in a ligtable"; break;
case list_tag: xtra = "in a charlist"; break;
case ext_tag: xtra = "extensible"; break;
default: xtra = ""; break;
}
if ((c > ' ') && (c < 127)) {
mp_snprintf(msg, 256, "Character %c is already %s", xord(c), xtra);
} else if (c == 256) {
mp_snprintf(msg, 256, "Character || is already %s", xtra);
} else {
mp_snprintf(msg, 256, "Character code %d is already %s", c, xtra);
}
@.Character c is already...@>;
mp_back_error (mp, msg, hlp, true);
mp_get_x_next (mp);
}
@ @<Declare action procedures for use by |do_statement|@>=
static void mp_do_tfm_command (MP mp);
@ @c
void mp_do_tfm_command (MP mp) {
int c, cc; /* character codes */
int k; /* index into the |kern| array */
int j; /* index into |header_byte| or |param| */
mp_value new_expr;
memset(&new_expr,0,sizeof(mp_value));
new_number(new_expr.data.n);
switch (cur_mod()) {
case char_list_code:
c = mp_get_code (mp);
/* we will store a list of character successors */
while (cur_cmd() == mp_colon) {
cc = mp_get_code (mp);
mp_set_tag (mp, c, list_tag, cc);
c = cc;
};
break;
case lig_table_code:
if (mp->lig_kern == NULL)
mp->lig_kern = xmalloc ((max_tfm_int + 1), sizeof (four_quarters));
if (mp->kern == NULL) {
int i;
mp->kern = xmalloc ((max_tfm_int + 1), sizeof (mp_number));
for (i=0;i<(max_tfm_int + 1);i++)
new_number (mp->kern[i]);
}
@<Store a list of ligature/kern steps@>;
break;
case extensible_code:
@<Define an extensible recipe@>;
break;
case header_byte_code:
case font_dimen_code:
c = cur_mod();
mp_get_x_next (mp);
mp_scan_expression (mp);
if ((mp->cur_exp.type != mp_known) || number_less(cur_exp_value_number (), half_unit_t)) {
const char *hlp[] = {
"I was looking for a known, positive number.",
"For safety's sake I'll ignore the present command.",
NULL };
mp_disp_err(mp, NULL);
mp_back_error (mp, "Improper location", hlp, true);
@.Improper location@>;
mp_get_x_next (mp);
} else {
j = round_unscaled (cur_exp_value_number ());
if (cur_cmd() != mp_colon) {
const char *hlp[] = {
"A colon should follow a headerbyte or fontinfo location.",
NULL };
mp_back_error (mp, "Missing `:' has been inserted", hlp, true);
@.Missing `:'@>;
}
if (c == header_byte_code) {
@<Store a list of header bytes@>;
} else {
if (mp->param == NULL) {
int i;
mp->param = xmalloc ((max_tfm_int + 1), sizeof (mp_number));
for (i=0;i<(max_tfm_int + 1);i++)
new_number (mp->param[i]);
}
@<Store a list of font dimensions@>;
}
}
break;
} /* there are no other cases */
}
@ @<Store a list of ligature/kern steps@>=
{
mp->lk_started = false;
CONTINUE:
mp_get_x_next (mp);
if ((cur_cmd() == mp_skip_to) && mp->lk_started)
@<Process a |skip_to| command and |goto done|@>;
if (cur_cmd() == mp_bchar_label) {
c = 256;
set_cur_cmd((mp_variable_type)mp_colon);
} else {
mp_back_input (mp);
c = mp_get_code (mp);
};
if ((cur_cmd() == mp_colon) || (cur_cmd() == mp_double_colon)) {
@<Record a label in a lig/kern subprogram and |goto continue|@>;
}
if (cur_cmd() == mp_lig_kern_token) {
@<Compile a ligature/kern command@>;
} else {
const char *hlp[] = { "I was looking for `=:' or `kern' here.", NULL };
mp_back_error (mp, "Illegal ligtable step", hlp, true);
@.Illegal ligtable step@>;
next_char (mp->nl) = qi (0);
op_byte (mp->nl) = qi (0);
rem_byte (mp->nl) = qi (0);
skip_byte (mp->nl) = stop_flag + 1; /* this specifies an unconditional stop */
}
if (mp->nl == max_tfm_int)
mp_fatal_error (mp, "ligtable too large");
mp->nl++;
if (cur_cmd() == mp_comma)
goto CONTINUE;
if (skip_byte (mp->nl - 1) < stop_flag)
skip_byte (mp->nl - 1) = stop_flag;
}
DONE:
@ @<Put each...@>=
mp_primitive (mp, "=:", mp_lig_kern_token, 0);
@:=:_}{\.{=:} primitive@>;
mp_primitive (mp, "=:|", mp_lig_kern_token, 1);
@:=:/_}{\.{=:\char'174} primitive@>;
mp_primitive (mp, "=:|>", mp_lig_kern_token, 5);
@:=:/>_}{\.{=:\char'174>} primitive@>;
mp_primitive (mp, "|=:", mp_lig_kern_token, 2);
@:=:/_}{\.{\char'174=:} primitive@>;
mp_primitive (mp, "|=:>", mp_lig_kern_token, 6);
@:=:/>_}{\.{\char'174=:>} primitive@>;
mp_primitive (mp, "|=:|", mp_lig_kern_token, 3);
@:=:/_}{\.{\char'174=:\char'174} primitive@>;
mp_primitive (mp, "|=:|>", mp_lig_kern_token, 7);
@:=:/>_}{\.{\char'174=:\char'174>} primitive@>;
mp_primitive (mp, "|=:|>>", mp_lig_kern_token, 11);
@:=:/>_}{\.{\char'174=:\char'174>>} primitive@>;
mp_primitive (mp, "kern", mp_lig_kern_token, mp_kern_flag);
@:kern_}{\&{kern} primitive@>
@ @<Cases of |print_cmd...@>=
case mp_lig_kern_token:
switch (m) {
case 0:
mp_print (mp, "=:");
break;
case 1:
mp_print (mp, "=:|");
break;
case 2:
mp_print (mp, "|=:");
break;
case 3:
mp_print (mp, "|=:|");
break;
case 5:
mp_print (mp, "=:|>");
break;
case 6:
mp_print (mp, "|=:>");
break;
case 7:
mp_print (mp, "|=:|>");
break;
case 11:
mp_print (mp, "|=:|>>");
break;
default:
mp_print (mp, "kern");
break;
}
break;
@ Local labels are implemented by maintaining the |skip_table| array,
where |skip_table[c]| is either |undefined_label| or the address of the
most recent lig/kern instruction that skips to local label~|c|. In the
latter case, the |skip_byte| in that instruction will (temporarily)
be zero if there were no prior skips to this label, or it will be the
distance to the prior skip.
We may need to cancel skips that span more than 127 lig/kern steps.
@d cancel_skips(A) mp->ll=(A);
do {
mp->lll=qo(skip_byte(mp->ll));
skip_byte(mp->ll)=stop_flag; mp->ll=(short)(mp->ll-mp->lll);
} while (mp->lll!=0)
@d skip_error(A) {
const char *hlp[] = { "At most 127 lig/kern steps can separate skipto1 from 1::.", NULL};
mp_error(mp, "Too far to skip", hlp, true);
@.Too far to skip@>
cancel_skips((A));
}
@<Process a |skip_to| command and |goto done|@>=
{
c = mp_get_code (mp);
if (mp->nl - mp->skip_table[c] > 128) {
skip_error (mp->skip_table[c]);
mp->skip_table[c] = (short) undefined_label;
}
if (mp->skip_table[c] == undefined_label)
skip_byte (mp->nl - 1) = qi (0);
else
skip_byte (mp->nl - 1) = qi (mp->nl - mp->skip_table[c] - 1);
mp->skip_table[c] = (short) (mp->nl - 1);
goto DONE;
}
@ @<Record a label in a lig/kern subprogram and |goto continue|@>=
{
if (cur_cmd() == mp_colon) {
if (c == 256)
mp->bch_label = mp->nl;
else
mp_set_tag (mp, c, lig_tag, mp->nl);
} else if (mp->skip_table[c] < undefined_label) {
mp->ll = mp->skip_table[c];
mp->skip_table[c] = undefined_label;
do {
mp->lll = qo (skip_byte (mp->ll));
if (mp->nl - mp->ll > 128) {
skip_error (mp->ll);
goto CONTINUE;
}
skip_byte (mp->ll) = qi (mp->nl - mp->ll - 1);
mp->ll = (short) (mp->ll - mp->lll);
} while (mp->lll != 0);
}
goto CONTINUE;
}
@ @<Compile a ligature/kern...@>=
{
next_char (mp->nl) = qi (c);
skip_byte (mp->nl) = qi (0);
if (cur_mod() < 128) { /* ligature op */
op_byte (mp->nl) = qi (cur_mod());
rem_byte (mp->nl) = qi (mp_get_code (mp));
} else {
mp_get_x_next (mp);
mp_scan_expression (mp);
if (mp->cur_exp.type != mp_known) {
const char *hlp[] = {
"The amount of kern should be a known numeric value.",
"I'm zeroing this one. Proceed, with fingers crossed.",
NULL };
mp_disp_err(mp, NULL);
set_number_to_zero (new_expr.data.n);
mp_back_error (mp, "Improper kern", hlp, true);
@.Improper kern@>;
mp_get_x_next (mp);
mp_flush_cur_exp (mp, new_expr);
}
number_clone (mp->kern[mp->nk], cur_exp_value_number ());
k = 0;
while (!number_equal (mp->kern[k], cur_exp_value_number ()))
incr (k);
if (k == mp->nk) {
if (mp->nk == max_tfm_int)
mp_fatal_error (mp, "too many TFM kerns");
mp->nk++;
}
op_byte (mp->nl) = qi (kern_flag + (k / 256));
rem_byte (mp->nl) = qi ((k % 256));
}
mp->lk_started = true;
}
@ @d missing_extensible_punctuation(A)
{
char msg[256];
const char *hlp[] = { "I'm processing `extensible c: t,m,b,r'.", NULL };
mp_snprintf(msg, 256, "Missing %s has been inserted", (A));
mp_back_error(mp, msg, hlp, true);
@.Missing `\char`\#'@>
}
@<Define an extensible recipe@>=
{
if (mp->ne == 256)
mp_fatal_error (mp, "too many extensible recipies");
c = mp_get_code (mp);
mp_set_tag (mp, c, ext_tag, mp->ne);
if (cur_cmd() != mp_colon)
missing_extensible_punctuation (":");
ext_top (mp->ne) = qi (mp_get_code (mp));
if (cur_cmd() != mp_comma)
missing_extensible_punctuation (",");
ext_mid (mp->ne) = qi (mp_get_code (mp));
if (cur_cmd() != mp_comma)
missing_extensible_punctuation (",");
ext_bot (mp->ne) = qi (mp_get_code (mp));
if (cur_cmd() != mp_comma)
missing_extensible_punctuation (",");
ext_rep (mp->ne) = qi (mp_get_code (mp));
mp->ne++;
}
@ The header could contain ASCII zeroes, so can't use |strdup|.
@<Store a list of header bytes@>=
j--;
do {
if (j >= mp->header_size) {
size_t l = (size_t) (mp->header_size + (mp->header_size / 4));
char *t = xmalloc (l, 1);
memset (t, 0, l);
(void) memcpy (t, mp->header_byte, (size_t) mp->header_size);
xfree (mp->header_byte);
mp->header_byte = t;
mp->header_size = (int) l;
}
mp->header_byte[j] = (char) mp_get_code (mp);
incr (j);
incr (mp->header_last);
} while (cur_cmd() == mp_comma)
@ @<Store a list of font dimensions@>=
do {
if (j > max_tfm_int)
mp_fatal_error (mp, "too many fontdimens");
while (j > mp->np) {
mp->np++;
set_number_to_zero(mp->param[mp->np]);
};
mp_get_x_next (mp);
mp_scan_expression (mp);
if (mp->cur_exp.type != mp_known) {
const char *hlp[] = { "I'm zeroing this one. Proceed, with fingers crossed.", NULL };
mp_disp_err(mp, NULL);
set_number_to_zero (new_expr.data.n);
mp_back_error (mp, "Improper font parameter", hlp, true);
@.Improper font parameter@>;
mp_get_x_next (mp);
mp_flush_cur_exp (mp, new_expr);
}
number_clone (mp->param[j], cur_exp_value_number ());
incr (j);
} while (cur_cmd() == mp_comma)
@ OK: We've stored all the data that is needed for the \.{TFM} file.
All that remains is to output it in the correct format.
An interesting problem needs to be solved in this connection, because
the \.{TFM} format allows at most 256~widths, 16~heights, 16~depths,
and 64~italic corrections. If the data has more distinct values than
this, we want to meet the necessary restrictions by perturbing the
given values as little as possible.
\MP\ solves this problem in two steps. First the values of a given
kind (widths, heights, depths, or italic corrections) are sorted;
then the list of sorted values is perturbed, if necessary.
The sorting operation is facilitated by having a special node of
essentially infinite |value| at the end of the current list.
@<Initialize table entries@>=
mp->inf_val = mp_get_value_node (mp);
set_value_number (mp->inf_val, fraction_four_t);
@ @<Free table entries@>=
mp_free_value_node (mp, mp->inf_val);
@ Straight linear insertion is good enough for sorting, since the lists
are usually not terribly long. As we work on the data, the current list
will start at |mp_link(temp_head)| and end at |inf_val|; the nodes in this
list will be in increasing order of their |value| fields.
Given such a list, the |sort_in| function takes a value and returns a pointer
to where that value can be found in the list. The value is inserted in
the proper place, if necessary.
At the time we need to do these operations, most of \MP's work has been
completed, so we will have plenty of memory to play with. The value nodes
that are allocated for sorting will never be returned to free storage.
@d clear_the_list mp_link(mp->temp_head)=mp->inf_val
@c
static mp_node mp_sort_in (MP mp, mp_number v) {
mp_node p, q, r; /* list manipulation registers */
p = mp->temp_head;
while (1) {
q = mp_link (p);
if (number_lessequal(v, value_number (q)))
break;
p = q;
}
if (number_less (v, value_number (q))) {
r = mp_get_value_node (mp);
set_value_number (r, v);
mp_link (r) = q;
mp_link (p) = r;
}
return mp_link (p);
}
@ Now we come to the interesting part, where we reduce the list if necessary
until it has the required size. The |min_cover| routine is basic to this
process; it computes the minimum number~|m| such that the values of the
current sorted list can be covered by |m|~intervals of width~|d|. It
also sets the global value |perturbation| to the smallest value $d'>d$
such that the covering found by this algorithm would be different.
In particular, |min_cover(0)| returns the number of distinct values in the
current list and sets |perturbation| to the minimum distance between
adjacent values.
@c
static integer mp_min_cover (MP mp, mp_number d) {
mp_node p; /* runs through the current list */
mp_number l; /* the least element covered by the current interval */
mp_number test;
integer m; /* lower bound on the size of the minimum cover */
m = 0;
new_number (l);
new_number (test);
p = mp_link (mp->temp_head);
set_number_to_inf(mp->perturbation);
while (p != mp->inf_val) {
incr (m);
number_clone (l, value_number (p));
do {
p = mp_link (p);
set_number_from_addition(test, l, d);
} while (number_lessequal(value_number (p), test));
set_number_from_substraction(test, value_number (p), l);
if (number_less (test, mp->perturbation)) {
number_clone (mp->perturbation, test);
}
}
free_number (test);
free_number (l);
return m;
}
@ @<Glob...@>=
mp_number perturbation; /* quantity related to \.{TFM} rounding */
integer excess; /* the list is this much too long */
@ @<Initialize table...@>=
new_number (mp->perturbation);
@ @<Dealloc...@>=
free_number (mp->perturbation);
@ The smallest |d| such that a given list can be covered with |m| intervals
is determined by the |threshold| routine, which is sort of an inverse
to |min_cover|. The idea is to increase the interval size rapidly until
finding the range, then to go sequentially until the exact borderline has
been discovered.
@c
static void mp_threshold (MP mp, mp_number *ret, integer m) {
mp_number d, arg1; /* lower bound on the smallest interval size */
new_number (d);
new_number (arg1);
mp->excess = mp_min_cover (mp, zero_t) - m;
if (mp->excess <= 0) {
number_clone (*ret, zero_t);
} else {
do {
number_clone (d, mp->perturbation);
set_number_from_addition(arg1, d, d);
} while (mp_min_cover (mp, arg1) > m);
while (mp_min_cover (mp, d) > m) {
number_clone (d, mp->perturbation);
}
number_clone (*ret, d);
}
free_number (d);
free_number (arg1);
}
@ The |skimp| procedure reduces the current list to at most |m| entries,
by changing values if necessary. It also sets |indep_value(p):=k| if |value(p)|
is the |k|th distinct value on the resulting list, and it sets
|perturbation| to the maximum amount by which a |value| field has
been changed. The size of the resulting list is returned as the
value of |skimp|.
@c
static integer mp_skimp (MP mp, integer m) {
mp_number d; /* the size of intervals being coalesced */
mp_node p, q, r; /* list manipulation registers */
mp_number l; /* the least value in the current interval */
mp_number v; /* a compromise value */
mp_number l_d;
new_number (d);
mp_threshold (mp, &d, m);
new_number (l);
new_number (l_d);
new_number (v);
set_number_to_zero (mp->perturbation);
q = mp->temp_head;
m = 0;
p = mp_link (mp->temp_head);
while (p != mp->inf_val) {
incr (m);
number_clone (l, value_number (p));
set_indep_value (p,m);
set_number_from_addition (l_d, l, d);
if (number_lessequal (value_number (mp_link (p)), l_d)) {
@<Replace an interval of values by its midpoint@>;
}
q = p;
p = mp_link (p);
}
free_number (l_d);
free_number (d);
free_number (l);
free_number (v);
return m;
}
@ @<Replace an interval...@>=
{
mp_number test;
new_number (test);
do {
p = mp_link (p);
set_indep_value (p, m);
decr (mp->excess);
if (mp->excess == 0) {
number_clone (l_d, l);
set_number_to_zero (d);
}
} while (number_lessequal(value_number (mp_link (p)), l_d));
set_number_from_substraction (test, value_number (p), l);
number_halfp(test);
set_number_from_addition (v, l, test);
set_number_from_substraction (test, value_number (p), v);
if (number_greater (test, mp->perturbation))
number_clone (mp->perturbation, test);
r = q;
do {
r = mp_link (r);
set_value_number (r, v);
} while (r != p);
mp_link (q) = p; /* remove duplicate values from the current list */
free_number (test);
}
@ A warning message is issued whenever something is perturbed by
more than 1/16\thinspace pt.
@c
static void mp_tfm_warning (MP mp, quarterword m) {
mp_print_nl (mp, "(some ");
mp_print (mp, internal_name (m));
@.some charwds...@>
@.some chardps...@>
@.some charhts...@>
@.some charics...@>;
mp_print (mp, " values had to be adjusted by as much as ");
print_number (mp->perturbation);
mp_print (mp, "pt)");
}
@ Here's an example of how we use these routines.
The width data needs to be perturbed only if there are 256 distinct
widths, but \MP\ must check for this case even though it is
highly unusual.
An integer variable |k| will be defined when we use this code.
The |dimen_head| array will contain pointers to the sorted
lists of dimensions.
@d tfm_warn_threshold_k ((math_data *)mp->math)->tfm_warn_threshold_t
@<Massage the \.{TFM} widths@>=
clear_the_list;
for (k = mp->bc; k <= mp->ec; k++) {
if (mp->char_exists[k])
mp->tfm_width[k] = mp_sort_in (mp, value_number (mp->tfm_width[k]));
}
mp->nw = (short) (mp_skimp (mp, 255) + 1);
mp->dimen_head[1] = mp_link (mp->temp_head);
if (number_greaterequal (mp->perturbation, tfm_warn_threshold_k))
mp_tfm_warning (mp, mp_char_wd)
@ @<Glob...@>=
mp_node dimen_head[5]; /* lists of \.{TFM} dimensions */
@ Heights, depths, and italic corrections are different from widths
not only because their list length is more severely restricted, but
also because zero values do not need to be put into the lists.
@<Massage the \.{TFM} heights, depths, and italic corrections@>=
clear_the_list;
for (k = mp->bc; k <= mp->ec; k++) {
if (mp->char_exists[k]) {
if (number_zero(value_number (mp->tfm_height[k])))
mp->tfm_height[k] = mp->zero_val;
else
mp->tfm_height[k] = mp_sort_in (mp, value_number (mp->tfm_height[k]));
}
}
mp->nh = (short) (mp_skimp (mp, 15) + 1);
mp->dimen_head[2] = mp_link (mp->temp_head);
if (number_greaterequal (mp->perturbation, tfm_warn_threshold_k))
mp_tfm_warning (mp, mp_char_ht);
clear_the_list;
for (k = mp->bc; k <= mp->ec; k++) {
if (mp->char_exists[k]) {
if (number_zero(value_number (mp->tfm_depth[k])))
mp->tfm_depth[k] = mp->zero_val;
else
mp->tfm_depth[k] = mp_sort_in (mp, value_number (mp->tfm_depth[k]));
}
}
mp->nd = (short) (mp_skimp (mp, 15) + 1);
mp->dimen_head[3] = mp_link (mp->temp_head);
if (number_greaterequal (mp->perturbation, tfm_warn_threshold_k))
mp_tfm_warning (mp, mp_char_dp);
clear_the_list;
for (k = mp->bc; k <= mp->ec; k++) {
if (mp->char_exists[k]) {
if (number_zero(value_number (mp->tfm_ital_corr[k])))
mp->tfm_ital_corr[k] = mp->zero_val;
else
mp->tfm_ital_corr[k] = mp_sort_in (mp, value_number (mp->tfm_ital_corr[k]));
}
}
mp->ni = (short) (mp_skimp (mp, 63) + 1);
mp->dimen_head[4] = mp_link (mp->temp_head);
if (number_greaterequal (mp->perturbation, tfm_warn_threshold_k))
mp_tfm_warning (mp, mp_char_ic)
@ @<Initialize table entries@>=
mp->zero_val = mp_get_value_node (mp);
set_value_number (mp->zero_val, zero_t);
@ @<Free table entries@>=
mp_free_value_node (mp, mp->zero_val);
@ Bytes 5--8 of the header are set to the design size, unless the user has
some crazy reason for specifying them differently.
@^design size@>
Error messages are not allowed at the time this procedure is called,
so a warning is printed instead.
The value of |max_tfm_dimen| is calculated so that
$$\hbox{|make_scaled(16*max_tfm_dimen,internal_value(mp_design_size))|}
< \\{three\_bytes}.$$
@d three_bytes 0100000000 /* $2^{24}$ */
@c
static void mp_fix_design_size (MP mp) {
mp_number d; /* the design size */
new_number (d);
number_clone (d, internal_value (mp_design_size));
if (number_less(d, unity_t) || number_greaterequal(d, fraction_half_t)) {
if (!number_zero (d))
mp_print_nl (mp, "(illegal design size has been changed to 128pt)");
@.illegal design size...@>;
set_number_from_scaled (d, 040000000);
number_clone (internal_value (mp_design_size), d);
}
if (mp->header_byte[4] == 0 && mp->header_byte[5] == 0 &&
mp->header_byte[6] == 0 && mp->header_byte[7] == 0) {
integer dd = number_to_scaled (d);
mp->header_byte[4] = (char) (dd / 04000000);
mp->header_byte[5] = (char) ((dd / 4096) % 256);
mp->header_byte[6] = (char) ((dd / 16) % 256);
mp->header_byte[7] = (char) ((dd % 16) * 16);
}
/* |mp->max_tfm_dimen = 16 * internal_value (mp_design_size) - 1 - internal_value (mp_design_size) / 010000000| */
{
mp_number secondpart;
new_number (secondpart);
number_clone (secondpart, internal_value (mp_design_size));
number_clone (mp->max_tfm_dimen, secondpart);
number_divide_int (secondpart, 010000000);
number_multiply_int (mp->max_tfm_dimen, 16);
number_add_scaled (mp->max_tfm_dimen, -1);
number_substract (mp->max_tfm_dimen, secondpart);
free_number (secondpart);
}
if (number_greaterequal (mp->max_tfm_dimen, fraction_half_t)) {
number_clone (mp->max_tfm_dimen, fraction_half_t);
number_add_scaled (mp->max_tfm_dimen, -1);
}
free_number (d);
}
@ The |dimen_out| procedure computes a |fix_word| relative to the
design size. If the data was out of range, it is corrected and the
global variable |tfm_changed| is increased by~one.
@c
static integer mp_dimen_out (MP mp, mp_number x_orig) {
integer ret;
mp_number abs_x;
mp_number x;
new_number (abs_x);
new_number (x);
number_clone (x, x_orig);
number_clone (abs_x, x_orig);
number_abs (abs_x);
if (number_greater (abs_x, mp->max_tfm_dimen)) {
incr (mp->tfm_changed);
if (number_positive(x))
number_clone (x, mp->max_tfm_dimen);
else {
number_clone (x, mp->max_tfm_dimen);
number_negate (x);
}
}
{
mp_number arg1;
new_number (arg1);
number_clone (arg1, x);
number_multiply_int (arg1, 16);
make_scaled (x, arg1, internal_value (mp_design_size));
free_number (arg1);
}
free_number (abs_x);
ret = number_to_scaled (x);
free_number (x);
return ret;
}
@ @<Glob...@>=
mp_number max_tfm_dimen; /* bound on widths, heights, kerns, etc. */
integer tfm_changed; /* the number of data entries that were out of bounds */
@ @<Initialize table...@>=
new_number (mp->max_tfm_dimen);
@ @<Dealloc...@>=
free_number (mp->max_tfm_dimen);
@ If the user has not specified any of the first four header bytes,
the |fix_check_sum| procedure replaces them by a ``check sum'' computed
from the |tfm_width| data relative to the design size.
@^check sum@>
@c
static void mp_fix_check_sum (MP mp) {
eight_bits k; /* runs through character codes */
eight_bits B1, B2, B3, B4; /* bytes of the check sum */
integer x; /* hash value used in check sum computation */
if (mp->header_byte[0] == 0 && mp->header_byte[1] == 0 &&
mp->header_byte[2] == 0 && mp->header_byte[3] == 0) {
@<Compute a check sum in |(b1,b2,b3,b4)|@>;
mp->header_byte[0] = (char) B1;
mp->header_byte[1] = (char) B2;
mp->header_byte[2] = (char) B3;
mp->header_byte[3] = (char) B4;
return;
}
}
@ @<Compute a check sum in |(b1,b2,b3,b4)|@>=
B1 = mp->bc;
B2 = mp->ec;
B3 = mp->bc;
B4 = mp->ec;
mp->tfm_changed = 0;
for (k = mp->bc; k <= mp->ec; k++) {
if (mp->char_exists[k]) {
x = mp_dimen_out (mp, value_number (mp->tfm_width[k])) + (k + 4) * 020000000; /* this is positive */
B1 = (eight_bits) ((B1 + B1 + x) % 255);
B2 = (eight_bits) ((B2 + B2 + x) % 253);
B3 = (eight_bits) ((B3 + B3 + x) % 251);
B4 = (eight_bits) ((B4 + B4 + x) % 247);
}
if (k == mp->ec)
break;
}
@ Finally we're ready to actually write the \.{TFM} information.
Here are some utility routines for this purpose.
@d tfm_out(A) do { /* output one byte to |tfm_file| */
unsigned char s=(unsigned char)(A);
(mp->write_binary_file)(mp,mp->tfm_file,(void *)&s,1);
} while (0)
@c
static void mp_tfm_two (MP mp, integer x) { /* output two bytes to |tfm_file| */
tfm_out (x / 256);
tfm_out (x % 256);
}
static void mp_tfm_four (MP mp, integer x) { /* output four bytes to |tfm_file| */
if (x >= 0)
tfm_out (x / three_bytes);
else {
x = x + 010000000000; /* use two's complement for negative values */
x = x + 010000000000;
tfm_out ((x / three_bytes) + 128);
};
x = x % three_bytes;
tfm_out (x / number_to_scaled (unity_t));
x = x % number_to_scaled (unity_t);
tfm_out (x / 0400);
tfm_out (x % 0400);
}
static void mp_tfm_qqqq (MP mp, four_quarters x) { /* output four quarterwords to |tfm_file| */
tfm_out (qo (x.b0));
tfm_out (qo (x.b1));
tfm_out (qo (x.b2));
tfm_out (qo (x.b3));
}
@ @<Finish the \.{TFM} file@>=
if (mp->job_name == NULL)
mp_open_log_file (mp);
mp_pack_job_name (mp, ".tfm");
while (!mp_open_out (mp, &mp->tfm_file, mp_filetype_metrics))
mp_prompt_file_name (mp, "file name for font metrics", ".tfm");
mp->metric_file_name = xstrdup (mp->name_of_file);
@<Output the subfile sizes and header bytes@>;
@<Output the character information bytes, then
output the dimensions themselves@>;
@<Output the ligature/kern program@>;
@<Output the extensible character recipes and the font metric parameters@>;
if (number_positive (internal_value (mp_tracing_stats)))
@<Log the subfile sizes of the \.{TFM} file@>;
mp_print_nl (mp, "Font metrics written on ");
mp_print (mp, mp->metric_file_name);
mp_print_char (mp, xord ('.'));
@.Font metrics written...@>;
(mp->close_file) (mp, mp->tfm_file)
@ Integer variables |lh|, |k|, and |lk_offset| will be defined when we use
this code.
@<Output the subfile sizes and header bytes@>=
k = mp->header_last;
LH = (k + 4) / 4; /* this is the number of header words */
if (mp->bc > mp->ec)
mp->bc = 1; /* if there are no characters, |ec=0| and |bc=1| */
@<Compute the ligature/kern program offset and implant the
left boundary label@>;
mp_tfm_two (mp,
6 + LH + (mp->ec - mp->bc + 1) + mp->nw + mp->nh + mp->nd + mp->ni +
mp->nl + lk_offset + mp->nk + mp->ne + mp->np);
/* this is the total number of file words that will be output */
mp_tfm_two (mp, LH);
mp_tfm_two (mp, mp->bc);
mp_tfm_two (mp, mp->ec);
mp_tfm_two (mp, mp->nw);
mp_tfm_two (mp, mp->nh);
mp_tfm_two (mp, mp->nd);
mp_tfm_two (mp, mp->ni);
mp_tfm_two (mp, mp->nl + lk_offset);
mp_tfm_two (mp, mp->nk);
mp_tfm_two (mp, mp->ne);
mp_tfm_two (mp, mp->np);
for (k = 0; k < 4 * LH; k++) {
tfm_out (mp->header_byte[k]);
}
@ @<Output the character information bytes...@>=
for (k = mp->bc; k <= mp->ec; k++) {
if (!mp->char_exists[k]) {
mp_tfm_four (mp, 0);
} else {
tfm_out (indep_value (mp->tfm_width[k])); /* the width index */
tfm_out ((indep_value (mp->tfm_height[k])) * 16 + indep_value (mp->tfm_depth[k]));
tfm_out ((indep_value (mp->tfm_ital_corr[k])) * 4 + mp->char_tag[k]);
tfm_out (mp->char_remainder[k]);
};
}
mp->tfm_changed = 0;
for (k = 1; k <= 4; k++) {
mp_tfm_four (mp, 0);
p = mp->dimen_head[k];
while (p != mp->inf_val) {
mp_tfm_four (mp, mp_dimen_out (mp, value_number (p)));
p = mp_link (p);
}
}
@ We need to output special instructions at the beginning of the
|lig_kern| array in order to specify the right boundary character
and/or to handle starting addresses that exceed 255. The |label_loc|
and |label_char| arrays have been set up to record all the
starting addresses; we have $-1=|label_loc|[0]<|label_loc|[1]\le\cdots
\le|label_loc|[|label_ptr]|$.
@<Compute the ligature/kern program offset...@>=
mp->bchar = round_unscaled (internal_value (mp_boundary_char));
if ((mp->bchar < 0) || (mp->bchar > 255)) {
mp->bchar = -1;
mp->lk_started = false;
lk_offset = 0;
} else {
mp->lk_started = true;
lk_offset = 1;
}
@<Find the minimum |lk_offset| and adjust all remainders@>;
if (mp->bch_label < undefined_label) {
skip_byte (mp->nl) = qi (255);
next_char (mp->nl) = qi (0);
op_byte (mp->nl) = qi (((mp->bch_label + lk_offset) / 256));
rem_byte (mp->nl) = qi (((mp->bch_label + lk_offset) % 256));
mp->nl++; /* possibly |nl=lig_table_size+1| */
}
@ @<Find the minimum |lk_offset|...@>=
k = mp->label_ptr; /* pointer to the largest unallocated label */
if (mp->label_loc[k] + lk_offset > 255) {
lk_offset = 0;
mp->lk_started = false; /* location 0 can do double duty */
do {
mp->char_remainder[mp->label_char[k]] = lk_offset;
while (mp->label_loc[k - 1] == mp->label_loc[k]) {
decr (k);
mp->char_remainder[mp->label_char[k]] = lk_offset;
}
incr (lk_offset);
decr (k);
} while (!(lk_offset + mp->label_loc[k] < 256));
/* N.B.: |lk_offset=256| satisfies this when |k=0| */
}
if (lk_offset > 0) {
while (k > 0) {
mp->char_remainder[mp->label_char[k]]
= mp->char_remainder[mp->label_char[k]] + lk_offset;
decr (k);
}
}
@ @<Output the ligature/kern program@>=
for (k = 0; k <= 255; k++) {
if (mp->skip_table[k] < undefined_label) {
mp_print_nl (mp, "(local label ");
mp_print_int (mp, k);
mp_print (mp, ":: was missing)");
@.local label l:: was missing@>;
cancel_skips (mp->skip_table[k]);
}
}
if (mp->lk_started) { /* |lk_offset=1| for the special |bchar| */
tfm_out (255);
tfm_out (mp->bchar);
mp_tfm_two (mp, 0);
} else {
for (k = 1; k <= lk_offset; k++) { /* output the redirection specs */
mp->ll = mp->label_loc[mp->label_ptr];
if (mp->bchar < 0) {
tfm_out (254);
tfm_out (0);
} else {
tfm_out (255);
tfm_out (mp->bchar);
};
mp_tfm_two (mp, mp->ll + lk_offset);
do {
mp->label_ptr--;
} while (!(mp->label_loc[mp->label_ptr] < mp->ll));
}
}
for (k = 0; k < mp->nl; k++)
mp_tfm_qqqq (mp, mp->lig_kern[k]);
{
mp_number arg;
new_number (arg);
for (k = 0; k < mp->nk; k++) {
number_clone (arg, mp->kern[k]);
mp_tfm_four (mp, mp_dimen_out (mp, arg));
}
free_number (arg);
}
@ @<Output the extensible character recipes...@>=
for (k = 0; k < mp->ne; k++)
mp_tfm_qqqq (mp, mp->exten[k]);
{
mp_number arg;
new_number (arg);
for (k = 1; k <= mp->np; k++) {
if (k == 1) {
number_clone (arg, mp->param[1]);
number_abs (arg);
if (number_less(arg, fraction_half_t)) {
mp_tfm_four (mp, number_to_scaled (mp->param[1]) * 16);
} else {
incr (mp->tfm_changed);
if (number_positive(mp->param[1]))
mp_tfm_four (mp, max_integer);
else
mp_tfm_four (mp, -max_integer);
}
} else {
number_clone (arg, mp->param[k]);
mp_tfm_four (mp, mp_dimen_out (mp, arg));
}
}
free_number (arg);
}
if (mp->tfm_changed > 0) {
if (mp->tfm_changed == 1) {
mp_print_nl (mp, "(a font metric dimension");
@.a font metric dimension...@>
} else {
mp_print_nl (mp, "(");
mp_print_int (mp, mp->tfm_changed);
@.font metric dimensions...@>;
mp_print (mp, " font metric dimensions");
}
mp_print (mp, " had to be decreased)");
}
@ @<Log the subfile sizes of the \.{TFM} file@>=
{
char s[200];
wlog_ln (" ");
if (mp->bch_label < undefined_label)
mp->nl--;
mp_snprintf (s, 128,
"(You used %iw,%ih,%id,%ii,%il,%ik,%ie,%ip metric file positions)",
mp->nw, mp->nh, mp->nd, mp->ni, mp->nl, mp->nk, mp->ne, mp->np);
wlog_ln (s);
}
@* Reading font metric data.
\MP\ isn't a typesetting program but it does need to find the bounding box
of a sequence of typeset characters. Thus it needs to read \.{TFM} files as
well as write them.
@<Glob...@>=
void *tfm_infile;
@ All the width, height, and depth information is stored in an array called
|font_info|. This array is allocated sequentially and each font is stored
as a series of |char_info| words followed by the width, height, and depth
tables. Since |font_name| entries are permanent, their |str_ref| values are
set to |MAX_STR_REF|.
@<Types...@>=
typedef unsigned int font_number; /* |0..font_max| */
@ The |font_info| array is indexed via a group directory arrays.
For example, the |char_info| data for character~|c| in font~|f| will be
in |font_info[char_base[f]+c].qqqq|.
@<Glob...@>=
font_number font_max; /* maximum font number for included text fonts */
size_t font_mem_size; /* number of words for \.{TFM} information for text fonts */
font_data *font_info; /* height, width, and depth data */
char **font_enc_name; /* encoding names, if any */
boolean *font_ps_name_fixed; /* are the postscript names fixed already? */
size_t next_fmem; /* next unused entry in |font_info| */
font_number last_fnum; /* last font number used so far */
integer *font_dsize; /* 16 times the ``design'' size in \ps\ points */
char **font_name; /* name as specified in the \&{infont} command */
char **font_ps_name; /* PostScript name for use when |internal[mp_prologues]>0| */
font_number last_ps_fnum; /* last valid |font_ps_name| index */
eight_bits *font_bc;
eight_bits *font_ec; /* first and last character code */
int *char_base; /* base address for |char_info| */
int *width_base; /* index for zeroth character width */
int *height_base; /* index for zeroth character height */
int *depth_base; /* index for zeroth character depth */
mp_node *font_sizes;
@ @<Allocate or initialize ...@>=
mp->font_mem_size = 10000;
mp->font_info = xmalloc ((mp->font_mem_size + 1), sizeof (font_data));
memset (mp->font_info, 0, sizeof (font_data) * (mp->font_mem_size + 1));
mp->last_fnum = null_font;
@ @<Dealloc variables@>=
for (k = 1; k <= (int) mp->last_fnum; k++) {
xfree (mp->font_enc_name[k]);
xfree (mp->font_name[k]);
xfree (mp->font_ps_name[k]);
}
for (k = 0; k <= 255; k++) {
/* These are disabled for now following a bug-report about double free
errors. TO BE FIXED, bug tracker id 831 */
/*|
mp_free_value_node (mp, mp->tfm_width[k]);
mp_free_value_node (mp, mp->tfm_height[k]);
mp_free_value_node (mp, mp->tfm_depth[k]);
mp_free_value_node (mp, mp->tfm_ital_corr[k]);
|*/
}
xfree (mp->font_info);
xfree (mp->font_enc_name);
xfree (mp->font_ps_name_fixed);
xfree (mp->font_dsize);
xfree (mp->font_name);
xfree (mp->font_ps_name);
xfree (mp->font_bc);
xfree (mp->font_ec);
xfree (mp->char_base);
xfree (mp->width_base);
xfree (mp->height_base);
xfree (mp->depth_base);
xfree (mp->font_sizes);
@
@c
void mp_reallocate_fonts (MP mp, font_number l) {
font_number f;
XREALLOC (mp->font_enc_name, l, char *);
XREALLOC (mp->font_ps_name_fixed, l, boolean);
XREALLOC (mp->font_dsize, l, integer);
XREALLOC (mp->font_name, l, char *);
XREALLOC (mp->font_ps_name, l, char *);
XREALLOC (mp->font_bc, l, eight_bits);
XREALLOC (mp->font_ec, l, eight_bits);
XREALLOC (mp->char_base, l, int);
XREALLOC (mp->width_base, l, int);
XREALLOC (mp->height_base, l, int);
XREALLOC (mp->depth_base, l, int);
XREALLOC (mp->font_sizes, l, mp_node);
for (f = (mp->last_fnum + 1); f <= l; f++) {
mp->font_enc_name[f] = NULL;
mp->font_ps_name_fixed[f] = false;
mp->font_name[f] = NULL;
mp->font_ps_name[f] = NULL;
mp->font_sizes[f] = NULL;
}
mp->font_max = l;
}
@ @<Internal library declarations@>=
void mp_reallocate_fonts (MP mp, font_number l);
@ A |null_font| containing no characters is useful for error recovery. Its
|font_name| entry starts out empty but is reset each time an erroneous font is
found. This helps to cut down on the number of duplicate error messages without
wasting a lot of space.
@d null_font 0 /* the |font_number| for an empty font */
@<Set initial...@>=
mp->font_dsize[null_font] = 0;
mp->font_bc[null_font] = 1;
mp->font_ec[null_font] = 0;
mp->char_base[null_font] = 0;
mp->width_base[null_font] = 0;
mp->height_base[null_font] = 0;
mp->depth_base[null_font] = 0;
mp->next_fmem = 0;
mp->last_fnum = null_font;
mp->last_ps_fnum = null_font;
{
static char nullfont_name[] = "nullfont";
static char nullfont_psname[] = "";
mp->font_name[null_font] = nullfont_name;
mp->font_ps_name[null_font] = nullfont_psname;
}
mp->font_ps_name_fixed[null_font] = false;
mp->font_enc_name[null_font] = NULL;
mp->font_sizes[null_font] = NULL;
@ Each |char_info| word is of type |four_quarters|. The |b0| field contains
the |width index|; the |b1| field contains the height
index; the |b2| fields contains the depth index, and the |b3| field used only
for temporary storage. (It is used to keep track of which characters occur in
an edge structure that is being shipped out.)
The corresponding words in the width, height, and depth tables are stored as
|scaled| values in units of \ps\ points.
With the macros below, the |char_info| word for character~|c| in font~|f| is
|char_mp_info(f,c)| and the width is
$$\hbox{|char_width(f,char_mp_info(f,c)).sc|.}$$
@d char_mp_info(A,B) mp->font_info[mp->char_base[(A)]+(B)].qqqq
@d char_width(A,B) mp->font_info[mp->width_base[(A)]+(B).b0].sc
@d char_height(A,B) mp->font_info[mp->height_base[(A)]+(B).b1].sc
@d char_depth(A,B) mp->font_info[mp->depth_base[(A)]+(B).b2].sc
@d ichar_exists(A) ((A).b0>0)
@ When we have a font name and we don't know whether it has been loaded yet,
we scan the |font_name| array before calling |read_font_info|.
@<Declarations@>=
static font_number mp_find_font (MP mp, char *f);
@ @c
font_number mp_find_font (MP mp, char *f) {
font_number n;
for (n = 0; n <= mp->last_fnum; n++) {
if (mp_xstrcmp (f, mp->font_name[n]) == 0) {
return n;
}
}
n = mp_read_font_info (mp, f);
return n;
}
@ This is an interface function for getting the width of character,
as a double in ps units
@c
double mp_get_char_dimension (MP mp, char *fname, int c, int t) {
unsigned n;
four_quarters cc;
font_number f = 0;
double w = -1.0;
for (n = 0; n <= mp->last_fnum; n++) {
if (mp_xstrcmp (fname, mp->font_name[n]) == 0) {
f = n;
break;
}
}
if (f == 0)
return 0.0;
cc = char_mp_info (f, c);
if (!ichar_exists (cc))
return 0.0;
if (t == 'w')
w = (double) char_width (f, cc);
else if (t == 'h')
w = (double) char_height (f, cc);
else if (t == 'd')
w = (double) char_depth (f, cc);
return w / 655.35 * (72.27 / 72);
}
@ @<Exported function ...@>=
double mp_get_char_dimension (MP mp, char *fname, int n, int t);
@ If we discover that the font doesn't have a requested character, we omit it
from the bounding box computation and expect the \ps\ interpreter to drop it.
This routine issues a warning message if the user has asked for it.
@<Declarations@>=
static void mp_lost_warning (MP mp, font_number f, int k);
@ @c
void mp_lost_warning (MP mp, font_number f, int k) {
if (number_positive (internal_value (mp_tracing_lost_chars))) {
mp_begin_diagnostic (mp);
if (mp->selector == log_only)
incr (mp->selector);
mp_print_nl (mp, "Missing character: There is no ");
@.Missing character@>;
mp_print_int (mp, k);
mp_print (mp, " in font ");
mp_print (mp, mp->font_name[f]);
mp_print_char (mp, xord ('!'));
mp_end_diagnostic (mp, false);
}
}
@ The whole purpose of saving the height, width, and depth information is to be
able to find the bounding box of an item of text in an edge structure. The
|set_text_box| procedure takes a text node and adds this information.
@<Declarations@>=
static void mp_set_text_box (MP mp, mp_text_node p);
@ @c
void mp_set_text_box (MP mp, mp_text_node p) {
font_number f; /* |mp_font_n(p)| */
ASCII_code bc, ec; /* range of valid characters for font |f| */
size_t k, kk; /* current character and character to stop at */
four_quarters cc; /* the |char_info| for the current character */
mp_number h, d; /* dimensions of the current character */
new_number(h);
new_number(d);
set_number_to_zero(p->width);
set_number_to_neg_inf(p->height);
set_number_to_neg_inf(p->depth);
f = (font_number) mp_font_n (p);
bc = mp->font_bc[f];
ec = mp->font_ec[f];
kk = mp_text_p (p)->len;
k = 0;
while (k < kk) {
@<Adjust |p|'s bounding box to contain |str_pool[k]|; advance |k|@>;
}
@<Set the height and depth to zero if the bounding box is empty@>;
free_number (h);
free_number (d);
}
@ @<Adjust |p|'s bounding box to contain |str_pool[k]|; advance |k|@>=
{
if ((*(mp_text_p (p)->str + k) < bc) || (*(mp_text_p (p)->str + k) > ec)) {
mp_lost_warning (mp, f, *(mp_text_p (p)->str + k));
} else {
cc = char_mp_info (f, *(mp_text_p (p)->str + k));
if (!ichar_exists (cc)) {
mp_lost_warning (mp, f, *(mp_text_p (p)->str + k));
} else {
set_number_from_scaled(p->width, number_to_scaled(p->width) + char_width (f, cc));
set_number_from_scaled(h, char_height (f, cc));
set_number_from_scaled(d, char_depth (f, cc));
if (number_greater(h, p->height))
number_clone(p->height, h);
if (number_greater(d, p->depth))
number_clone(p->depth, d);
}
}
incr (k);
}
@ Let's hope modern compilers do comparisons correctly when the difference would
overflow.
@<Set the height and depth to zero if the bounding box is empty@>=
if (number_to_scaled(p->height) < -number_to_scaled(p->depth)) {
set_number_to_zero(p->height);
set_number_to_zero(p->depth);
}
@ The new primitives fontmapfile and fontmapline.
@<Declare action procedures for use by |do_statement|@>=
static void mp_do_mapfile (MP mp);
static void mp_do_mapline (MP mp);
@ @c
static void mp_do_mapfile (MP mp) {
mp_get_x_next (mp);
mp_scan_expression (mp);
if (mp->cur_exp.type != mp_string_type) {
@<Complain about improper map operation@>;
} else {
mp_map_file (mp, cur_exp_str ());
}
}
static void mp_do_mapline (MP mp) {
mp_get_x_next (mp);
mp_scan_expression (mp);
if (mp->cur_exp.type != mp_string_type) {
@<Complain about improper map operation@>;
} else {
mp_map_line (mp, cur_exp_str ());
}
}
@ @<Complain about improper map operation@>=
{
const char *hlp[] = { "Only known strings can be map files or map lines.", NULL };
mp_disp_err(mp, NULL);
mp_back_error (mp, "Unsuitable expression", hlp, true);
mp_get_x_next (mp);
}
@ To print |scaled| value to PDF output we need some subroutines to ensure
accurary.
@d max_integer 0x7FFFFFFF /* $2^{31}-1$ */
@<Glob...@>=
integer ten_pow[10]; /* $10^0..10^9$ */
integer scaled_out; /* amount of |scaled| that was taken out in |divide_scaled| */
@ @<Set init...@>=
mp->ten_pow[0] = 1;
for (i = 1; i <= 9; i++) {
mp->ten_pow[i] = 10 * mp->ten_pow[i - 1];
}
@* Shipping pictures out.
The |ship_out| procedure, to be described below, is given a pointer to
an edge structure. Its mission is to output a file containing the \ps\
description of an edge structure.
@ Each time an edge structure is shipped out we write a new \ps\ output
file named according to the current \&{charcode}.
@:char_code_}{\&{charcode} primitive@>
This is the only backend function that remains in the main |mpost.w| file.
There are just too many variable accesses needed for status reporting
etcetera to make it worthwile to move the code to |psout.w|.
@<Internal library declarations@>=
void mp_open_output_file (MP mp);
char *mp_get_output_file_name (MP mp);
char *mp_set_output_file_name (MP mp, integer c);
@ @c
static void mp_append_to_template (MP mp, integer ff, integer c, boolean rounding) {
if (internal_type (c) == mp_string_type) {
char *ss = mp_str (mp, internal_string (c));
mp_print (mp, ss);
} else if (internal_type (c) == mp_known) {
if (rounding) {
int cc = round_unscaled (internal_value (c));
print_with_leading_zeroes (cc, ff);
} else {
print_number (internal_value (c));
}
}
}
char *mp_set_output_file_name (MP mp, integer c) {
char *ss = NULL; /* filename extension proposal */
char *nn = NULL; /* temp string for str() */
unsigned old_setting; /* previous |selector| setting */
size_t i; /* indexes into |filename_template| */
integer f; /* field width */
str_room (1024);
if (mp->job_name == NULL)
mp_open_log_file (mp);
if (internal_string (mp_output_template) == NULL) {
char *s; /* a file extension derived from |c| */
if (c < 0)
s = xstrdup (".ps");
else
@<Use |c| to compute the file extension |s|@>;
mp_pack_job_name (mp, s);
free (s);
ss = xstrdup (mp->name_of_file);
} else { /* initializations */
mp_string s, n, ftemplate; /* a file extension derived from |c| */
mp_number saved_char_code;
new_number (saved_char_code);
number_clone (saved_char_code, internal_value (mp_char_code));
set_internal_from_number (mp_char_code, unity_t);
number_multiply_int (internal_value (mp_char_code), c);
if (internal_string (mp_job_name) == NULL) {
if (mp->job_name == NULL) {
mp->job_name = xstrdup ("mpout");
}
@<Fix up |mp->internal[mp_job_name]|@>;
}
old_setting = mp->selector;
mp->selector = new_string;
i = 0;
n = mp_rts(mp,""); /* initialize */
ftemplate = internal_string (mp_output_template);
while (i < ftemplate->len) {
f = 0;
if (*(ftemplate->str + i) == '%') {
CONTINUE:
incr (i);
if (i < ftemplate->len) {
switch (*(ftemplate->str + i)) {
case 'j':
mp_append_to_template (mp, f, mp_job_name, true);
break;
case 'c':
if (number_negative (internal_value (mp_char_code))) {
mp_print (mp, "ps");
} else {
mp_append_to_template (mp, f, mp_char_code, true);
}
break;
case 'o':
mp_append_to_template (mp, f, mp_output_format, true);
break;
case 'd':
mp_append_to_template (mp, f, mp_day, true);
break;
case 'm':
mp_append_to_template (mp, f, mp_month, true);
break;
case 'y':
mp_append_to_template (mp, f, mp_year, true);
break;
case 'H':
mp_append_to_template (mp, f, mp_hour, true);
break;
case 'M':
mp_append_to_template (mp, f, mp_minute, true);
break;
case '{':
{
/* look up a name */
size_t l = 0;
size_t frst = i + 1;
while (i < ftemplate->len) {
i++;
if (*(ftemplate->str + i) == '}')
break;
l++;
}
if (l > 0) {
mp_sym p =
mp_id_lookup (mp, (char *) (ftemplate->str + frst), l, false);
char *id = xmalloc ((l + 1), 1);
(void) memcpy (id, (char *) (ftemplate->str + frst), (size_t) l);
*(id + l) = '\0';
if (p == NULL) {
char err[256];
mp_snprintf (err, 256,
"requested identifier (%s) in outputtemplate not found.",
id);
mp_warn (mp, err);
} else {
if (eq_type (p) == mp_internal_quantity) {
if (equiv (p) == mp_output_template) {
char err[256];
mp_snprintf (err, 256,
"The appearance of outputtemplate inside outputtemplate is ignored.");
mp_warn (mp, err);
} else {
mp_append_to_template (mp, f, equiv (p), false);
}
} else {
char err[256];
mp_snprintf (err, 256,
"requested identifier (%s) in outputtemplate is not an internal.",
id);
mp_warn (mp, err);
}
}
free (id);
}
}
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
if ((f < 10))
f = (f * 10) + ftemplate->str[i] - '0';
goto CONTINUE;
break;
case '%':
mp_print_char (mp, '%');
break;
default:
{
char err[256];
mp_snprintf (err, 256,
"requested format (%c) in outputtemplate is unknown.",
*(ftemplate->str + i));
mp_warn (mp, err);
}
mp_print_char (mp, *(ftemplate->str + i));
}
}
} else {
if (*(ftemplate->str + i) == '.')
if (n->len == 0)
n = mp_make_string (mp);
mp_print_char (mp, *(ftemplate->str + i));
};
incr (i);
}
s = mp_make_string (mp);
number_clone (internal_value (mp_char_code), saved_char_code);
free_number (saved_char_code);
mp->selector = old_setting;
if (n->len == 0) {
n = s;
s = mp_rts(mp,"");
}
ss = mp_str (mp, s);
nn = mp_str (mp, n);
mp_pack_file_name (mp, nn, "", ss);
delete_str_ref (n);
delete_str_ref (s);
}
return ss;
}
char *mp_get_output_file_name (MP mp) {
char *f;
char *saved_name; /* saved |name_of_file| */
saved_name = xstrdup (mp->name_of_file);
(void) mp_set_output_file_name (mp, round_unscaled (internal_value(mp_char_code)));
f = xstrdup (mp->name_of_file);
mp_pack_file_name (mp, saved_name, NULL, NULL);
free (saved_name);
return f;
}
void mp_open_output_file (MP mp) {
char *ss; /* filename extension proposal */
int c; /* \&{charcode} rounded to the nearest integer */
c = round_unscaled (internal_value (mp_char_code));
ss = mp_set_output_file_name (mp, c);
while (!mp_open_out (mp, (void *) &mp->output_file, mp_filetype_postscript))
mp_prompt_file_name (mp, "file name for output", ss);
mp_store_true_output_filename (mp, c);
}
@ The file extension created here could be up to five characters long in
extreme cases so it may have to be shortened on some systems.
@^system dependencies@>
@<Use |c| to compute the file extension |s|@>=
{
s = xmalloc (7, 1);
mp_snprintf (s, 7, ".%i", (int) c);
}
@ The user won't want to see all the output file names so we only save the
first and last ones and a count of how many there were. For this purpose
files are ordered primarily by \&{charcode} and secondarily by order of
creation.
@:char_code_}{\&{charcode} primitive@>
@<Internal library ...@>=
void mp_store_true_output_filename (MP mp, int c);
@ @c
void mp_store_true_output_filename (MP mp, int c)
{
if ((c < mp->first_output_code) && (mp->first_output_code >= 0)) {
mp->first_output_code = c;
xfree (mp->first_file_name);
mp->first_file_name = xstrdup (mp->name_of_file);
}
if (c >= mp->last_output_code) {
mp->last_output_code = c;
xfree (mp->last_file_name);
mp->last_file_name = xstrdup (mp->name_of_file);
}
set_internal_string (mp_output_filename, mp_rts (mp, mp->name_of_file));
}
@ @<Glob...@>=
char *first_file_name;
char *last_file_name; /* full file names */
integer first_output_code;
integer last_output_code; /* rounded \&{charcode} values */
@:char_code_}{\&{charcode} primitive@>
integer total_shipped; /* total number of |ship_out| operations completed */
@ @<Set init...@>=
mp->first_file_name = xstrdup ("");
mp->last_file_name = xstrdup ("");
mp->first_output_code = 32768;
mp->last_output_code = -32768;
mp->total_shipped = 0;
@ @<Dealloc variables@>=
xfree (mp->first_file_name);
xfree (mp->last_file_name);
@ @<Begin the progress report for the output of picture~|c|@>=
if ((int) mp->term_offset > mp->max_print_line - 6)
mp_print_ln (mp);
else if ((mp->term_offset > 0) || (mp->file_offset > 0))
mp_print_char (mp, xord (' '));
mp_print_char (mp, xord ('['));
if (c >= 0)
mp_print_int (mp, c)
@ @<End progress report@>=
mp_print_char (mp, xord (']'));
update_terminal();
incr (mp->total_shipped)
@ @<Explain what output files were written@>=
if (mp->total_shipped > 0) {
mp_print_nl (mp, "");
mp_print_int (mp, mp->total_shipped);
if (mp->noninteractive) {
mp_print (mp, " figure");
if (mp->total_shipped > 1)
mp_print_char (mp, xord ('s'));
mp_print (mp, " created.");
} else {
mp_print (mp, " output file");
if (mp->total_shipped > 1)
mp_print_char (mp, xord ('s'));
mp_print (mp, " written: ");
mp_print (mp, mp->first_file_name);
if (mp->total_shipped > 1) {
if (31 + strlen (mp->first_file_name) +
strlen (mp->last_file_name) > (unsigned) mp->max_print_line)
mp_print_ln (mp);
mp_print (mp, " .. ");
mp_print (mp, mp->last_file_name);
}
mp_print_nl (mp, "");
}
}
@ @<Internal library declarations@>=
boolean mp_has_font_size (MP mp, font_number f);
@ @c
boolean mp_has_font_size (MP mp, font_number f) {
return (mp->font_sizes[f] != NULL);
}
@ The \&{special} command saves up lines of text to be printed during the next
|ship_out| operation. The saved items are stored as a list of capsule tokens.
@<Glob...@>=
mp_node last_pending; /* the last token in a list of pending specials */
@ @<Declare action procedures for use by |do_statement|@>=
static void mp_do_special (MP mp);
@ @c
void mp_do_special (MP mp) {
mp_get_x_next (mp);
mp_scan_expression (mp);
if (mp->cur_exp.type != mp_string_type) {
@<Complain about improper special operation@>;
} else {
mp_link (mp->last_pending) = mp_stash_cur_exp (mp);
mp->last_pending = mp_link (mp->last_pending);
mp_link (mp->last_pending) = NULL;
}
}
@ @<Complain about improper special operation@>=
{
const char *hlp[] = { "Only known strings are allowed for output as specials.", NULL };
mp_disp_err(mp, NULL);
mp_back_error (mp, "Unsuitable expression", hlp, true);
mp_get_x_next (mp);
}
@ On the export side, we need an extra object type for special strings.
@<Graphical object codes@>=
mp_special_code = 8,
@ @<Export pending specials@>=
p = mp_link (mp->spec_head);
while (p != NULL) {
mp_special_object *tp;
tp = (mp_special_object *) mp_new_graphic_object (mp, mp_special_code);
gr_pre_script (tp) = mp_xstrdup(mp,mp_str (mp, value_str (p)));
if (hh->body == NULL)
hh->body = (mp_graphic_object *) tp;
else
gr_link (hp) = (mp_graphic_object *) tp;
hp = (mp_graphic_object *) tp;
p = mp_link (p);
}
mp_flush_token_list (mp, mp_link (mp->spec_head));
mp_link (mp->spec_head) = NULL;
mp->last_pending = mp->spec_head
@ We are now ready for the main output procedure. Note that the |selector|
setting is saved in a global variable so that |begin_diagnostic| can access it.
@<Declare the \ps\ output procedures@>=
static void mp_ship_out (MP mp, mp_node h);
@ Once again, the |gr_XXXX| macros are defined in |mppsout.h|
@d export_color(q,p)
if ( mp_color_model(p)==mp_uninitialized_model ) {
gr_color_model(q) = (unsigned char)(number_to_scaled (internal_value(mp_default_color_model))/65536);
gr_cyan_val(q) = 0;
gr_magenta_val(q) = 0;
gr_yellow_val(q) = 0;
gr_black_val(q) = ((gr_color_model(q)==mp_cmyk_model ? number_to_scaled (unity_t) : 0) / 65536.0);
} else {
gr_color_model(q) = (unsigned char)mp_color_model(p);
gr_cyan_val(q) = number_to_double(p->cyan);
gr_magenta_val(q) = number_to_double(p->magenta);
gr_yellow_val(q) = number_to_double(p->yellow);
gr_black_val(q) = number_to_double(p->black);
}
@d export_scripts(q,p)
if (mp_pre_script(p)!=NULL) gr_pre_script(q) = mp_xstrdup(mp, mp_str(mp,mp_pre_script(p)));
if (mp_post_script(p)!=NULL) gr_post_script(q) = mp_xstrdup(mp, mp_str(mp,mp_post_script(p)));
@c
struct mp_edge_object *mp_gr_export (MP mp, mp_edge_header_node h) {
mp_node p; /* the current graphical object */
integer t; /* a temporary value */
integer c; /* a rounded charcode */
mp_number d_width; /* the current pen width */
mp_edge_object *hh; /* the first graphical object */
mp_graphic_object *hq; /* something |hp| points to */
mp_text_object *tt;
mp_fill_object *tf;
mp_stroked_object *ts;
mp_clip_object *tc;
mp_bounds_object *tb;
mp_graphic_object *hp = NULL; /* the current graphical object */
mp_set_bbox (mp, h, true);
hh = xmalloc (1, sizeof (mp_edge_object));
hh->body = NULL;
hh->next = NULL;
hh->parent = mp;
hh->minx = number_to_double(h->minx);
hh->minx = (fabs(hh->minx)<0.00001 ? 0 : hh->minx);
hh->miny = number_to_double(h->miny);
hh->miny = (fabs(hh->miny)<0.00001 ? 0 : hh->miny);
hh->maxx = number_to_double(h->maxx);
hh->maxx = (fabs(hh->maxx)<0.00001 ? 0 : hh->maxx);
hh->maxy = number_to_double(h->maxy);
hh->maxy = (fabs(hh->maxy)<0.00001 ? 0 : hh->maxy);
hh->filename = mp_get_output_file_name (mp);
c = round_unscaled (internal_value (mp_char_code));
hh->charcode = c;
hh->width = number_to_double (internal_value (mp_char_wd));
hh->height = number_to_double (internal_value (mp_char_ht));
hh->depth = number_to_double (internal_value (mp_char_dp));
hh->ital_corr = number_to_double (internal_value (mp_char_ic));
@<Export pending specials@>;
p = mp_link (edge_list (h));
while (p != NULL) {
hq = mp_new_graphic_object (mp, (int) ((mp_type (p) - mp_fill_node_type) + 1));
switch (mp_type (p)) {
case mp_fill_node_type:
{
mp_fill_node p0 = (mp_fill_node)p;
tf = (mp_fill_object *) hq;
gr_pen_p (tf) = mp_export_knot_list (mp, mp_pen_p (p0));
new_number (d_width);
mp_get_pen_scale (mp, &d_width, mp_pen_p (p0)); /* whats the point ? */
free_number (d_width);
if ((mp_pen_p (p0) == NULL) || pen_is_elliptical (mp_pen_p (p0))) {
gr_path_p (tf) = mp_export_knot_list (mp, mp_path_p (p0));
} else {
mp_knot pc, pp;
pc = mp_copy_path (mp, mp_path_p (p0));
pp = mp_make_envelope (mp, pc, mp_pen_p (p0), p0->ljoin, 0, p0->miterlim);
gr_path_p (tf) = mp_export_knot_list (mp, pp);
mp_toss_knot_list (mp, pp);
pc = mp_htap_ypoc (mp, mp_path_p (p0));
pp = mp_make_envelope (mp, pc, mp_pen_p ((mp_fill_node) p), p0->ljoin, 0, p0->miterlim);
gr_htap_p (tf) = mp_export_knot_list (mp, pp);
mp_toss_knot_list (mp, pp);
}
export_color (tf, p0);
export_scripts (tf, p);
gr_ljoin_val (tf) = p0->ljoin;
gr_miterlim_val (tf) = number_to_double(p0->miterlim);
}
break;
case mp_stroked_node_type:
{
mp_stroked_node p0 = (mp_stroked_node)p;
ts = (mp_stroked_object *) hq;
gr_pen_p (ts) = mp_export_knot_list (mp, mp_pen_p (p0));
new_number (d_width);
mp_get_pen_scale (mp, &d_width, mp_pen_p (p0));
if (pen_is_elliptical (mp_pen_p (p0))) {
gr_path_p (ts) = mp_export_knot_list (mp, mp_path_p (p0));
} else {
mp_knot pc;
pc = mp_copy_path (mp, mp_path_p (p0));
t = p0->lcap;
if (mp_left_type (pc) != mp_endpoint) {
mp_left_type (mp_insert_knot (mp, pc, pc->x_coord, pc->y_coord)) = mp_endpoint;
mp_right_type (pc) = mp_endpoint;
pc = mp_next_knot (pc);
t = 1;
}
pc =
mp_make_envelope (mp, pc, mp_pen_p (p0),
p0->ljoin, (quarterword) t,
p0->miterlim);
gr_path_p (ts) = mp_export_knot_list (mp, pc);
mp_toss_knot_list (mp, pc);
}
export_color (ts, p0);
export_scripts (ts, p);
gr_ljoin_val (ts) = p0->ljoin;
gr_miterlim_val (ts) = number_to_double(p0->miterlim);
gr_lcap_val (ts) = p0->lcap;
gr_dash_p (ts) = mp_export_dashes (mp, p0, d_width);
free_number (d_width);
}
break;
case mp_text_node_type:
{
mp_text_node p0 = (mp_text_node)p;
tt = (mp_text_object *) hq;
gr_text_p (tt) = mp_xstrldup (mp, mp_str (mp, mp_text_p (p)),mp_text_p (p)->len);
gr_text_l (tt) = (size_t) mp_text_p (p)->len;
gr_font_n (tt) = (unsigned int) mp_font_n (p);
gr_font_name (tt) = mp_xstrdup (mp, mp->font_name[mp_font_n (p)]);
gr_font_dsize (tt) = mp->font_dsize[mp_font_n (p)] / 65536.0;
export_color (tt, p0);
export_scripts (tt, p);
gr_width_val (tt) = number_to_double(p0->width);
gr_height_val (tt) = number_to_double(p0->height);
gr_depth_val (tt) = number_to_double(p0->depth);
gr_tx_val (tt) = number_to_double(p0->tx);
gr_ty_val (tt) = number_to_double(p0->ty);
gr_txx_val (tt) = number_to_double(p0->txx);
gr_txy_val (tt) = number_to_double(p0->txy);
gr_tyx_val (tt) = number_to_double(p0->tyx);
gr_tyy_val (tt) = number_to_double(p0->tyy);
}
break;
case mp_start_clip_node_type:
tc = (mp_clip_object *) hq;
gr_path_p (tc) =
mp_export_knot_list (mp, mp_path_p ((mp_start_clip_node) p));
break;
case mp_start_bounds_node_type:
tb = (mp_bounds_object *) hq;
gr_path_p (tb) =
mp_export_knot_list (mp, mp_path_p ((mp_start_bounds_node) p));
break;
case mp_stop_clip_node_type:
case mp_stop_bounds_node_type:
/* nothing to do here */
break;
default: /* there are no other valid cases, but please the compiler */
break;
}
if (hh->body == NULL)
hh->body = hq;
else
gr_link (hp) = hq;
hp = hq;
p = mp_link (p);
}
return hh;
}
@ This function is only used for the |glyph| operator, so
it takes quite a few shortcuts for cases that cannot appear
in the output of |mp_ps_font_charstring|.
@c
mp_edge_header_node mp_gr_import (MP mp, struct mp_edge_object *hh) {
mp_edge_header_node h; /* the edge object */
mp_node ph, pn, pt; /* for adding items */
mp_graphic_object *p; /* the current graphical object */
h = mp_get_edge_header_node (mp);
mp_init_edges (mp, h);
ph = edge_list (h);
pt = ph;
p = hh->body;
set_number_from_double(h->minx, hh->minx);
set_number_from_double(h->miny, hh->miny);
set_number_from_double(h->maxx, hh->maxx);
set_number_from_double(h->maxy, hh->maxy);
while (p != NULL) {
switch (gr_type (p)) {
case mp_fill_code:
if (gr_pen_p ((mp_fill_object *) p) == NULL) {
mp_number turns;
new_number (turns);
pn = mp_new_fill_node (mp, NULL);
mp_path_p ((mp_fill_node) pn) =
mp_import_knot_list (mp, gr_path_p ((mp_fill_object *) p));
mp_color_model (pn) = mp_grey_model;
mp_turn_cycles (mp, &turns, mp_path_p ((mp_fill_node) pn));
if (number_negative(turns)) {
set_number_to_unity(((mp_fill_node) pn)->grey);
mp_link (pt) = pn;
pt = mp_link (pt);
} else {
set_number_to_zero(((mp_fill_node) pn)->grey);
mp_link (pn) = mp_link (ph);
mp_link (ph) = pn;
if (ph == pt)
pt = pn;
}
free_number (turns);
}
break;
case mp_stroked_code:
case mp_text_code:
case mp_start_clip_code:
case mp_stop_clip_code:
case mp_start_bounds_code:
case mp_stop_bounds_code:
case mp_special_code:
break;
} /* all cases are enumerated */
p = p->next;
}
mp_gr_toss_objects (hh);
return h;
}
@ @<Declarations@>=
struct mp_edge_object *mp_gr_export (MP mp, mp_edge_header_node h);
mp_edge_header_node mp_gr_import (MP mp, struct mp_edge_object *h);
@ This function is now nearly trivial.
@c
void mp_ship_out (MP mp, mp_node h) { /* output edge structure |h| */
int c; /* \&{charcode} rounded to the nearest integer */
c = round_unscaled (internal_value (mp_char_code));
@<Begin the progress report for the output of picture~|c|@>;
(mp->shipout_backend) (mp, h);
@<End progress report@>;
if (number_positive (internal_value (mp_tracing_output)))
mp_print_edges (mp, h, " (just shipped out)", true);
}
@ @<Declarations@>=
static void mp_shipout_backend (MP mp, void *h);
@
@c
void mp_shipout_backend (MP mp, void *voidh) {
char *s;
mp_edge_object *hh; /* the first graphical object */
mp_edge_header_node h = (mp_edge_header_node) voidh;
hh = mp_gr_export (mp, h);
s = NULL;
if (internal_string (mp_output_format) != NULL)
s = mp_str (mp, internal_string (mp_output_format));
if (s && strcmp (s, "svg") == 0) {
(void) mp_svg_gr_ship_out (hh,
(number_to_scaled (internal_value (mp_prologues)) / 65536), false);
} else if (s && strcmp (s, "png") == 0) {
(void) mp_png_gr_ship_out (hh, (const char *)((internal_string (mp_output_format_options))->str), false);
} else {
(void) mp_gr_ship_out (hh,
(number_to_scaled (internal_value (mp_prologues)) / 65536),
(number_to_scaled (internal_value (mp_procset)) / 65536), false);
}
mp_gr_toss_objects (hh);
}
@ @<Exported types@>=
typedef void (*mp_backend_writer) (MP, void *);
@ @<Option variables@>=
mp_backend_writer shipout_backend;
@ Now that we've finished |ship_out|, let's look at the other commands
by which a user can send things to the \.{GF} file.
@ @<Glob...@>=
psout_data ps;
svgout_data svg;
pngout_data png;
@ @<Allocate or initialize ...@>=
mp_ps_backend_initialize (mp);
mp_svg_backend_initialize (mp);
mp_png_backend_initialize (mp);
@ @<Dealloc...@>=
mp_ps_backend_free (mp);
mp_svg_backend_free (mp);
mp_png_backend_free (mp);
@* Dumping and undumping the tables.
When \.{MP} is started, it is possible to preload a macro file
containing definitions that will be usable in the main input
file. This action even takes place automatically, based on the
name of the executable (\.{mpost} will attempt to preload the
macros in the file \.{mpost.mp}). If such a preload is not
desired, the option variable |ini_version| has to be set |true|.
The variable |mem_file| holds the open file pointer.
@<Glob...@>=
void *mem_file; /* file for input or preloaded macros */
@ @<Declarations@>=
extern boolean mp_load_preload_file (MP mp);
@ Preloading a file is a lot like |mp_run| itself, except that
\MP\ should not exit and that a bit of trickery is needed with
the input buffer to make sure that the preloading does not
interfere with the actual job.
@c
boolean mp_load_preload_file (MP mp) {
size_t k;
in_state_record old_state;
integer old_in_open = mp->in_open;
void *old_cur_file = cur_file;
char *fname = xstrdup (mp->name_of_file);
size_t l = strlen (fname);
old_state = mp->cur_input;
str_room (l);
for (k = 0; k < l; k++) {
append_char (*(fname + k));
}
name = mp_make_string (mp);
if (!mp->log_opened) {
mp_open_log_file (mp);
} /* |open_log_file| doesn't |show_context|, so |limit|
and |loc| needn't be set to meaningful values yet */
if (((int) mp->term_offset + (int) strlen (fname)) > (mp->max_print_line - 2))
mp_print_ln (mp);
else if ((mp->term_offset > 0) || (mp->file_offset > 0))
mp_print_char (mp, xord (' '));
mp_print_char (mp, xord ('('));
incr (mp->open_parens);
mp_print (mp, fname);
update_terminal();
{
line = 1;
start = loc = limit + (mp->noninteractive ? 0 : 1);
cur_file = mp->mem_file;
(void) mp_input_ln (mp, cur_file);
mp_firm_up_the_line (mp);
mp->buffer[limit] = xord ('%');
mp->first = (size_t) (limit + 1);
loc = start;
}
mp->reading_preload = true;
do {
mp_do_statement (mp);
} while (!(cur_cmd() == mp_stop)); /* "dump" or EOF */
mp->reading_preload = false;
mp_primitive (mp, "dump", mp_relax, 0); /* reset |dump| */
while (mp->input_ptr > 0) {
if (token_state)
mp_end_token_list (mp);
else
mp_end_file_reading (mp);
}
while (mp->loop_ptr != NULL)
mp_stop_iteration (mp);
while (mp->open_parens > 0) {
mp_print (mp, " )");
decr (mp->open_parens);
};
while (mp->cond_ptr != NULL) {
mp_print_nl (mp, "(dump occurred when ");
@.dump occurred...@>;
mp_print_cmd_mod (mp, mp_fi_or_else, mp->cur_if);
/* `\.{if}' or `\.{elseif}' or `\.{else}' */
if (mp->if_line != 0) {
mp_print (mp, " on line ");
mp_print_int (mp, mp->if_line);
}
mp_print (mp, " was incomplete)");
mp->if_line = if_line_field (mp->cond_ptr);
mp->cur_if = mp_name_type (mp->cond_ptr);
mp->cond_ptr = mp_link (mp->cond_ptr);
}
/* |(mp->close_file) (mp, mp->mem_file);| */
cur_file = old_cur_file;
mp->cur_input = old_state;
mp->in_open = old_in_open;
return true;
}
@* The main program.
This is it: the part of \MP\ that executes all those procedures we have
written.
Well---almost. We haven't put the parsing subroutines into the
program yet; and we'd better leave space for a few more routines that may
have been forgotten.
@c
@<Declare the basic parsing subroutines@>;
@<Declare miscellaneous procedures that were declared |forward|@>
@ Here we do whatever is needed to complete \MP's job gracefully on the
local operating system. The code here might come into play after a fatal
error; it must therefore consist entirely of ``safe'' operations that
cannot produce error messages. For example, it would be a mistake to call
|str_room| or |make_string| at this time, because a call on |overflow|
might lead to an infinite loop.
@^system dependencies@>
@ @c
void mp_close_files_and_terminate (MP mp) {
integer k; /* all-purpose index */
integer LH; /* the length of the \.{TFM} header, in words */
int lk_offset; /* extra words inserted at beginning of |lig_kern| array */
mp_node p; /* runs through a list of \.{TFM} dimensions */
if (mp->finished)
return;
@<Close all open files in the |rd_file| and |wr_file| arrays@>;
if (number_positive (internal_value (mp_tracing_stats)))
@<Output statistics about this job@>;
wake_up_terminal();
@<Do all the finishing work on the \.{TFM} file@>;
@<Explain what output files were written@>;
if (mp->log_opened && !mp->noninteractive) {
wlog_cr;
(mp->close_file) (mp, mp->log_file);
mp->selector = mp->selector - 2;
if (mp->selector == term_only) {
mp_print_nl (mp, "Transcript written on ");
@.Transcript written...@>;
mp_print (mp, mp->log_name);
mp_print_char (mp, xord ('.'));
}
}
mp_print_ln (mp);
mp->finished = true;
}
@ @<Declarations@>=
static void mp_close_files_and_terminate (MP mp);
@ @<Close all open files in the |rd_file| and |wr_file| arrays@>=
if (mp->rd_fname != NULL) {
for (k = 0; k < (int) mp->read_files; k++) {
if (mp->rd_fname[k] != NULL) {
(mp->close_file) (mp, mp->rd_file[k]);
xfree (mp->rd_fname[k]);
}
}
}
if (mp->wr_fname != NULL) {
for (k = 0; k < (int) mp->write_files; k++) {
if (mp->wr_fname[k] != NULL) {
(mp->close_file) (mp, mp->wr_file[k]);
xfree (mp->wr_fname[k]);
}
}
}
@ @<Dealloc ...@>=
for (k = 0; k < (int) mp->max_read_files; k++) {
if (mp->rd_fname[k] != NULL) {
(mp->close_file) (mp, mp->rd_file[k]);
xfree (mp->rd_fname[k]);
}
}
xfree (mp->rd_file);
xfree (mp->rd_fname);
for (k = 0; k < (int) mp->max_write_files; k++) {
if (mp->wr_fname[k] != NULL) {
(mp->close_file) (mp, mp->wr_file[k]);
xfree (mp->wr_fname[k]);
}
}
xfree (mp->wr_file);
xfree (mp->wr_fname);
@ We want to produce a \.{TFM} file if and only if |mp_fontmaking| is positive.
We reclaim all of the variable-size memory at this point, so that
there is no chance of another memory overflow after the memory capacity
has already been exceeded.
@<Do all the finishing work on the \.{TFM} file@>=
if (number_positive (internal_value (mp_fontmaking))) {
@<Massage the \.{TFM} widths@>;
mp_fix_design_size (mp);
mp_fix_check_sum (mp);
@<Massage the \.{TFM} heights, depths, and italic corrections@>;
set_number_to_zero (internal_value (mp_fontmaking)); /* avoid loop in case of fatal error */
@<Finish the \.{TFM} file@>;
}
@ The present section goes directly to the log file instead of using
|print| commands, because there's no need for these strings to take
up |str_pool| memory when a non-{\bf stat} version of \MP\ is being used.
@<Output statistics...@>=
if (mp->log_opened) {
char s[128];
wlog_ln (" ");
wlog_ln ("Here is how much of MetaPost's memory you used:");
@.Here is how much...@>;
mp_snprintf (s, 128, " %i string%s using %i character%s",
(int) mp->max_strs_used, (mp->max_strs_used != 1 ? "s" : ""),
(int) mp->max_pl_used, (mp->max_pl_used != 1 ? "s" : ""));
wlog_ln (s);
mp_snprintf (s, 128, " %i bytes of node memory", (int) mp->var_used_max);
wlog_ln (s);
mp_snprintf (s, 128, " %i symbolic tokens", (int) mp->st_count);
wlog_ln (s);
mp_snprintf (s, 128,
" %ii,%in,%ip,%ib,%if stack positions out of %ii,%in,%ip,%ib,%if",
(int) mp->max_in_stack, (int) mp->int_ptr,
(int) mp->max_param_stack, (int) mp->max_buf_stack + 1,
(int) mp->in_open_max - file_bottom, (int) mp->stack_size,
(int) mp->max_internal, (int) mp->param_size, (int) mp->buf_size,
(int) mp->max_in_open - file_bottom);
wlog_ln (s);
}
@ It is nice to have have some of the stats available from the API.
@<Exported function ...@>=
int mp_memory_usage (MP mp);
int mp_hash_usage (MP mp);
int mp_param_usage (MP mp);
int mp_open_usage (MP mp);
@ @c
int mp_memory_usage (MP mp) {
return (int) mp->var_used;
}
int mp_hash_usage (MP mp) {
return (int) mp->st_count;
}
int mp_param_usage (MP mp) {
return (int) mp->max_param_stack;
}
int mp_open_usage (MP mp) {
return (int) mp->max_in_stack;
}
@ We get to the |final_cleanup| routine when \&{end} or \&{dump} has
been scanned.
@c
void mp_final_cleanup (MP mp) {
/* -Wunused: integer c; */ /* 0 for \&{end}, 1 for \&{dump} */
/* clang: never read: |c = cur_mod();| */
if (mp->job_name == NULL)
mp_open_log_file (mp);
while (mp->input_ptr > 0) {
if (token_state)
mp_end_token_list (mp);
else
mp_end_file_reading (mp);
}
while (mp->loop_ptr != NULL)
mp_stop_iteration (mp);
while (mp->open_parens > 0) {
mp_print (mp, " )");
decr (mp->open_parens);
};
while (mp->cond_ptr != NULL) {
mp_print_nl (mp, "(end occurred when ");
@.end occurred...@>;
mp_print_cmd_mod (mp, mp_fi_or_else, mp->cur_if);
/* `\.{if}' or `\.{elseif}' or `\.{else}' */
if (mp->if_line != 0) {
mp_print (mp, " on line ");
mp_print_int (mp, mp->if_line);
}
mp_print (mp, " was incomplete)");
mp->if_line = if_line_field (mp->cond_ptr);
mp->cur_if = mp_name_type (mp->cond_ptr);
mp->cond_ptr = mp_link (mp->cond_ptr);
}
if (mp->history != mp_spotless)
if (((mp->history == mp_warning_issued)
|| (mp->interaction < mp_error_stop_mode)))
if (mp->selector == term_and_log) {
mp->selector = term_only;
mp_print_nl (mp,
"(see the transcript file for additional information)");
@.see the transcript file...@>;
mp->selector = term_and_log;
}
}
@ @<Declarations@>=
static void mp_final_cleanup (MP mp);
static void mp_init_prim (MP mp);
static void mp_init_tab (MP mp);
@ @c
void mp_init_prim (MP mp) { /* initialize all the primitives */
@<Put each...@>;
}
@#
void mp_init_tab (MP mp) { /* initialize other tables */
@<Initialize table entries@>;
}
@ When we begin the following code, \MP's tables may still contain garbage;
thus we must proceed cautiously to get bootstrapped in.
But when we finish this part of the program, \MP\ is ready to call on the
|main_control| routine to do its work.
@<Get the first line...@>=
{
@<Initialize the input routines@>;
if (!mp->ini_version) {
if (!mp_load_preload_file (mp)) {
mp->history = mp_fatal_error_stop;
return mp;
}
}
@<Initializations following first line@>;
}
@ @<Initializations following first line@>=
mp->buffer[limit] = (ASCII_code) '%';
mp_fix_date_and_time (mp);
if (mp->random_seed == 0)
mp->random_seed = (number_to_scaled (internal_value (mp_time)) / number_to_scaled (unity_t)) + number_to_scaled (internal_value (mp_day));
init_randoms (mp->random_seed);
initialize_print_selector();
mp_normalize_selector (mp);
if (loc < limit)
if (mp->buffer[loc] != '\\')
mp_start_input (mp); /* \&{input} assumed */
@* Debugging.
@* System-dependent changes.
This section should be replaced, if necessary, by any special
modification of the program
that are necessary to make \MP\ work at a particular installation.
It is usually best to design your change file so that all changes to
previous sections preserve the section numbering; then everybody's version
will be consistent with the published program. More extensive changes,
which introduce new sections, can be inserted here; then only the index
itself will get a new section number.
@^system dependencies@>
@* Index.
Here is where you can find all uses of each identifier in the program,
with underlined entries pointing to where the identifier was defined.
If the identifier is only one letter long, however, you get to see only
the underlined entries. {\sl All references are to section numbers instead of
page numbers.}
This index also lists error messages and other aspects of the program
that you might want to look up some day. For example, the entry
for ``system dependencies'' lists all sections that should receive
special attention from people who are installing \MP\ in a new
operating environment. A list of various things that can't happen appears
under ``this can't happen''.
Approximately 25 sections are listed under ``inner loop''; these account
for more than 60\pct! of \MP's running time, exclusive of input and output.
|