aboutsummaryrefslogtreecommitdiff
path: root/shar/python-0.9.1-11-21.shar
blob: 59aa0a2df6d86474958736ed5ea281e8a055617c (plain)
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
: This is a shell archive.
: Extract with 'sh this_file'.
:
: Extract part 01 first since it makes all directories
echo 'Start of pack.out, part 11 out of 21:'
if test -s 'lib/Buttons.py'
then echo '*** I will not over-write existing file lib/Buttons.py'
else
echo 'x - lib/Buttons.py'
sed 's/^X//' > 'lib/Buttons.py' << 'EOF'
X# Module 'Buttons'
X
X
X# Import module 'rect' renamed as '_rect' to avoid exporting it on
X# 'from Buttons import *'
X#
Ximport rect
X_rect = rect
Xdel rect
X
X
X# Field indices in mouse event detail
X#
X_HV = 0
X_CLICKS = 1
X_BUTTON = 2
X_MASK = 3
X
X
X# LabelAppearance provides defaults for all appearance methods.
X# selected state not visible
X# disabled --> crossed out
X# hilited --> inverted
X#
Xclass LabelAppearance():
X #
X # Initialization
X #
X def init_appearance(self):
X self.bounds = _rect.empty
X self.enabled = 1
X self.hilited = 0
X self.selected = 0
X self.text = ''
X #
X # Size enquiry
X #
X def minsize(self, m):
X try:
X self.text = self.text
X except NameError:
X self.text = ''
X return m.textwidth(self.text) + 6, m.lineheight() + 6
X #
X def getbounds(self):
X return self.bounds
X #
X # Changing the parameters
X #
X def settext(self, text):
X self.text = text
X if self.bounds <> _rect.empty:
X self.recalctextpos()
X self.redraw()
X #
X def setbounds(self, bounds):
X if self.bounds <> _rect.empty:
X self.parent.change(self.bounds)
X self.bounds = bounds
X if self.bounds <> _rect.empty:
X self.recalc()
X self.parent.change(bounds)
X #
X # Changing the state bits
X #
X def enable(self, flag):
X if flag <> self.enabled:
X self.enabled = flag
X if self.bounds <> _rect.empty:
X self.flipenable(self.parent.begindrawing())
X #
X def hilite(self, flag):
X if flag <> self.hilited:
X self.hilited = flag
X if self.bounds <> _rect.empty:
X self.fliphilite(self.parent.begindrawing())
X #
X def select(self, flag):
X if flag <> self.selected:
X self.selected = flag
X if self.bounds <> _rect.empty:
X self.redraw()
X #
X # Recalculate the box bounds and text position.
X # This can be overridden by buttons that draw different boxes
X # or want their text in a different position.
X #
X def recalc(self):
X if self.bounds <> _rect.empty:
X self.recalcbounds()
X self.recalctextpos()
X #
X def recalcbounds(self):
X self.hilitebounds = _rect.inset(self.bounds, (3, 3))
X self.crossbounds = self.bounds
X #
X def recalctextpos(self):
X (left, top), (right, bottom) = self.bounds
X m = self.parent.beginmeasuring()
X h = (left + right - m.textwidth(self.text)) / 2
X v = (top + bottom - m.lineheight()) / 2
X self.textpos = h, v
X #
X # Generic drawing interface.
X # Do not override redraw() or draw() methods; override drawit() c.s.
X #
X def redraw(self):
X if self.bounds <> _rect.empty:
X self.draw(self.parent.begindrawing(), self.bounds)
X #
X def draw(self, (d, area)):
X area = _rect.intersect(area, self.bounds)
X if area = _rect.empty:
X return
X d.cliprect(area)
X d.erase(self.bounds)
X self.drawit(d)
X d.noclip()
X #
X # The drawit() method is fairly generic but may be overridden.
X #
X def drawit(self, d):
X self.drawpict(d)
X if self.text:
X d.text(self.textpos, self.text)
X if not self.enabled:
X self.flipenable(d)
X if self.hilited:
X self.fliphilite(d)
X #
X # Default drawing detail functions.
X # Overriding these is normally sufficient to get different
X # appearances.
X #
X def drawpict(self, d):
X pass
X #
X def flipenable(self, d):
X _xorcross(d, self.crossbounds)
X #
X def fliphilite(self, d):
X d.invert(self.hilitebounds)
X
X
X# ButtonAppearance displays a centered string in a box.
X# selected --> bold border
X# disabled --> crossed out
X# hilited --> inverted
X#
Xclass ButtonAppearance() = LabelAppearance():
X #
X def drawpict(self, d):
X d.box(_rect.inset(self.bounds, (1, 1)))
X if self.selected:
X # Make a thicker box
X d.box(self.bounds)
X d.box(_rect.inset(self.bounds, (2, 2)))
X d.box(_rect.inset(self.bounds, (3, 3)))
X #
X
X
X# CheckAppearance displays a small square box and a left-justified string.
X# selected --> a cross appears in the box
X# disabled --> whole button crossed out
X# hilited --> box is inverted
X#
Xclass CheckAppearance() = LabelAppearance():
X #
X def minsize(self, m):
X width, height = m.textwidth(self.text) + 6, m.lineheight() + 6
X return width + height + m.textwidth(' '), height
X #
X def drawpict(self, d):
X d.box(self.boxbounds)
X if self.selected: _xorcross(d, self.boxbounds)
X #
X def recalcbounds(self):
X LabelAppearance.recalcbounds(self)
X (left, top), (right, bottom) = self.bounds
X self.size = bottom - top - 4
X self.boxbounds = (left+2, top+2), (left+2+self.size, bottom-2)
X self.hilitebounds = self.boxbounds
X #
X def recalctextpos(self):
X m = self.parent.beginmeasuring()
X (left, top), (right, bottom) = self.boxbounds
X h = right + m.textwidth(' ')
X v = top + (self.size - m.lineheight()) / 2
X self.textpos = h, v
X #
X
X
X# RadioAppearance displays a round indicator and a left-justified string.
X# selected --> a dot appears in the indicator
X# disabled --> whole button crossed out
X# hilited --> indicator is inverted
X#
Xclass RadioAppearance() = CheckAppearance():
X #
X def drawpict(self, d):
X (left, top), (right, bottom) = self.boxbounds
X radius = self.size / 2
X h, v = left + radius, top + radius
X d.circle((h, v), radius)
X if self.selected:
X some = radius/3
X d.paint((h-some, v-some), (h+some, v+some))
X #
X
X
X# NoReactivity ignores mouse events.
X#
Xclass NoReactivity():
X def init_reactivity(self): pass
X
X
X# BaseReactivity defines hooks and asks for mouse events,
X# but provides only dummy mouse event handlers.
X# The trigger methods call the corresponding hooks set by the user.
X# Hooks (and triggers) mean the following:
X# down_hook called on some mouse-down events
X# move_hook called on some mouse-move events
X# up_hook called on mouse-up events
X# on_hook called for buttons with on/off state, when it goes on
X# hook called when a button 'fires' or a radiobutton goes on
X# There are usually extra conditions, e.g., hooks are only called
X# when the button is enabled, or active, or selected (on).
X#
Xclass BaseReactivity():
X #
X def init_reactivity(self):
X self.down_hook = self.move_hook = self.up_hook = \
X self.on_hook = self.off_hook = \
X self.hook = self.active = 0
X self.parent.need_mouse(self)
X #
X def mousetest(self, hv):
X return _rect.pointinrect(hv, self.bounds)
X #
X def mouse_down(self, detail):
X pass
X #
X def mouse_move(self, detail):
X pass
X #
X def mouse_up(self, detail):
X pass
X #
X def down_trigger(self):
X if self.down_hook: self.down_hook(self)
X #
X def move_trigger(self):
X if self.move_hook: self.move_hook(self)
X #
X def up_trigger(self):
X if self.up_hook: self.up_hook(self)
X #
X def on_trigger(self):
X if self.on_hook: self.on_hook(self)
X #
X def off_trigger(self):
X if self.off_hook: self.off_hook(self)
X #
X def trigger(self):
X if self.hook: self.hook(self)
X
X
X# ToggleReactivity acts like a simple pushbutton.
X# It toggles its hilite state on mouse down events.
X#
Xclass ToggleReactivity() = BaseReactivity():
X #
X def mouse_down(self, detail):
X if self.enabled and self.mousetest(detail[_HV]):
X self.active = 1
X self.hilite(not self.hilited)
X self.down_trigger()
X #
X def mouse_move(self, detail):
X if self.active:
X self.move_trigger()
X #
X def mouse_up(self, detail):
X if self.active:
X self.up_trigger()
X self.active = 0
X #
X def down_trigger(self):
X if self.hilited:
X self.on_trigger()
X else:
X self.off_trigger()
X self.trigger()
X #
X
X
X# TriggerReactivity acts like a fancy pushbutton.
X# It hilites itself while the mouse is down within its bounds.
X#
Xclass TriggerReactivity() = BaseReactivity():
X #
X def mouse_down(self, detail):
X if self.enabled and self.mousetest(detail[_HV]):
X self.active = 1
X self.hilite(1)
X self.down_trigger()
X #
X def mouse_move(self, detail):
X if self.active:
X self.hilite(self.mousetest(detail[_HV]))
X if self.hilited:
X self.move_trigger()
X #
X def mouse_up(self, detail):
X if self.active:
X self.hilite(self.mousetest(detail[_HV]))
X if self.hilited:
X self.up_trigger()
X self.trigger()
X self.active = 0
X self.hilite(0)
X #
X
X
X# CheckReactivity handles mouse events like TriggerReactivity,
X# It overrides the up_trigger method to flip its selected state.
X#
Xclass CheckReactivity() = TriggerReactivity():
X #
X def up_trigger(self):
X self.select(not self.selected)
X if self.selected:
X self.on_trigger()
X else:
X self.off_trigger()
X self.trigger()
X
X
X# RadioReactivity turns itself on and the other buttons in its group
X# off when its up_trigger method is called.
X#
Xclass RadioReactivity() = TriggerReactivity():
X #
X def init_reactivity(self):
X TriggerReactivity.init_reactivity(self)
X self.group = []
X #
X def up_trigger(self):
X for b in self.group:
X if b <> self:
X if b.selected:
X b.select(0)
X b.off_trigger()
X self.select(1)
X self.on_trigger()
X self.trigger()
X
X
X# Auxiliary class for 'define' method.
X# Call the initializers in the right order.
X#
Xclass Define():
X #
X def define(self, parent):
X self.parent = parent
X parent.addchild(self)
X self.init_appearance()
X self.init_reactivity()
X return self
X #
X def destroy(self):
X self.parent = 0
X #
X def definetext(self, (parent, text)):
X self = self.define(parent)
X self.settext(text)
X return self
X
X
X# Subroutine to cross out a rectangle.
X#
Xdef _xorcross(d, bounds):
X ((left, top), (right, bottom)) = bounds
X # This is s bit funny to make it look better
X left = left + 2
X right = right - 2
X top = top + 2
X bottom = bottom - 3
X d.xorline(((left, top), (right, bottom)))
X d.xorline((left, bottom), (right, top))
X
X
X# Ready-made button classes.
X#
Xclass Label() = NoReactivity(), LabelAppearance(), Define(): pass
Xclass PushButton() = TriggerReactivity(), ButtonAppearance(), Define(): pass
Xclass CheckButton() = CheckReactivity(), CheckAppearance(), Define(): pass
Xclass RadioButton() = RadioReactivity(), RadioAppearance(), Define(): pass
Xclass ToggleButton() = ToggleReactivity(), ButtonAppearance(), Define(): pass
EOF
fi
if test -s 'lib/TclUtil.py'
then echo '*** I will not over-write existing file lib/TclUtil.py'
else
echo 'x - lib/TclUtil.py'
sed 's/^X//' > 'lib/TclUtil.py' << 'EOF'
X# Utilities used by 'Tcl' emulator.
X
X
X# Many functions in this file parse specific constructs from strings.
X# In order to limit the number of slice operations (the strings can
X# be very large), they always receive indices into the string that
X# indicate the slice of the string that should be considered.
X# The return value is in general another index, pointing to the first
X# character in the string beyond the recognized construct.
X# Errors are reported as exceptions (TclSyntaxError, TclMatchingError).
X# A few functions have multiple return values.
X
X
X# For efficiency, the Tcl "tokenizing" routines used pre-compiled
X# regular expressions. This is less readable but should be much faster
X# than scanning the string a character at a time.
X#
X# The global variables
X# containing the compiled regexp's are named _foo_prog where foo is
X# an indication of the function that uses them.
X#
X# The patterns always
X# have the form <something>* so they always match at the start of the
X# search buffer---maybe with the empty string. This makes it possible
X# to use the expression "_foo_prog.exec(str, i)[0][1]" to find the first
X# character beyond the matched string. Note that this may be beyond the
X# end variable -- where this matters, "min(i, end)" is used.
X
X# Constructs that cannot
X# be recognized by a finite automaton (like matching braces) are scanned
X# by a hybrid technique where the regular expression excludes the
X# braces.
X#
X# Many regular expressions contain an expression that matches
X# a Tcl backslash sequence as a subpart:
X# \\\\C?M?(.|\n)
X#
X# This is a bit hard to
X# read because the backslash contained in it must be doubled twice:
X# once to get past Python's backslash mechanism, once to get past that
X# of regular expressions. It uses (.|\n) to match absolutely
X# *every character*, becase the MULTILINE regular expression package does
X# not accept '\n' as a match for '.'.
X#
X# There is also a simplification in the pattern for backslashes:
X# *any* single character following a backslash is escaped,
X# so hex and octal
X# excapes are not scanned fully. The forms \Cx, \Mx and \CMx are
X# scanned correctly, as these may hide a special character.
X# (This does not invalidate the recognition of strings, although the
X# match is effectuated in a different way than by the Backslash function.)
X
Ximport regexp
X
X
X# Exceptions raised for various error conditions.
X
XTclAssertError = 'Tcl assert error'
XTclSyntaxError = 'Tcl syntax error'
XTclRuntimeError = 'Tcl runtime error'
XTclMatchingError = 'Tcl matching error'
X
X
X# Find a variable name.
X# A variable name is either a (possiblly empty) sequence of letters,
X# digits and underscores, or anything enclosed in matching braces.
X# Return the index past the end of the name.
X
X_varname_prog = regexp.compile('[a-zA-Z0-9_]*')
X
Xdef FindVarName(str, i, end):
X if i < end and str[i] = '{': return BalanceBraces(str, i, end)
X i = _varname_prog.exec(str, i)[0][1]
X return min(i, end)
X
X
X# Split a list into its elements.
X# Return a list of elements (strings).
X
Xdef SplitList(str):
X i, end = 0, len(str)
X list = []
X while 1:
X i = SkipSpaces(str, i, end)
X if i >= end: break
X j = i
X i = FindNextElement(str, i, end)
X if str[j] = '{' and str[i-1] = '}':
X element = str[j+1:i-1]
X else:
X element = Collapse(str[j:i])
X list.append(element)
X return list
X
X
X# Find the next element from a list.
X
X_element_prog = regexp.compile('([^ \t\n\\]+|\\\\C?M?(.|\n))*')
X
Xdef FindNextElement(str, i, end):
X if i < end and str[i] = '{':
X i = BalanceBraces(str, i, end)
X if i < end and str[i] not in ' \t\n':
X raise TclSyntaxError, 'Garbage after } in list'
X return i
X i = _element_prog.exec(str, i)[0][1]
X return min(i, end)
X
X
X# Copy a string, expanding all backslash sequences.
X
X_collapse_prog = regexp.compile('(\n|[^\\]+)*')
X
Xdef Collapse(str):
X if '\\' not in str: return str
X i, end = 0, len(str)
X result = ''
X while i < end:
X j = _collapse_prog.exec(str, i)[0][1]
X j = min(j, end)
X result = result + str[i:j]
X if j >= end: break
X c = str[j]
X if c <> '\\': raise TclAssertError, 'collapse error'
X x, i = Backslash(str, j, end)
X result = result + x
X return result
X
X
X# Find the next full command.
X# Return a list of begin, end indices of words in the string,
X# and an index pointing just after the terminating newline or
X# semicolon.
X# Initial spaces are skipped.
X# If the command begins with '#', it is considered empty and
X# characters until '\n' are skipped.
X
X_eol_prog = regexp.compile('[^\n]*')
X
Xdef FindNextCommand(str, i, end, bracketed):
X i = SkipSpaces(str, i, end)
X if i >= end: return [], end
X if str[i] = '#':
X i = _eol_prog.exec(str, i)
X i = min(i, end)
X if i < end and str[i] = '\n': i = i+1
X return [], i
X if bracketed: terminators = [';']
X else: terminators = [';', '\n']
X list = []
X while i < end:
X j = FindNextWord(str, i, end)
X word = str[i:j]
X if word in terminators:
X i = j
X break
X if word <> '\n': list.append(i, j)
X i = SkipSpaces(str, j, end)
X return list, i
X
X
X# Find the next word of a command.
X# Semicolon and newline terminate words but also count as a word
X# themselves.
X# The start index must point to the start of the word.
X
X_word_prog = regexp.compile('([^ \t\n;[\\]+|\\\\C?M?(.|\n))*')
X
Xdef FindNextWord(str, i, end):
X if i >= end: return end
X if str[i] in '{"':
X if str[i] = '{': i = BalanceBraces(str, i, end)
X else: i = BalanceQuotes(str, i, end)
X if i >= end or str[i] in ' \t\n;': return min(i, end)
X raise TclSyntaxError, 'Garbage after } or "'
X begin = i
X while i < end:
X i = _word_prog.exec(str, i)[0][1]
X if i >= end:
X i = end
X break
X c = str[i]
X if c in ' \t': break
X if c in ';\n':
X if i = begin: i = i+1
X break
X if c = '[': i = BalanceBrackets(str, i, end)
X else: raise TclAssertError, 'word error'
X return i
X
X
X# Parse balanced brackets from str[i:end].
X# str[i] must be '['.
X# Returns end such that str[i:end] ends with ']'
X# and contains balanced braces and brackets.
X
X_brackets_prog = regexp.compile('([^][{\\]+|\n|\\\\C?M?(.|\n))*')
X
Xdef BalanceBrackets(str, i, end):
X if i >= end or str[i] <> '[':
X raise TclAssertError, 'BalanceBrackets'
X nesting = 0
X while i < end:
X i = _brackets_prog.exec(str, i)[0][1]
X if i >= end: break
X c = str[i]
X if c = '{': i = BalanceBraces(str, i, end)
X else:
X i = i+1
X if c = '[': nesting = nesting + 1
X elif c = ']':
X nesting = nesting - 1
X if nesting = 0: return i
X else: raise TclAssertError, 'brackets error'
X raise TclMatchingError, 'Unmatched bracket ([)'
X
X
X# Parse balanced braces from str[i:end].
X# str[i] must be '{'.
X# Returns end such that str[i:end] ends with '}'
X# and contains balanced braces.
X
X_braces_prog = regexp.compile('([^{}\\]+|\n|\\\\C?M?(.|\n))*')
X
Xdef BalanceBraces(str, i, end):
X if i >= end or str[i] <> '{':
X raise TclAssertError, 'BalanceBraces'
X nesting = 0
X while i < end:
X i = _braces_prog.exec(str, i)[0][1]
X if i >= end: break
X c = str[i]
X i = i+1
X if c = '{': nesting = nesting + 1
X elif c = '}':
X nesting = nesting - 1
X if nesting = 0: return i
X else: raise TclAssertError, 'braces error'
X raise TclMatchingError, 'Unmatched brace ({)'
X
X
X# Parse double quotes from str[i:end].
X# str[i] must be '"'.
X# Returns end such that str[i:end] ends with an unescaped '"'.
X
X_quotes_prog = regexp.compile('([^"\\]+|\n|\\\\C?M?(.|\n))*')
X
Xdef BalanceQuotes(str, i, end):
X if i >= end or str[i] <> '"':
X raise TclAssertError, 'BalanceQuotes'
X i = _quotes_prog.exec(str, i+1)[0][1]
X if i < end and str[i] = '"': return i+1
X raise TclMatchingError, 'Unmatched quote (")'
X
X
X# Static data used by Backslash()
X
X_bstab = {}
X_bstab['n'] = '\n'
X_bstab['r'] = '\r'
X_bstab['t'] = '\t'
X_bstab['b'] = '\b'
X_bstab['e'] = '\033'
X_bstab['\n'] = ''
Xfor c in ' {}[]$";\\': _bstab[c] = c
Xdel c
X
X# Backslash interpretation.
X# First character must be a backslash.
X# Return a pair (<replacement string>, <end of sequence>).
X# Unrecognized or incomplete backslash sequences are not errors;
X# this takes only the backslash itself off the string.
X
Xdef Backslash(str, i, end):
X if i >= end or str[i] <> '\\':
X raise TclAssertError, 'Backslash'
X i = i+1
X if i = end: return '\\', i
X c = str[i]
X i = i+1
X if _bstab.has_key(c): return _bstab[c], i
X if c = 'C':
X if i = end: return '\\', i-1
X c = str[i]
X i = i+1
X if c = 'M':
X if i = end: return '\\', i-2
X c = str[i]
X i = i+1
X x = ord(c) % 040 + 0200
X else:
X x = ord(c) % 040
X return chr(x), i
X elif c = 'M':
X if i = end: return '\\', i-1
X c = str[i]
X i = i+1
X x = ord(c)
X if x < 0200: x = x + 0200
X return chr(x), i
X elif c and c in '0123456789':
X x = ord(c) - ord('0')
X end = min(end, i+2)
X while i < end:
X c = str[i]
X if c not in '0123456789': break
X i = i+1
X x = x*8 + ord(c) - ord('0')
X return ord(x), i
X else:
X # Not something that we recognize
X return '\\', i-1
X
X
X# Skip over spaces and tabs (but not newlines).
X
X_spaces_prog = regexp.compile('[ \t]*')
X
Xdef SkipSpaces(str, i, end):
X i = _spaces_prog.exec(str, i)[0][1]
X return min(i, end)
X
X
X# Concatenate the elements of a list with intervening spaces.
X
Xdef Concat(argv):
X result = ''
X sep = ''
X for arg in argv:
X result = result + (sep + arg)
X sep = ' '
X return result
X
X
X# Concatenate list elements, adding braces etc. to make them parseable
X# again with SplitList.
X
Xdef BuildList(argv):
X result = ''
X sep = ''
X for arg in argv:
X arg = AddBraces(arg)
X result = result + (sep + arg)
X sep = ' '
X return result
X
X
X# Add braces around a string if necessary to make it parseable by SplitList.
X
Xdef AddBraces(str):
X # Special case for empty string
X if str = '': return '{}'
X # See if it contains balanced braces
X res = '{' + str + '}'
X if TryNextElement(res):
X # See if it would survive unquoted
X # XXX should escape [] and $ as well???
X if TryNextElement(str) and Collapse(str) = str: return str
X # No -- return with added braces
X return res
X # Unbalanced braces. Add backslashes before suspect characters
X res = ''
X for c in str:
X if c in '$\\[]{} ;': c = '\\' + c
X elif c = '\n': c = '\\n'
X elif c = '\t': c = '\\t'
X res = res + c
X return res
X
X
Xdef TryNextElement(str):
X end = len(str)
X try:
X i = FindNextElement(str, 0, end)
X return i = end
X except (TclSyntaxError, TclMatchingError):
X return 0
EOF
fi
if test -s 'lib/testall.py'
then echo '*** I will not over-write existing file lib/testall.py'
else
echo 'x - lib/testall.py'
sed 's/^X//' > 'lib/testall.py' << 'EOF'
X# Module 'testall'
X#
X# Python test set, should exercise:
X# - all lexical and grammatical constructs
X# - all opcodes from "opcode.h"
X# - all operations on all object types
X# - all builtin functions
X# Ideally also:
X# - all possible exception situations (Thank God we've got 'try')
X# - all boundary cases
X
X
XTestFailed = 'testall -- test failed' # Exception
X
X
X#########################################################
X# Part 1. Test all lexical and grammatical constructs.
X# This just tests whether the parser accepts them all.
X#########################################################
X
Xprint '1. Parser'
X
Xprint '1.1 Tokens'
X
Xprint '1.1.1 Backslashes'
X
X# Backslash means line continuation:
Xx = 1 \
X+ 1
Xif x <> 2: raise TestFailed, 'backslash for line continuation'
X
X# Backslash does not means continuation in comments :\
Xx = 0
Xif x <> 0: raise TestFailed, 'backslash ending comment'
X
Xprint '1.1.2 Number formats'
X
Xif 0xff <> 255: raise TestFailed, 'hex number'
Xif 0377 <> 255: raise TestFailed, 'octal number'
Xx = 3.14
Xx = 0.314
Xx = 3e14
Xx = 3E14
Xx = 3e-14
X
Xprint '1.2 Grammar'
X
Xprint 'single_input' # NEWLINE | simple_stmt | compound_stmt NEWLINE
X# XXX can't test in a script -- this rule is only used when interactive
X
Xprint 'file_input' # (NEWLINE | stmt)* ENDMARKER
X# Being tested as this very moment this very module
X
Xprint 'expr_input' # testlist NEWLINE
X# XXX Hard to test -- used only in calls to input()
X
Xprint 'eval_input' # testlist ENDMARKER
Xx = eval('1, 0 or 1')
X
Xprint 'funcdef' # 'def' NAME parameters ':' suite
X### parameters: '(' [fplist] ')'
X### fplist: fpdef (',' fpdef)*
X### fpdef: NAME | '(' fplist ')'
Xdef f1(): pass
Xdef f2(one_argument): pass
Xdef f3(two, arguments): pass
Xdef f4(two, (compound, (arguments))): pass
X
X### stmt: simple_stmt | compound_stmt
X### simple_stmt: expr_stmt | print_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt
X# Tested below
X
Xprint 'expr_stmt' # (exprlist '=')* exprlist NEWLINE
X1
X1, 2, 3
Xx = 1
Xx = 1, 2, 3
Xx = y = z = 1, 2, 3
Xx, y, z = 1, 2, 3
Xabc = a, b, c = x, y, z = xyz = 1, 2, (3, 4)
X# NB these variables are deleted below
X
Xprint 'print_stmt' # 'print' (test ',')* [test] NEWLINE
Xprint 1, 2, 3
Xprint 1, 2, 3,
Xprint
Xprint 0 or 1, 0 or 1,
Xprint 0 or 1
X
Xprint 'del_stmt' # 'del' exprlist NEWLINE
Xdel abc
Xdel x, y, (z, xyz)
X
Xprint 'pass_stmt' # 'pass' NEWLINE
Xpass
X
Xprint 'flow_stmt' # break_stmt | return_stmt | raise_stmt
X# Tested below
X
Xprint 'break_stmt' # 'break' NEWLINE
Xwhile 1: break
X
Xprint 'return_stmt' # 'return' [testlist] NEWLINE
Xdef g1(): return
Xdef g2(): return 1
Xg1()
Xx = g2()
X
Xprint 'raise_stmt' # 'raise' expr [',' expr] NEWLINE
Xtry: raise RuntimeError, 'just testing'
Xexcept RuntimeError: pass
Xtry: raise KeyboardInterrupt
Xexcept KeyboardInterrupt: pass
X
Xprint 'import_stmt' # 'import' NAME (',' NAME)* NEWLINE | 'from' NAME 'import' ('*' | NAME (',' NAME)*) NEWLINE
X[1]
Ximport sys
X[2]
Ximport time, math
X[3]
Xfrom time import sleep
X[4]
Xfrom math import *
X[5]
Xfrom sys import modules, ps1, ps2
X[6]
X
X### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
X# Tested below
X
Xprint 'if_stmt' # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
Xif 1: pass
Xif 1: pass
Xelse: pass
Xif 0: pass
Xelif 0: pass
Xif 0: pass
Xelif 0: pass
Xelif 0: pass
Xelif 0: pass
Xelse: pass
X
Xprint 'while_stmt' # 'while' test ':' suite ['else' ':' suite]
Xwhile 0: pass
Xwhile 0: pass
Xelse: pass
X
Xprint 'for_stmt' # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
X[1]
Xfor i in 1, 2, 3: pass
X[2]
Xfor i, j, k in (): pass
Xelse: pass
X[3]
X
Xprint 'try_stmt' # 'try' ':' suite (except_clause ':' suite)* ['finally' ':' suite]
X### except_clause: 'except' [expr [',' expr]]
Xtry: pass
Xtry: 1/0
Xexcept RuntimeError: pass
Xtry: 1/0
Xexcept EOFError: pass
Xexcept TypeError, msg: pass
Xexcept RuntimeError, msg: pass
Xexcept: pass
Xtry: pass
Xfinally: pass
Xtry: 1/0
Xexcept: pass
Xfinally: pass
X
Xprint 'suite' # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT
Xif 1: pass
Xif 1:
X pass
Xif 1:
X #
X #
X #
X pass
X pass
X #
X pass
X #
X
Xprint 'test' # and_test ('or' and_test)*
X### and_test: not_test ('and' not_test)*
X### not_test: 'not' not_test | comparison
X### comparison: expr (comp_op expr)*
X### comp_op: '<'|'>'|'='|'>' '='|'<' '='|'<' '>'|'in'|'not' 'in'|'is'|'is' 'not'
Xif 1: pass
Xif 1 = 1: pass
Xif 1 < 1 > 1 = 1 >= 1 <= 1 <> 1 in 1 not in 1 is 1 is not 1: pass
Xif not 1 = 1 = 1: pass
Xif not 1 = 1 and 1 and 1: pass
Xif 1 and 1 or 1 and 1 and 1 or not 1 = 1 = 1 and 1: pass
X
Xprint 'expr' # term (('+'|'-') term)*
Xx = 1
Xx = 1 + 1
Xx = 1 - 1 - 1
Xx = 1 - 1 + 1 - 1 + 1
X
Xprint 'term' # factor (('*'|'/'|'%') factor)*
Xx = 1 * 1
Xx = 1 / 1
Xx = 1 % 1
Xx = 1 / 1 * 1 % 1
X
Xprint 'factor' # ('+'|'-') factor | atom trailer*
X### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME
X### subscript: expr | [expr] ':' [expr]
Xx = +1
Xx = -1
Xx = 1
Xc = sys.ps1[0]
Xx = time.time()
Xx = sys.modules['time'].time()
Xa = '01234'
Xc = a[0]
Xc = a[0:5]
Xc = a[:5]
Xc = a[0:]
Xc = a[:]
Xc = a[-5:]
Xc = a[:-1]
Xc = a[-4:-3]
X
Xprint 'atom' # '(' [testlist] ')' | '[' [testlist] ']' | '{' '}' | '`' testlist '`' | NAME | NUMBER | STRING
Xx = (1)
Xx = (1 or 2 or 3)
Xx = (1 or 2 or 3, 2, 3)
Xx = []
Xx = [1]
Xx = [1 or 2 or 3]
Xx = [1 or 2 or 3, 2, 3]
Xx = []
Xx = {}
Xx = `x`
Xx = x
Xx = 'x'
Xx = 123
X
X### exprlist: expr (',' expr)* [',']
X### testlist: test (',' test)* [',']
X# These have been exercised enough above
X
Xprint 'classdef' # 'class' NAME parameters ['=' baselist] ':' suite
X### baselist: atom arguments (',' atom arguments)*
X### arguments: '(' [testlist] ')'
Xclass B(): pass
Xclass C1() = B(): pass
Xclass C2() = B(): pass
Xclass D() = C1(), C2(), B(): pass
Xclass C():
X def meth1(self): pass
X def meth2(self, arg): pass
X def meth3(self, (a1, a2)): pass
X
X
X#########################################################
X# Part 2. Test all opcodes from "opcode.h"
X#########################################################
X
Xprint '2. Opcodes'
Xprint 'XXX Not yet fully implemented'
X
Xprint '2.1 try inside for loop'
Xn = 0
Xfor i in range(10):
X n = n+i
X try: 1/0
X except NameError: pass
X except RuntimeError: pass
X except TypeError: pass
X finally: pass
X try: pass
X except: pass
X try: pass
X finally: pass
X n = n+i
Xif n <> 90:
X raise TestFailed, 'try inside for'
X
X
X#########################################################
X# Part 3. Test all operations on all object types
X#########################################################
X
Xprint '3. Object types'
Xprint 'XXX Not yet implemented'
X
X
X#########################################################
X# Part 4. Test all built-in functions
X#########################################################
X
Xprint '4. Built-in functions'
X
Xprint 'abs'
Xif abs(0) <> 0: raise TestFailed, 'abs(0)'
Xif abs(1234) <> 1234: raise TestFailed, 'abs(1234)'
Xif abs(-1234) <> 1234: raise TestFailed, 'abs(-1234)'
Xif abs(0.0) <> 0.0: raise TestFailed, 'abs(0.0)'
Xif abs(3.14) <> 3.14: raise TestFailed, 'abs(3.14)'
Xif abs(-3.14) <> 3.14: raise TestFailed, 'abs(-3.14)'
X
Xprint 'dir'
Xif 'x' not in dir(): raise TestFailed, 'dir()'
Xif 'modules' not in dir(sys): raise TestFailed, 'dir(sys)'
X
Xprint 'divmod'
Xif divmod(12, 7) <> (1, 5): raise TestFailed, 'divmod(12, 7)'
Xif divmod(-12, 7) <> (-2, 2): raise TestFailed, 'divmod(-12, 7)'
Xif divmod(12, -7) <> (-2, -2): raise TestFailed, 'divmod(12, -7)'
Xif divmod(-12, -7) <> (1, -5): raise TestFailed, 'divmod(-12, -7)'
X
Xprint 'eval'
Xif eval('1+1') <> 2: raise TestFailed, 'eval(\'1+1\')'
X
Xprint 'exec'
Xexec('z=1+1\n')
Xif z <> 2: raise TestFailed, 'exec(\'z=1+1\'\\n)'
X
Xprint 'float'
Xif float(3.14) <> 3.14: raise TestFailed, 'float(3.14)'
Xif float(314) <> 314.0: raise TestFailed, 'float(314)'
X
Xprint 'input'
X# Can't test in a script
X
Xprint 'int'
Xif int(100) <> 100: raise TestFailed, 'int(100)'
Xif int(3.14) <> 3: raise TestFailed, 'int(3.14)'
X
Xprint 'len'
Xif len('123') <> 3: raise TestFailed, 'len(\'123\')'
Xif len(()) <> 0: raise TestFailed, 'len(())'
Xif len((1, 2, 3, 4)) <> 4: raise TestFailed, 'len((1, 2, 3, 4))'
Xif len([1, 2, 3, 4]) <> 4: raise TestFailed, 'len([1, 2, 3, 4])'
Xif len({}) <> 0: raise TestFailed, 'len({})'
X
Xprint 'min'
Xif min('123123') <> '1': raise TestFailed, 'min(\'123123\')'
Xif min(1, 2, 3) <> 1: raise TestFailed, 'min(1, 2, 3)'
Xif min((1, 2, 3, 1, 2, 3)) <> 1: raise TestFailed, 'min((1, 2, 3, 1, 2, 3))'
Xif min([1, 2, 3, 1, 2, 3]) <> 1: raise TestFailed, 'min([1, 2, 3, 1, 2, 3])'
X
Xprint 'max'
Xif max('123123') <> '3': raise TestFailed, 'max(\'123123\')'
Xif max(1, 2, 3) <> 3: raise TestFailed, 'max(1, 2, 3)'
Xif max((1, 2, 3, 1, 2, 3)) <> 3: raise TestFailed, 'max((1, 2, 3, 1, 2, 3))'
Xif max([1, 2, 3, 1, 2, 3]) <> 3: raise TestFailed, 'max([1, 2, 3, 1, 2, 3])'
X
Xprint 'open'
Xprint 'NB! This test creates a file named "@test" in the current directory.'
Xfp = open('@test', 'w')
Xfp.write('The quick brown fox jumps over the lazy dog')
Xfp.write('.\n')
Xfp.write('Dear John\n')
Xfp.write('XXX'*100)
Xfp.write('YYY'*100)
Xfp.close()
Xdel fp
Xfp = open('@test', 'r')
Xif fp.readline() <> 'The quick brown fox jumps over the lazy dog.\n':
X raise TestFailed, 'readline()'
Xif fp.readline(4) <> 'Dear': raise TestFailed, 'readline(4) # short'
Xif fp.readline(100) <> ' John\n': raise TestFailed, 'readline(100)'
Xif fp.read(300) <> 'XXX'*100: raise TestFailed, 'read(300)'
Xif fp.read(1000) <> 'YYY'*100: raise TestFailed, 'read(1000) # truncate'
Xfp.close()
Xdel fp
X
Xprint 'range'
Xif range(3) <> [0, 1, 2]: raise TestFailed, 'range(3)'
Xif range(1, 5) <> [1, 2, 3, 4]: raise TestFailed, 'range(1, 5)'
Xif range(0) <> []: raise TestFailed, 'range(0)'
Xif range(-3) <> []: raise TestFailed, 'range(-3)'
Xif range(1, 10, 3) <> [1, 4, 7]: raise TestFailed, 'range(1, 10, 3)'
Xif range(5, -5, -3) <> [5, 2, -1, -4]: raise TestFailed, 'range(5, -5, -3)'
X
Xprint 'raw_input'
Xsavestdin = sys.stdin
Xtry:
X sys.stdin = open('@test', 'r')
X if raw_input() <> 'The quick brown fox jumps over the lazy dog.':
X raise TestFailed, 'raw_input()'
X if raw_input('testing\n') <> 'Dear John':
X raise TestFailed, 'raw_input(\'testing\\n\')'
Xfinally:
X sys.stdin = savestdin
X
Xprint 'reload'
Ximport string
Xreload(string)
X
Xprint 'type'
Xif type('') <> type('123') or type('') = type(()):
X raise TestFailed, 'type()'
X
X
Xprint 'Passed all tests.'
X
Xtry:
X import mac
X unlink = mac.unlink
Xexcept NameError:
X try:
X import posix
X unlink = posix.unlink
X except NameError:
X pass
X
Xunlink('@test')
Xprint 'Unlinked @test'
EOF
fi
if test -s 'src/listobject.c'
then echo '*** I will not over-write existing file src/listobject.c'
else
echo 'x - src/listobject.c'
sed 's/^X//' > 'src/listobject.c' << 'EOF'
X/***********************************************************
XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The
XNetherlands.
X
X All Rights Reserved
X
XPermission to use, copy, modify, and distribute this software and its
Xdocumentation for any purpose and without fee is hereby granted,
Xprovided that the above copyright notice appear in all copies and that
Xboth that copyright notice and this permission notice appear in
Xsupporting documentation, and that the names of Stichting Mathematisch
XCentrum or CWI not be used in advertising or publicity pertaining to
Xdistribution of the software without specific, written prior permission.
X
XSTICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
XTHIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
XFITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
XFOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
XWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
XACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
XOF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
X
X******************************************************************/
X
X/* List object implementation */
X
X#include "allobjects.h"
X
Xobject *
Xnewlistobject(size)
X int size;
X{
X int i;
X listobject *op;
X if (size < 0) {
X err_badcall();
X return NULL;
X }
X op = (listobject *) malloc(sizeof(listobject));
X if (op == NULL) {
X return err_nomem();
X }
X if (size <= 0) {
X op->ob_item = NULL;
X }
X else {
X op->ob_item = (object **) malloc(size * sizeof(object *));
X if (op->ob_item == NULL) {
X free((ANY *)op);
X return err_nomem();
X }
X }
X NEWREF(op);
X op->ob_type = &Listtype;
X op->ob_size = size;
X for (i = 0; i < size; i++)
X op->ob_item[i] = NULL;
X return (object *) op;
X}
X
Xint
Xgetlistsize(op)
X object *op;
X{
X if (!is_listobject(op)) {
X err_badcall();
X return -1;
X }
X else
X return ((listobject *)op) -> ob_size;
X}
X
Xobject *
Xgetlistitem(op, i)
X object *op;
X int i;
X{
X if (!is_listobject(op)) {
X err_badcall();
X return NULL;
X }
X if (i < 0 || i >= ((listobject *)op) -> ob_size) {
X err_setstr(IndexError, "list index out of range");
X return NULL;
X }
X return ((listobject *)op) -> ob_item[i];
X}
X
Xint
Xsetlistitem(op, i, newitem)
X register object *op;
X register int i;
X register object *newitem;
X{
X register object *olditem;
X if (!is_listobject(op)) {
X if (newitem != NULL)
X DECREF(newitem);
X err_badcall();
X return -1;
X }
X if (i < 0 || i >= ((listobject *)op) -> ob_size) {
X if (newitem != NULL)
X DECREF(newitem);
X err_setstr(IndexError, "list assignment index out of range");
X return -1;
X }
X olditem = ((listobject *)op) -> ob_item[i];
X ((listobject *)op) -> ob_item[i] = newitem;
X if (olditem != NULL)
X DECREF(olditem);
X return 0;
X}
X
Xstatic int
Xins1(self, where, v)
X listobject *self;
X int where;
X object *v;
X{
X int i;
X object **items;
X if (v == NULL) {
X err_badcall();
X return -1;
X }
X items = self->ob_item;
X RESIZE(items, object *, self->ob_size+1);
X if (items == NULL) {
X err_nomem();
X return -1;
X }
X if (where < 0)
X where = 0;
X if (where > self->ob_size)
X where = self->ob_size;
X for (i = self->ob_size; --i >= where; )
X items[i+1] = items[i];
X INCREF(v);
X items[where] = v;
X self->ob_item = items;
X self->ob_size++;
X return 0;
X}
X
Xint
Xinslistitem(op, where, newitem)
X object *op;
X int where;
X object *newitem;
X{
X if (!is_listobject(op)) {
X err_badcall();
X return -1;
X }
X return ins1((listobject *)op, where, newitem);
X}
X
Xint
Xaddlistitem(op, newitem)
X object *op;
X object *newitem;
X{
X if (!is_listobject(op)) {
X err_badcall();
X return -1;
X }
X return ins1((listobject *)op,
X (int) ((listobject *)op)->ob_size, newitem);
X}
X
X/* Methods */
X
Xstatic void
Xlist_dealloc(op)
X listobject *op;
X{
X int i;
X for (i = 0; i < op->ob_size; i++) {
X if (op->ob_item[i] != NULL)
X DECREF(op->ob_item[i]);
X }
X if (op->ob_item != NULL)
X free((ANY *)op->ob_item);
X free((ANY *)op);
X}
X
Xstatic void
Xlist_print(op, fp, flags)
X listobject *op;
X FILE *fp;
X int flags;
X{
X int i;
X fprintf(fp, "[");
X for (i = 0; i < op->ob_size && !StopPrint; i++) {
X if (i > 0) {
X fprintf(fp, ", ");
X }
X printobject(op->ob_item[i], fp, flags);
X }
X fprintf(fp, "]");
X}
X
Xobject *
Xlist_repr(v)
X listobject *v;
X{
X object *s, *t, *comma;
X int i;
X s = newstringobject("[");
X comma = newstringobject(", ");
X for (i = 0; i < v->ob_size && s != NULL; i++) {
X if (i > 0)
X joinstring(&s, comma);
X t = reprobject(v->ob_item[i]);
X joinstring(&s, t);
X DECREF(t);
X }
X DECREF(comma);
X t = newstringobject("]");
X joinstring(&s, t);
X DECREF(t);
X return s;
X}
X
Xstatic int
Xlist_compare(v, w)
X listobject *v, *w;
X{
X int len = (v->ob_size < w->ob_size) ? v->ob_size : w->ob_size;
X int i;
X for (i = 0; i < len; i++) {
X int cmp = cmpobject(v->ob_item[i], w->ob_item[i]);
X if (cmp != 0)
X return cmp;
X }
X return v->ob_size - w->ob_size;
X}
X
Xstatic int
Xlist_length(a)
X listobject *a;
X{
X return a->ob_size;
X}
X
Xstatic object *
Xlist_item(a, i)
X listobject *a;
X int i;
X{
X if (i < 0 || i >= a->ob_size) {
X err_setstr(IndexError, "list index out of range");
X return NULL;
X }
X INCREF(a->ob_item[i]);
X return a->ob_item[i];
X}
X
Xstatic object *
Xlist_slice(a, ilow, ihigh)
X listobject *a;
X int ilow, ihigh;
X{
X listobject *np;
X int i;
X if (ilow < 0)
X ilow = 0;
X else if (ilow > a->ob_size)
X ilow = a->ob_size;
X if (ihigh < 0)
X ihigh = 0;
X if (ihigh < ilow)
X ihigh = ilow;
X else if (ihigh > a->ob_size)
X ihigh = a->ob_size;
X np = (listobject *) newlistobject(ihigh - ilow);
X if (np == NULL)
X return NULL;
X for (i = ilow; i < ihigh; i++) {
X object *v = a->ob_item[i];
X INCREF(v);
X np->ob_item[i - ilow] = v;
X }
X return (object *)np;
X}
X
Xstatic object *
Xlist_concat(a, bb)
X listobject *a;
X object *bb;
X{
X int size;
X int i;
X listobject *np;
X if (!is_listobject(bb)) {
X err_badarg();
X return NULL;
X }
X#define b ((listobject *)bb)
X size = a->ob_size + b->ob_size;
X np = (listobject *) newlistobject(size);
X if (np == NULL) {
X return err_nomem();
X }
X for (i = 0; i < a->ob_size; i++) {
X object *v = a->ob_item[i];
X INCREF(v);
X np->ob_item[i] = v;
X }
X for (i = 0; i < b->ob_size; i++) {
X object *v = b->ob_item[i];
X INCREF(v);
X np->ob_item[i + a->ob_size] = v;
X }
X return (object *)np;
X#undef b
X}
X
Xstatic int
Xlist_ass_item(a, i, v)
X listobject *a;
X int i;
X object *v;
X{
X if (i < 0 || i >= a->ob_size) {
X err_setstr(IndexError, "list assignment index out of range");
X return -1;
X }
X if (v == NULL)
X return list_ass_slice(a, i, i+1, v);
X INCREF(v);
X DECREF(a->ob_item[i]);
X a->ob_item[i] = v;
X return 0;
X}
X
Xstatic int
Xlist_ass_slice(a, ilow, ihigh, v)
X listobject *a;
X int ilow, ihigh;
X object *v;
X{
X object **item;
X int n; /* Size of replacement list */
X int d; /* Change in size */
X int k; /* Loop index */
X#define b ((listobject *)v)
X if (v == NULL)
X n = 0;
X else if (is_listobject(v))
X n = b->ob_size;
X else {
X err_badarg();
X return -1;
X }
X if (ilow < 0)
X ilow = 0;
X else if (ilow > a->ob_size)
X ilow = a->ob_size;
X if (ihigh < 0)
X ihigh = 0;
X if (ihigh < ilow)
X ihigh = ilow;
X else if (ihigh > a->ob_size)
X ihigh = a->ob_size;
X item = a->ob_item;
X d = n - (ihigh-ilow);
X if (d <= 0) { /* Delete -d items; DECREF ihigh-ilow items */
X for (k = ilow; k < ihigh; k++)
X DECREF(item[k]);
X if (d < 0) {
X for (/*k = ihigh*/; k < a->ob_size; k++)
X item[k+d] = item[k];
X a->ob_size += d;
X RESIZE(item, object *, a->ob_size); /* Can't fail */
X a->ob_item = item;
X }
X }
X else { /* Insert d items; DECREF ihigh-ilow items */
X RESIZE(item, object *, a->ob_size + d);
X if (item == NULL) {
X err_nomem();
X return -1;
X }
X for (k = a->ob_size; --k >= ihigh; )
X item[k+d] = item[k];
X for (/*k = ihigh-1*/; k >= ilow; --k)
X DECREF(item[k]);
X a->ob_item = item;
X a->ob_size += d;
X }
X for (k = 0; k < n; k++, ilow++) {
X object *w = b->ob_item[k];
X INCREF(w);
X item[ilow] = w;
X }
X return 0;
X#undef b
X}
X
Xstatic object *
Xins(self, where, v)
X listobject *self;
X int where;
X object *v;
X{
X if (ins1(self, where, v) != 0)
X return NULL;
X INCREF(None);
X return None;
X}
X
Xstatic object *
Xlistinsert(self, args)
X listobject *self;
X object *args;
X{
X int i;
X if (args == NULL || !is_tupleobject(args) || gettuplesize(args) != 2) {
X err_badarg();
X return NULL;
X }
X if (!getintarg(gettupleitem(args, 0), &i))
X return NULL;
X return ins(self, i, gettupleitem(args, 1));
X}
X
Xstatic object *
Xlistappend(self, args)
X listobject *self;
X object *args;
X{
X return ins(self, (int) self->ob_size, args);
X}
X
Xstatic int
Xcmp(v, w)
X char *v, *w;
X{
X return cmpobject(* (object **) v, * (object **) w);
X}
X
Xstatic object *
Xlistsort(self, args)
X listobject *self;
X object *args;
X{
X if (args != NULL) {
X err_badarg();
X return NULL;
X }
X err_clear();
X if (self->ob_size > 1)
X qsort((char *)self->ob_item,
X (int) self->ob_size, sizeof(object *), cmp);
X if (err_occurred())
X return NULL;
X INCREF(None);
X return None;
X}
X
Xint
Xsortlist(v)
X object *v;
X{
X if (v == NULL || !is_listobject(v)) {
X err_badcall();
X return -1;
X }
X v = listsort((listobject *)v, (object *)NULL);
X if (v == NULL)
X return -1;
X DECREF(v);
X return 0;
X}
X
Xstatic struct methodlist list_methods[] = {
X {"append", listappend},
X {"insert", listinsert},
X {"sort", listsort},
X {NULL, NULL} /* sentinel */
X};
X
Xstatic object *
Xlist_getattr(f, name)
X listobject *f;
X char *name;
X{
X return findmethod(list_methods, (object *)f, name);
X}
X
Xstatic sequence_methods list_as_sequence = {
X list_length, /*sq_length*/
X list_concat, /*sq_concat*/
X 0, /*sq_repeat*/
X list_item, /*sq_item*/
X list_slice, /*sq_slice*/
X list_ass_item, /*sq_ass_item*/
X list_ass_slice, /*sq_ass_slice*/
X};
X
Xtypeobject Listtype = {
X OB_HEAD_INIT(&Typetype)
X 0,
X "list",
X sizeof(listobject),
X 0,
X list_dealloc, /*tp_dealloc*/
X list_print, /*tp_print*/
X list_getattr, /*tp_getattr*/
X 0, /*tp_setattr*/
X list_compare, /*tp_compare*/
X list_repr, /*tp_repr*/
X 0, /*tp_as_number*/
X &list_as_sequence, /*tp_as_sequence*/
X 0, /*tp_as_mapping*/
X};
EOF
fi
if test -s 'src/parser.c'
then echo '*** I will not over-write existing file src/parser.c'
else
echo 'x - src/parser.c'
sed 's/^X//' > 'src/parser.c' << 'EOF'
X/***********************************************************
XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The
XNetherlands.
X
X All Rights Reserved
X
XPermission to use, copy, modify, and distribute this software and its
Xdocumentation for any purpose and without fee is hereby granted,
Xprovided that the above copyright notice appear in all copies and that
Xboth that copyright notice and this permission notice appear in
Xsupporting documentation, and that the names of Stichting Mathematisch
XCentrum or CWI not be used in advertising or publicity pertaining to
Xdistribution of the software without specific, written prior permission.
X
XSTICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
XTHIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
XFITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
XFOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
XWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
XACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
XOF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
X
X******************************************************************/
X
X/* Parser implementation */
X
X/* For a description, see the comments at end of this file */
X
X/* XXX To do: error recovery */
X
X#include "pgenheaders.h"
X#include "assert.h"
X#include "token.h"
X#include "grammar.h"
X#include "node.h"
X#include "parser.h"
X#include "errcode.h"
X
X
X#ifdef DEBUG
Xextern int debugging;
X#define D(x) if (!debugging); else x
X#else
X#define D(x)
X#endif
X
X
X/* STACK DATA TYPE */
X
Xstatic void s_reset PROTO((stack *));
X
Xstatic void
Xs_reset(s)
X stack *s;
X{
X s->s_top = &s->s_base[MAXSTACK];
X}
X
X#define s_empty(s) ((s)->s_top == &(s)->s_base[MAXSTACK])
X
Xstatic int s_push PROTO((stack *, dfa *, node *));
X
Xstatic int
Xs_push(s, d, parent)
X register stack *s;
X dfa *d;
X node *parent;
X{
X register stackentry *top;
X if (s->s_top == s->s_base) {
X fprintf(stderr, "s_push: parser stack overflow\n");
X return -1;
X }
X top = --s->s_top;
X top->s_dfa = d;
X top->s_parent = parent;
X top->s_state = 0;
X return 0;
X}
X
X#ifdef DEBUG
X
Xstatic void s_pop PROTO((stack *));
X
Xstatic void
Xs_pop(s)
X register stack *s;
X{
X if (s_empty(s)) {
X fprintf(stderr, "s_pop: parser stack underflow -- FATAL\n");
X abort();
X }
X s->s_top++;
X}
X
X#else /* !DEBUG */
X
X#define s_pop(s) (s)->s_top++
X
X#endif
X
X
X/* PARSER CREATION */
X
Xparser_state *
Xnewparser(g, start)
X grammar *g;
X int start;
X{
X parser_state *ps;
X
X if (!g->g_accel)
X addaccelerators(g);
X ps = NEW(parser_state, 1);
X if (ps == NULL)
X return NULL;
X ps->p_grammar = g;
X ps->p_tree = newtree(start);
X if (ps->p_tree == NULL) {
X DEL(ps);
X return NULL;
X }
X s_reset(&ps->p_stack);
X (void) s_push(&ps->p_stack, finddfa(g, start), ps->p_tree);
X return ps;
X}
X
Xvoid
Xdelparser(ps)
X parser_state *ps;
X{
X /* NB If you want to save the parse tree,
X you must set p_tree to NULL before calling delparser! */
X freetree(ps->p_tree);
X DEL(ps);
X}
X
X
X/* PARSER STACK OPERATIONS */
X
Xstatic int shift PROTO((stack *, int, char *, int, int));
X
Xstatic int
Xshift(s, type, str, newstate, lineno)
X register stack *s;
X int type;
X char *str;
X int newstate;
X int lineno;
X{
X assert(!s_empty(s));
X if (addchild(s->s_top->s_parent, type, str, lineno) == NULL) {
X fprintf(stderr, "shift: no mem in addchild\n");
X return -1;
X }
X s->s_top->s_state = newstate;
X return 0;
X}
X
Xstatic int push PROTO((stack *, int, dfa *, int, int));
X
Xstatic int
Xpush(s, type, d, newstate, lineno)
X register stack *s;
X int type;
X dfa *d;
X int newstate;
X int lineno;
X{
X register node *n;
X n = s->s_top->s_parent;
X assert(!s_empty(s));
X if (addchild(n, type, (char *)NULL, lineno) == NULL) {
X fprintf(stderr, "push: no mem in addchild\n");
X return -1;
X }
X s->s_top->s_state = newstate;
X return s_push(s, d, CHILD(n, NCH(n)-1));
X}
X
X
X/* PARSER PROPER */
X
Xstatic int classify PROTO((grammar *, int, char *));
X
Xstatic int
Xclassify(g, type, str)
X grammar *g;
X register int type;
X char *str;
X{
X register int n = g->g_ll.ll_nlabels;
X
X if (type == NAME) {
X register char *s = str;
X register label *l = g->g_ll.ll_label;
X register int i;
X for (i = n; i > 0; i--, l++) {
X if (l->lb_type == NAME && l->lb_str != NULL &&
X l->lb_str[0] == s[0] &&
X strcmp(l->lb_str, s) == 0) {
X D(printf("It's a keyword\n"));
X return n - i;
X }
X }
X }
X
X {
X register label *l = g->g_ll.ll_label;
X register int i;
X for (i = n; i > 0; i--, l++) {
X if (l->lb_type == type && l->lb_str == NULL) {
X D(printf("It's a token we know\n"));
X return n - i;
X }
X }
X }
X
X D(printf("Illegal token\n"));
X return -1;
X}
X
Xint
Xaddtoken(ps, type, str, lineno)
X register parser_state *ps;
X register int type;
X char *str;
X int lineno;
X{
X register int ilabel;
X
X D(printf("Token %s/'%s' ... ", tok_name[type], str));
X
X /* Find out which label this token is */
X ilabel = classify(ps->p_grammar, type, str);
X if (ilabel < 0)
X return E_SYNTAX;
X
X /* Loop until the token is shifted or an error occurred */
X for (;;) {
X /* Fetch the current dfa and state */
X register dfa *d = ps->p_stack.s_top->s_dfa;
X register state *s = &d->d_state[ps->p_stack.s_top->s_state];
X
X D(printf(" DFA '%s', state %d:",
X d->d_name, ps->p_stack.s_top->s_state));
X
X /* Check accelerator */
X if (s->s_lower <= ilabel && ilabel < s->s_upper) {
X register int x = s->s_accel[ilabel - s->s_lower];
X if (x != -1) {
X if (x & (1<<7)) {
X /* Push non-terminal */
X int nt = (x >> 8) + NT_OFFSET;
X int arrow = x & ((1<<7)-1);
X dfa *d1 = finddfa(ps->p_grammar, nt);
X if (push(&ps->p_stack, nt, d1,
X arrow, lineno) < 0) {
X D(printf(" MemError: push.\n"));
X return E_NOMEM;
X }
X D(printf(" Push ...\n"));
X continue;
X }
X
X /* Shift the token */
X if (shift(&ps->p_stack, type, str,
X x, lineno) < 0) {
X D(printf(" MemError: shift.\n"));
X return E_NOMEM;
X }
X D(printf(" Shift.\n"));
X /* Pop while we are in an accept-only state */
X while (s = &d->d_state
X [ps->p_stack.s_top->s_state],
X s->s_accept && s->s_narcs == 1) {
X D(printf(" Direct pop.\n"));
X s_pop(&ps->p_stack);
X if (s_empty(&ps->p_stack)) {
X D(printf(" ACCEPT.\n"));
X return E_DONE;
X }
X d = ps->p_stack.s_top->s_dfa;
X }
X return E_OK;
X }
X }
X
X if (s->s_accept) {
X /* Pop this dfa and try again */
X s_pop(&ps->p_stack);
X D(printf(" Pop ...\n"));
X if (s_empty(&ps->p_stack)) {
X D(printf(" Error: bottom of stack.\n"));
X return E_SYNTAX;
X }
X continue;
X }
X
X /* Stuck, report syntax error */
X D(printf(" Error.\n"));
X return E_SYNTAX;
X }
X}
X
X
X#ifdef DEBUG
X
X/* DEBUG OUTPUT */
X
Xvoid
Xdumptree(g, n)
X grammar *g;
X node *n;
X{
X int i;
X
X if (n == NULL)
X printf("NIL");
X else {
X label l;
X l.lb_type = TYPE(n);
X l.lb_str = TYPE(str);
X printf("%s", labelrepr(&l));
X if (ISNONTERMINAL(TYPE(n))) {
X printf("(");
X for (i = 0; i < NCH(n); i++) {
X if (i > 0)
X printf(",");
X dumptree(g, CHILD(n, i));
X }
X printf(")");
X }
X }
X}
X
Xvoid
Xshowtree(g, n)
X grammar *g;
X node *n;
X{
X int i;
X
X if (n == NULL)
X return;
X if (ISNONTERMINAL(TYPE(n))) {
X for (i = 0; i < NCH(n); i++)
X showtree(g, CHILD(n, i));
X }
X else if (ISTERMINAL(TYPE(n))) {
X printf("%s", tok_name[TYPE(n)]);
X if (TYPE(n) == NUMBER || TYPE(n) == NAME)
X printf("(%s)", STR(n));
X printf(" ");
X }
X else
X printf("? ");
X}
X
Xvoid
Xprinttree(ps)
X parser_state *ps;
X{
X if (debugging) {
X printf("Parse tree:\n");
X dumptree(ps->p_grammar, ps->p_tree);
X printf("\n");
X printf("Tokens:\n");
X showtree(ps->p_grammar, ps->p_tree);
X printf("\n");
X }
X printf("Listing:\n");
X listtree(ps->p_tree);
X printf("\n");
X}
X
X#endif /* DEBUG */
X
X/*
X
XDescription
X-----------
X
XThe parser's interface is different than usual: the function addtoken()
Xmust be called for each token in the input. This makes it possible to
Xturn it into an incremental parsing system later. The parsing system
Xconstructs a parse tree as it goes.
X
XA parsing rule is represented as a Deterministic Finite-state Automaton
X(DFA). A node in a DFA represents a state of the parser; an arc represents
Xa transition. Transitions are either labeled with terminal symbols or
Xwith non-terminals. When the parser decides to follow an arc labeled
Xwith a non-terminal, it is invoked recursively with the DFA representing
Xthe parsing rule for that as its initial state; when that DFA accepts,
Xthe parser that invoked it continues. The parse tree constructed by the
Xrecursively called parser is inserted as a child in the current parse tree.
X
XThe DFA's can be constructed automatically from a more conventional
Xlanguage description. An extended LL(1) grammar (ELL(1)) is suitable.
XCertain restrictions make the parser's life easier: rules that can produce
Xthe empty string should be outlawed (there are other ways to put loops
Xor optional parts in the language). To avoid the need to construct
XFIRST sets, we can require that all but the last alternative of a rule
X(really: arc going out of a DFA's state) must begin with a terminal
Xsymbol.
X
XAs an example, consider this grammar:
X
Xexpr: term (OP term)*
Xterm: CONSTANT | '(' expr ')'
X
XThe DFA corresponding to the rule for expr is:
X
X------->.---term-->.------->
X ^ |
X | |
X \----OP----/
X
XThe parse tree generated for the input a+b is:
X
X(expr: (term: (NAME: a)), (OP: +), (term: (NAME: b)))
X
X*/
EOF
fi
if test -s 'src/patchlevel.h'
then echo '*** I will not over-write existing file src/patchlevel.h'
else
echo 'x - src/patchlevel.h'
sed 's/^X//' > 'src/patchlevel.h' << 'EOF'
X1
EOF
fi
if test -s 'src/posixmodule.c'
then echo '*** I will not over-write existing file src/posixmodule.c'
else
echo 'x - src/posixmodule.c'
sed 's/^X//' > 'src/posixmodule.c' << 'EOF'
X/***********************************************************
XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The
XNetherlands.
X
X All Rights Reserved
X
XPermission to use, copy, modify, and distribute this software and its
Xdocumentation for any purpose and without fee is hereby granted,
Xprovided that the above copyright notice appear in all copies and that
Xboth that copyright notice and this permission notice appear in
Xsupporting documentation, and that the names of Stichting Mathematisch
XCentrum or CWI not be used in advertising or publicity pertaining to
Xdistribution of the software without specific, written prior permission.
X
XSTICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
XTHIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
XFITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
XFOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
XWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
XACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
XOF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
X
X******************************************************************/
X
X/* POSIX module implementation */
X
X#include <signal.h>
X#include <string.h>
X#include <setjmp.h>
X#include <sys/types.h>
X#include <sys/stat.h>
X#include <sys/time.h>
X#ifdef SYSV
X#include <dirent.h>
X#define direct dirent
X#else
X#include <sys/dir.h>
X#endif
X
X#include "allobjects.h"
X#include "modsupport.h"
X
Xextern char *strerror PROTO((int));
X
X#ifdef AMOEBA
X#define NO_LSTAT
X#endif
X
X
X/* Return a dictionary corresponding to the POSIX environment table */
X
Xextern char **environ;
X
Xstatic object *
Xconvertenviron()
X{
X object *d;
X char **e;
X d = newdictobject();
X if (d == NULL)
X return NULL;
X if (environ == NULL)
X return d;
X /* XXX This part ignores errors */
X for (e = environ; *e != NULL; e++) {
X object *v;
X char *p = strchr(*e, '=');
X if (p == NULL)
X continue;
X v = newstringobject(p+1);
X if (v == NULL)
X continue;
X *p = '\0';
X (void) dictinsert(d, *e, v);
X *p = '=';
X DECREF(v);
X }
X return d;
X}
X
X
Xstatic object *PosixError; /* Exception posix.error */
X
X/* Set a POSIX-specific error from errno, and return NULL */
X
Xstatic object *
Xposix_error()
X{
X return err_errno(PosixError);
X}
X
X
X/* POSIX generic methods */
X
Xstatic object *
Xposix_1str(args, func)
X object *args;
X int (*func) FPROTO((const char *));
X{
X object *path1;
X if (!getstrarg(args, &path1))
X return NULL;
X if ((*func)(getstringvalue(path1)) < 0)
X return posix_error();
X INCREF(None);
X return None;
X}
X
Xstatic object *
Xposix_2str(args, func)
X object *args;
X int (*func) FPROTO((const char *, const char *));
X{
X object *path1, *path2;
X if (!getstrstrarg(args, &path1, &path2))
X return NULL;
X if ((*func)(getstringvalue(path1), getstringvalue(path2)) < 0)
X return posix_error();
X INCREF(None);
X return None;
X}
X
Xstatic object *
Xposix_strint(args, func)
X object *args;
X int (*func) FPROTO((const char *, int));
X{
X object *path1;
X int i;
X if (!getstrintarg(args, &path1, &i))
X return NULL;
X if ((*func)(getstringvalue(path1), i) < 0)
X return posix_error();
X INCREF(None);
X return None;
X}
X
Xstatic object *
Xposix_do_stat(self, args, statfunc)
X object *self;
X object *args;
X int (*statfunc) FPROTO((const char *, struct stat *));
X{
X struct stat st;
X object *path;
X object *v;
X if (!getstrarg(args, &path))
X return NULL;
X if ((*statfunc)(getstringvalue(path), &st) != 0)
X return posix_error();
X v = newtupleobject(10);
X if (v == NULL)
X return NULL;
X#define SET(i, st_member) settupleitem(v, i, newintobject((long)st.st_member))
X SET(0, st_mode);
X SET(1, st_ino);
X SET(2, st_dev);
X SET(3, st_nlink);
X SET(4, st_uid);
X SET(5, st_gid);
X SET(6, st_size);
X SET(7, st_atime);
X SET(8, st_mtime);
X SET(9, st_ctime);
X#undef SET
X if (err_occurred()) {
X DECREF(v);
X return NULL;
X }
X return v;
X}
X
X
X/* POSIX methods */
X
Xstatic object *
Xposix_chdir(self, args)
X object *self;
X object *args;
X{
X extern int chdir PROTO((const char *));
X return posix_1str(args, chdir);
X}
X
Xstatic object *
Xposix_chmod(self, args)
X object *self;
X object *args;
X{
X extern int chmod PROTO((const char *, mode_t));
X return posix_strint(args, chmod);
X}
X
Xstatic object *
Xposix_getcwd(self, args)
X object *self;
X object *args;
X{
X char buf[1026];
X extern char *getcwd PROTO((char *, int));
X if (!getnoarg(args))
X return NULL;
X if (getcwd(buf, sizeof buf) == NULL)
X return posix_error();
X return newstringobject(buf);
X}
X
Xstatic object *
Xposix_link(self, args)
X object *self;
X object *args;
X{
X extern int link PROTO((const char *, const char *));
X return posix_2str(args, link);
X}
X
Xstatic object *
Xposix_listdir(self, args)
X object *self;
X object *args;
X{
X object *name, *d, *v;
X DIR *dirp;
X struct direct *ep;
X if (!getstrarg(args, &name))
X return NULL;
X if ((dirp = opendir(getstringvalue(name))) == NULL)
X return posix_error();
X if ((d = newlistobject(0)) == NULL) {
X closedir(dirp);
X return NULL;
X }
X while ((ep = readdir(dirp)) != NULL) {
X v = newstringobject(ep->d_name);
X if (v == NULL) {
X DECREF(d);
X d = NULL;
X break;
X }
X if (addlistitem(d, v) != 0) {
X DECREF(v);
X DECREF(d);
X d = NULL;
X break;
X }
X DECREF(v);
X }
X closedir(dirp);
X return d;
X}
X
Xstatic object *
Xposix_mkdir(self, args)
X object *self;
X object *args;
X{
X extern int mkdir PROTO((const char *, mode_t));
X return posix_strint(args, mkdir);
X}
X
Xstatic object *
Xposix_rename(self, args)
X object *self;
X object *args;
X{
X extern int rename PROTO((const char *, const char *));
X return posix_2str(args, rename);
X}
X
Xstatic object *
Xposix_rmdir(self, args)
X object *self;
X object *args;
X{
X extern int rmdir PROTO((const char *));
X return posix_1str(args, rmdir);
X}
X
Xstatic object *
Xposix_stat(self, args)
X object *self;
X object *args;
X{
X extern int stat PROTO((const char *, struct stat *));
X return posix_do_stat(self, args, stat);
X}
X
Xstatic object *
Xposix_system(self, args)
X object *self;
X object *args;
X{
X object *command;
X int sts;
X if (!getstrarg(args, &command))
X return NULL;
X sts = system(getstringvalue(command));
X return newintobject((long)sts);
X}
X
Xstatic object *
Xposix_umask(self, args)
X object *self;
X object *args;
X{
X int i;
X if (!getintarg(args, &i))
X return NULL;
X i = umask(i);
X if (i < 0)
X return posix_error();
X return newintobject((long)i);
X}
X
Xstatic object *
Xposix_unlink(self, args)
X object *self;
X object *args;
X{
X extern int unlink PROTO((const char *));
X return posix_1str(args, unlink);
X}
X
Xstatic object *
Xposix_utimes(self, args)
X object *self;
X object *args;
X{
X object *path;
X struct timeval tv[2];
X if (args == NULL || !is_tupleobject(args) || gettuplesize(args) != 2) {
X err_badarg();
X return NULL;
X }
X if (!getstrarg(gettupleitem(args, 0), &path) ||
X !getlonglongargs(gettupleitem(args, 1),
X &tv[0].tv_sec, &tv[1].tv_sec))
X return NULL;
X tv[0].tv_usec = tv[1].tv_usec = 0;
X if (utimes(getstringvalue(path), tv) < 0)
X return posix_error();
X INCREF(None);
X return None;
X}
X
X
X#ifndef NO_LSTAT
X
Xstatic object *
Xposix_lstat(self, args)
X object *self;
X object *args;
X{
X extern int lstat PROTO((const char *, struct stat *));
X return posix_do_stat(self, args, lstat);
X}
X
Xstatic object *
Xposix_readlink(self, args)
X object *self;
X object *args;
X{
X char buf[1024]; /* XXX Should use MAXPATHLEN */
X object *path;
X int n;
X if (!getstrarg(args, &path))
X return NULL;
X n = readlink(getstringvalue(path), buf, sizeof buf);
X if (n < 0)
X return posix_error();
X return newsizedstringobject(buf, n);
X}
X
Xstatic object *
Xposix_symlink(self, args)
X object *self;
X object *args;
X{
X extern int symlink PROTO((const char *, const char *));
X return posix_2str(args, symlink);
X}
X
X#endif /* NO_LSTAT */
X
X
Xstatic struct methodlist posix_methods[] = {
X {"chdir", posix_chdir},
X {"chmod", posix_chmod},
X {"getcwd", posix_getcwd},
X {"link", posix_link},
X {"listdir", posix_listdir},
X {"mkdir", posix_mkdir},
X {"rename", posix_rename},
X {"rmdir", posix_rmdir},
X {"stat", posix_stat},
X {"system", posix_system},
X {"umask", posix_umask},
X {"unlink", posix_unlink},
X {"utimes", posix_utimes},
X#ifndef NO_LSTAT
X {"lstat", posix_lstat},
X {"readlink", posix_readlink},
X {"symlink", posix_symlink},
X#endif
X {NULL, NULL} /* Sentinel */
X};
X
X
Xvoid
Xinitposix()
X{
X object *m, *d, *v;
X
X m = initmodule("posix", posix_methods);
X d = getmoduledict(m);
X
X /* Initialize posix.environ dictionary */
X v = convertenviron();
X if (v == NULL || dictinsert(d, "environ", v) != 0)
X fatal("can't define posix.environ");
X DECREF(v);
X
X /* Initialize posix.error exception */
X PosixError = newstringobject("posix.error");
X if (PosixError == NULL || dictinsert(d, "error", PosixError) != 0)
X fatal("can't define posix.error");
X}
EOF
fi
echo 'Part 11 out of 21 of pack.out complete.'
exit 0