summaryrefslogtreecommitdiffstats
path: root/generic/tclAssembly.c
blob: 120fd9a80e0163bed460b5e89243bdce1aff657a (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
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
/*
 * tclAssembly.c --
 *
 *	Assembler for Tcl bytecodes.
 *
 * This file contains the procedures that convert Tcl Assembly Language (TAL)
 * to a sequence of bytecode instructions for the Tcl execution engine.
 *
 * Copyright (c) 2010 by Ozgur Dogan Ugurlu.
 * Copyright (c) 2010 by Kevin B. Kenny.
 *
 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

/*-
 *- THINGS TO DO:
 *- More instructions:
 *-   done - alternate exit point (affects stack and exception range checking)
 *-   break and continue - if exception ranges can be sorted out.
 *-   foreach_start4, foreach_step4
 *-   returnImm, returnStk
 *-   expandStart, expandStkTop, invokeExpanded, expandDrop
 *-   dictFirst, dictNext, dictDone
 *-   dictUpdateStart, dictUpdateEnd
 *-   jumpTable testing
 *-   syntax (?)
 *-   returnCodeBranch
 *-   tclooNext, tclooNextClass
 */

#include "tclInt.h"
#include "tclCompile.h"
#include "tclOOInt.h"

/*
 * Structure that represents a range of instructions in the bytecode.
 */

typedef struct CodeRange {
    int startOffset;		/* Start offset in the bytecode array */
    int endOffset;		/* End offset in the bytecode array */
} CodeRange;

/*
 * State identified for a basic block's catch context.
 */

typedef enum BasicBlockCatchState {
    BBCS_UNKNOWN = 0,		/* Catch context has not yet been identified */
    BBCS_NONE,			/* Block is outside of any catch */
    BBCS_INCATCH,		/* Block is within a catch context */
    BBCS_CAUGHT 		/* Block is within a catch context and
				 * may be executed after an exception fires */
} BasicBlockCatchState;

/*
 * Structure that defines a basic block - a linear sequence of bytecode
 * instructions with no jumps in or out (including not changing the
 * state of any exception range).
 */

typedef struct BasicBlock {
    int originalStartOffset;	/* Instruction offset before JUMP1s were
				 * substituted with JUMP4's */
    int startOffset;		/* Instruction offset of the start of the
				 * block */
    int startLine;		/* Line number in the input script of the
				 * instruction at the start of the block */
    int jumpOffset;		/* Bytecode offset of the 'jump' instruction
				 * that ends the block, or -1 if there is no
				 * jump. */
    int jumpLine;		/* Line number in the input script of the
				 * 'jump' instruction that ends the block, or
				 * -1 if there is no jump */
    struct BasicBlock* prevPtr;	/* Immediate predecessor of this block */
    struct BasicBlock* predecessor;
				/* Predecessor of this block in the spanning
				 * tree */
    struct BasicBlock* successor1;
				/* BasicBlock structure of the following
				 * block: NULL at the end of the bytecode
				 * sequence. */
    Tcl_Obj* jumpTarget;	/* Jump target label if the jump target is
				 * unresolved */
    int initialStackDepth;	/* Absolute stack depth on entry */
    int minStackDepth;		/* Low-water relative stack depth */
    int maxStackDepth;		/* High-water relative stack depth */
    int finalStackDepth;	/* Relative stack depth on exit */
    enum BasicBlockCatchState catchState;
				/* State of the block for 'catch' analysis */
    int catchDepth;		/* Number of nested catches in which the basic
				 * block appears */
    struct BasicBlock* enclosingCatch;
				/* BasicBlock structure of the last startCatch
				 * executed on a path to this block, or NULL
				 * if there is no enclosing catch */
    int foreignExceptionBase;	/* Base index of foreign exceptions */
    int foreignExceptionCount;	/* Count of foreign exceptions */
    ExceptionRange* foreignExceptions;
				/* ExceptionRange structures for exception
				 * ranges belonging to embedded scripts and
				 * expressions in this block */
    JumptableInfo* jtPtr;	/* Jump table at the end of this basic block */
    int flags;			/* Boolean flags */
} BasicBlock;

/*
 * Flags that pertain to a basic block.
 */

enum BasicBlockFlags {
    BB_VISITED = (1 << 0),	/* Block has been visited in the current
				 * traversal */
    BB_FALLTHRU = (1 << 1),	/* Control may pass from this block to a
				 * successor */
    BB_JUMP1 = (1 << 2),	/* Basic block ends with a 1-byte-offset jump
				 * and may need expansion */
    BB_JUMPTABLE = (1 << 3),	/* Basic block ends with a jump table */
    BB_BEGINCATCH = (1 << 4),	/* Block ends with a 'beginCatch' instruction,
				 * marking it as the start of a 'catch'
				 * sequence. The 'jumpTarget' is the exception
				 * exit from the catch block. */
    BB_ENDCATCH = (1 << 5)	/* Block ends with an 'endCatch' instruction,
				 * unwinding the catch from the exception
				 * stack. */
};

/*
 * Source instruction type recognized by the assembler.
 */

typedef enum TalInstType {
    ASSEM_1BYTE,		/* Fixed arity, 1-byte instruction */
    ASSEM_BEGIN_CATCH,		/* Begin catch: one 4-byte jump offset to be
				 * converted to appropriate exception
				 * ranges */
    ASSEM_BOOL,			/* One Boolean operand */
    ASSEM_BOOL_LVT4,		/* One Boolean, one 4-byte LVT ref. */
    ASSEM_CLOCK_READ,		/* 1-byte unsigned-integer case number, in the
				 * range 0-3 */
    ASSEM_CONCAT1,		/* 1-byte unsigned-integer operand count, must
				 * be strictly positive, consumes N, produces
				 * 1 */
    ASSEM_DICT_GET,		/* 'dict get' and related - consumes N+1
				 * operands, produces 1, N > 0 */
    ASSEM_DICT_SET,		/* specifies key count and LVT index, consumes
				 * N+1 operands, produces 1, N > 0 */
    ASSEM_DICT_UNSET,		/* specifies key count and LVT index, consumes
				 * N operands, produces 1, N > 0 */
    ASSEM_END_CATCH,		/* End catch. No args. Exception range popped
				 * from stack and stack pointer restored. */
    ASSEM_EVAL,			/* 'eval' - evaluate a constant script (by
				 * compiling it in line with the assembly
				 * code! I love Tcl!) */
    ASSEM_INDEX,		/* 4 byte operand, integer or end-integer */
    ASSEM_INVOKE,		/* 1- or 4-byte operand count, must be
				 * strictly positive, consumes N, produces
				 * 1. */
    ASSEM_JUMP,			/* Jump instructions */
    ASSEM_JUMP4,		/* Jump instructions forcing a 4-byte offset */
    ASSEM_JUMPTABLE,		/* Jumptable (switch -exact) */
    ASSEM_LABEL,		/* The assembly directive that defines a
				 * label */
    ASSEM_LINDEX_MULTI,		/* 4-byte operand count, must be strictly
				 * positive, consumes N, produces 1 */
    ASSEM_LIST,			/* 4-byte operand count, must be nonnegative,
				 * consumses N, produces 1 */
    ASSEM_LSET_FLAT,		/* 4-byte operand count, must be >= 3,
				 * consumes N, produces 1 */
    ASSEM_LVT,			/* One operand that references a local
				 * variable */
    ASSEM_LVT1,			/* One 1-byte operand that references a local
				 * variable */
    ASSEM_LVT1_SINT1,		/* One 1-byte operand that references a local
				 * variable, one signed-integer 1-byte
				 * operand */
    ASSEM_LVT4,			/* One 4-byte operand that references a local
				 * variable */
    ASSEM_OVER,			/* OVER: 4-byte operand count, consumes N+1,
				 * produces N+2 */
    ASSEM_PUSH,			/* one literal operand */
    ASSEM_REGEXP,		/* One Boolean operand, but weird mapping to
				 * call flags */
    ASSEM_REVERSE,		/* REVERSE: 4-byte operand count, consumes N,
				 * produces N */
    ASSEM_SINT1,		/* One 1-byte signed-integer operand
				 * (INCR_STK_IMM) */
    ASSEM_SINT4_LVT4		/* Signed 4-byte integer operand followed by
				 * LVT entry.  Fixed arity */
} TalInstType;

/*
 * Description of an instruction recognized by the assembler.
 */

typedef struct TalInstDesc {
    const char *name;		/* Name of instruction. */
    TalInstType instType;	/* The type of instruction */
    int tclInstCode;		/* Instruction code. For instructions having
				 * 1- and 4-byte variables, tclInstCode is
				 * ((1byte)<<8) || (4byte) */
    int operandsConsumed;	/* Number of operands consumed by the
				 * operation, or INT_MIN if the operation is
				 * variadic */
    int operandsProduced;	/* Number of operands produced by the
				 * operation. If negative, the operation has a
				 * net stack effect of -1-operandsProduced */
} TalInstDesc;

/*
 * Structure that holds the state of the assembler while generating code.
 */

typedef struct AssemblyEnv {
    CompileEnv* envPtr;		/* Compilation environment being used for code
				 * generation */
    Tcl_Parse* parsePtr;	/* Parse of the current line of source */
    Tcl_HashTable labelHash;	/* Hash table whose keys are labels and whose
				 * values are 'label' objects storing the code
				 * offsets of the labels. */
    int cmdLine;		/* Current line number within the assembly
				 * code */
    int* clNext;		/* Invisible continuation line for
				 * [info frame] */
    BasicBlock* head_bb;	/* First basic block in the code */
    BasicBlock* curr_bb;	/* Current basic block */
    int maxDepth;		/* Maximum stack depth encountered */
    int curCatchDepth;		/* Current depth of catches */
    int maxCatchDepth;		/* Maximum depth of catches encountered */
    int flags;			/* Compilation flags (TCL_EVAL_DIRECT) */
} AssemblyEnv;

/*
 * Static functions defined in this file.
 */

static void		AddBasicBlockRangeToErrorInfo(AssemblyEnv*,
			    BasicBlock*);
static BasicBlock *	AllocBB(AssemblyEnv*);
static int		AssembleOneLine(AssemblyEnv* envPtr);
static void		BBAdjustStackDepth(BasicBlock* bbPtr, int consumed,
			    int produced);
static void		BBUpdateStackReqs(BasicBlock* bbPtr, int tblIdx,
			    int count);
static void		BBEmitInstInt1(AssemblyEnv* assemEnvPtr, int tblIdx,
			    int opnd, int count);
static void		BBEmitInstInt4(AssemblyEnv* assemEnvPtr, int tblIdx,
			    int opnd, int count);
static void		BBEmitInst1or4(AssemblyEnv* assemEnvPtr, int tblIdx,
			    int param, int count);
static void		BBEmitOpcode(AssemblyEnv* assemEnvPtr, int tblIdx,
			    int count);
static int		BuildExceptionRanges(AssemblyEnv* assemEnvPtr);
static int		CalculateJumpRelocations(AssemblyEnv*, int*);
static int		CheckForUnclosedCatches(AssemblyEnv*);
static int		CheckForThrowInWrongContext(AssemblyEnv*);
static int		CheckNonThrowingBlock(AssemblyEnv*, BasicBlock*);
static int		BytecodeMightThrow(unsigned char);
static int		CheckJumpTableLabels(AssemblyEnv*, BasicBlock*);
static int		CheckNamespaceQualifiers(Tcl_Interp*, const char*,
			    int);
static int		CheckNonNegative(Tcl_Interp*, int);
static int		CheckOneByte(Tcl_Interp*, int);
static int		CheckSignedOneByte(Tcl_Interp*, int);
static int		CheckStack(AssemblyEnv*);
static int		CheckStrictlyPositive(Tcl_Interp*, int);
static ByteCode *	CompileAssembleObj(Tcl_Interp *interp,
			    Tcl_Obj *objPtr);
static void		CompileEmbeddedScript(AssemblyEnv*, Tcl_Token*,
			    const TalInstDesc*);
static int		DefineLabel(AssemblyEnv* envPtr, const char* label);
static void		DeleteMirrorJumpTable(JumptableInfo* jtPtr);
static void		DupAssembleCodeInternalRep(Tcl_Obj* src,
			    Tcl_Obj* dest);
static void		FillInJumpOffsets(AssemblyEnv*);
static int		CreateMirrorJumpTable(AssemblyEnv* assemEnvPtr,
			    Tcl_Obj* jumpTable);
static int		FindLocalVar(AssemblyEnv* envPtr,
			    Tcl_Token** tokenPtrPtr);
static int		FinishAssembly(AssemblyEnv*);
static void		FreeAssembleCodeInternalRep(Tcl_Obj *objPtr);
static void		FreeAssemblyEnv(AssemblyEnv*);
static int		GetBooleanOperand(AssemblyEnv*, Tcl_Token**, int*);
static int		GetListIndexOperand(AssemblyEnv*, Tcl_Token**, int*);
static int		GetIntegerOperand(AssemblyEnv*, Tcl_Token**, int*);
static int		GetNextOperand(AssemblyEnv*, Tcl_Token**, Tcl_Obj**);
static void		LookForFreshCatches(BasicBlock*, BasicBlock**);
static void		MoveCodeForJumps(AssemblyEnv*, int);
static void		MoveExceptionRangesToBasicBlock(AssemblyEnv*, int,
			    int);
static AssemblyEnv*	NewAssemblyEnv(CompileEnv*, int);
static int		ProcessCatches(AssemblyEnv*);
static int		ProcessCatchesInBasicBlock(AssemblyEnv*, BasicBlock*,
			    BasicBlock*, enum BasicBlockCatchState, int);
static void		ResetVisitedBasicBlocks(AssemblyEnv*);
static void		ResolveJumpTableTargets(AssemblyEnv*, BasicBlock*);
static void		ReportUndefinedLabel(AssemblyEnv*, BasicBlock*,
			    Tcl_Obj*);
static void		RestoreEmbeddedExceptionRanges(AssemblyEnv*);
static int		StackCheckBasicBlock(AssemblyEnv*, BasicBlock *,
			    BasicBlock *, int);
static BasicBlock*	StartBasicBlock(AssemblyEnv*, int fallthrough,
			    Tcl_Obj* jumpLabel);
/* static int		AdvanceIp(const unsigned char *pc); */
static int		StackCheckBasicBlock(AssemblyEnv*, BasicBlock *,
			    BasicBlock *, int);
static int		StackCheckExit(AssemblyEnv*);
static void		StackFreshCatches(AssemblyEnv*, BasicBlock*, int,
			    BasicBlock**, int*);
static void		SyncStackDepth(AssemblyEnv*);
static int		TclAssembleCode(CompileEnv* envPtr, const char* code,
			    int codeLen, int flags);
static void		UnstackExpiredCatches(CompileEnv*, BasicBlock*, int,
			    BasicBlock**, int*);

/*
 * Tcl_ObjType that describes bytecode emitted by the assembler.
 */

static const Tcl_ObjType assembleCodeType = {
    "assemblecode",
    FreeAssembleCodeInternalRep, /* freeIntRepProc */
    DupAssembleCodeInternalRep,	 /* dupIntRepProc */
    NULL,			 /* updateStringProc */
    NULL			 /* setFromAnyProc */
};

/*
 * Source instructions recognized in the Tcl Assembly Language (TAL)
 */

static const TalInstDesc TalInstructionTable[] = {
    /* PUSH must be first, see the code near the end of TclAssembleCode */
    {"push",		ASSEM_PUSH,	(INST_PUSH1<<8
					 | INST_PUSH4),		0,	1},

    {"add",		ASSEM_1BYTE,	INST_ADD,		2,	1},
    {"append",		ASSEM_LVT,	(INST_APPEND_SCALAR1<<8
					 | INST_APPEND_SCALAR4),1,	1},
    {"appendArray",	ASSEM_LVT,	(INST_APPEND_ARRAY1<<8
					 | INST_APPEND_ARRAY4),	2,	1},
    {"appendArrayStk",	ASSEM_1BYTE,	INST_APPEND_ARRAY_STK,	3,	1},
    {"appendStk",	ASSEM_1BYTE,	INST_APPEND_STK,	2,	1},
    {"arrayExistsImm",	ASSEM_LVT4,	INST_ARRAY_EXISTS_IMM,	0,	1},
    {"arrayExistsStk",	ASSEM_1BYTE,	INST_ARRAY_EXISTS_STK,	1,	1},
    {"arrayMakeImm",	ASSEM_LVT4,	INST_ARRAY_MAKE_IMM,	0,	0},
    {"arrayMakeStk",	ASSEM_1BYTE,	INST_ARRAY_MAKE_STK,	1,	0},
    {"beginCatch",	ASSEM_BEGIN_CATCH,
					INST_BEGIN_CATCH4,	0,	0},
    {"bitand",		ASSEM_1BYTE,	INST_BITAND,		2,	1},
    {"bitnot",		ASSEM_1BYTE,	INST_BITNOT,		1,	1},
    {"bitor",		ASSEM_1BYTE,	INST_BITOR,		2,	1},
    {"bitxor",		ASSEM_1BYTE,	INST_BITXOR,		2,	1},
    {"clockRead",	ASSEM_CLOCK_READ, INST_CLOCK_READ,	0,	1},
    {"concat",		ASSEM_CONCAT1,	INST_STR_CONCAT1,	INT_MIN,1},
    {"concatStk",	ASSEM_LIST,	INST_CONCAT_STK,	INT_MIN,1},
    {"coroName",	ASSEM_1BYTE,	INST_COROUTINE_NAME,	0,	1},
    {"currentNamespace",ASSEM_1BYTE,	INST_NS_CURRENT,	0,	1},
    {"dictAppend",	ASSEM_LVT4,	INST_DICT_APPEND,	2,	1},
    {"dictExists",	ASSEM_DICT_GET, INST_DICT_EXISTS,	INT_MIN,1},
    {"dictExpand",	ASSEM_1BYTE,	INST_DICT_EXPAND,	3,	1},
    {"dictGet",		ASSEM_DICT_GET, INST_DICT_GET,		INT_MIN,1},
    {"dictIncrImm",	ASSEM_SINT4_LVT4,
					INST_DICT_INCR_IMM,	1,	1},
    {"dictLappend",	ASSEM_LVT4,	INST_DICT_LAPPEND,	2,	1},
    {"dictRecombineStk",ASSEM_1BYTE,	INST_DICT_RECOMBINE_STK,3,	0},
    {"dictRecombineImm",ASSEM_LVT4,	INST_DICT_RECOMBINE_IMM,2,	0},
    {"dictSet",		ASSEM_DICT_SET, INST_DICT_SET,		INT_MIN,1},
    {"dictUnset",	ASSEM_DICT_UNSET,
					INST_DICT_UNSET,	INT_MIN,1},
    {"div",		ASSEM_1BYTE,	INST_DIV,		2,	1},
    {"dup",		ASSEM_1BYTE,	INST_DUP,		1,	2},
    {"endCatch",	ASSEM_END_CATCH,INST_END_CATCH,		0,	0},
    {"eq",		ASSEM_1BYTE,	INST_EQ,		2,	1},
    {"eval",		ASSEM_EVAL,	INST_EVAL_STK,		1,	1},
    {"evalStk",		ASSEM_1BYTE,	INST_EVAL_STK,		1,	1},
    {"exist",		ASSEM_LVT4,	INST_EXIST_SCALAR,	0,	1},
    {"existArray",	ASSEM_LVT4,	INST_EXIST_ARRAY,	1,	1},
    {"existArrayStk",	ASSEM_1BYTE,	INST_EXIST_ARRAY_STK,	2,	1},
    {"existStk",	ASSEM_1BYTE,	INST_EXIST_STK,		1,	1},
    {"expon",		ASSEM_1BYTE,	INST_EXPON,		2,	1},
    {"expr",		ASSEM_EVAL,	INST_EXPR_STK,		1,	1},
    {"exprStk",		ASSEM_1BYTE,	INST_EXPR_STK,		1,	1},
    {"ge",		ASSEM_1BYTE,	INST_GE,		2,	1},
    {"gt",		ASSEM_1BYTE,	INST_GT,		2,	1},
    {"incr",		ASSEM_LVT1,	INST_INCR_SCALAR1,	1,	1},
    {"incrArray",	ASSEM_LVT1,	INST_INCR_ARRAY1,	2,	1},
    {"incrArrayImm",	ASSEM_LVT1_SINT1,
					INST_INCR_ARRAY1_IMM,	1,	1},
    {"incrArrayStk",	ASSEM_1BYTE,	INST_INCR_ARRAY_STK,	3,	1},
    {"incrArrayStkImm", ASSEM_SINT1,	INST_INCR_ARRAY_STK_IMM,2,	1},
    {"incrImm",		ASSEM_LVT1_SINT1,
					INST_INCR_SCALAR1_IMM,	0,	1},
    {"incrStk",		ASSEM_1BYTE,	INST_INCR_STK,		2,	1},
    {"incrStkImm",	ASSEM_SINT1,	INST_INCR_STK_IMM,	1,	1},
    {"infoLevelArgs",	ASSEM_1BYTE,	INST_INFO_LEVEL_ARGS,	1,	1},
    {"infoLevelNumber",	ASSEM_1BYTE,	INST_INFO_LEVEL_NUM,	0,	1},
    {"invokeStk",	ASSEM_INVOKE,	(INST_INVOKE_STK1 << 8
					 | INST_INVOKE_STK4),	INT_MIN,1},
    {"jump",		ASSEM_JUMP,	INST_JUMP1,		0,	0},
    {"jump4",		ASSEM_JUMP4,	INST_JUMP4,		0,	0},
    {"jumpFalse",	ASSEM_JUMP,	INST_JUMP_FALSE1,	1,	0},
    {"jumpFalse4",	ASSEM_JUMP4,	INST_JUMP_FALSE4,	1,	0},
    {"jumpTable",	ASSEM_JUMPTABLE,INST_JUMP_TABLE,	1,	0},
    {"jumpTrue",	ASSEM_JUMP,	INST_JUMP_TRUE1,	1,	0},
    {"jumpTrue4",	ASSEM_JUMP4,	INST_JUMP_TRUE4,	1,	0},
    {"label",		ASSEM_LABEL,	0,			0,	0},
    {"land",		ASSEM_1BYTE,	INST_LAND,		2,	1},
    {"lappend",		ASSEM_LVT,	(INST_LAPPEND_SCALAR1<<8
					 | INST_LAPPEND_SCALAR4),
								1,	1},
    {"lappendArray",	ASSEM_LVT,	(INST_LAPPEND_ARRAY1<<8
					 | INST_LAPPEND_ARRAY4),2,	1},
    {"lappendArrayStk", ASSEM_1BYTE,	INST_LAPPEND_ARRAY_STK,	3,	1},
    {"lappendList",	ASSEM_LVT4,	INST_LAPPEND_LIST,	1,	1},
    {"lappendListArray",ASSEM_LVT4,	INST_LAPPEND_LIST_ARRAY,2,	1},
    {"lappendListArrayStk", ASSEM_1BYTE,INST_LAPPEND_LIST_ARRAY_STK, 3,	1},
    {"lappendListStk",	ASSEM_1BYTE,	INST_LAPPEND_LIST_STK,	2,	1},
    {"lappendStk",	ASSEM_1BYTE,	INST_LAPPEND_STK,	2,	1},
    {"le",		ASSEM_1BYTE,	INST_LE,		2,	1},
    {"lindexMulti",	ASSEM_LINDEX_MULTI,
					INST_LIST_INDEX_MULTI,	INT_MIN,1},
    {"list",		ASSEM_LIST,	INST_LIST,		INT_MIN,1},
    {"listConcat",	ASSEM_1BYTE,	INST_LIST_CONCAT,	2,	1},
    {"listIn",		ASSEM_1BYTE,	INST_LIST_IN,		2,	1},
    {"listIndex",	ASSEM_1BYTE,	INST_LIST_INDEX,	2,	1},
    {"listIndexImm",	ASSEM_INDEX,	INST_LIST_INDEX_IMM,	1,	1},
    {"listLength",	ASSEM_1BYTE,	INST_LIST_LENGTH,	1,	1},
    {"listNotIn",	ASSEM_1BYTE,	INST_LIST_NOT_IN,	2,	1},
    {"load",		ASSEM_LVT,	(INST_LOAD_SCALAR1 << 8
					 | INST_LOAD_SCALAR4),	0,	1},
    {"loadArray",	ASSEM_LVT,	(INST_LOAD_ARRAY1<<8
					 | INST_LOAD_ARRAY4),	1,	1},
    {"loadArrayStk",	ASSEM_1BYTE,	INST_LOAD_ARRAY_STK,	2,	1},
    {"loadStk",		ASSEM_1BYTE,	INST_LOAD_STK,		1,	1},
    {"lor",		ASSEM_1BYTE,	INST_LOR,		2,	1},
    {"lsetFlat",	ASSEM_LSET_FLAT,INST_LSET_FLAT,		INT_MIN,1},
    {"lsetList",	ASSEM_1BYTE,	INST_LSET_LIST,		3,	1},
    {"lshift",		ASSEM_1BYTE,	INST_LSHIFT,		2,	1},
    {"lt",		ASSEM_1BYTE,	INST_LT,		2,	1},
    {"mod",		ASSEM_1BYTE,	INST_MOD,		2,	1},
    {"mult",		ASSEM_1BYTE,	INST_MULT,		2,	1},
    {"neq",		ASSEM_1BYTE,	INST_NEQ,		2,	1},
    {"nop",		ASSEM_1BYTE,	INST_NOP,		0,	0},
    {"not",		ASSEM_1BYTE,	INST_LNOT,		1,	1},
    {"nsupvar",		ASSEM_LVT4,	INST_NSUPVAR,		2,	1},
    {"numericType",	ASSEM_1BYTE,	INST_NUM_TYPE,		1,	1},
    {"originCmd",	ASSEM_1BYTE,	INST_ORIGIN_COMMAND,	1,	1},
    {"over",		ASSEM_OVER,	INST_OVER,		INT_MIN,-1-1},
    {"pop",		ASSEM_1BYTE,	INST_POP,		1,	0},
    {"pushReturnCode",	ASSEM_1BYTE,	INST_PUSH_RETURN_CODE,	0,	1},
    {"pushReturnOpts",	ASSEM_1BYTE,	INST_PUSH_RETURN_OPTIONS,
								0,	1},
    {"pushResult",	ASSEM_1BYTE,	INST_PUSH_RESULT,	0,	1},
    {"regexp",		ASSEM_REGEXP,	INST_REGEXP,		2,	1},
    {"resolveCmd",	ASSEM_1BYTE,	INST_RESOLVE_COMMAND,	1,	1},
    {"reverse",		ASSEM_REVERSE,	INST_REVERSE,		INT_MIN,-1-0},
    {"rshift",		ASSEM_1BYTE,	INST_RSHIFT,		2,	1},
    {"store",		ASSEM_LVT,	(INST_STORE_SCALAR1<<8
					 | INST_STORE_SCALAR4),	1,	1},
    {"storeArray",	ASSEM_LVT,	(INST_STORE_ARRAY1<<8
					 | INST_STORE_ARRAY4),	2,	1},
    {"storeArrayStk",	ASSEM_1BYTE,	INST_STORE_ARRAY_STK,	3,	1},
    {"storeStk",	ASSEM_1BYTE,	INST_STORE_STK,		2,	1},
    {"strcaseLower",	ASSEM_1BYTE,	INST_STR_LOWER,		1,	1},
    {"strcaseTitle",	ASSEM_1BYTE,	INST_STR_TITLE,		1,	1},
    {"strcaseUpper",	ASSEM_1BYTE,	INST_STR_UPPER,		1,	1},
    {"strcmp",		ASSEM_1BYTE,	INST_STR_CMP,		2,	1},
    {"strcat",		ASSEM_CONCAT1,	INST_STR_CONCAT1,	INT_MIN,1},
    {"streq",		ASSEM_1BYTE,	INST_STR_EQ,		2,	1},
    {"strfind",		ASSEM_1BYTE,	INST_STR_FIND,		2,	1},
    {"strindex",	ASSEM_1BYTE,	INST_STR_INDEX,		2,	1},
    {"strlen",		ASSEM_1BYTE,	INST_STR_LEN,		1,	1},
    {"strmap",		ASSEM_1BYTE,	INST_STR_MAP,		3,	1},
    {"strmatch",	ASSEM_BOOL,	INST_STR_MATCH,		2,	1},
    {"strneq",		ASSEM_1BYTE,	INST_STR_NEQ,		2,	1},
    {"strrange",	ASSEM_1BYTE,	INST_STR_RANGE,		3,	1},
    {"strreplace",	ASSEM_1BYTE,	INST_STR_REPLACE,	4,	1},
    {"strrfind",	ASSEM_1BYTE,	INST_STR_FIND_LAST,	2,	1},
    {"strtrim",		ASSEM_1BYTE,	INST_STR_TRIM,		2,	1},
    {"strtrimLeft",	ASSEM_1BYTE,	INST_STR_TRIM_LEFT,	2,	1},
    {"strtrimRight",	ASSEM_1BYTE,	INST_STR_TRIM_RIGHT,	2,	1},
    {"sub",		ASSEM_1BYTE,	INST_SUB,		2,	1},
    {"tclooClass",	ASSEM_1BYTE,	INST_TCLOO_CLASS,	1,	1},
    {"tclooIsObject",	ASSEM_1BYTE,	INST_TCLOO_IS_OBJECT,	1,	1},
    {"tclooNamespace",	ASSEM_1BYTE,	INST_TCLOO_NS,		1,	1},
    {"tclooSelf",	ASSEM_1BYTE,	INST_TCLOO_SELF,	0,	1},
    {"tryCvtToBoolean",	ASSEM_1BYTE,	INST_TRY_CVT_TO_BOOLEAN,1,	2},
    {"tryCvtToNumeric",	ASSEM_1BYTE,	INST_TRY_CVT_TO_NUMERIC,1,	1},
    {"uminus",		ASSEM_1BYTE,	INST_UMINUS,		1,	1},
    {"unset",		ASSEM_BOOL_LVT4,INST_UNSET_SCALAR,	0,	0},
    {"unsetArray",	ASSEM_BOOL_LVT4,INST_UNSET_ARRAY,	1,	0},
    {"unsetArrayStk",	ASSEM_BOOL,	INST_UNSET_ARRAY_STK,	2,	0},
    {"unsetStk",	ASSEM_BOOL,	INST_UNSET_STK,		1,	0},
    {"uplus",		ASSEM_1BYTE,	INST_UPLUS,		1,	1},
    {"upvar",		ASSEM_LVT4,	INST_UPVAR,		2,	1},
    {"variable",	ASSEM_LVT4,	INST_VARIABLE,		1,	0},
    {"verifyDict",	ASSEM_1BYTE,	INST_DICT_VERIFY,	1,	0},
    {"yield",		ASSEM_1BYTE,	INST_YIELD,		1,	1},
    {NULL,		0,		0,			0,	0}
};

/*
 * List of instructions that cannot throw an exception under any
 * circumstances.  These instructions are the ones that are permissible after
 * an exception is caught but before the corresponding exception range is
 * popped from the stack.
 * The instructions must be in ascending order by numeric operation code.
 */

static const unsigned char NonThrowingByteCodes[] = {
    INST_PUSH1, INST_PUSH4, INST_POP, INST_DUP,			/* 1-4 */
    INST_JUMP1, INST_JUMP4,					/* 34-35 */
    INST_END_CATCH, INST_PUSH_RESULT, INST_PUSH_RETURN_CODE,	/* 70-72 */
    INST_LIST,							/* 79 */
    INST_OVER,							/* 95 */
    INST_PUSH_RETURN_OPTIONS,					/* 108 */
    INST_REVERSE,						/* 126 */
    INST_NOP,							/* 132 */
    INST_STR_MAP,						/* 143 */
    INST_STR_FIND,						/* 144 */
    INST_COROUTINE_NAME,					/* 149 */
    INST_NS_CURRENT,						/* 151 */
    INST_INFO_LEVEL_NUM,					/* 152 */
    INST_RESOLVE_COMMAND,					/* 154 */
    INST_STR_TRIM, INST_STR_TRIM_LEFT, INST_STR_TRIM_RIGHT,	/* 166-168 */
    INST_CONCAT_STK,						/* 169 */
    INST_STR_UPPER, INST_STR_LOWER, INST_STR_TITLE,		/* 170-172 */
    INST_NUM_TYPE						/* 180 */
};

/*
 * Helper macros.
 */

#if defined(TCL_DEBUG_ASSEMBLY) && defined(__GNUC__) && __GNUC__ > 2
#define DEBUG_PRINT(...)	fprintf(stderr, ##__VA_ARGS__);fflush(stderr)
#elif defined(__GNUC__) && __GNUC__ > 2
#define DEBUG_PRINT(...)	/* nothing */
#else
#define DEBUG_PRINT		/* nothing */
#endif

/*
 *-----------------------------------------------------------------------------
 *
 * BBAdjustStackDepth --
 *
 *	When an opcode is emitted, adjusts the stack information in the basic
 *	block to reflect the number of operands produced and consumed.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Updates minimum, maximum and final stack requirements in the basic
 *	block.
 *
 *-----------------------------------------------------------------------------
 */

static void
BBAdjustStackDepth(
    BasicBlock *bbPtr,		/* Structure describing the basic block */
    int consumed,		/* Count of operands consumed by the
				 * operation */
    int produced)		/* Count of operands produced by the
				 * operation */
{
    int depth = bbPtr->finalStackDepth;

    depth -= consumed;
    if (depth < bbPtr->minStackDepth) {
	bbPtr->minStackDepth = depth;
    }
    depth += produced;
    if (depth > bbPtr->maxStackDepth) {
	bbPtr->maxStackDepth = depth;
    }
    bbPtr->finalStackDepth = depth;
}

/*
 *-----------------------------------------------------------------------------
 *
 * BBUpdateStackReqs --
 *
 *	Updates the stack requirements of a basic block, given the opcode
 *	being emitted and an operand count.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Updates min, max and final stack requirements in the basic block.
 *
 * Notes:
 *	This function must not be called for instructions such as REVERSE and
 *	OVER that are variadic but do not consume all their operands. Instead,
 *	BBAdjustStackDepth should be called directly.
 *
 *	count should be provided only for variadic operations. For operations
 *	with known arity, count should be 0.
 *
 *-----------------------------------------------------------------------------
 */

static void
BBUpdateStackReqs(
    BasicBlock* bbPtr,		/* Structure describing the basic block */
    int tblIdx,			/* Index in TalInstructionTable of the
				 * operation being assembled */
    int count)			/* Count of operands for variadic insts */
{
    int consumed = TalInstructionTable[tblIdx].operandsConsumed;
    int produced = TalInstructionTable[tblIdx].operandsProduced;

    if (consumed == INT_MIN) {
	/*
	 * The instruction is variadic; it consumes 'count' operands.
	 */

	consumed = count;
    }
    if (produced < 0) {
	/*
	 * The instruction leaves some of its variadic operands on the stack,
	 * with net stack effect of '-1-produced'
	 */

	produced = consumed - produced - 1;
    }
    BBAdjustStackDepth(bbPtr, consumed, produced);
}

/*
 *-----------------------------------------------------------------------------
 *
 * BBEmitOpcode, BBEmitInstInt1, BBEmitInstInt4 --
 *
 *	Emit the opcode part of an instruction, or the entirety of an
 *	instruction with a 1- or 4-byte operand, and adjust stack
 *	requirements.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Stores instruction and operand in the operand stream, and adjusts the
 *	stack.
 *
 *-----------------------------------------------------------------------------
 */

static void
BBEmitOpcode(
    AssemblyEnv* assemEnvPtr,	/* Assembly environment */
    int tblIdx,			/* Table index in TalInstructionTable of op */
    int count)			/* Operand count for variadic ops */
{
    CompileEnv* envPtr = assemEnvPtr->envPtr;
				/* Compilation environment */
    BasicBlock* bbPtr = assemEnvPtr->curr_bb;
				/* Current basic block */
    int op = TalInstructionTable[tblIdx].tclInstCode & 0xff;

    /*
     * If this is the first instruction in a basic block, record its line
     * number.
     */

    if (bbPtr->startOffset == envPtr->codeNext - envPtr->codeStart) {
	bbPtr->startLine = assemEnvPtr->cmdLine;
    }

    TclEmitInt1(op, envPtr);
    TclUpdateAtCmdStart(op, envPtr);
    BBUpdateStackReqs(bbPtr, tblIdx, count);
}

static void
BBEmitInstInt1(
    AssemblyEnv* assemEnvPtr,	/* Assembly environment */
    int tblIdx,			/* Index in TalInstructionTable of op */
    int opnd,			/* 1-byte operand */
    int count)			/* Operand count for variadic ops */
{
    BBEmitOpcode(assemEnvPtr, tblIdx, count);
    TclEmitInt1(opnd, assemEnvPtr->envPtr);
}

static void
BBEmitInstInt4(
    AssemblyEnv* assemEnvPtr,	/* Assembly environment */
    int tblIdx,			/* Index in TalInstructionTable of op */
    int opnd,			/* 4-byte operand */
    int count)			/* Operand count for variadic ops */
{
    BBEmitOpcode(assemEnvPtr, tblIdx, count);
    TclEmitInt4(opnd, assemEnvPtr->envPtr);
}

/*
 *-----------------------------------------------------------------------------
 *
 * BBEmitInst1or4 --
 *
 *	Emits a 1- or 4-byte operation according to the magnitude of the
 *	operand.
 *
 *-----------------------------------------------------------------------------
 */

static void
BBEmitInst1or4(
    AssemblyEnv* assemEnvPtr,	/* Assembly environment */
    int tblIdx,			/* Index in TalInstructionTable of op */
    int param,			/* Variable-length parameter */
    int count)			/* Arity if variadic */
{
    CompileEnv* envPtr = assemEnvPtr->envPtr;
				/* Compilation environment */
    BasicBlock* bbPtr = assemEnvPtr->curr_bb;
				/* Current basic block */
    int op = TalInstructionTable[tblIdx].tclInstCode;

    if (param <= 0xff) {
	op >>= 8;
    } else {
	op &= 0xff;
    }
    TclEmitInt1(op, envPtr);
    if (param <= 0xff) {
	TclEmitInt1(param, envPtr);
    } else {
	TclEmitInt4(param, envPtr);
    }
    TclUpdateAtCmdStart(op, envPtr);
    BBUpdateStackReqs(bbPtr, tblIdx, count);
}

/*
 *-----------------------------------------------------------------------------
 *
 * Tcl_AssembleObjCmd, TclNRAssembleObjCmd --
 *
 *	Direct evaluation path for tcl::unsupported::assemble
 *
 * Results:
 *	Returns a standard Tcl result.
 *
 * Side effects:
 *	Assembles the code in objv[1], and executes it, so side effects
 *	include whatever the code does.
 *
 *-----------------------------------------------------------------------------
 */

int
Tcl_AssembleObjCmd(
    ClientData dummy,		/* Not used. */
    Tcl_Interp *interp,		/* Current interpreter. */
    int objc,			/* Number of arguments. */
    Tcl_Obj *const objv[])	/* Argument objects. */
{
    /*
     * Boilerplate - make sure that there is an NRE trampoline on the C stack
     * because there needs to be one in place to execute bytecode.
     */

    return Tcl_NRCallObjProc(interp, TclNRAssembleObjCmd, dummy, objc, objv);
}

int
TclNRAssembleObjCmd(
    ClientData dummy,		/* Not used. */
    Tcl_Interp *interp,		/* Current interpreter. */
    int objc,			/* Number of arguments. */
    Tcl_Obj *const objv[])	/* Argument objects. */
{
    ByteCode *codePtr;		/* Pointer to the bytecode to execute */
    Tcl_Obj* backtrace;		/* Object where extra error information is
				 * constructed. */

    if (objc != 2) {
	Tcl_WrongNumArgs(interp, 1, objv, "bytecodeList");
	return TCL_ERROR;
    }

    /*
     * Assemble the source to bytecode.
     */

    codePtr = CompileAssembleObj(interp, objv[1]);

    /*
     * On failure, report error line.
     */

    if (codePtr == NULL) {
	Tcl_AddErrorInfo(interp, "\n    (\"");
	Tcl_AppendObjToErrorInfo(interp, objv[0]);
	Tcl_AddErrorInfo(interp, "\" body, line ");
	backtrace = Tcl_NewIntObj(Tcl_GetErrorLine(interp));
	Tcl_AppendObjToErrorInfo(interp, backtrace);
	Tcl_AddErrorInfo(interp, ")");
	return TCL_ERROR;
    }

    /*
     * Use NRE to evaluate the bytecode from the trampoline.
     */

    return TclNRExecuteByteCode(interp, codePtr);
}

/*
 *-----------------------------------------------------------------------------
 *
 * CompileAssembleObj --
 *
 *	Sets up and assembles Tcl bytecode for the direct-execution path in
 *	the Tcl bytecode assembler.
 *
 * Results:
 *	Returns a pointer to the assembled code. Returns NULL if the assembly
 *	fails for any reason, with an appropriate error message in the
 *	interpreter.
 *
 *-----------------------------------------------------------------------------
 */

static ByteCode *
CompileAssembleObj(
    Tcl_Interp *interp,		/* Tcl interpreter */
    Tcl_Obj *objPtr)		/* Source code to assemble */
{
    Interp *iPtr = (Interp *) interp;
				/* Internals of the interpreter */
    CompileEnv compEnv;		/* Compilation environment structure */
    register ByteCode *codePtr = NULL;
				/* Bytecode resulting from the assembly */
    Namespace* namespacePtr;	/* Namespace in which variable and command
				 * names in the bytecode resolve */
    int status;			/* Status return from Tcl_AssembleCode */
    const char* source;		/* String representation of the source code */
    int sourceLen;		/* Length of the source code in bytes */


    /*
     * Get the expression ByteCode from the object. If it exists, make sure it
     * is valid in the current context.
     */

    if (objPtr->typePtr == &assembleCodeType) {
	namespacePtr = iPtr->varFramePtr->nsPtr;
	codePtr = objPtr->internalRep.twoPtrValue.ptr1;
	if (((Interp *) *codePtr->interpHandle == iPtr)
		&& (codePtr->compileEpoch == iPtr->compileEpoch)
		&& (codePtr->nsPtr == namespacePtr)
		&& (codePtr->nsEpoch == namespacePtr->resolverEpoch)
		&& (codePtr->localCachePtr
			== iPtr->varFramePtr->localCachePtr)) {
	    return codePtr;
	}

	/*
	 * Not valid, so free it and regenerate.
	 */

	FreeAssembleCodeInternalRep(objPtr);
    }

    /*
     * Set up the compilation environment, and assemble the code.
     */

    source = TclGetStringFromObj(objPtr, &sourceLen);
    TclInitCompileEnv(interp, &compEnv, source, sourceLen, NULL, 0);
    status = TclAssembleCode(&compEnv, source, sourceLen, TCL_EVAL_DIRECT);
    if (status != TCL_OK) {
	/*
	 * Assembly failed. Clean up and report the error.
	 */
	TclFreeCompileEnv(&compEnv);
	return NULL;
    }

    /*
     * Add a "done" instruction as the last instruction and change the object
     * into a ByteCode object. Ownership of the literal objects and aux data
     * items is given to the ByteCode object.
     */

    TclEmitOpcode(INST_DONE, &compEnv);
    TclInitByteCodeObj(objPtr, &compEnv);
    objPtr->typePtr = &assembleCodeType;
    TclFreeCompileEnv(&compEnv);

    /*
     * Record the local variable context to which the bytecode pertains
     */

    codePtr = objPtr->internalRep.twoPtrValue.ptr1;
    if (iPtr->varFramePtr->localCachePtr) {
	codePtr->localCachePtr = iPtr->varFramePtr->localCachePtr;
	codePtr->localCachePtr->refCount++;
    }

    /*
     * Report on what the assembler did.
     */

#ifdef TCL_COMPILE_DEBUG
    if (tclTraceCompile >= 2) {
	TclPrintByteCodeObj(interp, objPtr);
	fflush(stdout);
    }
#endif /* TCL_COMPILE_DEBUG */

    return codePtr;
}

/*
 *-----------------------------------------------------------------------------
 *
 * TclCompileAssembleCmd --
 *
 *	Compilation procedure for the '::tcl::unsupported::assemble' command.
 *
 * Results:
 *	Returns a standard Tcl result.
 *
 * Side effects:
 *	Puts the result of assembling the code into the bytecode stream in
 *	'compileEnv'.
 *
 * This procedure makes sure that the command has a single arg, which is
 * constant. If that condition is met, the procedure calls TclAssembleCode to
 * produce bytecode for the given assembly code, and returns any error
 * resulting from the assembly.
 *
 *-----------------------------------------------------------------------------
 */

int
TclCompileAssembleCmd(
    Tcl_Interp *interp,		/* Used for error reporting. */
    Tcl_Parse *parsePtr,	/* Points to a parse structure for the command
				 * created by Tcl_ParseCommand. */
    Command *cmdPtr,		/* Points to defintion of command being
				 * compiled. */
    CompileEnv *envPtr)		/* Holds resulting instructions. */
{
    Tcl_Token *tokenPtr;	/* Token in the input script */

    int numCommands = envPtr->numCommands;
    int offset = envPtr->codeNext - envPtr->codeStart;
    int depth = envPtr->currStackDepth;

    /*
     * Make sure that the command has a single arg that is a simple word.
     */

    if (parsePtr->numWords != 2) {
	return TCL_ERROR;
    }
    tokenPtr = TokenAfter(parsePtr->tokenPtr);
    if (tokenPtr->type != TCL_TOKEN_SIMPLE_WORD) {
	return TCL_ERROR;
    }

    /*
     * Compile the code and convert any error from the compilation into
     * bytecode reporting the error;
     */

    if (TCL_ERROR == TclAssembleCode(envPtr, tokenPtr[1].start,
	    tokenPtr[1].size, TCL_EVAL_DIRECT)) {

	Tcl_AppendObjToErrorInfo(interp, Tcl_ObjPrintf(
		"\n    (\"%.*s\" body, line %d)",
		parsePtr->tokenPtr->size, parsePtr->tokenPtr->start,
		Tcl_GetErrorLine(interp)));
	envPtr->numCommands = numCommands;
	envPtr->codeNext = envPtr->codeStart + offset;
	envPtr->currStackDepth = depth;
	TclCompileSyntaxError(interp, envPtr);
    }
    return TCL_OK;
}

/*
 *-----------------------------------------------------------------------------
 *
 * TclAssembleCode --
 *
 *	Take a list of instructions in a Tcl_Obj, and assemble them to Tcl
 *	bytecodes
 *
 * Results:
 *	Returns TCL_OK on success, TCL_ERROR on failure.  If 'flags' includes
 *	TCL_EVAL_DIRECT, places an error message in the interpreter result.
 *
 * Side effects:
 *	Adds byte codes to the compile environment, and updates the
 *	environment's stack depth.
 *
 *-----------------------------------------------------------------------------
 */

static int
TclAssembleCode(
    CompileEnv *envPtr,		/* Compilation environment that is to receive
				 * the generated bytecode */
    const char* codePtr,	/* Assembly-language code to be processed */
    int codeLen,		/* Length of the code */
    int flags)			/* OR'ed combination of flags */
{
    Tcl_Interp* interp = (Tcl_Interp*) envPtr->iPtr;
				/* Tcl interpreter */
    /*
     * Walk through the assembly script using the Tcl parser.  Each 'command'
     * will be an instruction or assembly directive.
     */

    const char* instPtr = codePtr;
				/* Where to start looking for a line of code */
    const char* nextPtr;	/* Pointer to the end of the line of code */
    int bytesLeft = codeLen;	/* Number of bytes of source code remaining to
				 * be parsed */
    int status;			/* Tcl status return */
    AssemblyEnv* assemEnvPtr = NewAssemblyEnv(envPtr, flags);
    Tcl_Parse* parsePtr = assemEnvPtr->parsePtr;

    do {
	/*
	 * Parse out one command line from the assembly script.
	 */

	status = Tcl_ParseCommand(interp, instPtr, bytesLeft, 0, parsePtr);

	/*
	 * Report errors in the parse.
	 */

	if (status != TCL_OK) {
	    if (flags & TCL_EVAL_DIRECT) {
		Tcl_LogCommandInfo(interp, codePtr, parsePtr->commandStart,
			parsePtr->term + 1 - parsePtr->commandStart);
	    }
	    FreeAssemblyEnv(assemEnvPtr);
	    return TCL_ERROR;
	}

	/*
	 * Advance the pointers around any leading commentary.
	 */

	TclAdvanceLines(&assemEnvPtr->cmdLine, instPtr,
		parsePtr->commandStart);
	TclAdvanceContinuations(&assemEnvPtr->cmdLine, &assemEnvPtr->clNext,
		parsePtr->commandStart - envPtr->source);

	/*
	 * Process the line of code.
	 */

	if (parsePtr->numWords > 0) {
	    int instLen = parsePtr->commandSize;
		    /* Length in bytes of the current command */

	    if (parsePtr->term == parsePtr->commandStart + instLen - 1) {
		--instLen;
	    }

	    /*
	     * If tracing, show each line assembled as it happens.
	     */

#ifdef TCL_COMPILE_DEBUG
	    if ((tclTraceCompile >= 2) && (envPtr->procPtr == NULL)) {
		printf("  %4ld Assembling: ",
			(long)(envPtr->codeNext - envPtr->codeStart));
		TclPrintSource(stdout, parsePtr->commandStart,
			TclMin(instLen, 55));
		printf("\n");
	    }
#endif
	    if (AssembleOneLine(assemEnvPtr) != TCL_OK) {
		if (flags & TCL_EVAL_DIRECT) {
		    Tcl_LogCommandInfo(interp, codePtr,
			    parsePtr->commandStart, instLen);
		}
		Tcl_FreeParse(parsePtr);
		FreeAssemblyEnv(assemEnvPtr);
		return TCL_ERROR;
	    }
	}

	/*
	 * Advance to the next line of code.
	 */

	nextPtr = parsePtr->commandStart + parsePtr->commandSize;
	bytesLeft -= (nextPtr - instPtr);
	instPtr = nextPtr;
	TclAdvanceLines(&assemEnvPtr->cmdLine, parsePtr->commandStart,
		instPtr);
	TclAdvanceContinuations(&assemEnvPtr->cmdLine, &assemEnvPtr->clNext,
		instPtr - envPtr->source);
	Tcl_FreeParse(parsePtr);
    } while (bytesLeft > 0);

    /*
     * Done with parsing the code.
     */

    status = FinishAssembly(assemEnvPtr);
    FreeAssemblyEnv(assemEnvPtr);
    return status;
}

/*
 *-----------------------------------------------------------------------------
 *
 * NewAssemblyEnv --
 *
 *	Creates an environment for the assembler to run in.
 *
 * Results:
 *	Allocates, initialises and returns an assembler environment
 *
 *-----------------------------------------------------------------------------
 */

static AssemblyEnv*
NewAssemblyEnv(
    CompileEnv* envPtr,		/* Compilation environment being used for code
				 * generation*/
    int flags)			/* Compilation flags (TCL_EVAL_DIRECT) */
{
    Tcl_Interp* interp = (Tcl_Interp*) envPtr->iPtr;
				/* Tcl interpreter */
    AssemblyEnv* assemEnvPtr = TclStackAlloc(interp, sizeof(AssemblyEnv));
				/* Assembler environment under construction */
    Tcl_Parse* parsePtr = TclStackAlloc(interp, sizeof(Tcl_Parse));
				/* Parse of one line of assembly code */

    assemEnvPtr->envPtr = envPtr;
    assemEnvPtr->parsePtr = parsePtr;
    assemEnvPtr->cmdLine = 1;
    assemEnvPtr->clNext = envPtr->clNext;

    /*
     * Make the hashtables that store symbol resolution.
     */

    Tcl_InitHashTable(&assemEnvPtr->labelHash, TCL_STRING_KEYS);

    /*
     * Start the first basic block.
     */

    assemEnvPtr->curr_bb = NULL;
    assemEnvPtr->head_bb = AllocBB(assemEnvPtr);
    assemEnvPtr->curr_bb = assemEnvPtr->head_bb;
    assemEnvPtr->head_bb->startLine = 1;

    /*
     * Stash compilation flags.
     */

    assemEnvPtr->flags = flags;
    return assemEnvPtr;
}

/*
 *-----------------------------------------------------------------------------
 *
 * FreeAssemblyEnv --
 *
 *	Cleans up the assembler environment when assembly is complete.
 *
 *-----------------------------------------------------------------------------
 */

static void
FreeAssemblyEnv(
    AssemblyEnv* assemEnvPtr)	/* Environment to free */
{
    CompileEnv* envPtr = assemEnvPtr->envPtr;
				/* Compilation environment being used for code
				 * generation */
    Tcl_Interp* interp = (Tcl_Interp*) envPtr->iPtr;
				/* Tcl interpreter */
    BasicBlock* thisBB;		/* Pointer to a basic block being deleted */
    BasicBlock* nextBB;		/* Pointer to a deleted basic block's
				 * successor */

    /*
     * Free all the basic block structures.
     */

    for (thisBB = assemEnvPtr->head_bb; thisBB != NULL; thisBB = nextBB) {
	if (thisBB->jumpTarget != NULL) {
	    Tcl_DecrRefCount(thisBB->jumpTarget);
	}
	if (thisBB->foreignExceptions != NULL) {
	    ckfree(thisBB->foreignExceptions);
	}
	nextBB = thisBB->successor1;
	if (thisBB->jtPtr != NULL) {
	    DeleteMirrorJumpTable(thisBB->jtPtr);
	    thisBB->jtPtr = NULL;
	}
	ckfree(thisBB);
    }

    /*
     * Dispose what's left.
     */

    Tcl_DeleteHashTable(&assemEnvPtr->labelHash);
    TclStackFree(interp, assemEnvPtr->parsePtr);
    TclStackFree(interp, assemEnvPtr);
}

/*
 *-----------------------------------------------------------------------------
 *
 * AssembleOneLine --
 *
 *	Assembles a single command from an assembly language source.
 *
 * Results:
 *	Returns TCL_ERROR with an appropriate error message if the assembly
 *	fails. Returns TCL_OK if the assembly succeeds. Updates the assembly
 *	environment with the state of the assembly.
 *
 *-----------------------------------------------------------------------------
 */

static int
AssembleOneLine(
    AssemblyEnv* assemEnvPtr)	/* State of the assembly */
{
    CompileEnv* envPtr = assemEnvPtr->envPtr;
				/* Compilation environment being used for code
				 * gen */
    Tcl_Interp* interp = (Tcl_Interp*) envPtr->iPtr;
				/* Tcl interpreter */
    Tcl_Parse* parsePtr = assemEnvPtr->parsePtr;
				/* Parse of the line of code */
    Tcl_Token* tokenPtr;	/* Current token within the line of code */
    Tcl_Obj* instNameObj;	/* Name of the instruction */
    int tblIdx;			/* Index in TalInstructionTable of the
				 * instruction */
    enum TalInstType instType;	/* Type of the instruction */
    Tcl_Obj* operand1Obj = NULL;
				/* First operand to the instruction */
    const char* operand1;	/* String rep of the operand */
    int operand1Len;		/* String length of the operand */
    int opnd;			/* Integer representation of an operand */
    int litIndex;		/* Literal pool index of a constant */
    int localVar;		/* LVT index of a local variable */
    int flags;			/* Flags for a basic block */
    JumptableInfo* jtPtr;	/* Pointer to a jumptable */
    int infoIndex;		/* Index of the jumptable in auxdata */
    int status = TCL_ERROR;	/* Return value from this function */

    /*
     * Make sure that the instruction name is known at compile time.
     */

    tokenPtr = parsePtr->tokenPtr;
    if (GetNextOperand(assemEnvPtr, &tokenPtr, &instNameObj) != TCL_OK) {
	return TCL_ERROR;
    }

    /*
     * Look up the instruction name.
     */

    if (Tcl_GetIndexFromObjStruct(interp, instNameObj,
	    &TalInstructionTable[0].name, sizeof(TalInstDesc), "instruction",
	    TCL_EXACT, &tblIdx) != TCL_OK) {
	goto cleanup;
    }

    /*
     * Vector on the type of instruction being processed.
     */

    instType = TalInstructionTable[tblIdx].instType;
    switch (instType) {

    case ASSEM_PUSH:
	if (parsePtr->numWords != 2) {
	    Tcl_WrongNumArgs(interp, 1, &instNameObj, "value");
	    goto cleanup;
	}
	if (GetNextOperand(assemEnvPtr, &tokenPtr, &operand1Obj) != TCL_OK) {
	    goto cleanup;
	}
	operand1 = Tcl_GetStringFromObj(operand1Obj, &operand1Len);
	litIndex = TclRegisterNewLiteral(envPtr, operand1, operand1Len);
	BBEmitInst1or4(assemEnvPtr, tblIdx, litIndex, 0);
	break;

    case ASSEM_1BYTE:
	if (parsePtr->numWords != 1) {
	    Tcl_WrongNumArgs(interp, 1, &instNameObj, "");
	    goto cleanup;
	}
	BBEmitOpcode(assemEnvPtr, tblIdx, 0);
	break;

    case ASSEM_BEGIN_CATCH:
	/*
	 * Emit the BEGIN_CATCH instruction with the code offset of the
	 * exception branch target instead of the exception range index. The
	 * correct index will be generated and inserted later, when catches
	 * are being resolved.
	 */

	if (parsePtr->numWords != 2) {
	    Tcl_WrongNumArgs(interp, 1, &instNameObj, "label");
	    goto cleanup;
	}
	if (GetNextOperand(assemEnvPtr, &tokenPtr, &operand1Obj) != TCL_OK) {
	    goto cleanup;
	}
	assemEnvPtr->curr_bb->jumpLine = assemEnvPtr->cmdLine;
	assemEnvPtr->curr_bb->jumpOffset = envPtr->codeNext-envPtr->codeStart;
	BBEmitInstInt4(assemEnvPtr, tblIdx, 0, 0);
	assemEnvPtr->curr_bb->flags |= BB_BEGINCATCH;
	StartBasicBlock(assemEnvPtr, BB_FALLTHRU, operand1Obj);
	break;

    case ASSEM_BOOL:
	if (parsePtr->numWords != 2) {
	    Tcl_WrongNumArgs(interp, 1, &instNameObj, "boolean");
	    goto cleanup;
	}
	if (GetBooleanOperand(assemEnvPtr, &tokenPtr, &opnd) != TCL_OK) {
	    goto cleanup;
	}
	BBEmitInstInt1(assemEnvPtr, tblIdx, opnd, 0);
	break;

    case ASSEM_BOOL_LVT4:
	if (parsePtr->numWords != 3) {
	    Tcl_WrongNumArgs(interp, 1, &instNameObj, "boolean varName");
	    goto cleanup;
	}
	if (GetBooleanOperand(assemEnvPtr, &tokenPtr, &opnd) != TCL_OK) {
	    goto cleanup;
	}
	localVar = FindLocalVar(assemEnvPtr, &tokenPtr);
	if (localVar < 0) {
	    goto cleanup;
	}
	BBEmitInstInt1(assemEnvPtr, tblIdx, opnd, 0);
	TclEmitInt4(localVar, envPtr);
	break;

    case ASSEM_CLOCK_READ:
	if (parsePtr->numWords != 2) {
	    Tcl_WrongNumArgs(interp, 1, &instNameObj, "imm8");
	    goto cleanup;
	}
	if (GetIntegerOperand(assemEnvPtr, &tokenPtr, &opnd) != TCL_OK) {
	    goto cleanup;
	}
	if (opnd < 0 || opnd > 3) {
	    Tcl_SetObjResult(interp,
			     Tcl_NewStringObj("operand must be [0..3]", -1));
	    Tcl_SetErrorCode(interp, "TCL", "ASSEM", "OPERAND<0,>3", NULL);
	    goto cleanup;
	}
	BBEmitInstInt1(assemEnvPtr, tblIdx, opnd, opnd);
	break;

    case ASSEM_CONCAT1:
	if (parsePtr->numWords != 2) {
	    Tcl_WrongNumArgs(interp, 1, &instNameObj, "imm8");
	    goto cleanup;
	}
	if (GetIntegerOperand(assemEnvPtr, &tokenPtr, &opnd) != TCL_OK
		|| CheckOneByte(interp, opnd) != TCL_OK
		|| CheckStrictlyPositive(interp, opnd) != TCL_OK) {
	    goto cleanup;
	}
	BBEmitInstInt1(assemEnvPtr, tblIdx, opnd, opnd);
	break;

    case ASSEM_DICT_GET:
	if (parsePtr->numWords != 2) {
	    Tcl_WrongNumArgs(interp, 1, &instNameObj, "count");
	    goto cleanup;
	}
	if (GetIntegerOperand(assemEnvPtr, &tokenPtr, &opnd) != TCL_OK
		|| CheckStrictlyPositive(interp, opnd) != TCL_OK) {
	    goto cleanup;
	}
	BBEmitInstInt4(assemEnvPtr, tblIdx, opnd, opnd+1);
	break;

    case ASSEM_DICT_SET:
	if (parsePtr->numWords != 3) {
	    Tcl_WrongNumArgs(interp, 1, &instNameObj, "count varName");
	    goto cleanup;
	}
	if (GetIntegerOperand(assemEnvPtr, &tokenPtr, &opnd) != TCL_OK
		|| CheckStrictlyPositive(interp, opnd) != TCL_OK) {
	    goto cleanup;
	}
	localVar = FindLocalVar(assemEnvPtr, &tokenPtr);
	if (localVar < 0) {
	    goto cleanup;
	}
	BBEmitInstInt4(assemEnvPtr, tblIdx, opnd, opnd+1);
	TclEmitInt4(localVar, envPtr);
	break;

    case ASSEM_DICT_UNSET:
	if (parsePtr->numWords != 3) {
	    Tcl_WrongNumArgs(interp, 1, &instNameObj, "count varName");
	    goto cleanup;
	}
	if (GetIntegerOperand(assemEnvPtr, &tokenPtr, &opnd) != TCL_OK
		|| CheckStrictlyPositive(interp, opnd) != TCL_OK) {
	    goto cleanup;
	}
	localVar = FindLocalVar(assemEnvPtr, &tokenPtr);
	if (localVar < 0) {
	    goto cleanup;
	}
	BBEmitInstInt4(assemEnvPtr, tblIdx, opnd, opnd);
	TclEmitInt4(localVar, envPtr);
	break;

    case ASSEM_END_CATCH:
	if (parsePtr->numWords != 1) {
	    Tcl_WrongNumArgs(interp, 1, &instNameObj, "");
	    goto cleanup;
	}
	assemEnvPtr->curr_bb->flags |= BB_ENDCATCH;
	BBEmitOpcode(assemEnvPtr, tblIdx, 0);
	StartBasicBlock(assemEnvPtr, BB_FALLTHRU, NULL);
	break;

    case ASSEM_EVAL:
	/* TODO - Refactor this stuff into a subroutine that takes the inst
	 * code, the message ("script" or "expression") and an evaluator
	 * callback that calls TclCompileScript or TclCompileExpr. */

	if (parsePtr->numWords != 2) {
	    Tcl_WrongNumArgs(interp, 1, &instNameObj,
		    ((TalInstructionTable[tblIdx].tclInstCode
		    == INST_EVAL_STK) ? "script" : "expression"));
	    goto cleanup;
	}
	if (tokenPtr->type == TCL_TOKEN_SIMPLE_WORD) {
	    CompileEmbeddedScript(assemEnvPtr, tokenPtr+1,
		    TalInstructionTable+tblIdx);
	} else if (GetNextOperand(assemEnvPtr, &tokenPtr,
		&operand1Obj) != TCL_OK) {
	    goto cleanup;
	} else {
	    operand1 = Tcl_GetStringFromObj(operand1Obj, &operand1Len);
	    litIndex = TclRegisterNewLiteral(envPtr, operand1, operand1Len);

	    /*
	     * Assumes that PUSH is the first slot!
	     */

	    BBEmitInst1or4(assemEnvPtr, 0, litIndex, 0);
	    BBEmitOpcode(assemEnvPtr, tblIdx, 0);
	}
	break;

    case ASSEM_INVOKE:
	if (parsePtr->numWords != 2) {
	    Tcl_WrongNumArgs(interp, 1, &instNameObj, "count");
	    goto cleanup;
	}
	if (GetIntegerOperand(assemEnvPtr, &tokenPtr, &opnd) != TCL_OK
		|| CheckStrictlyPositive(interp, opnd) != TCL_OK) {
	    goto cleanup;
	}

	BBEmitInst1or4(assemEnvPtr, tblIdx, opnd, opnd);
	break;

    case ASSEM_JUMP:
    case ASSEM_JUMP4:
	if (parsePtr->numWords != 2) {
	    Tcl_WrongNumArgs(interp, 1, &instNameObj, "label");
	    goto cleanup;
	}
	if (GetNextOperand(assemEnvPtr, &tokenPtr, &operand1Obj) != TCL_OK) {
	    goto cleanup;
	}
	assemEnvPtr->curr_bb->jumpOffset = envPtr->codeNext-envPtr->codeStart;
	if (instType == ASSEM_JUMP) {
	    flags = BB_JUMP1;
	    BBEmitInstInt1(assemEnvPtr, tblIdx, 0, 0);
	} else {
	    flags = 0;
	    BBEmitInstInt4(assemEnvPtr, tblIdx, 0, 0);
	}

	/*
	 * Start a new basic block at the instruction following the jump.
	 */

	assemEnvPtr->curr_bb->jumpLine = assemEnvPtr->cmdLine;
	if (TalInstructionTable[tblIdx].operandsConsumed != 0) {
	    flags |= BB_FALLTHRU;
	}
	StartBasicBlock(assemEnvPtr, flags, operand1Obj);
	break;

    case ASSEM_JUMPTABLE:
	if (parsePtr->numWords != 2) {
	    Tcl_WrongNumArgs(interp, 1, &instNameObj, "table");
	    goto cleanup;
	}
	if (GetNextOperand(assemEnvPtr, &tokenPtr, &operand1Obj) != TCL_OK) {
	    goto cleanup;
	}

	jtPtr = ckalloc(sizeof(JumptableInfo));

	Tcl_InitHashTable(&jtPtr->hashTable, TCL_STRING_KEYS);
	assemEnvPtr->curr_bb->jumpLine = assemEnvPtr->cmdLine;
	assemEnvPtr->curr_bb->jumpOffset = envPtr->codeNext-envPtr->codeStart;
	DEBUG_PRINT("bb %p jumpLine %d jumpOffset %d\n",
		assemEnvPtr->curr_bb, assemEnvPtr->cmdLine,
		envPtr->codeNext - envPtr->codeStart);

	infoIndex = TclCreateAuxData(jtPtr, &tclJumptableInfoType, envPtr);
	DEBUG_PRINT("auxdata index=%d\n", infoIndex);

	BBEmitInstInt4(assemEnvPtr, tblIdx, infoIndex, 0);
	if (CreateMirrorJumpTable(assemEnvPtr, operand1Obj) != TCL_OK) {
	    goto cleanup;
	}
	StartBasicBlock(assemEnvPtr, BB_JUMPTABLE|BB_FALLTHRU, NULL);
	break;

    case ASSEM_LABEL:
	if (parsePtr->numWords != 2) {
	    Tcl_WrongNumArgs(interp, 1, &instNameObj, "name");
	    goto cleanup;
	}
	if (GetNextOperand(assemEnvPtr, &tokenPtr, &operand1Obj) != TCL_OK) {
	    goto cleanup;
	}

	/*
	 * Add the (label_name, address) pair to the hash table.
	 */

	if (DefineLabel(assemEnvPtr, Tcl_GetString(operand1Obj)) != TCL_OK) {
	    goto cleanup;
	}
	break;

    case ASSEM_LINDEX_MULTI:
	if (parsePtr->numWords != 2) {
	    Tcl_WrongNumArgs(interp, 1, &instNameObj, "count");
	    goto cleanup;
	}
	if (GetIntegerOperand(assemEnvPtr, &tokenPtr, &opnd) != TCL_OK
		|| CheckStrictlyPositive(interp, opnd) != TCL_OK) {
	    goto cleanup;
	}
	BBEmitInstInt4(assemEnvPtr, tblIdx, opnd, opnd);
	break;

    case ASSEM_LIST:
	if (parsePtr->numWords != 2) {
	    Tcl_WrongNumArgs(interp, 1, &instNameObj, "count");
	    goto cleanup;
	}
	if (GetIntegerOperand(assemEnvPtr, &tokenPtr, &opnd) != TCL_OK
		|| CheckNonNegative(interp, opnd) != TCL_OK) {
	    goto cleanup;
	}
	BBEmitInstInt4(assemEnvPtr, tblIdx, opnd, opnd);
	break;

    case ASSEM_INDEX:
	if (parsePtr->numWords != 2) {
	    Tcl_WrongNumArgs(interp, 1, &instNameObj, "count");
	    goto cleanup;
	}
	if (GetListIndexOperand(assemEnvPtr, &tokenPtr, &opnd) != TCL_OK) {
	    goto cleanup;
	}
	BBEmitInstInt4(assemEnvPtr, tblIdx, opnd, opnd);
	break;

    case ASSEM_LSET_FLAT:
	if (parsePtr->numWords != 2) {
	    Tcl_WrongNumArgs(interp, 1, &instNameObj, "count");
	    goto cleanup;
	}
	if (GetIntegerOperand(assemEnvPtr, &tokenPtr, &opnd) != TCL_OK) {
	    goto cleanup;
	}
	if (opnd < 2) {
	    if (assemEnvPtr->flags & TCL_EVAL_DIRECT) {
		Tcl_SetObjResult(interp,
			Tcl_NewStringObj("operand must be >=2", -1));
		Tcl_SetErrorCode(interp, "TCL", "ASSEM", "OPERAND>=2", NULL);
	    }
	    goto cleanup;
	}
	BBEmitInstInt4(assemEnvPtr, tblIdx, opnd, opnd);
	break;

    case ASSEM_LVT:
	if (parsePtr->numWords != 2) {
	    Tcl_WrongNumArgs(interp, 1, &instNameObj, "varname");
	    goto cleanup;
	}
	localVar = FindLocalVar(assemEnvPtr, &tokenPtr);
	if (localVar < 0) {
	    goto cleanup;
	}
	BBEmitInst1or4(assemEnvPtr, tblIdx, localVar, 0);
	break;

    case ASSEM_LVT1:
	if (parsePtr->numWords != 2) {
	    Tcl_WrongNumArgs(interp, 1, &instNameObj, "varname");
	    goto cleanup;
	}
	localVar = FindLocalVar(assemEnvPtr, &tokenPtr);
	if (localVar < 0 || CheckOneByte(interp, localVar)) {
	    goto cleanup;
	}
	BBEmitInstInt1(assemEnvPtr, tblIdx, localVar, 0);
	break;

    case ASSEM_LVT1_SINT1:
	if (parsePtr->numWords != 3) {
	    Tcl_WrongNumArgs(interp, 1, &instNameObj, "varName imm8");
	    goto cleanup;
	}
	localVar = FindLocalVar(assemEnvPtr, &tokenPtr);
	if (localVar < 0 || CheckOneByte(interp, localVar)
		|| GetIntegerOperand(assemEnvPtr, &tokenPtr, &opnd) != TCL_OK
		|| CheckSignedOneByte(interp, opnd)) {
	    goto cleanup;
	}
	BBEmitInstInt1(assemEnvPtr, tblIdx, localVar, 0);
	TclEmitInt1(opnd, envPtr);
	break;

    case ASSEM_LVT4:
	if (parsePtr->numWords != 2) {
	    Tcl_WrongNumArgs(interp, 1, &instNameObj, "varname");
	    goto cleanup;
	}
	localVar = FindLocalVar(assemEnvPtr, &tokenPtr);
	if (localVar < 0) {
	    goto cleanup;
	}
	BBEmitInstInt4(assemEnvPtr, tblIdx, localVar, 0);
	break;

    case ASSEM_OVER:
	if (parsePtr->numWords != 2) {
	    Tcl_WrongNumArgs(interp, 1, &instNameObj, "count");
	    goto cleanup;
	}
	if (GetIntegerOperand(assemEnvPtr, &tokenPtr, &opnd) != TCL_OK
		|| CheckNonNegative(interp, opnd) != TCL_OK) {
	    goto cleanup;
	}
	BBEmitInstInt4(assemEnvPtr, tblIdx, opnd, opnd+1);
	break;

    case ASSEM_REGEXP:
	if (parsePtr->numWords != 2) {
	    Tcl_WrongNumArgs(interp, 1, &instNameObj, "boolean");
	    goto cleanup;
	}
	if (GetBooleanOperand(assemEnvPtr, &tokenPtr, &opnd) != TCL_OK) {
	    goto cleanup;
	}
	{
	    int flags = TCL_REG_ADVANCED | (opnd ? TCL_REG_NOCASE : 0);

	    BBEmitInstInt1(assemEnvPtr, tblIdx, flags, 0);
	}
	break;

    case ASSEM_REVERSE:
	if (parsePtr->numWords != 2) {
	    Tcl_WrongNumArgs(interp, 1, &instNameObj, "count");
	    goto cleanup;
	}
	if (GetIntegerOperand(assemEnvPtr, &tokenPtr, &opnd) != TCL_OK
		|| CheckNonNegative(interp, opnd) != TCL_OK) {
	    goto cleanup;
	}
	BBEmitInstInt4(assemEnvPtr, tblIdx, opnd, opnd);
	break;

    case ASSEM_SINT1:
	if (parsePtr->numWords != 2) {
	    Tcl_WrongNumArgs(interp, 1, &instNameObj, "imm8");
	    goto cleanup;
	}
	if (GetIntegerOperand(assemEnvPtr, &tokenPtr, &opnd) != TCL_OK
		|| CheckSignedOneByte(interp, opnd) != TCL_OK) {
	    goto cleanup;
	}
	BBEmitInstInt1(assemEnvPtr, tblIdx, opnd, 0);
	break;

    case ASSEM_SINT4_LVT4:
	if (parsePtr->numWords != 3) {
	    Tcl_WrongNumArgs(interp, 1, &instNameObj, "count varName");
	    goto cleanup;
	}
	if (GetIntegerOperand(assemEnvPtr, &tokenPtr, &opnd) != TCL_OK) {
	    goto cleanup;
	}
	localVar = FindLocalVar(assemEnvPtr, &tokenPtr);
	if (localVar < 0) {
	    goto cleanup;
	}
	BBEmitInstInt4(assemEnvPtr, tblIdx, opnd, 0);
	TclEmitInt4(localVar, envPtr);
	break;

    default:
	Tcl_Panic("Instruction \"%s\" could not be found, can't happen\n",
		Tcl_GetString(instNameObj));
    }

    status = TCL_OK;
 cleanup:
    Tcl_DecrRefCount(instNameObj);
    if (operand1Obj) {
	Tcl_DecrRefCount(operand1Obj);
    }
    return status;
}

/*
 *-----------------------------------------------------------------------------
 *
 * CompileEmbeddedScript --
 *
 *	Compile an embedded 'eval' or 'expr' that appears in assembly code.
 *
 * This procedure is called when the 'eval' or 'expr' assembly directive is
 * encountered, and the argument to the directive is a simple word that
 * requires no substitution. The appropriate compiler (TclCompileScript or
 * TclCompileExpr) is invoked recursively, and emits bytecode.
 *
 * Before the compiler is invoked, the compilation environment's stack
 * consumption is reset to zero. Upon return from the compilation, the net
 * stack effect of the compilation is in the compiler env, and this stack
 * effect is posted to the assembler environment. The compile environment's
 * stack consumption is then restored to what it was before (which is actually
 * the state of the stack on entry to the block of assembly code).
 *
 * Any exception ranges pushed by the compilation are copied to the basic
 * block and removed from the compiler environment. They will be rebuilt at
 * the end of assembly, when the exception stack depth is actually known.
 *
 *-----------------------------------------------------------------------------
 */

static void
CompileEmbeddedScript(
    AssemblyEnv* assemEnvPtr,	/* Assembly environment */
    Tcl_Token* tokenPtr,	/* Tcl_Token containing the script */
    const TalInstDesc* instPtr)	/* Instruction that determines whether
				 * the script is 'expr' or 'eval' */
{
    CompileEnv* envPtr = assemEnvPtr->envPtr;
				/* Compilation environment */
    Tcl_Interp* interp = (Tcl_Interp*) envPtr->iPtr;
				/* Tcl interpreter */

    /*
     * The expression or script is not only known at compile time, but
     * actually a "simple word". It can be compiled inline by invoking the
     * compiler recursively.
     *
     * Save away the stack depth and reset it before compiling the script.
     * We'll record the stack usage of the script in the BasicBlock, and
     * accumulate it together with the stack usage of the enclosing assembly
     * code.
     */

    int savedStackDepth = envPtr->currStackDepth;
    int savedMaxStackDepth = envPtr->maxStackDepth;
    int savedCodeIndex = envPtr->codeNext - envPtr->codeStart;
    int savedExceptArrayNext = envPtr->exceptArrayNext;

    envPtr->currStackDepth = 0;
    envPtr->maxStackDepth = 0;

    StartBasicBlock(assemEnvPtr, BB_FALLTHRU, NULL);
    switch(instPtr->tclInstCode) {
    case INST_EVAL_STK:
	TclCompileScript(interp, tokenPtr->start, tokenPtr->size, envPtr);
	break;
    case INST_EXPR_STK:
	TclCompileExpr(interp, tokenPtr->start, tokenPtr->size, envPtr, 1);
	break;
    default:
	Tcl_Panic("no ASSEM_EVAL case for %s (%d), can't happen",
		instPtr->name, instPtr->tclInstCode);
    }

    /*
     * Roll up the stack usage of the embedded block into the assembler
     * environment.
     */

    SyncStackDepth(assemEnvPtr);
    envPtr->currStackDepth = savedStackDepth;
    envPtr->maxStackDepth = savedMaxStackDepth;

    /*
     * Save any exception ranges that were pushed by the compiler; they will
     * need to be fixed up once the stack depth is known.
     */

    MoveExceptionRangesToBasicBlock(assemEnvPtr, savedCodeIndex,
	    savedExceptArrayNext);

    /*
     * Flush the current basic block.
     */

    StartBasicBlock(assemEnvPtr, BB_FALLTHRU, NULL);
}

/*
 *-----------------------------------------------------------------------------
 *
 * SyncStackDepth --
 *
 *	Copies the stack depth from the compile environment to a basic block.
 *
 * Side effects:
 *	Current and max stack depth in the current basic block are adjusted.
 *
 * This procedure is called on return from invoking the compiler for the
 * 'eval' and 'expr' operations. It adjusts the stack depth of the current
 * basic block to reflect the stack required by the just-compiled code.
 *
 *-----------------------------------------------------------------------------
 */

static void
SyncStackDepth(
    AssemblyEnv* assemEnvPtr)	/* Assembly environment */
{
    CompileEnv* envPtr = assemEnvPtr->envPtr;
				/* Compilation environment */
    BasicBlock* curr_bb = assemEnvPtr->curr_bb;
				/* Current basic block */
    int maxStackDepth = curr_bb->finalStackDepth + envPtr->maxStackDepth;
				/* Max stack depth in the basic block */

    if (maxStackDepth > curr_bb->maxStackDepth) {
	curr_bb->maxStackDepth = maxStackDepth;
    }
    curr_bb->finalStackDepth += envPtr->currStackDepth;
}

/*
 *-----------------------------------------------------------------------------
 *
 * MoveExceptionRangesToBasicBlock --
 *
 *	Removes exception ranges that were created by compiling an embedded
 *	script from the CompileEnv, and stores them in the BasicBlock. They
 *	will be reinstalled, at the correct stack depth, after control flow
 *	analysis is complete on the assembly code.
 *
 *-----------------------------------------------------------------------------
 */

static void
MoveExceptionRangesToBasicBlock(
    AssemblyEnv* assemEnvPtr,	/* Assembly environment */
    int savedCodeIndex,		/* Start of the embedded code */
    int savedExceptArrayNext)	/* Saved index of the end of the exception
				 * range array */
{
    CompileEnv* envPtr = assemEnvPtr->envPtr;
				/* Compilation environment */
    BasicBlock* curr_bb = assemEnvPtr->curr_bb;
				/* Current basic block */
    int exceptionCount = envPtr->exceptArrayNext - savedExceptArrayNext;
				/* Number of ranges that must be moved */
    int i;

    if (exceptionCount == 0) {
	/* Nothing to do */
	return;
    }

    /*
     * Save the exception ranges in the basic block. They will be re-added at
     * the conclusion of assembly; at this time, the INST_BEGIN_CATCH
     * instructions in the block will be adjusted from whatever range indices
     * they have [savedExceptArrayNext .. envPtr->exceptArrayNext) to the
     * indices that the exceptions acquire. The saved exception ranges are
     * converted to a relative nesting depth. The depth will be recomputed
     * once flow analysis has determined the actual stack depth of the block.
     */

    DEBUG_PRINT("basic block %p has %d exceptions starting at %d\n",
	    curr_bb, exceptionCount, savedExceptArrayNext);
    curr_bb->foreignExceptionBase = savedExceptArrayNext;
    curr_bb->foreignExceptionCount = exceptionCount;
    curr_bb->foreignExceptions =
	    ckalloc(exceptionCount * sizeof(ExceptionRange));
    memcpy(curr_bb->foreignExceptions,
	    envPtr->exceptArrayPtr + savedExceptArrayNext,
	    exceptionCount * sizeof(ExceptionRange));
    for (i = 0; i < exceptionCount; ++i) {
	curr_bb->foreignExceptions[i].nestingLevel -= envPtr->exceptDepth;
    }
    envPtr->exceptArrayNext = savedExceptArrayNext;
}

/*
 *-----------------------------------------------------------------------------
 *
 * CreateMirrorJumpTable --
 *
 *	Makes a jump table with comparison values and assembly code labels.
 *
 * Results:
 *	Returns a standard Tcl status, with an error message in the
 *	interpreter on error.
 *
 * Side effects:
 *	Initializes the jump table pointer in the current basic block to a
 *	JumptableInfo. The keys in the JumptableInfo are the comparison
 *	strings. The values, instead of being jump displacements, are
 *	Tcl_Obj's with the code labels.
 */

static int
CreateMirrorJumpTable(
    AssemblyEnv* assemEnvPtr,	/* Assembly environment */
    Tcl_Obj* jumps)		/* List of alternating keywords and labels */
{
    int objc;			/* Number of elements in the 'jumps' list */
    Tcl_Obj** objv;		/* Pointers to the elements in the list */
    CompileEnv* envPtr = assemEnvPtr->envPtr;
				/* Compilation environment */
    Tcl_Interp* interp = (Tcl_Interp*) envPtr->iPtr;
				/* Tcl interpreter */
    BasicBlock* bbPtr = assemEnvPtr->curr_bb;
				/* Current basic block */
    JumptableInfo* jtPtr;
    Tcl_HashTable* jtHashPtr;	/* Hashtable in the JumptableInfo */
    Tcl_HashEntry* hashEntry;	/* Entry for a key in the hashtable */
    int isNew;			/* Flag==1 if the key is not yet in the
				 * table. */
    int i;

    if (Tcl_ListObjGetElements(interp, jumps, &objc, &objv) != TCL_OK) {
	return TCL_ERROR;
    }
    if (objc % 2 != 0) {
	if (assemEnvPtr->flags & TCL_EVAL_DIRECT) {
	    Tcl_SetObjResult(interp, Tcl_NewStringObj(
		    "jump table must have an even number of list elements",
		    -1));
	    Tcl_SetErrorCode(interp, "TCL", "ASSEM", "BADJUMPTABLE", NULL);
	}
	return TCL_ERROR;
    }

    /*
     * Allocate the jumptable.
     */

    jtPtr = ckalloc(sizeof(JumptableInfo));
    jtHashPtr = &jtPtr->hashTable;
    Tcl_InitHashTable(jtHashPtr, TCL_STRING_KEYS);

    /*
     * Fill the keys and labels into the table.
     */

    DEBUG_PRINT("jump table {\n");
    for (i = 0; i < objc; i+=2) {
	DEBUG_PRINT("  %s -> %s\n", Tcl_GetString(objv[i]),
		Tcl_GetString(objv[i+1]));
	hashEntry = Tcl_CreateHashEntry(jtHashPtr, Tcl_GetString(objv[i]),
		&isNew);
	if (!isNew) {
	    if (assemEnvPtr->flags & TCL_EVAL_DIRECT) {
		Tcl_SetObjResult(interp, Tcl_ObjPrintf(
			"duplicate entry in jump table for \"%s\"",
			Tcl_GetString(objv[i])));
		Tcl_SetErrorCode(interp, "TCL", "ASSEM", "DUPJUMPTABLEENTRY");
		DeleteMirrorJumpTable(jtPtr);
		return TCL_ERROR;
	    }
	}
	Tcl_SetHashValue(hashEntry, objv[i+1]);
	Tcl_IncrRefCount(objv[i+1]);
    }
    DEBUG_PRINT("}\n");

    /*
     * Put the mirror jumptable in the basic block struct.
     */

    bbPtr->jtPtr = jtPtr;
    return TCL_OK;
}

/*
 *-----------------------------------------------------------------------------
 *
 * DeleteMirrorJumpTable --
 *
 *	Cleans up a jump table when the basic block is deleted.
 *
 *-----------------------------------------------------------------------------
 */

static void
DeleteMirrorJumpTable(
    JumptableInfo* jtPtr)
{
    Tcl_HashTable* jtHashPtr = &jtPtr->hashTable;
				/* Hash table pointer */
    Tcl_HashSearch search;	/* Hash search control */
    Tcl_HashEntry* entry;	/* Hash table entry containing a jump label */
    Tcl_Obj* label;		/* Jump label from the hash table */

    for (entry = Tcl_FirstHashEntry(jtHashPtr, &search);
	    entry != NULL;
	    entry = Tcl_NextHashEntry(&search)) {
	label = Tcl_GetHashValue(entry);
	Tcl_DecrRefCount(label);
	Tcl_SetHashValue(entry, NULL);
    }
    Tcl_DeleteHashTable(jtHashPtr);
    ckfree(jtPtr);
}

/*
 *-----------------------------------------------------------------------------
 *
 * GetNextOperand --
 *
 *	Retrieves the next operand in sequence from an assembly instruction,
 *	and makes sure that its value is known at compile time.
 *
 * Results:
 *	If successful, returns TCL_OK and leaves a Tcl_Obj with the operand
 *	text in *operandObjPtr. In case of failure, returns TCL_ERROR and
 *	leaves *operandObjPtr untouched.
 *
 * Side effects:
 *	Advances *tokenPtrPtr around the token just processed.
 *
 *-----------------------------------------------------------------------------
 */

static int
GetNextOperand(
    AssemblyEnv* assemEnvPtr,	/* Assembly environment */
    Tcl_Token** tokenPtrPtr,	/* INPUT/OUTPUT: Pointer to the token holding
				 * the operand */
    Tcl_Obj** operandObjPtr)	/* OUTPUT: Tcl object holding the operand text
				 * with \-substitutions done. */
{
    Tcl_Interp* interp = (Tcl_Interp*) assemEnvPtr->envPtr->iPtr;
    Tcl_Obj* operandObj = Tcl_NewObj();

    if (!TclWordKnownAtCompileTime(*tokenPtrPtr, operandObj)) {
	Tcl_DecrRefCount(operandObj);
	if (assemEnvPtr->flags & TCL_EVAL_DIRECT) {
	    Tcl_SetObjResult(interp, Tcl_NewStringObj(
		    "assembly code may not contain substitutions", -1));
	    Tcl_SetErrorCode(interp, "TCL", "ASSEM", "NOSUBST", NULL);
	}
	return TCL_ERROR;
    }
    *tokenPtrPtr = TokenAfter(*tokenPtrPtr);
    Tcl_IncrRefCount(operandObj);
    *operandObjPtr = operandObj;
    return TCL_OK;
}

/*
 *-----------------------------------------------------------------------------
 *
 * GetBooleanOperand --
 *
 *	Retrieves a Boolean operand from the input stream and advances
 *	the token pointer.
 *
 * Results:
 *	Returns a standard Tcl result (with an error message in the
 *	interpreter on failure).
 *
 * Side effects:
 *	Stores the Boolean value in (*result) and advances (*tokenPtrPtr)
 *	to the next token.
 *
 *-----------------------------------------------------------------------------
 */

static int
GetBooleanOperand(
    AssemblyEnv* assemEnvPtr,	/* Assembly environment */
    Tcl_Token** tokenPtrPtr,	/* Current token from the parser */
    int* result)		/* OUTPUT: Integer extracted from the token */
{
    CompileEnv* envPtr = assemEnvPtr->envPtr;
				/* Compilation environment */
    Tcl_Interp* interp = (Tcl_Interp*) envPtr->iPtr;
				/* Tcl interpreter */
    Tcl_Token* tokenPtr = *tokenPtrPtr;
				/* INOUT: Pointer to the next token in the
				 * source code */
    Tcl_Obj* intObj;		/* Integer from the source code */
    int status;			/* Tcl status return */

    /*
     * Extract the next token as a string.
     */

    if (GetNextOperand(assemEnvPtr, tokenPtrPtr, &intObj) != TCL_OK) {
	return TCL_ERROR;
    }

    /*
     * Convert to an integer, advance to the next token and return.
     */

    status = Tcl_GetBooleanFromObj(interp, intObj, result);
    Tcl_DecrRefCount(intObj);
    *tokenPtrPtr = TokenAfter(tokenPtr);
    return status;
}

/*
 *-----------------------------------------------------------------------------
 *
 * GetIntegerOperand --
 *
 *	Retrieves an integer operand from the input stream and advances the
 *	token pointer.
 *
 * Results:
 *	Returns a standard Tcl result (with an error message in the
 *	interpreter on failure).
 *
 * Side effects:
 *	Stores the integer value in (*result) and advances (*tokenPtrPtr) to
 *	the next token.
 *
 *-----------------------------------------------------------------------------
 */

static int
GetIntegerOperand(
    AssemblyEnv* assemEnvPtr,	/* Assembly environment */
    Tcl_Token** tokenPtrPtr,	/* Current token from the parser */
    int* result)		/* OUTPUT: Integer extracted from the token */
{
    CompileEnv* envPtr = assemEnvPtr->envPtr;
				/* Compilation environment */
    Tcl_Interp* interp = (Tcl_Interp*) envPtr->iPtr;
				/* Tcl interpreter */
    Tcl_Token* tokenPtr = *tokenPtrPtr;
				/* INOUT: Pointer to the next token in the
				 * source code */
    Tcl_Obj* intObj;		/* Integer from the source code */
    int status;			/* Tcl status return */

    /*
     * Extract the next token as a string.
     */

    if (GetNextOperand(assemEnvPtr, tokenPtrPtr, &intObj) != TCL_OK) {
	return TCL_ERROR;
    }

    /*
     * Convert to an integer, advance to the next token and return.
     */

    status = Tcl_GetIntFromObj(interp, intObj, result);
    Tcl_DecrRefCount(intObj);
    *tokenPtrPtr = TokenAfter(tokenPtr);
    return status;
}

/*
 *-----------------------------------------------------------------------------
 *
 * GetListIndexOperand --
 *
 *	Gets the value of an operand intended to serve as a list index.
 *
 * Results:
 *	Returns a standard Tcl result: TCL_OK if the parse is successful and
 *	TCL_ERROR (with an appropriate error message) if the parse fails.
 *
 * Side effects:
 *	Stores the list index at '*index'. Values between -1 and 0x7fffffff
 *	have their natural meaning; values between -2 and -0x80000000
 *	represent 'end-2-N'.
 *
 *-----------------------------------------------------------------------------
 */

static int
GetListIndexOperand(
    AssemblyEnv* assemEnvPtr,	/* Assembly environment */
    Tcl_Token** tokenPtrPtr,	/* Current token from the parser */
    int* result)		/* OUTPUT: Integer extracted from the token */
{
    CompileEnv* envPtr = assemEnvPtr->envPtr;
				/* Compilation environment */
    Tcl_Interp* interp = (Tcl_Interp*) envPtr->iPtr;
				/* Tcl interpreter */
    Tcl_Token* tokenPtr = *tokenPtrPtr;
				/* INOUT: Pointer to the next token in the
				 * source code */
    Tcl_Obj* intObj;		/* Integer from the source code */
    int status;			/* Tcl status return */

    /*
     * Extract the next token as a string.
     */

    if (GetNextOperand(assemEnvPtr, tokenPtrPtr, &intObj) != TCL_OK) {
	return TCL_ERROR;
    }

    /*
     * Convert to an integer, advance to the next token and return.
     */

    status = TclGetIntForIndex(interp, intObj, -2, result);
    Tcl_DecrRefCount(intObj);
    *tokenPtrPtr = TokenAfter(tokenPtr);
    return status;
}

/*
 *-----------------------------------------------------------------------------
 *
 * FindLocalVar --
 *
 *	Gets the name of a local variable from the input stream and advances
 *	the token pointer.
 *
 * Results:
 *	Returns the LVT index of the local variable.  Returns -1 if the
 *	variable is non-local, not known at compile time, or cannot be
 *	installed in the LVT (leaving an error message in the interpreter
 *	result if necessary).
 *
 * Side effects:
 *	Advances the token pointer.  May define a new LVT slot if the variable
 *	has not yet been seen and the execution context allows for it.
 *
 *-----------------------------------------------------------------------------
 */

static int
FindLocalVar(
    AssemblyEnv* assemEnvPtr,	/* Assembly environment */
    Tcl_Token** tokenPtrPtr)
{
    CompileEnv* envPtr = assemEnvPtr->envPtr;
				/* Compilation environment */
    Tcl_Interp* interp = (Tcl_Interp*) envPtr->iPtr;
				/* Tcl interpreter */
    Tcl_Token* tokenPtr = *tokenPtrPtr;
				/* INOUT: Pointer to the next token in the
				 * source code. */
    Tcl_Obj* varNameObj;	/* Name of the variable */
    const char* varNameStr;
    int varNameLen;
    int localVar;		/* Index of the variable in the LVT */

    if (GetNextOperand(assemEnvPtr, tokenPtrPtr, &varNameObj) != TCL_OK) {
	return -1;
    }
    varNameStr = Tcl_GetStringFromObj(varNameObj, &varNameLen);
    if (CheckNamespaceQualifiers(interp, varNameStr, varNameLen)) {
	Tcl_DecrRefCount(varNameObj);
	return -1;
    }
    localVar = TclFindCompiledLocal(varNameStr, varNameLen, 1, envPtr);
    Tcl_DecrRefCount(varNameObj);
    if (localVar == -1) {
	if (assemEnvPtr->flags & TCL_EVAL_DIRECT) {
	    Tcl_SetObjResult(interp, Tcl_NewStringObj(
		    "cannot use this instruction to create a variable"
		    " in a non-proc context", -1));
	    Tcl_SetErrorCode(interp, "TCL", "ASSEM", "LVT", NULL);
	}
	return -1;
    }
    *tokenPtrPtr = TokenAfter(tokenPtr);
    return localVar;
}

/*
 *-----------------------------------------------------------------------------
 *
 * CheckNamespaceQualifiers --
 *
 *	Verify that a variable name has no namespace qualifiers before
 *	attempting to install it in the LVT.
 *
 * Results:
 *	On success, returns TCL_OK. On failure, returns TCL_ERROR and stores
 *	an error message in the interpreter result.
 *
 *-----------------------------------------------------------------------------
 */

static int
CheckNamespaceQualifiers(
    Tcl_Interp* interp,		/* Tcl interpreter for error reporting */
    const char* name,		/* Variable name to check */
    int nameLen)		/* Length of the variable */
{
    const char* p;

    for (p = name; p+2 < name+nameLen;  p++) {
	if ((*p == ':') && (p[1] == ':')) {
	    Tcl_SetObjResult(interp, Tcl_ObjPrintf(
		    "variable \"%s\" is not local", name));
	    Tcl_SetErrorCode(interp, "TCL", "ASSEM", "NONLOCAL", name, NULL);
	    return TCL_ERROR;
	}
    }
    return TCL_OK;
}

/*
 *-----------------------------------------------------------------------------
 *
 * CheckOneByte --
 *
 *	Verify that a constant fits in a single byte in the instruction
 *	stream.
 *
 * Results:
 *	On success, returns TCL_OK. On failure, returns TCL_ERROR and stores
 *	an error message in the interpreter result.
 *
 * This code is here primarily to verify that instructions like INCR_SCALAR1
 * are possible on a given local variable. The fact that there is no
 * INCR_SCALAR4 is puzzling.
 *
 *-----------------------------------------------------------------------------
 */

static int
CheckOneByte(
    Tcl_Interp* interp,		/* Tcl interpreter for error reporting */
    int value)			/* Value to check */
{
    Tcl_Obj* result;		/* Error message */

    if (value < 0 || value > 0xff) {
	result = Tcl_NewStringObj("operand does not fit in one byte", -1);
	Tcl_SetObjResult(interp, result);
	Tcl_SetErrorCode(interp, "TCL", "ASSEM", "1BYTE", NULL);
	return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 *-----------------------------------------------------------------------------
 *
 * CheckSignedOneByte --
 *
 *	Verify that a constant fits in a single signed byte in the instruction
 *	stream.
 *
 * Results:
 *	On success, returns TCL_OK. On failure, returns TCL_ERROR and stores
 *	an error message in the interpreter result.
 *
 * This code is here primarily to verify that instructions like INCR_SCALAR1
 * are possible on a given local variable. The fact that there is no
 * INCR_SCALAR4 is puzzling.
 *
 *-----------------------------------------------------------------------------
 */

static int
CheckSignedOneByte(
    Tcl_Interp* interp,		/* Tcl interpreter for error reporting */
    int value)			/* Value to check */
{
    Tcl_Obj* result;		/* Error message */

    if (value > 0x7f || value < -0x80) {
	result = Tcl_NewStringObj("operand does not fit in one byte", -1);
	Tcl_SetObjResult(interp, result);
	Tcl_SetErrorCode(interp, "TCL", "ASSEM", "1BYTE", NULL);
	return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 *-----------------------------------------------------------------------------
 *
 * CheckNonNegative --
 *
 *	Verify that a constant is nonnegative
 *
 * Results:
 *	On success, returns TCL_OK. On failure, returns TCL_ERROR and stores
 *	an error message in the interpreter result.
 *
 * This code is here primarily to verify that instructions like INCR_INVOKE
 * are consuming a positive number of operands
 *
 *-----------------------------------------------------------------------------
 */

static int
CheckNonNegative(
    Tcl_Interp* interp,		/* Tcl interpreter for error reporting */
    int value)			/* Value to check */
{
    Tcl_Obj* result;		/* Error message */

    if (value < 0) {
	result = Tcl_NewStringObj("operand must be nonnegative", -1);
	Tcl_SetObjResult(interp, result);
	Tcl_SetErrorCode(interp, "TCL", "ASSEM", "NONNEGATIVE", NULL);
	return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 *-----------------------------------------------------------------------------
 *
 * CheckStrictlyPositive --
 *
 *	Verify that a constant is positive
 *
 * Results:
 *	On success, returns TCL_OK. On failure, returns TCL_ERROR and
 *	stores an error message in the interpreter result.
 *
 * This code is here primarily to verify that instructions like INCR_INVOKE
 * are consuming a positive number of operands
 *
 *-----------------------------------------------------------------------------
 */

static int
CheckStrictlyPositive(
    Tcl_Interp* interp,		/* Tcl interpreter for error reporting */
    int value)			/* Value to check */
{
    Tcl_Obj* result;		/* Error message */

    if (value <= 0) {
	result = Tcl_NewStringObj("operand must be positive", -1);
	Tcl_SetObjResult(interp, result);
	Tcl_SetErrorCode(interp, "TCL", "ASSEM", "POSITIVE", NULL);
	return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 *-----------------------------------------------------------------------------
 *
 * DefineLabel --
 *
 *	Defines a label appearing in the assembly sequence.
 *
 * Results:
 *	Returns a standard Tcl result. Returns TCL_OK and an empty result if
 *	the definition succeeds; returns TCL_ERROR and an appropriate message
 *	if a duplicate definition is found.
 *
 *-----------------------------------------------------------------------------
 */

static int
DefineLabel(
    AssemblyEnv* assemEnvPtr,	/* Assembly environment */
    const char* labelName)	/* Label being defined */
{
    CompileEnv* envPtr = assemEnvPtr->envPtr;
				/* Compilation environment */
    Tcl_Interp* interp = (Tcl_Interp*) envPtr->iPtr;
				/* Tcl interpreter */
    Tcl_HashEntry* entry;	/* Label's entry in the symbol table */
    int isNew;			/* Flag == 1 iff the label was previously
				 * undefined */

    /* TODO - This can now be simplified! */

    StartBasicBlock(assemEnvPtr, BB_FALLTHRU, NULL);

    /*
     * Look up the newly-defined label in the symbol table.
     */

    entry = Tcl_CreateHashEntry(&assemEnvPtr->labelHash, labelName, &isNew);
    if (!isNew) {
	/*
	 * This is a duplicate label.
	 */

	if (assemEnvPtr->flags & TCL_EVAL_DIRECT) {
	    Tcl_SetObjResult(interp, Tcl_ObjPrintf(
		    "duplicate definition of label \"%s\"", labelName));
	    Tcl_SetErrorCode(interp, "TCL", "ASSEM", "DUPLABEL", labelName,
		    NULL);
	}
	return TCL_ERROR;
    }

    /*
     * This is the first appearance of the label in the code.
     */

    Tcl_SetHashValue(entry, assemEnvPtr->curr_bb);
    return TCL_OK;
}

/*
 *-----------------------------------------------------------------------------
 *
 * StartBasicBlock --
 *
 *	Starts a new basic block when a label or jump is encountered.
 *
 * Results:
 *	Returns a pointer to the BasicBlock structure of the new
 *	basic block.
 *
 *-----------------------------------------------------------------------------
 */

static BasicBlock*
StartBasicBlock(
    AssemblyEnv* assemEnvPtr,	/* Assembly environment */
    int flags,			/* Flags to apply to the basic block being
				 * closed, if there is one. */
    Tcl_Obj* jumpLabel)		/* Label of the location that the block jumps
				 * to, or NULL if the block does not jump */
{
    CompileEnv* envPtr = assemEnvPtr->envPtr;
				/* Compilation environment */
    BasicBlock* newBB;		/* BasicBlock structure for the new block */
    BasicBlock* currBB = assemEnvPtr->curr_bb;

    /*
     * Coalesce zero-length blocks.
     */

    if (currBB->startOffset == envPtr->codeNext - envPtr->codeStart) {
	currBB->startLine = assemEnvPtr->cmdLine;
	return currBB;
    }

    /*
     * Make the new basic block.
     */

    newBB = AllocBB(assemEnvPtr);

    /*
     * Record the jump target if there is one.
     */

    currBB->jumpTarget = jumpLabel;
    if (jumpLabel != NULL) {
	Tcl_IncrRefCount(currBB->jumpTarget);
    }

    /*
     * Record the fallthrough if there is one.
     */

    currBB->flags |= flags;

    /*
     * Record the successor block.
     */

    currBB->successor1 = newBB;
    assemEnvPtr->curr_bb = newBB;
    return newBB;
}

/*
 *-----------------------------------------------------------------------------
 *
 * AllocBB --
 *
 *	Allocates a new basic block
 *
 * Results:
 *	Returns a pointer to the newly allocated block, which is initialized
 *	to contain no code and begin at the current instruction pointer.
 *
 *-----------------------------------------------------------------------------
 */

static BasicBlock *
AllocBB(
    AssemblyEnv* assemEnvPtr)	/* Assembly environment */
{
    CompileEnv* envPtr = assemEnvPtr->envPtr;
    BasicBlock *bb = ckalloc(sizeof(BasicBlock));

    bb->originalStartOffset =
	    bb->startOffset = envPtr->codeNext - envPtr->codeStart;
    bb->startLine = assemEnvPtr->cmdLine + 1;
    bb->jumpOffset = -1;
    bb->jumpLine = -1;
    bb->prevPtr = assemEnvPtr->curr_bb;
    bb->predecessor = NULL;
    bb->successor1 = NULL;
    bb->jumpTarget = NULL;
    bb->initialStackDepth = 0;
    bb->minStackDepth = 0;
    bb->maxStackDepth = 0;
    bb->finalStackDepth = 0;
    bb->catchDepth = 0;
    bb->enclosingCatch = NULL;
    bb->foreignExceptionBase = -1;
    bb->foreignExceptionCount = 0;
    bb->foreignExceptions = NULL;
    bb->jtPtr = NULL;
    bb->flags = 0;

    return bb;
}

/*
 *-----------------------------------------------------------------------------
 *
 * FinishAssembly --
 *
 *	Postprocessing after all bytecode has been generated for a block of
 *	assembly code.
 *
 * Results:
 *	Returns a standard Tcl result, with an error message left in the
 *	interpreter if appropriate.
 *
 * Side effects:
 *	The program is checked to see if any undefined labels remain.  The
 *	initial stack depth of all the basic blocks in the flow graph is
 *	calculated and saved.  The stack balance on exit is computed, checked
 *	and saved.
 *
 *-----------------------------------------------------------------------------
 */

static int
FinishAssembly(
    AssemblyEnv* assemEnvPtr)	/* Assembly environment */
{
    int mustMove;		/* Amount by which the code needs to be grown
				 * because of expanding jumps */

    /*
     * Resolve the targets of all jumps and determine whether code needs to be
     * moved around.
     */

    if (CalculateJumpRelocations(assemEnvPtr, &mustMove)) {
	return TCL_ERROR;
    }

    /*
     * Move the code if necessary.
     */

    if (mustMove) {
	MoveCodeForJumps(assemEnvPtr, mustMove);
    }

    /*
     * Resolve jump target labels to bytecode offsets.
     */

    FillInJumpOffsets(assemEnvPtr);

    /*
     * Label each basic block with its catch context. Quit on inconsistency.
     */

    if (ProcessCatches(assemEnvPtr) != TCL_OK) {
	return TCL_ERROR;
    }

    /*
     * Make sure that no block accessible from a catch's error exit that hasn't
     * popped the exception stack can throw an exception.
     */

    if (CheckForThrowInWrongContext(assemEnvPtr) != TCL_OK) {
	return TCL_ERROR;
    }

    /*
     * Compute stack balance throughout the program.
     */

    if (CheckStack(assemEnvPtr) != TCL_OK) {
	return TCL_ERROR;
    }

    /*
     * TODO - Check for unreachable code. Or maybe not; unreachable code is
     * Mostly Harmless.
     */

    return TCL_OK;
}

/*
 *-----------------------------------------------------------------------------
 *
 * CalculateJumpRelocations --
 *
 *	Calculate any movement that has to be done in the assembly code to
 *	expand JUMP1 instructions to JUMP4 (because they jump more than a
 *	1-byte range).
 *
 * Results:
 *	Returns a standard Tcl result, with an appropriate error message if
 *	anything fails.
 *
 * Side effects:
 *	Sets the 'startOffset' pointer in every basic block to the new origin
 *	of the block, and turns off JUMP1 flags on instructions that must be
 *	expanded (and adjusts them to the corresponding JUMP4's).  Does *not*
 *	store the jump offsets at this point.
 *
 *	Sets *mustMove to 1 if and only if at least one instruction changed
 *	size so the code must be moved.
 *
 *	As a side effect, also checks for undefined labels and reports them.
 *
 *-----------------------------------------------------------------------------
 */

static int
CalculateJumpRelocations(
    AssemblyEnv* assemEnvPtr,	/* Assembly environment */
    int* mustMove)		/* OUTPUT: Number of bytes that have been
				 * added to the code */
{
    CompileEnv* envPtr = assemEnvPtr->envPtr;
				/* Compilation environment */
    BasicBlock* bbPtr;		/* Pointer to a basic block being checked */
    Tcl_HashEntry* entry;	/* Exit label's entry in the symbol table */
    BasicBlock* jumpTarget;	/* Basic block where the jump goes */
    int motion;			/* Amount by which the code has expanded */
    int offset;			/* Offset in the bytecode from a jump
				 * instruction to its target */
    unsigned opcode;		/* Opcode in the bytecode being adjusted */

    /*
     * Iterate through basic blocks as long as a change results in code
     * expansion.
     */

    *mustMove = 0;
    do {
	motion = 0;
	for (bbPtr = assemEnvPtr->head_bb;
		bbPtr != NULL;
		bbPtr = bbPtr->successor1) {
	    /*
	     * Advance the basic block start offset by however many bytes we
	     * have inserted in the code up to this point
	     */

	    bbPtr->startOffset += motion;

	    /*
	     * If the basic block references a label (and hence performs a
	     * jump), find the location of the label. Report an error if the
	     * label is missing.
	     */

	    if (bbPtr->jumpTarget != NULL) {
		entry = Tcl_FindHashEntry(&assemEnvPtr->labelHash,
			Tcl_GetString(bbPtr->jumpTarget));
		if (entry == NULL) {
		    ReportUndefinedLabel(assemEnvPtr, bbPtr,
			    bbPtr->jumpTarget);
		    return TCL_ERROR;
		}

		/*
		 * If the instruction is a JUMP1, turn it into a JUMP4 if its
		 * target is out of range.
		 */

		jumpTarget = Tcl_GetHashValue(entry);
		if (bbPtr->flags & BB_JUMP1) {
		    offset = jumpTarget->startOffset
			    - (bbPtr->jumpOffset + motion);
		    if (offset < -0x80 || offset > 0x7f) {
			opcode = TclGetUInt1AtPtr(envPtr->codeStart
				+ bbPtr->jumpOffset);
			++opcode;
			TclStoreInt1AtPtr(opcode,
				envPtr->codeStart + bbPtr->jumpOffset);
			motion += 3;
			bbPtr->flags &= ~BB_JUMP1;
		    }
		}
	    }

	    /*
	     * If the basic block references a jump table, that doesn't affect
	     * the code locations, but resolve the labels now, and store basic
	     * block pointers in the jumptable hash.
	     */

	    if (bbPtr->flags & BB_JUMPTABLE) {
		if (CheckJumpTableLabels(assemEnvPtr, bbPtr) != TCL_OK) {
		    return TCL_ERROR;
		}
	    }
	}
	*mustMove += motion;
    } while (motion != 0);

    return TCL_OK;
}

/*
 *-----------------------------------------------------------------------------
 *
 * CheckJumpTableLabels --
 *
 *	Make sure that all the labels in a jump table are defined.
 *
 * Results:
 *	Returns TCL_OK if they are, TCL_ERROR if they aren't.
 *
 *-----------------------------------------------------------------------------
 */

static int
CheckJumpTableLabels(
    AssemblyEnv* assemEnvPtr,	/* Assembly environment */
    BasicBlock* bbPtr)		/* Basic block that ends in a jump table */
{
    Tcl_HashTable* symHash = &bbPtr->jtPtr->hashTable;
				/* Hash table with the symbols */
    Tcl_HashSearch search;	/* Hash table iterator */
    Tcl_HashEntry* symEntryPtr;	/* Hash entry for the symbols */
    Tcl_Obj* symbolObj;		/* Jump target */
    Tcl_HashEntry* valEntryPtr;	/* Hash entry for the resolutions */

    /*
     * Look up every jump target in the jump hash.
     */

    DEBUG_PRINT("check jump table labels %p {\n", bbPtr);
    for (symEntryPtr = Tcl_FirstHashEntry(symHash, &search);
	    symEntryPtr != NULL;
	    symEntryPtr = Tcl_NextHashEntry(&search)) {
	symbolObj = Tcl_GetHashValue(symEntryPtr);
	valEntryPtr = Tcl_FindHashEntry(&assemEnvPtr->labelHash,
		Tcl_GetString(symbolObj));
	DEBUG_PRINT("  %s -> %s (%d)\n",
		(char*) Tcl_GetHashKey(symHash, symEntryPtr),
		Tcl_GetString(symbolObj), (valEntryPtr != NULL));
	if (valEntryPtr == NULL) {
	    ReportUndefinedLabel(assemEnvPtr, bbPtr, symbolObj);
	    return TCL_ERROR;
	}
    }
    DEBUG_PRINT("}\n");
    return TCL_OK;
}

/*
 *-----------------------------------------------------------------------------
 *
 * ReportUndefinedLabel --
 *
 *	Report that a basic block refers to an undefined jump label
 *
 * Side effects:
 *	Stores an error message, error code, and line number information in
 *	the assembler's Tcl interpreter.
 *
 *-----------------------------------------------------------------------------
 */

static void
ReportUndefinedLabel(
    AssemblyEnv* assemEnvPtr,	/* Assembly environment */
    BasicBlock* bbPtr,		/* Basic block that contains the undefined
				 * label */
    Tcl_Obj* jumpTarget)	/* Label of a jump target */
{
    CompileEnv* envPtr = assemEnvPtr->envPtr;
				/* Compilation environment */
    Tcl_Interp* interp = (Tcl_Interp*) envPtr->iPtr;
				/* Tcl interpreter */

    if (assemEnvPtr->flags & TCL_EVAL_DIRECT) {
	Tcl_SetObjResult(interp, Tcl_ObjPrintf(
		"undefined label \"%s\"", Tcl_GetString(jumpTarget)));
	Tcl_SetErrorCode(interp, "TCL", "ASSEM", "NOLABEL",
		Tcl_GetString(jumpTarget), NULL);
	Tcl_SetErrorLine(interp, bbPtr->jumpLine);
    }
}

/*
 *-----------------------------------------------------------------------------
 *
 * MoveCodeForJumps --
 *
 *	Move bytecodes in memory to accommodate JUMP1 instructions that have
 *	expanded to become JUMP4's.
 *
 *-----------------------------------------------------------------------------
 */

static void
MoveCodeForJumps(
    AssemblyEnv* assemEnvPtr,	/* Assembler environment */
    int mustMove)		/* Number of bytes of added code */
{
    CompileEnv* envPtr = assemEnvPtr->envPtr;
				/* Compilation environment */
    BasicBlock* bbPtr;		/* Pointer to a basic block being checked */
    int topOffset;		/* Bytecode offset of the following basic
				 * block before code motion */

    /*
     * Make sure that there is enough space in the bytecode array to
     * accommodate the expanded code.
     */

    while (envPtr->codeEnd < envPtr->codeNext + mustMove) {
	TclExpandCodeArray(envPtr);
    }

    /*
     * Iterate through the bytecodes in reverse order, and move them upward to
     * their new homes.
     */

    topOffset = envPtr->codeNext - envPtr->codeStart;
    for (bbPtr = assemEnvPtr->curr_bb; bbPtr != NULL; bbPtr = bbPtr->prevPtr) {
	DEBUG_PRINT("move code from %d to %d\n",
		bbPtr->originalStartOffset, bbPtr->startOffset);
	memmove(envPtr->codeStart + bbPtr->startOffset,
		envPtr->codeStart + bbPtr->originalStartOffset,
		topOffset - bbPtr->originalStartOffset);
	topOffset = bbPtr->originalStartOffset;
	bbPtr->jumpOffset += (bbPtr->startOffset - bbPtr->originalStartOffset);
    }
    envPtr->codeNext += mustMove;
}

/*
 *-----------------------------------------------------------------------------
 *
 * FillInJumpOffsets --
 *
 *	Fill in the final offsets of all jump instructions once bytecode
 *	locations have been completely determined.
 *
 *-----------------------------------------------------------------------------
 */

static void
FillInJumpOffsets(
    AssemblyEnv* assemEnvPtr)	/* Assembly environment */
{
    CompileEnv* envPtr = assemEnvPtr->envPtr;
				/* Compilation environment */
    BasicBlock* bbPtr;		/* Pointer to a basic block being checked */
    Tcl_HashEntry* entry;	/* Hashtable entry for a jump target label */
    BasicBlock* jumpTarget;	/* Basic block where a jump goes */
    int fromOffset;		/* Bytecode location of a jump instruction */
    int targetOffset;		/* Bytecode location of a jump instruction's
				 * target */

    for (bbPtr = assemEnvPtr->head_bb;
	    bbPtr != NULL;
	    bbPtr = bbPtr->successor1) {
	if (bbPtr->jumpTarget != NULL) {
	    entry = Tcl_FindHashEntry(&assemEnvPtr->labelHash,
		    Tcl_GetString(bbPtr->jumpTarget));
	    jumpTarget = Tcl_GetHashValue(entry);
	    fromOffset = bbPtr->jumpOffset;
	    targetOffset = jumpTarget->startOffset;
	    if (bbPtr->flags & BB_JUMP1) {
		TclStoreInt1AtPtr(targetOffset - fromOffset,
			envPtr->codeStart + fromOffset + 1);
	    } else {
		TclStoreInt4AtPtr(targetOffset - fromOffset,
			envPtr->codeStart + fromOffset + 1);
	    }
	}
	if (bbPtr->flags & BB_JUMPTABLE) {
	    ResolveJumpTableTargets(assemEnvPtr, bbPtr);
	}
    }
}

/*
 *-----------------------------------------------------------------------------
 *
 * ResolveJumpTableTargets --
 *
 *	Puts bytecode addresses for the targets of a jumptable into the
 *	table
 *
 * Results:
 *	Returns TCL_OK if they are, TCL_ERROR if they aren't.
 *
 *-----------------------------------------------------------------------------
 */

static void
ResolveJumpTableTargets(
    AssemblyEnv* assemEnvPtr,	/* Assembly environment */
    BasicBlock* bbPtr)		/* Basic block that ends in a jump table */
{
    CompileEnv* envPtr = assemEnvPtr->envPtr;
				/* Compilation environment */
    Tcl_HashTable* symHash = &bbPtr->jtPtr->hashTable;
				/* Hash table with the symbols */
    Tcl_HashSearch search;	/* Hash table iterator */
    Tcl_HashEntry* symEntryPtr;	/* Hash entry for the symbols */
    Tcl_Obj* symbolObj;		/* Jump target */
    Tcl_HashEntry* valEntryPtr;	/* Hash entry for the resolutions */
    int auxDataIndex;		/* Index of the auxdata */
    JumptableInfo* realJumpTablePtr;
				/* Jump table in the actual code */
    Tcl_HashTable* realJumpHashPtr;
				/* Jump table hash in the actual code */
    Tcl_HashEntry* realJumpEntryPtr;
				/* Entry in the jump table hash in
				 * the actual code */
    BasicBlock* jumpTargetBBPtr;
				/* Basic block that the jump proceeds to */
    int junk;

    auxDataIndex = TclGetInt4AtPtr(envPtr->codeStart + bbPtr->jumpOffset + 1);
    DEBUG_PRINT("bbPtr = %p jumpOffset = %d auxDataIndex = %d\n",
	    bbPtr, bbPtr->jumpOffset, auxDataIndex);
    realJumpTablePtr = TclFetchAuxData(envPtr, auxDataIndex);
    realJumpHashPtr = &realJumpTablePtr->hashTable;

    /*
     * Look up every jump target in the jump hash.
     */

    DEBUG_PRINT("resolve jump table {\n");
    for (symEntryPtr = Tcl_FirstHashEntry(symHash, &search);
	    symEntryPtr != NULL;
	    symEntryPtr = Tcl_NextHashEntry(&search)) {
	symbolObj = Tcl_GetHashValue(symEntryPtr);
	DEBUG_PRINT("     symbol %s\n", Tcl_GetString(symbolObj));

	valEntryPtr = Tcl_FindHashEntry(&assemEnvPtr->labelHash,
		Tcl_GetString(symbolObj));
	jumpTargetBBPtr = Tcl_GetHashValue(valEntryPtr);

	realJumpEntryPtr = Tcl_CreateHashEntry(realJumpHashPtr,
		Tcl_GetHashKey(symHash, symEntryPtr), &junk);
	DEBUG_PRINT("  %s -> %s -> bb %p (pc %d)    hash entry %p\n",
		(char*) Tcl_GetHashKey(symHash, symEntryPtr),
		Tcl_GetString(symbolObj), jumpTargetBBPtr,
		jumpTargetBBPtr->startOffset, realJumpEntryPtr);

	Tcl_SetHashValue(realJumpEntryPtr,
		INT2PTR(jumpTargetBBPtr->startOffset - bbPtr->jumpOffset));
    }
    DEBUG_PRINT("}\n");
}

/*
 *-----------------------------------------------------------------------------
 *
 * CheckForThrowInWrongContext --
 *
 *	Verify that no beginCatch/endCatch sequence can throw an exception
 *	after an original exception is caught and before its exception context
 *	is removed from the stack.
 *
 * Results:
 *	Returns a standard Tcl result.
 *
 * Side effects:
 *	Stores an appropriate error message in the interpreter as needed.
 *
 *-----------------------------------------------------------------------------
 */

static int
CheckForThrowInWrongContext(
    AssemblyEnv* assemEnvPtr)	/* Assembly environment */
{
    BasicBlock* blockPtr;	/* Current basic block */

    /*
     * Walk through the basic blocks in turn, checking all the ones that have
     * caught an exception and not disposed of it properly.
     */

    for (blockPtr = assemEnvPtr->head_bb;
	    blockPtr != NULL;
	    blockPtr = blockPtr->successor1) {
	if (blockPtr->catchState == BBCS_CAUGHT) {
	    /*
	     * Walk through the instructions in the basic block.
	     */

	    if (CheckNonThrowingBlock(assemEnvPtr, blockPtr) != TCL_OK) {
		return TCL_ERROR;
	    }
	}
    }
    return TCL_OK;
}

/*
 *-----------------------------------------------------------------------------
 *
 * CheckNonThrowingBlock --
 *
 *	Check that a basic block cannot throw an exception.
 *
 * Results:
 *	Returns TCL_ERROR if the block cannot be proven to be nonthrowing.
 *
 * Side effects:
 *	Stashes an error message in the interpreter result.
 *
 *-----------------------------------------------------------------------------
 */

static int
CheckNonThrowingBlock(
    AssemblyEnv* assemEnvPtr,	/* Assembly environment */
    BasicBlock* blockPtr)	/* Basic block where exceptions are not
				 * allowed */
{
    CompileEnv* envPtr = assemEnvPtr->envPtr;
				/* Compilation environment */
    Tcl_Interp* interp = (Tcl_Interp*) envPtr->iPtr;
				/* Tcl interpreter */
    BasicBlock* nextPtr;	/* Pointer to the succeeding basic block */
    int offset;			/* Bytecode offset of the current
				 * instruction */
    int bound;			/* Bytecode offset following the last
				 * instruction of the block. */
    unsigned char opcode;	/* Current bytecode instruction */

    /*
     * Determine where in the code array the basic block ends.
     */

    nextPtr = blockPtr->successor1;
    if (nextPtr == NULL) {
	bound = envPtr->codeNext - envPtr->codeStart;
    } else {
	bound = nextPtr->startOffset;
    }

    /*
     * Walk through the instructions of the block.
     */

    offset = blockPtr->startOffset;
    while (offset < bound) {
	/*
	 * Determine whether an instruction is nonthrowing.
	 */

	opcode = (envPtr->codeStart)[offset];
	if (BytecodeMightThrow(opcode)) {
	    /*
	     * Report an error for a throw in the wrong context.
	     */

	    if (assemEnvPtr->flags & TCL_EVAL_DIRECT) {
		Tcl_SetObjResult(interp, Tcl_ObjPrintf(
			"\"%s\" instruction may not appear in "
			"a context where an exception has been "
			"caught and not disposed of.",
			tclInstructionTable[opcode].name));
		Tcl_SetErrorCode(interp, "TCL", "ASSEM", "BADTHROW", NULL);
		AddBasicBlockRangeToErrorInfo(assemEnvPtr, blockPtr);
	    }
	    return TCL_ERROR;
	}
	offset += tclInstructionTable[opcode].numBytes;
    }
    return TCL_OK;
}

/*
 *-----------------------------------------------------------------------------
 *
 * BytecodeMightThrow --
 *
 *	Tests if a given bytecode instruction might throw an exception.
 *
 * Results:
 *	Returns 1 if the bytecode might throw an exception, 0 if the
 *	instruction is known never to throw.
 *
 *-----------------------------------------------------------------------------
 */

static int
BytecodeMightThrow(
    unsigned char opcode)
{
    /*
     * Binary search on the non-throwing bytecode list.
     */

    int min = 0;
    int max = sizeof(NonThrowingByteCodes) - 1;
    int mid;
    unsigned char c;

    while (max >= min) {
	mid = (min + max) / 2;
	c = NonThrowingByteCodes[mid];
	if (opcode < c) {
	    max = mid-1;
	} else if (opcode > c) {
	    min = mid+1;
	} else {
	    /*
	     * Opcode is nonthrowing.
	     */

	    return 0;
	}
    }

    return 1;
}

/*
 *-----------------------------------------------------------------------------
 *
 * CheckStack --
 *
 *	Audit stack usage in a block of assembly code.
 *
 * Results:
 *	Returns a standard Tcl result.
 *
 * Side effects:
 *	Updates stack depth on entry for all basic blocks in the flowgraph.
 *	Calculates the max stack depth used in the program, and updates the
 *	compilation environment to reflect it.
 *
 *-----------------------------------------------------------------------------
 */

static int
CheckStack(
    AssemblyEnv* assemEnvPtr)	/* Assembly environment */
{
    CompileEnv* envPtr = assemEnvPtr->envPtr;
				/* Compilation environment */
    int maxDepth;		/* Maximum stack depth overall */

    /*
     * Checking the head block will check all the other blocks recursively.
     */

    assemEnvPtr->maxDepth = 0;
    if (StackCheckBasicBlock(assemEnvPtr, assemEnvPtr->head_bb, NULL,
	    0) == TCL_ERROR) {
	return TCL_ERROR;
    }

    /*
     * Post the max stack depth back to the compilation environment.
     */

    maxDepth = assemEnvPtr->maxDepth + envPtr->currStackDepth;
    if (maxDepth > envPtr->maxStackDepth) {
	envPtr->maxStackDepth = maxDepth;
    }

    /*
     * If the exit is reachable, make sure that the program exits with 1
     * operand on the stack.
     */

    if (StackCheckExit(assemEnvPtr) != TCL_OK) {
	return TCL_ERROR;
    }

    /*
     * Reset the visited state on all basic blocks.
     */

    ResetVisitedBasicBlocks(assemEnvPtr);
    return TCL_OK;
}

/*
 *-----------------------------------------------------------------------------
 *
 * StackCheckBasicBlock --
 *
 *	Checks stack consumption for a basic block (and recursively for its
 *	successors).
 *
 * Results:
 *	Returns a standard Tcl result.
 *
 * Side effects:
 *	Updates initial stack depth for the basic block and its successors.
 *	(Final and maximum stack depth are relative to initial, and are not
 *	touched).
 *
 * This procedure eventually checks, for the entire flow graph, whether stack
 * balance is consistent.  It is an error for a given basic block to be
 * reachable along multiple flow paths with different stack depths.
 *
 *-----------------------------------------------------------------------------
 */

static int
StackCheckBasicBlock(
    AssemblyEnv* assemEnvPtr,	/* Assembly environment */
    BasicBlock* blockPtr,	/* Pointer to the basic block being checked */
    BasicBlock* predecessor,	/* Pointer to the block that passed control to
				 * this one. */
    int initialStackDepth)	/* Stack depth on entry to the block */
{
    CompileEnv* envPtr = assemEnvPtr->envPtr;
				/* Compilation environment */
    Tcl_Interp* interp = (Tcl_Interp*) envPtr->iPtr;
				/* Tcl interpreter */
    BasicBlock* jumpTarget;	/* Basic block where a jump goes */
    int stackDepth;		/* Current stack depth */
    int maxDepth;		/* Maximum stack depth so far */
    int result;			/* Tcl status return */
    Tcl_HashSearch jtSearch;	/* Search structure for the jump table */
    Tcl_HashEntry* jtEntry;	/* Hash entry in the jump table */
    Tcl_Obj* targetLabel;	/* Target label from the jump table */
    Tcl_HashEntry* entry;	/* Hash entry in the label table */

    if (blockPtr->flags & BB_VISITED) {
	/*
	 * If the block is already visited, check stack depth for consistency
	 * among the paths that reach it.
	 */

	if (blockPtr->initialStackDepth == initialStackDepth) {
	    return TCL_OK;
	}
	if (assemEnvPtr->flags & TCL_EVAL_DIRECT) {
	    Tcl_SetObjResult(interp, Tcl_NewStringObj(
		    "inconsistent stack depths on two execution paths", -1));

	    /*
	     * TODO - add execution trace of both paths
	     */

	    Tcl_SetErrorLine(interp, blockPtr->startLine);
	    Tcl_SetErrorCode(interp, "TCL", "ASSEM", "BADSTACK", NULL);
	}
	return TCL_ERROR;
    }

    /*
     * If the block is not already visited, set the 'predecessor' link to
     * indicate how control got to it. Set the initial stack depth to the
     * current stack depth in the flow of control.
     */

    blockPtr->flags |= BB_VISITED;
    blockPtr->predecessor = predecessor;
    blockPtr->initialStackDepth = initialStackDepth;

    /*
     * Calculate minimum stack depth, and flag an error if the block
     * underflows the stack.
     */

    if (initialStackDepth + blockPtr->minStackDepth < 0) {
	if (assemEnvPtr->flags & TCL_EVAL_DIRECT) {
	    Tcl_SetObjResult(interp, Tcl_NewStringObj("stack underflow", -1));
	    Tcl_SetErrorCode(interp, "TCL", "ASSEM", "BADSTACK", NULL);
	    AddBasicBlockRangeToErrorInfo(assemEnvPtr, blockPtr);
	    Tcl_SetErrorLine(interp, blockPtr->startLine);
	}
	return TCL_ERROR;
    }

    /*
     * Make sure that the block doesn't try to pop below the stack level of an
     * enclosing catch.
     */

    if (blockPtr->enclosingCatch != 0 &&
	    initialStackDepth + blockPtr->minStackDepth
	    < (blockPtr->enclosingCatch->initialStackDepth
		+ blockPtr->enclosingCatch->finalStackDepth)) {
	if (assemEnvPtr->flags & TCL_EVAL_DIRECT) {
	    Tcl_SetObjResult(interp, Tcl_NewStringObj(
		    "code pops stack below level of enclosing catch", -1));
	    Tcl_SetErrorCode(interp, "TCL", "ASSEM", "BADSTACKINCATCH", -1);
	    AddBasicBlockRangeToErrorInfo(assemEnvPtr, blockPtr);
	    Tcl_SetErrorLine(interp, blockPtr->startLine);
	}
	return TCL_ERROR;
    }

    /*
     * Update maximum stgack depth.
     */

    maxDepth = initialStackDepth + blockPtr->maxStackDepth;
    if (maxDepth > assemEnvPtr->maxDepth) {
	assemEnvPtr->maxDepth = maxDepth;
    }

    /*
     * Calculate stack depth on exit from the block, and invoke this procedure
     * recursively to check successor blocks.
     */

    stackDepth = initialStackDepth + blockPtr->finalStackDepth;
    result = TCL_OK;
    if (blockPtr->flags & BB_FALLTHRU) {
	result = StackCheckBasicBlock(assemEnvPtr, blockPtr->successor1,
		blockPtr, stackDepth);
    }

    if (result == TCL_OK && blockPtr->jumpTarget != NULL) {
	entry = Tcl_FindHashEntry(&assemEnvPtr->labelHash,
		Tcl_GetString(blockPtr->jumpTarget));
	jumpTarget = Tcl_GetHashValue(entry);
	result = StackCheckBasicBlock(assemEnvPtr, jumpTarget, blockPtr,
		stackDepth);
    }

    /*
     * All blocks referenced in a jump table are successors.
     */

    if (blockPtr->flags & BB_JUMPTABLE) {
	for (jtEntry = Tcl_FirstHashEntry(&blockPtr->jtPtr->hashTable,
		    &jtSearch);
		result == TCL_OK && jtEntry != NULL;
		jtEntry = Tcl_NextHashEntry(&jtSearch)) {
	    targetLabel = Tcl_GetHashValue(jtEntry);
	    entry = Tcl_FindHashEntry(&assemEnvPtr->labelHash,
		    Tcl_GetString(targetLabel));
	    jumpTarget = Tcl_GetHashValue(entry);
	    result = StackCheckBasicBlock(assemEnvPtr, jumpTarget,
		    blockPtr, stackDepth);
	}
    }

    return result;
}

/*
 *-----------------------------------------------------------------------------
 *
 * StackCheckExit --
 *
 *	Makes sure that the net stack effect of an entire assembly language
 *	script is to push 1 result.
 *
 * Results:
 *	Returns a standard Tcl result, with an error message in the
 *	interpreter result if the stack is wrong.
 *
 * Side effects:
 *	If the assembly code had a net stack effect of zero, emits code to the
 *	concluding block to push a null result. In any case, updates the stack
 *	depth in the compile environment to reflect the net effect of the
 *	assembly code.
 *
 *-----------------------------------------------------------------------------
 */

static int
StackCheckExit(
    AssemblyEnv* assemEnvPtr)	/* Assembly environment */
{
    CompileEnv* envPtr = assemEnvPtr->envPtr;
				/* Compilation environment */
    Tcl_Interp* interp = (Tcl_Interp*) envPtr->iPtr;
				/* Tcl interpreter */
    int depth;			/* Net stack effect */
    int litIndex;		/* Index in the literal pool of the empty
				 * string */
    BasicBlock* curr_bb = assemEnvPtr->curr_bb;
				/* Final basic block in the assembly */

    /*
     * Don't perform these checks if execution doesn't reach the exit (either
     * because of an infinite loop or because the only return is from the
     * middle.
     */

    if (curr_bb->flags & BB_VISITED) {
	/*
	 * Exit with no operands; push an empty one.
	 */

	depth = curr_bb->finalStackDepth + curr_bb->initialStackDepth;
	if (depth == 0) {
	    /*
	     * Emit a 'push' of the empty literal.
	     */

	    litIndex = TclRegisterNewLiteral(envPtr, "", 0);

	    /*
	     * Assumes that 'push' is at slot 0 in TalInstructionTable.
	     */

	    BBEmitInst1or4(assemEnvPtr, 0, litIndex, 0);
	    ++depth;
	}

	/*
	 * Exit with unbalanced stack.
	 */

	if (depth != 1) {
	    if (assemEnvPtr->flags & TCL_EVAL_DIRECT) {
		Tcl_SetObjResult(interp, Tcl_ObjPrintf(
			"stack is unbalanced on exit from the code (depth=%d)",
			depth));
		Tcl_SetErrorCode(interp, "TCL", "ASSEM", "BADSTACK", NULL);
	    }
	    return TCL_ERROR;
	}

	/*
	 * Record stack usage.
	 */

	envPtr->currStackDepth += depth;
    }

    return TCL_OK;
}

/*
 *-----------------------------------------------------------------------------
 *
 * ProcessCatches --
 *
 *	First pass of 'catch' processing.
 *
 * Results:
 *	Returns a standard Tcl result, with an appropriate error message if
 *	the result is TCL_ERROR.
 *
 * Side effects:
 *	Labels all basic blocks with their enclosing catches.
 *
 *-----------------------------------------------------------------------------
 */

static int
ProcessCatches(
    AssemblyEnv* assemEnvPtr)	/* Assembly environment */
{
    BasicBlock* blockPtr;	/* Pointer to a basic block */

    /*
     * Clear the catch state of all basic blocks.
     */

    for (blockPtr = assemEnvPtr->head_bb;
	    blockPtr != NULL;
	    blockPtr = blockPtr->successor1) {
	blockPtr->catchState = BBCS_UNKNOWN;
	blockPtr->enclosingCatch = NULL;
    }

    /*
     * Start the check recursively from the first basic block, which is
     * outside any exception context
     */

    if (ProcessCatchesInBasicBlock(assemEnvPtr, assemEnvPtr->head_bb,
	    NULL, BBCS_NONE, 0) != TCL_OK) {
	return TCL_ERROR;
    }

    /*
     * Check for unclosed catch on exit.
     */

    if (CheckForUnclosedCatches(assemEnvPtr) != TCL_OK) {
	return TCL_ERROR;
    }

    /*
     * Now there's enough information to build the exception ranges.
     */

    if (BuildExceptionRanges(assemEnvPtr) != TCL_OK) {
	return TCL_ERROR;
    }

    /*
     * Finally, restore any exception ranges from embedded scripts.
     */

    RestoreEmbeddedExceptionRanges(assemEnvPtr);
    return TCL_OK;
}

/*
 *-----------------------------------------------------------------------------
 *
 * ProcessCatchesInBasicBlock --
 *
 *	First-pass catch processing for one basic block.
 *
 * Results:
 *	Returns a standard Tcl result, with error message in the interpreter
 *	result if an error occurs.
 *
 * This procedure checks consistency of the exception context through the
 * assembler program, and records the enclosing 'catch' for every basic block.
 *
 *-----------------------------------------------------------------------------
 */

static int
ProcessCatchesInBasicBlock(
    AssemblyEnv* assemEnvPtr,	/* Assembly environment */
    BasicBlock* bbPtr,		/* Basic block being processed */
    BasicBlock* enclosing,	/* Start basic block of the enclosing catch */
    enum BasicBlockCatchState state,
				/* BBCS_NONE, BBCS_INCATCH, or BBCS_CAUGHT */
    int catchDepth)		/* Depth of nesting of catches */
{
    CompileEnv* envPtr = assemEnvPtr->envPtr;
				/* Compilation environment */
    Tcl_Interp* interp = (Tcl_Interp*) envPtr->iPtr;
				/* Tcl interpreter */
    int result;			/* Return value from this procedure */
    BasicBlock* fallThruEnclosing;
				/* Enclosing catch if execution falls thru */
    enum BasicBlockCatchState fallThruState;
				/* Catch state of the successor block */
    BasicBlock* jumpEnclosing;	/* Enclosing catch if execution goes to jump
				 * target */
    enum BasicBlockCatchState jumpState;
				/* Catch state of the jump target */
    int changed = 0;		/* Flag == 1 iff successor blocks need to be
				 * checked because the state of this block has
				 * changed. */
    BasicBlock* jumpTarget;	/* Basic block where a jump goes */
    Tcl_HashSearch jtSearch;	/* Hash search control for a jumptable */
    Tcl_HashEntry* jtEntry;	/* Entry in a jumptable */
    Tcl_Obj* targetLabel;	/* Target label from a jumptable */
    Tcl_HashEntry* entry;	/* Entry from the label table */

    /*
     * Update the state of the current block, checking for consistency.  Set
     * 'changed' to 1 if the state changes and successor blocks need to be
     * rechecked.
     */

    if (bbPtr->catchState == BBCS_UNKNOWN) {
	bbPtr->enclosingCatch = enclosing;
    } else if (bbPtr->enclosingCatch != enclosing) {
	if (assemEnvPtr->flags & TCL_EVAL_DIRECT) {
	    Tcl_SetObjResult(interp, Tcl_NewStringObj(
		    "execution reaches an instruction in inconsistent "
		    "exception contexts", -1));
	    Tcl_SetErrorLine(interp, bbPtr->startLine);
	    Tcl_SetErrorCode(interp, "TCL", "ASSEM", "BADCATCH", NULL);
	}
	return TCL_ERROR;
    }
    if (state > bbPtr->catchState) {
	bbPtr->catchState = state;
	changed = 1;
    }

    /*
     * If this block has been visited before, and its state hasn't changed,
     * we're done with it for now.
     */

    if (!changed) {
	return TCL_OK;
    }
    bbPtr->catchDepth = catchDepth;

    /*
     * Determine enclosing catch and 'caught' state for the fallthrough and
     * the jump target. Default for both is the state of the current block.
     */

    fallThruEnclosing = enclosing;
    fallThruState = state;
    jumpEnclosing = enclosing;
    jumpState = state;

    /*
     * TODO: Make sure that the test cases include validating that a natural
     * loop can't include 'beginCatch' or 'endCatch'
     */

    if (bbPtr->flags & BB_BEGINCATCH) {
	/*
	 * If the block begins a catch, the state for the successor is 'in
	 * catch'. The jump target is the exception exit, and the state of the
	 * jump target is 'caught.'
	 */

	fallThruEnclosing = bbPtr;
	fallThruState = BBCS_INCATCH;
	jumpEnclosing = bbPtr;
	jumpState = BBCS_CAUGHT;
	++catchDepth;
    }

    if (bbPtr->flags & BB_ENDCATCH) {
	/*
	 * If the block ends a catch, the state for the successor is whatever
	 * the state was on entry to the catch.
	 */

	if (enclosing == NULL) {
	    if (assemEnvPtr->flags & TCL_EVAL_DIRECT) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj(
			"endCatch without a corresponding beginCatch", -1));
		Tcl_SetErrorLine(interp, bbPtr->startLine);
		Tcl_SetErrorCode(interp, "TCL", "ASSEM", "BADENDCATCH", NULL);
	    }
	    return TCL_ERROR;
	}
	fallThruEnclosing = enclosing->enclosingCatch;
	fallThruState = enclosing->catchState;
	--catchDepth;
    }

    /*
     * Visit any successor blocks with the appropriate exception context
     */

    result = TCL_OK;
    if (bbPtr->flags & BB_FALLTHRU) {
	result = ProcessCatchesInBasicBlock(assemEnvPtr, bbPtr->successor1,
		fallThruEnclosing, fallThruState, catchDepth);
    }
    if (result == TCL_OK && bbPtr->jumpTarget != NULL) {
	entry = Tcl_FindHashEntry(&assemEnvPtr->labelHash,
		Tcl_GetString(bbPtr->jumpTarget));
	jumpTarget = Tcl_GetHashValue(entry);
	result = ProcessCatchesInBasicBlock(assemEnvPtr, jumpTarget,
		jumpEnclosing, jumpState, catchDepth);
    }

    /*
     * All blocks referenced in a jump table are successors.
     */

    if (bbPtr->flags & BB_JUMPTABLE) {
	for (jtEntry = Tcl_FirstHashEntry(&bbPtr->jtPtr->hashTable,&jtSearch);
		result == TCL_OK && jtEntry != NULL;
		jtEntry = Tcl_NextHashEntry(&jtSearch)) {
	    targetLabel = Tcl_GetHashValue(jtEntry);
	    entry = Tcl_FindHashEntry(&assemEnvPtr->labelHash,
		    Tcl_GetString(targetLabel));
	    jumpTarget = Tcl_GetHashValue(entry);
	    result = ProcessCatchesInBasicBlock(assemEnvPtr, jumpTarget,
		    jumpEnclosing, jumpState, catchDepth);
	}
    }

    return result;
}

/*
 *-----------------------------------------------------------------------------
 *
 * CheckForUnclosedCatches --
 *
 *	Checks that a sequence of assembly code has no unclosed catches on
 *	exit.
 *
 * Results:
 *	Returns a standard Tcl result, with an error message for unclosed
 *	catches.
 *
 *-----------------------------------------------------------------------------
 */

static int
CheckForUnclosedCatches(
    AssemblyEnv* assemEnvPtr)	/* Assembly environment */
{
    CompileEnv* envPtr = assemEnvPtr->envPtr;
				/* Compilation environment */
    Tcl_Interp* interp = (Tcl_Interp*) envPtr->iPtr;
				/* Tcl interpreter */

    if (assemEnvPtr->curr_bb->catchState >= BBCS_INCATCH) {
	if (assemEnvPtr->flags & TCL_EVAL_DIRECT) {
	    Tcl_SetObjResult(interp, Tcl_NewStringObj(
		    "catch still active on exit from assembly code", -1));
	    Tcl_SetErrorLine(interp,
		    assemEnvPtr->curr_bb->enclosingCatch->startLine);
	    Tcl_SetErrorCode(interp, "TCL", "ASSEM", "UNCLOSEDCATCH", NULL);
	}
	return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 *-----------------------------------------------------------------------------
 *
 * BuildExceptionRanges --
 *
 *	Walks through the assembly code and builds exception ranges for the
 *	catches embedded therein.
 *
 * Results:
 *	Returns a standard Tcl result with an error message in the interpreter
 *	if anything is unsuccessful.
 *
 * Side effects:
 *	Each contiguous block of code with a given catch exit is assigned an
 *	exception range at the appropriate level.
 *	Exception ranges in embedded blocks have their levels corrected and
 *	collated into the table.
 *	Blocks that end with 'beginCatch' are associated with the innermost
 *	exception range of the following block.
 *
 *-----------------------------------------------------------------------------
 */

static int
BuildExceptionRanges(
    AssemblyEnv* assemEnvPtr)	/* Assembly environment */
{
    CompileEnv* envPtr = assemEnvPtr->envPtr;
				/* Compilation environment */
    BasicBlock* bbPtr;		/* Current basic block */
    BasicBlock* prevPtr = NULL;	/* Previous basic block */
    int catchDepth = 0;		/* Current catch depth */
    int maxCatchDepth = 0;	/* Maximum catch depth in the program */
    BasicBlock** catches;	/* Stack of catches in progress */
    int* catchIndices;		/* Indices of the exception ranges of catches
				 * in progress */
    int i;

    /*
     * Determine the max catch depth for the entire assembly script
     * (excluding embedded eval's and expr's, which will be handled later).
     */

    for (bbPtr=assemEnvPtr->head_bb; bbPtr != NULL; bbPtr=bbPtr->successor1) {
	if (bbPtr->catchDepth > maxCatchDepth) {
	    maxCatchDepth = bbPtr->catchDepth;
	}
    }

    /*
     * Allocate memory for a stack of active catches.
     */

    catches = ckalloc(maxCatchDepth * sizeof(BasicBlock*));
    catchIndices = ckalloc(maxCatchDepth * sizeof(int));
    for (i = 0; i < maxCatchDepth; ++i) {
	catches[i] = NULL;
	catchIndices[i] = -1;
    }

    /*
     * Walk through the basic blocks and manage exception ranges.
     */

    for (bbPtr=assemEnvPtr->head_bb; bbPtr != NULL; bbPtr=bbPtr->successor1) {
	UnstackExpiredCatches(envPtr, bbPtr, catchDepth, catches,
		catchIndices);
	LookForFreshCatches(bbPtr, catches);
	StackFreshCatches(assemEnvPtr, bbPtr, catchDepth, catches,
		catchIndices);

	/*
	 * If the last block was a 'begin catch', fill in the exception range.
	 */

	catchDepth = bbPtr->catchDepth;
	if (prevPtr != NULL && (prevPtr->flags & BB_BEGINCATCH)) {
	    TclStoreInt4AtPtr(catchIndices[catchDepth-1],
		    envPtr->codeStart + bbPtr->startOffset - 4);
	}

	prevPtr = bbPtr;
    }

    /* Make sure that all catches are closed */

    if (catchDepth != 0) {
	Tcl_Panic("unclosed catch at end of code in "
		"tclAssembly.c:BuildExceptionRanges, can't happen");
    }

    /* Free temp storage */

    ckfree(catchIndices);
    ckfree(catches);

    return TCL_OK;
}

/*
 *-----------------------------------------------------------------------------
 *
 * UnstackExpiredCatches --
 *
 *	Unstacks and closes the exception ranges for any catch contexts that
 *	were active in the previous basic block but are inactive in the
 *	current one.
 *
 *-----------------------------------------------------------------------------
 */

static void
UnstackExpiredCatches(
    CompileEnv* envPtr,		/* Compilation environment */
    BasicBlock* bbPtr,		/* Basic block being processed */
    int catchDepth,		/* Depth of nesting of catches prior to entry
				 * to this block */
    BasicBlock** catches,	/* Array of catch contexts */
    int* catchIndices)		/* Indices of the exception ranges
				 * corresponding to the catch contexts */
{
    ExceptionRange* range;	/* Exception range for a specific catch */
    BasicBlock* catch;		/* Catch block being examined */
    BasicBlockCatchState catchState;
				/* State of the code relative to the catch
				 * block being examined ("in catch" or
				 * "caught"). */

    /*
     * Unstack any catches that are deeper than the nesting level of the basic
     * block being entered.
     */

    while (catchDepth > bbPtr->catchDepth) {
	--catchDepth;
	if (catches[catchDepth] != NULL) {
	    range = envPtr->exceptArrayPtr + catchIndices[catchDepth];
	    range->numCodeBytes = bbPtr->startOffset - range->codeOffset;
	    catches[catchDepth] = NULL;
	    catchIndices[catchDepth] = -1;
	}
    }

    /*
     * Unstack any catches that don't match the basic block being entered,
     * either because they are no longer part of the context, or because the
     * context has changed from INCATCH to CAUGHT.
     */

    catchState = bbPtr->catchState;
    catch = bbPtr->enclosingCatch;
    while (catchDepth > 0) {
	--catchDepth;
	if (catches[catchDepth] != NULL) {
	    if (catches[catchDepth] != catch || catchState >= BBCS_CAUGHT) {
		range = envPtr->exceptArrayPtr + catchIndices[catchDepth];
		range->numCodeBytes = bbPtr->startOffset - range->codeOffset;
		catches[catchDepth] = NULL;
		catchIndices[catchDepth] = -1;
	    }
	    catchState = catch->catchState;
	    catch = catch->enclosingCatch;
	}
    }
}

/*
 *-----------------------------------------------------------------------------
 *
 * LookForFreshCatches --
 *
 *	Determines whether a basic block being entered needs any exception
 *	ranges that are not already stacked.
 *
 * Does not create the ranges: this procedure iterates from the innermost
 * catch outward, but exception ranges must be created from the outermost
 * catch inward.
 *
 *-----------------------------------------------------------------------------
 */

static void
LookForFreshCatches(
    BasicBlock* bbPtr,		/* Basic block being entered */
    BasicBlock** catches)	/* Array of catch contexts that are already
				 * entered */
{
    BasicBlockCatchState catchState;
				/* State ("in catch" or "caught") of the
				 * current catch. */
    BasicBlock* catch;		/* Current enclosing catch */
    int catchDepth;		/* Nesting depth of the current catch */

    catchState = bbPtr->catchState;
    catch = bbPtr->enclosingCatch;
    catchDepth = bbPtr->catchDepth;
    while (catchDepth > 0) {
	--catchDepth;
	if (catches[catchDepth] != catch && catchState < BBCS_CAUGHT) {
	    catches[catchDepth] = catch;
	}
	catchState = catch->catchState;
	catch = catch->enclosingCatch;
    }
}

/*
 *-----------------------------------------------------------------------------
 *
 * StackFreshCatches --
 *
 *	Make ExceptionRange records for any catches that are in the basic
 *	block being entered and were not in the previous basic block.
 *
 *-----------------------------------------------------------------------------
 */

static void
StackFreshCatches(
    AssemblyEnv* assemEnvPtr,	/* Assembly environment */
    BasicBlock* bbPtr,		/* Basic block being processed */
    int catchDepth,		/* Depth of nesting of catches prior to entry
				 * to this block */
    BasicBlock** catches,	/* Array of catch contexts */
    int* catchIndices)		/* Indices of the exception ranges
				 * corresponding to the catch contexts */
{
    CompileEnv* envPtr = assemEnvPtr->envPtr;
				/* Compilation environment */
    ExceptionRange* range;	/* Exception range for a specific catch */
    BasicBlock* catch;		/* Catch block being examined */
    BasicBlock* errorExit;	/* Error exit from the catch block */
    Tcl_HashEntry* entryPtr;

    catchDepth = 0;

    /*
     * Iterate through the enclosing catch blocks from the outside in,
     * looking for ones that don't have exception ranges (and are uncaught)
     */

    for (catchDepth = 0; catchDepth < bbPtr->catchDepth; ++catchDepth) {
	if (catchIndices[catchDepth] == -1 && catches[catchDepth] != NULL) {
	    /*
	     * Create an exception range for a block that needs one.
	     */

	    catch = catches[catchDepth];
	    catchIndices[catchDepth] =
		    TclCreateExceptRange(CATCH_EXCEPTION_RANGE, envPtr);
	    range = envPtr->exceptArrayPtr + catchIndices[catchDepth];
	    range->nestingLevel = envPtr->exceptDepth + catchDepth;
	    envPtr->maxExceptDepth =
		    TclMax(range->nestingLevel + 1, envPtr->maxExceptDepth);
	    range->codeOffset = bbPtr->startOffset;

	    entryPtr = Tcl_FindHashEntry(&assemEnvPtr->labelHash,
		    Tcl_GetString(catch->jumpTarget));
	    if (entryPtr == NULL) {
		Tcl_Panic("undefined label in tclAssembly.c:"
			"BuildExceptionRanges, can't happen");
	    }

	    errorExit = Tcl_GetHashValue(entryPtr);
	    range->catchOffset = errorExit->startOffset;
	}
    }
}

/*
 *-----------------------------------------------------------------------------
 *
 * RestoreEmbeddedExceptionRanges --
 *
 *	Processes an assembly script, replacing any exception ranges that
 *	were present in embedded code.
 *
 *-----------------------------------------------------------------------------
 */

static void
RestoreEmbeddedExceptionRanges(
    AssemblyEnv* assemEnvPtr)	/* Assembly environment */
{
    CompileEnv* envPtr = assemEnvPtr->envPtr;
				/* Compilation environment */
    BasicBlock* bbPtr;		/* Current basic block */
    int rangeBase;		/* Base of the foreign exception ranges when
				 * they are reinstalled */
    int rangeIndex;		/* Index of the current foreign exception
				 * range as reinstalled */
    ExceptionRange* range;	/* Current foreign exception range */
    unsigned char opcode;	/* Current instruction's opcode */
    int catchIndex;		/* Index of the exception range to which the
				 * current instruction refers */
    int i;

    /*
     * Walk the basic blocks looking for exceptions in embedded scripts.
     */

    for (bbPtr = assemEnvPtr->head_bb;
	    bbPtr != NULL;
	    bbPtr = bbPtr->successor1) {
	if (bbPtr->foreignExceptionCount != 0) {
	    /*
	     * Reinstall the embedded exceptions and track their nesting level
	     */

	    rangeBase = envPtr->exceptArrayNext;
	    for (i = 0; i < bbPtr->foreignExceptionCount; ++i) {
		range = bbPtr->foreignExceptions + i;
		rangeIndex = TclCreateExceptRange(range->type, envPtr);
		range->nestingLevel += envPtr->exceptDepth + bbPtr->catchDepth;
		memcpy(envPtr->exceptArrayPtr + rangeIndex, range,
			sizeof(ExceptionRange));
		if (range->nestingLevel >= envPtr->maxExceptDepth) {
		    envPtr->maxExceptDepth = range->nestingLevel + 1;
		}
	    }

	    /*
	     * Walk through the bytecode of the basic block, and relocate
	     * INST_BEGIN_CATCH4 instructions to the new locations
	     */

	    i = bbPtr->startOffset;
	    while (i < bbPtr->successor1->startOffset) {
		opcode = envPtr->codeStart[i];
		if (opcode == INST_BEGIN_CATCH4) {
		    catchIndex = TclGetUInt4AtPtr(envPtr->codeStart + i + 1);
		    if (catchIndex >= bbPtr->foreignExceptionBase
			    && catchIndex < (bbPtr->foreignExceptionBase +
			    bbPtr->foreignExceptionCount)) {
			catchIndex -= bbPtr->foreignExceptionBase;
			catchIndex += rangeBase;
			TclStoreInt4AtPtr(catchIndex, envPtr->codeStart+i+1);
		    }
		}
		i += tclInstructionTable[opcode].numBytes;
	    }
	}
    }
}

/*
 *-----------------------------------------------------------------------------
 *
 * ResetVisitedBasicBlocks --
 *
 *	Turns off the 'visited' flag in all basic blocks at the conclusion
 *	of a pass.
 *
 *-----------------------------------------------------------------------------
 */

static void
ResetVisitedBasicBlocks(
    AssemblyEnv* assemEnvPtr)	/* Assembly environment */
{
    BasicBlock* block;

    for (block = assemEnvPtr->head_bb; block != NULL;
	    block = block->successor1) {
	block->flags &= ~BB_VISITED;
    }
}

/*
 *-----------------------------------------------------------------------------
 *
 * AddBasicBlockRangeToErrorInfo --
 *
 *	Updates the error info of the Tcl interpreter to show a given basic
 *	block in the code.
 *
 * This procedure is used to label the callstack with source location
 * information when reporting an error in stack checking.
 *
 *-----------------------------------------------------------------------------
 */

static void
AddBasicBlockRangeToErrorInfo(
    AssemblyEnv* assemEnvPtr,	/* Assembly environment */
    BasicBlock* bbPtr)		/* Basic block in which the error is found */
{
    CompileEnv* envPtr = assemEnvPtr->envPtr;
				/* Compilation environment */
    Tcl_Interp* interp = (Tcl_Interp*) envPtr->iPtr;
				/* Tcl interpreter */
    Tcl_Obj* lineNo;		/* Line number in the source */

    Tcl_AddErrorInfo(interp, "\n    in assembly code between lines ");
    lineNo = Tcl_NewIntObj(bbPtr->startLine);
    Tcl_IncrRefCount(lineNo);
    Tcl_AppendObjToErrorInfo(interp, lineNo);
    Tcl_AddErrorInfo(interp, " and ");
    if (bbPtr->successor1 != NULL) {
	Tcl_SetIntObj(lineNo, bbPtr->successor1->startLine);
	Tcl_AppendObjToErrorInfo(interp, lineNo);
    } else {
	Tcl_AddErrorInfo(interp, "end of assembly code");
    }
    Tcl_DecrRefCount(lineNo);
}

/*
 *-----------------------------------------------------------------------------
 *
 * DupAssembleCodeInternalRep --
 *
 *	Part of the Tcl object type implementation for Tcl assembly language
 *	bytecode. We do not copy the bytecode intrep. Instead, we return
 *	without setting copyPtr->typePtr, so the copy is a plain string copy
 *	of the assembly source, and if it is to be used as a compiled
 *	expression, it will need to be reprocessed.
 *
 *	This makes sense, because with Tcl's copy-on-write practices, the
 *	usual (only?) time Tcl_DuplicateObj() will be called is when the copy
 *	is about to be modified, which would invalidate any copied bytecode
 *	anyway. The only reason it might make sense to copy the bytecode is if
 *	we had some modifying routines that operated directly on the intrep,
 *	as we do for lists and dicts.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *-----------------------------------------------------------------------------
 */

static void
DupAssembleCodeInternalRep(
    Tcl_Obj *srcPtr,
    Tcl_Obj *copyPtr)
{
    return;
}

/*
 *-----------------------------------------------------------------------------
 *
 * FreeAssembleCodeInternalRep --
 *
 *	Part of the Tcl object type implementation for Tcl expression
 *	bytecode. Frees the storage allocated to hold the internal rep, unless
 *	ref counts indicate bytecode execution is still in progress.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	May free allocated memory. Leaves objPtr untyped.
 *
 *-----------------------------------------------------------------------------
 */

static void
FreeAssembleCodeInternalRep(
    Tcl_Obj *objPtr)
{
    ByteCode *codePtr = objPtr->internalRep.twoPtrValue.ptr1;

    codePtr->refCount--;
    if (codePtr->refCount <= 0) {
	TclCleanupByteCode(codePtr);
    }
    objPtr->typePtr = NULL;
}

/*
 * Local Variables:
 * mode: c
 * c-basic-offset: 4
 * fill-column: 78
 * End:
 */
hl str">", name.data(),root->section,root->tArgLists ? (int)root->tArgLists->count() : -1); usingCd = new ClassDef( "<using>",1, name,ClassDef::Class); Doxygen::hiddenClasses->append(root->name,usingCd); usingCd->setArtificial(TRUE); } else { Debug::print(Debug::Classes,0," Found used class %s in scope=%s\n", usingCd->name().data(),nd?nd->name().data():fd->name().data()); } #if 0 if (mtd) // add the typedef to the correct scope { if (nd) { //printf("Inside namespace %s\n",nd->name().data()); nd->addUsingDeclaration(mtd); } else if (fd) { //printf("Inside file %s\n",nd->name().data()); fd->addUsingDeclaration(mtd); } } else #endif if (usingCd) // add the class to the correct scope { if (nd) { //printf("Inside namespace %s\n",nd->name().data()); nd->addUsingDeclaration(usingCd); } else if (fd) { //printf("Inside file %s\n",nd->name().data()); fd->addUsingDeclaration(usingCd); } } } rootNav->releaseEntry(); } RECURSE_ENTRYTREE(findUsingDeclarations,rootNav); } //---------------------------------------------------------------------- static void findUsingDeclImports(EntryNav *rootNav) { if (rootNav->section()==Entry::USINGDECL_SEC && (rootNav->parent()->section()&Entry::COMPOUND_MASK) // in a class/struct member ) { //printf("Found using declaration %s at line %d of %s inside section %x\n", // root->name.data(),root->startLine,root->fileName.data(), // root->parent->section); QCString fullName=removeRedundantWhiteSpace(rootNav->parent()->name()); fullName=stripAnonymousNamespaceScope(fullName); fullName=stripTemplateSpecifiersFromScope(fullName); ClassDef *cd = getClass(fullName); if (cd) { //printf("found class %s\n",cd->name().data()); int i=rootNav->name().find("::"); if (i!=-1) { QCString scope=rootNav->name().left(i); QCString memName=rootNav->name().right(rootNav->name().length()-i-2); ClassDef *bcd = getResolvedClass(cd,0,scope); // todo: file in fileScope parameter if (bcd) { //printf("found class %s\n",bcd->name().data()); MemberNameInfoSDict *mndict=bcd->memberNameInfoSDict(); if (mndict) { MemberNameInfo *mni = mndict->find(memName); if (mni) { MemberNameInfoIterator mnii(*mni); MemberInfo *mi; for ( ; (mi=mnii.current()) ; ++mnii ) { MemberDef *md = mi->memberDef; if (md && md->protection()!=Private) { rootNav->loadEntry(g_storage); Entry *root = rootNav->entry(); //printf("found member %s\n",mni->memberName()); MemberDef *newMd = 0; { LockingPtr<ArgumentList> templAl = md->templateArguments(); LockingPtr<ArgumentList> al = md->templateArguments(); newMd = new MemberDef( root->fileName,root->startLine, md->typeString(),memName,md->argsString(), md->excpString(),root->protection,root->virt, md->isStatic(),Member,md->memberType(), templAl.pointer(),al.pointer() ); } newMd->setMemberClass(cd); cd->insertMember(newMd); if (!root->doc.isEmpty() || !root->brief.isEmpty()) { newMd->setDocumentation(root->doc,root->docFile,root->docLine); newMd->setBriefDescription(root->brief,root->briefFile,root->briefLine); newMd->setInbodyDocumentation(root->inbodyDocs,root->inbodyFile,root->inbodyLine); } else { newMd->setDocumentation(md->documentation(),md->docFile(),md->docLine()); newMd->setBriefDescription(md->briefDescription(),md->briefFile(),md->briefLine()); newMd->setInbodyDocumentation(md->inbodyDocumentation(),md->inbodyFile(),md->inbodyLine()); } newMd->setDefinition(md->definition()); newMd->enableCallGraph(root->callGraph); newMd->enableCallerGraph(root->callerGraph); newMd->setBitfields(md->bitfieldString()); newMd->addSectionsToDefinition(root->anchors); newMd->setBodySegment(md->getStartBodyLine(),md->getEndBodyLine()); newMd->setBodyDef(md->getBodyDef()); newMd->setInitializer(md->initializer()); newMd->setMaxInitLines(md->initializerLines()); newMd->setMemberGroupId(root->mGrpId); newMd->setMemberSpecifiers(md->getMemberSpecifiers()); rootNav->releaseEntry(); } } } } } } } } RECURSE_ENTRYTREE(findUsingDeclImports,rootNav); } //---------------------------------------------------------------------- static void findIncludedUsingDirectives() { // first mark all files as not visited FileNameListIterator fnli(*Doxygen::inputNameList); FileName *fn; for (fnli.toFirst();(fn=fnli.current());++fnli) { FileNameIterator fni(*fn); FileDef *fd; for (;(fd=fni.current());++fni) { fd->visited=FALSE; } } // then recursively add using directives found in #include files // to files that have not been visited. for (fnli.toFirst();(fn=fnli.current());++fnli) { FileNameIterator fni(*fn); FileDef *fd; for (fni.toFirst();(fd=fni.current());++fni) { if (!fd->visited) { //printf("----- adding using directives for file %s\n",fd->name().data()); fd->addIncludedUsingDirectives(); } } } } //---------------------------------------------------------------------- static MemberDef *addVariableToClass( EntryNav *rootNav, ClassDef *cd, MemberDef::MemberType mtype, const QCString &name, bool fromAnnScope, MemberDef *fromAnnMemb, Protection prot, Relationship related) { Entry *root = rootNav->entry(); QCString qualScope = cd->qualifiedNameWithTemplateParameters(); QCString scopeSeparator="::"; if (Config_getBool("OPTIMIZE_OUTPUT_JAVA")) { qualScope = substitute(qualScope,"::","."); scopeSeparator="."; } Debug::print(Debug::Variables,0, " class variable:\n" " `%s' `%s'::`%s' `%s' prot=`%d ann=%d init=`%s'\n", root->type.data(), qualScope.data(), name.data(), root->args.data(), root->protection, fromAnnScope, root->initializer.data() ); QCString def; if (!root->type.isEmpty()) { if (related || mtype==MemberDef::Friend || Config_getBool("HIDE_SCOPE_NAMES")) { def=root->type+" "+name+root->args; } else { def=root->type+" "+qualScope+scopeSeparator+name+root->args; } } else { if (Config_getBool("HIDE_SCOPE_NAMES")) { def=name+root->args; } else { def=qualScope+scopeSeparator+name+root->args; } } def.stripPrefix("static "); // see if the member is already found in the same scope // (this may be the case for a static member that is initialized // outside the class) MemberName *mn=Doxygen::memberNameSDict->find(name); if (mn) { MemberNameIterator mni(*mn); MemberDef *md; for (mni.toFirst();(md=mni.current());++mni) { //printf("md->getClassDef()=%p cd=%p type=[%s] md->typeString()=[%s]\n", // md->getClassDef(),cd,root->type.data(),md->typeString()); if (md->getClassDef()==cd && removeRedundantWhiteSpace(root->type)==md->typeString()) // member already in the scope { if (root->objc && root->mtype==Property && md->memberType()==MemberDef::Variable) { // Objective-C 2.0 property // turn variable into a property md->setProtection(root->protection); cd->reclassifyMember(md,MemberDef::Property); } addMemberDocs(rootNav,md,def,0,FALSE); //printf(" Member already found!\n"); return md; } } } // new member variable, typedef or enum value MemberDef *md=new MemberDef( root->fileName,root->startLine, root->type,name,root->args,0, prot,Normal,root->stat,related, mtype,0,0); md->setTagInfo(rootNav->tagInfo()); md->setMemberClass(cd); // also sets outer scope (i.e. getOuterScope()) //md->setDefFile(root->fileName); //md->setDefLine(root->startLine); md->setDocumentation(root->doc,root->docFile,root->docLine); md->setBriefDescription(root->brief,root->briefFile,root->briefLine); md->setInbodyDocumentation(root->inbodyDocs,root->inbodyFile,root->inbodyLine); md->setDefinition(def); md->setBitfields(root->bitfields); md->addSectionsToDefinition(root->anchors); md->setFromAnonymousScope(fromAnnScope); md->setFromAnonymousMember(fromAnnMemb); //md->setIndentDepth(indentDepth); md->setBodySegment(root->bodyLine,root->endBodyLine); md->setInitializer(root->initializer); md->setMaxInitLines(root->initLines); md->setMemberGroupId(root->mGrpId); md->setMemberSpecifiers(root->spec); md->setReadAccessor(root->read); md->setWriteAccessor(root->write); md->enableCallGraph(root->callGraph); md->enableCallerGraph(root->callerGraph); md->setHidden(root->hidden); md->setArtificial(root->artificial); addMemberToGroups(root,md); //if (root->mGrpId!=-1) //{ // printf("memberdef %s in memberGroup %d\n",name.data(),root->mGrpId); // md->setMemberGroup(memberGroupDict[root->mGrpId]); // md->setBodyDef(rootNav->fileDef()); //printf(" Adding member=%s\n",md->name().data()); // add the member to the global list if (mn) { mn->append(md); } else // new variable name { mn = new MemberName(name); mn->append(md); //printf("Adding memberName=%s\n",mn->memberName()); //Doxygen::memberNameDict.insert(name,mn); //Doxygen::memberNameList.append(mn); Doxygen::memberNameSDict->append(name,mn); // add the member to the class } //printf(" New member adding to %s (%p)!\n",cd->name().data(),cd); cd->insertMember(md); md->setRefItems(root->sli); //TODO: insert FileDef instead of filename strings. cd->insertUsedFile(root->fileName); rootNav->changeSection(Entry::EMPTY_SEC); return md; } //---------------------------------------------------------------------- static MemberDef *addVariableToFile( EntryNav *rootNav, MemberDef::MemberType mtype, const QCString &scope, const QCString &name, bool fromAnnScope, /*int indentDepth,*/ MemberDef *fromAnnMemb) { Entry *root = rootNav->entry(); Debug::print(Debug::Variables,0, " global variable:\n" " type=`%s' scope=`%s' name=`%s' args=`%s' prot=`%d mtype=%d\n", root->type.data(), scope.data(), name.data(), root->args.data(), root->protection, mtype ); FileDef *fd = rootNav->fileDef(); // see if the function is inside a namespace NamespaceDef *nd = 0; QCString nscope; if (!scope.isEmpty()) { nscope=removeAnonymousScopes(scope); if (!nscope.isEmpty()) { nd = getResolvedNamespace(nscope); } } QCString def; // determine the definition of the global variable if (nd && !nd->name().isEmpty() && nd->name().at(0)!='@' && !Config_getBool("HIDE_SCOPE_NAMES") ) // variable is inside a namespace, so put the scope before the name { static bool optimizeForJava = Config_getBool("OPTIMIZE_OUTPUT_JAVA"); QCString sep="::"; if (optimizeForJava) sep="."; if (!root->type.isEmpty()) { def=root->type+" "+nd->name()+sep+name+root->args; } else { def=nd->name()+sep+name+root->args; } } else { if (!root->type.isEmpty() && !root->name.isEmpty()) { if (name.at(0)=='@') // dummy variable representing annonymous union def=root->type; else def=root->type+" "+name+root->args; } else { def=name+root->args; } } def.stripPrefix("static "); MemberName *mn=Doxygen::functionNameSDict->find(name); if (mn) { //QCString nscope=removeAnonymousScopes(scope); //NamespaceDef *nd=0; //if (!nscope.isEmpty()) //{ // nd = getResolvedNamespace(nscope); //} MemberNameIterator mni(*mn); MemberDef *md; for (mni.toFirst();(md=mni.current());++mni) { if ( ((nd==0 && md->getNamespaceDef()==0 && md->getFileDef() && root->fileName==md->getFileDef()->absFilePath() ) // both variable names in the same file || (nd!=0 && md->getNamespaceDef()==nd) // both in same namespace ) && !md->isDefine() // function style #define's can be "overloaded" by typedefs or variables && !md->isEnumerate() // in C# an enum value and enum can have the same name ) // variable already in the scope { if (md->getFileDef() && ! // not a php array ( (getLanguageFromFileName(md->getFileDef()->name())==SrcLangExt_PHP) && (md->argsString()!=root->args && root->args.find('[')!=-1) ) ) // not a php array variable { Debug::print(Debug::Variables,0, " variable already found: scope=%s\n",md->getOuterScope()->name().data()); addMemberDocs(rootNav,md,def,0,FALSE); md->setRefItems(root->sli); return md; } } } } Debug::print(Debug::Variables,0, " new variable, nd=%s!\n",nd?nd->name().data():"<global>"); // new global variable, enum value or typedef MemberDef *md=new MemberDef( root->fileName,root->startLine, root->type,name,root->args,0, Public, Normal,root->stat,Member, mtype,0,0); md->setTagInfo(rootNav->tagInfo()); md->setDocumentation(root->doc,root->docFile,root->docLine); md->setBriefDescription(root->brief,root->briefFile,root->briefLine); md->setInbodyDocumentation(root->inbodyDocs,root->inbodyFile,root->inbodyLine); md->addSectionsToDefinition(root->anchors); md->setFromAnonymousScope(fromAnnScope); md->setFromAnonymousMember(fromAnnMemb); md->setInitializer(root->initializer); md->setMaxInitLines(root->initLines); md->setMemberGroupId(root->mGrpId); md->setDefinition(def); md->enableCallGraph(root->callGraph); md->enableCallerGraph(root->callerGraph); md->setExplicitExternal(root->explicitExternal); //md->setOuterScope(fd); if (!root->explicitExternal) { md->setBodySegment(root->bodyLine,root->endBodyLine); md->setBodyDef(fd); } addMemberToGroups(root,md); md->setRefItems(root->sli); if (nd && !nd->name().isEmpty() && nd->name().at(0)!='@') { md->setNamespace(nd); nd->insertMember(md); } // add member to the file (we do this even if we have already inserted // it into the namespace. if (fd) { md->setFileDef(fd); fd->insertMember(md); } // add member definition to the list of globals if (mn) { mn->append(md); } else { mn = new MemberName(name); mn->append(md); Doxygen::functionNameSDict->append(name,mn); } rootNav->changeSection(Entry::EMPTY_SEC); return md; } /*! See if the return type string \a type is that of a function pointer * \returns -1 if this is not a function pointer variable or * the index at which the brace of (...*name) was found. */ static int findFunctionPtr(const QCString &type,int *pLength=0) { static const QRegExp re("([^)]*\\*[^)]*)"); int i=-1,l; if (!type.isEmpty() && // return type is non-empty (i=re.match(type,0,&l))!=-1 && // contains (...*...) type.find("operator")==-1 && // not an operator (type.find(")(")==-1 || type.find("typedef ")!=-1) // not a function pointer return type ) { if (pLength) *pLength=l; return i; } else { return -1; } } /*! Returns TRUE iff \a type is a class within scope \a context. * Used to detect variable declarations that look like function prototypes. */ static bool isVarWithConstructor(EntryNav *rootNav) { static QRegExp initChars("[0-9\"'&*!^]+"); static QRegExp idChars("[a-z_A-Z][a-z_A-Z0-9]*"); bool result=FALSE; bool typeIsClass; QCString type; Definition *ctx = 0; FileDef *fd = 0; int ti; //printf("isVarWithConstructor(%s)\n",rootNav->name().data()); rootNav->loadEntry(g_storage); Entry *root = rootNav->entry(); if (rootNav->parent()->section() & Entry::COMPOUND_MASK) { // inside a class result=FALSE; goto done; } else if ((fd = rootNav->fileDef()) && (fd->name().right(2)==".c" || fd->name().right(2)==".h") ) { // inside a .c file result=FALSE; goto done; } if (root->type.isEmpty()) { result=FALSE; goto done; } if (!rootNav->parent()->name().isEmpty()) { ctx=Doxygen::namespaceSDict->find(rootNav->parent()->name()); } type = root->type; // remove qualifiers findAndRemoveWord(type,"const"); findAndRemoveWord(type,"static"); findAndRemoveWord(type,"volatile"); //if (type.left(6)=="const ") type=type.right(type.length()-6); typeIsClass=getResolvedClass(ctx,fd,type)!=0; if (!typeIsClass && (ti=type.find('<'))!=-1) { typeIsClass=getResolvedClass(ctx,fd,type.left(ti))!=0; } if (typeIsClass) // now we still have to check if the arguments are // types or values. Since we do not have complete type info // we need to rely on heuristics :-( { //printf("typeIsClass\n"); ArgumentList *al = root->argList; if (al==0 || al->isEmpty()) { result=FALSE; // empty arg list -> function prototype. goto done; } ArgumentListIterator ali(*al); Argument *a; for (ali.toFirst();(a=ali.current());++ali) { if (!a->name.isEmpty() || !a->defval.isEmpty()) { if (a->name.find(initChars)==0) { result=TRUE; } else { result=FALSE; // arg has (type,name) pair -> function prototype } goto done; } if (a->type.isEmpty() || getResolvedClass(ctx,fd,a->type)!=0) { result=FALSE; // arg type is a known type goto done; } if (checkIfTypedef(ctx,fd,a->type)) { //printf("%s:%d: false (arg is typedef)\n",__FILE__,__LINE__); result=FALSE; // argument is a typedef goto done; } if (a->type.at(a->type.length()-1)=='*' || a->type.at(a->type.length()-1)=='&') // type ends with * or & => pointer or reference { result=FALSE; goto done; } if (a->type.find(initChars)==0) { result=TRUE; // argument type starts with typical initializer char goto done; } QCString resType=resolveTypeDef(ctx,a->type); if (resType.isEmpty()) resType=a->type; int len; if (idChars.match(resType,0,&len)==0) // resType starts with identifier { resType=resType.left(len); //printf("resType=%s\n",resType.data()); if (resType=="int" || resType=="long" || resType=="float" || resType=="double" || resType=="char" || resType=="signed" || resType=="const" || resType=="unsigned" || resType=="void") { result=FALSE; // type keyword -> function prototype goto done; } } } result=TRUE; } done: //printf("isVarWithConstructor(%s,%s)=%d\n",rootNav->parent()->name().data(), // root->type.data(),result); rootNav->releaseEntry(); return result; } static void addVariable(EntryNav *rootNav,int isFuncPtr=-1) { rootNav->loadEntry(g_storage); Entry *root = rootNav->entry(); Debug::print(Debug::Variables,0, "VARIABLE_SEC: \n" " type=`%s' name=`%s' args=`%s' bodyLine=`%d' mGrpId=%d\n", root->type.data(), root->name.data(), root->args.data(), root->bodyLine, root->mGrpId ); //printf("root->parent->name=%s\n",root->parent->name.data()); if (root->type.isEmpty() && root->name.find("operator")==-1 && (root->name.find('*')!=-1 || root->name.find('&')!=-1)) { // recover from parse error caused by redundant braces // like in "int *(var[10]);", which is parsed as // type="" name="int *" args="(var[10])" root->type=root->name; static const QRegExp reName("[a-z_A-Z][a-z_A-Z0-9]*"); int l; int i=root->args.isEmpty() ? -1 : reName.match(root->args,0,&l); root->name=root->args.mid(i,l); root->args=root->args.mid(i+l,root->args.find(')',i+l)-i-l); //printf("new: type=`%s' name=`%s' args=`%s'\n", // root->type.data(),root->name.data(),root->args.data()); } else { int i=isFuncPtr; if (i==-1) i=findFunctionPtr(root->type); // for typedefs isFuncPtr is not yet set if (i!=-1) // function pointer { int ai = root->type.find('[',i); if (ai>i) // function pointer array { root->args.prepend(root->type.right(root->type.length()-ai)); root->type=root->type.left(ai); } else if (root->type.find(')',i)!=-1) // function ptr, not variable like "int (*bla)[10]" { root->type=root->type.left(root->type.length()-1); root->args.prepend(")"); //printf("root->type=%s root->args=%s\n",root->type.data(),root->args.data()); } } else if (root->type.find("typedef ")!=-1 && root->type.right(2)=="()") // typedef void (func)(int) { root->type=root->type.left(root->type.length()-1); root->args.prepend(")"); } } QCString scope,name=removeRedundantWhiteSpace(root->name); // find the scope of this variable EntryNav *p = rootNav->parent(); while ((p->section() & Entry::SCOPE_MASK)) { QCString scopeName = p->name(); if (!scopeName.isEmpty()) { scope.prepend(scopeName); break; } p=p->parent(); } MemberDef::MemberType mtype; QCString type=root->type.stripWhiteSpace(); ClassDef *cd=0; bool isRelated=FALSE; bool isMemberOf=FALSE; QCString classScope=stripAnonymousNamespaceScope(scope); classScope=stripTemplateSpecifiersFromScope(classScope,FALSE); QCString annScopePrefix=scope.left(scope.length()-classScope.length()); if (root->name.findRev("::")!=-1) { if (root->type=="friend class" || root->type=="friend struct" || root->type=="friend union") { cd=getClass(scope); if (cd) { addVariableToClass(rootNav, // entry cd, // class to add member to MemberDef::Friend, // type of member name, // name of the member FALSE, // from Anonymous scope 0, // anonymous member Public, // protection Member // related to a class ); } } goto nextMember; /* skip this member, because it is a * static variable definition (always?), which will be * found in a class scope as well, but then we know the * correct protection level, so only then it will be * inserted in the correct list! */ } if (type=="@") mtype=MemberDef::EnumValue; else if (type.left(8)=="typedef ") mtype=MemberDef::Typedef; else if (type.left(7)=="friend ") mtype=MemberDef::Friend; else if (root->mtype==Property) mtype=MemberDef::Property; else if (root->mtype==Event) mtype=MemberDef::Event; else mtype=MemberDef::Variable; if (!root->relates.isEmpty()) // related variable { isRelated=TRUE; isMemberOf=(root->relatesType == MemberOf); if (getClass(root->relates)==0 && !scope.isEmpty()) scope=mergeScopes(scope,root->relates); else scope=root->relates; } cd=getClass(scope); if (cd==0 && classScope!=scope) cd=getClass(classScope); if (cd) { MemberDef *md=0; // if cd is an annonymous scope we insert the member // into a non-annonymous scope as well. This is needed to // be able to refer to it using \var or \fn //int indentDepth=0; int si=scope.find('@'); //int anonyScopes = 0; bool added=FALSE; if (si!=-1) // anonymous scope { QCString pScope; ClassDef *pcd=0; pScope = scope.left(QMAX(si-2,0)); if (!pScope.isEmpty()) pScope.prepend(annScopePrefix); else if (annScopePrefix.length()>2) pScope=annScopePrefix.left(annScopePrefix.length()-2); if (name.at(0)!='@') { if (!pScope.isEmpty() && (pcd=getClass(pScope))) { md=addVariableToClass(rootNav, // entry pcd, // class to add member to mtype, // member type name, // member name TRUE, // from anonymous scope 0, // from anonymous member root->protection, isMemberOf ? Foreign : isRelated ? Related : Member ); added=TRUE; } else // anonymous scope inside namespace or file => put variable in the global scope { if (mtype==MemberDef::Variable) { md=addVariableToFile(rootNav,mtype,pScope,name,TRUE,0); } added=TRUE; } } } //printf("name=`%s' scope=%s scope.right=%s\n", // name.data(),scope.data(), // scope.right(scope.length()-si).data()); addVariableToClass(rootNav, // entry cd, // class to add member to mtype, // member type name, // name of the member FALSE, // from anonymous scope md, // from anonymous member root->protection, isMemberOf ? Foreign : isRelated ? Related : Member); } else if (!name.isEmpty()) // global variable { //printf("Inserting member in global scope %s!\n",scope.data()); addVariableToFile(rootNav,mtype,scope,name,FALSE,/*0,*/0); } nextMember: rootNav->releaseEntry(); } //---------------------------------------------------------------------- // Searches the Entry tree for typedef documentation sections. // If found they are stored in their class or in the global list. static void buildTypedefList(EntryNav *rootNav) { //printf("buildVarList(%s)\n",rootNav->name().data()); if (!rootNav->name().isEmpty() && rootNav->section()==Entry::VARIABLE_SEC && rootNav->type().find("typedef ")!=-1 // its a typedef ) { addVariable(rootNav); } if (rootNav->children()) { EntryNavListIterator eli(*rootNav->children()); EntryNav *e; for (;(e=eli.current());++eli) { if (e->section()!=Entry::ENUM_SEC) { buildTypedefList(e); } } } } //---------------------------------------------------------------------- // Searches the Entry tree for Variable documentation sections. // If found they are stored in their class or in the global list. static void buildVarList(EntryNav *rootNav) { //printf("buildVarList(%s)\n",rootNav->name().data()); int isFuncPtr=-1; if (!rootNav->name().isEmpty() && (rootNav->type().isEmpty() || compoundKeywordDict.find(rootNav->type())==0) && ( (rootNav->section()==Entry::VARIABLE_SEC // it's a variable ) || (rootNav->section()==Entry::FUNCTION_SEC && // or maybe a function pointer variable (isFuncPtr=findFunctionPtr(rootNav->type()))!=-1 ) || (rootNav->section()==Entry::FUNCTION_SEC && // class variable initialized by constructor isVarWithConstructor(rootNav) ) ) ) // documented variable { addVariable(rootNav,isFuncPtr); } if (rootNav->children()) { EntryNavListIterator eli(*rootNav->children()); EntryNav *e; for (;(e=eli.current());++eli) { if (e->section()!=Entry::ENUM_SEC) { buildVarList(e); } } } } //---------------------------------------------------------------------- // Searches the Entry tree for Function sections. // If found they are stored in their class or in the global list. static void addMethodToClass(EntryNav *rootNav,ClassDef *cd, const QCString &rname,bool isFriend) { Entry *root = rootNav->entry(); FileDef *fd=rootNav->fileDef(); int l,i=-1; static QRegExp re("([a-z_A-Z0-9: ]*[ &*]+[ ]*"); if (!root->type.isEmpty() && (i=re.match(root->type,0,&l))!=-1) // function variable { root->args+=root->type.right(root->type.length()-i-l); root->type=root->type.left(i+l); } QCString name=removeRedundantWhiteSpace(rname); if (name.left(2)=="::") name=name.right(name.length()-2); MemberDef::MemberType mtype; if (isFriend) mtype=MemberDef::Friend; else if (root->mtype==Signal) mtype=MemberDef::Signal; else if (root->mtype==Slot) mtype=MemberDef::Slot; else if (root->mtype==DCOP) mtype=MemberDef::DCOP; else mtype=MemberDef::Function; // strip redundant template specifier for constructors if ((fd==0 || getLanguageFromFileName(fd->name())==SrcLangExt_Cpp) && name.left(9)!="operator " && (i=name.find('<'))!=-1 && name.find('>')!=-1) { name=name.left(i); } //printf("root->name=`%s; root->args=`%s' root->argList=`%s'\n", // root->name.data(),root->args.data(),argListToString(root->argList).data() // ); // adding class member MemberDef *md=new MemberDef( root->fileName,root->startLine, root->type,name,root->args,root->exception, root->protection,root->virt, root->stat && root->relatesType != MemberOf, root->relates.isEmpty() ? Member : root->relatesType == MemberOf ? Foreign : Related, mtype,root->tArgLists ? root->tArgLists->last() : 0,root->argList); md->setTagInfo(rootNav->tagInfo()); md->setMemberClass(cd); md->setDocumentation(root->doc,root->docFile,root->docLine); md->setDocsForDefinition(!root->proto); md->setBriefDescription(root->brief,root->briefFile,root->briefLine); md->setInbodyDocumentation(root->inbodyDocs,root->inbodyFile,root->inbodyLine); md->setBodySegment(root->bodyLine,root->endBodyLine); md->setMemberSpecifiers(root->spec); md->setMemberGroupId(root->mGrpId); md->setTypeConstraints(root->typeConstr); md->setBodyDef(fd); md->setFileDef(fd); //md->setScopeTemplateArguments(root->tArgList); md->addSectionsToDefinition(root->anchors); QCString def; QCString qualScope = cd->qualifiedNameWithTemplateParameters(); QCString scopeSeparator="::"; if (Config_getBool("OPTIMIZE_OUTPUT_JAVA")) { qualScope = substitute(qualScope,"::","."); scopeSeparator="."; } if (!root->relates.isEmpty() || isFriend || Config_getBool("HIDE_SCOPE_NAMES")) { if (!root->type.isEmpty()) { if (root->argList) { def=root->type+" "+name; } else { def=root->type+" "+name+root->args; } } else { if (root->argList) { def=name; } else { def=name+root->args; } } } else { if (!root->type.isEmpty()) { if (root->argList) { def=root->type+" "+qualScope+scopeSeparator+name; } else { def=root->type+" "+qualScope+scopeSeparator+name+root->args; } } else { if (root->argList) { def=qualScope+scopeSeparator+name; } else { def=qualScope+scopeSeparator+name+root->args; } } } if (def.left(7)=="friend ") def=def.right(def.length()-7); md->setDefinition(def); md->enableCallGraph(root->callGraph); md->enableCallerGraph(root->callerGraph); Debug::print(Debug::Functions,0, " Func Member:\n" " `%s' `%s'::`%s' `%s' proto=%d\n" " def=`%s'\n", root->type.data(), qualScope.data(), rname.data(), root->args.data(), root->proto, def.data() ); // add member to the global list of all members //printf("Adding member=%s class=%s\n",md->name().data(),cd->name().data()); MemberName *mn; if ((mn=Doxygen::memberNameSDict->find(name))) { mn->append(md); } else { mn = new MemberName(name); mn->append(md); Doxygen::memberNameSDict->append(name,mn); } // add member to the class cd cd->insertMember(md); // add file to list of used files cd->insertUsedFile(root->fileName); addMemberToGroups(root,md); rootNav->changeSection(Entry::EMPTY_SEC); md->setRefItems(root->sli); } static void buildFunctionList(EntryNav *rootNav) { if (rootNav->section()==Entry::FUNCTION_SEC) { rootNav->loadEntry(g_storage); Entry *root = rootNav->entry(); Debug::print(Debug::Functions,0, "FUNCTION_SEC:\n" " `%s' `%s'::`%s' `%s' relates=`%s' relatesType=`%d' file=`%s' line=`%d' bodyLine=`%d' #tArgLists=%d mGrpId=%d spec=%d proto=%d docFile=%s\n", root->type.data(), rootNav->parent()->name().data(), root->name.data(), root->args.data(), root->relates.data(), root->relatesType, root->fileName.data(), root->startLine, root->bodyLine, root->tArgLists ? (int)root->tArgLists->count() : -1, root->mGrpId, root->spec, root->proto, root->docFile.data() ); bool isFriend=root->type.find("friend ")!=-1; QCString rname = removeRedundantWhiteSpace(root->name); //printf("rname=%s\n",rname.data()); if (!rname.isEmpty()) { ClassDef *cd=0; // check if this function's parent is a class QCString scope=rootNav->parent()->name(); //stripAnonymousNamespaceScope(root->parent->name); scope=stripTemplateSpecifiersFromScope(scope,FALSE); FileDef *rfd=rootNav->fileDef(); int memIndex=rname.findRev("::"); cd=getClass(scope); if (cd && scope+"::"==rname.left(scope.length()+2)) // found A::f inside A { // strip scope from name rname=rname.right(rname.length()-rootNav->parent()->name().length()-2); } NamespaceDef *nd = 0; bool isMember=FALSE; if (memIndex!=-1) { int ts=rname.find('<'); int te=rname.find('>'); if (memIndex>0 && (ts==-1 || te==-1)) { // note: the following code was replaced by inMember=TRUE to deal with a // function rname='X::foo' of class X inside a namespace also called X... // bug id 548175 //nd = Doxygen::namespaceSDict->find(rname.left(memIndex)); //isMember = nd==0; //if (nd) //{ // // strip namespace scope from name // scope=rname.left(memIndex); // rname=rname.right(rname.length()-memIndex-2); //} isMember = TRUE; } else { isMember=memIndex<ts || memIndex>te; } } static QRegExp re("([a-z_A-Z0-9: ]*[ &*]+[ ]*"); if (!rootNav->parent()->name().isEmpty() && (rootNav->parent()->section() & Entry::COMPOUND_MASK) && cd && // do some fuzzy things to exclude function pointers (root->type.isEmpty() || (root->type.find(re,0)==-1 || root->args.find(")[")!=-1) || // type contains ..(..* and args not )[.. -> function pointer root->type.find(")(")!=-1 || root->type.find("operator")!=-1 // type contains ..)(.. and not "operator" ) ) { Debug::print(Debug::Functions,0," --> member %s of class %s!\n", rname.data(),cd->name().data()); addMethodToClass(rootNav,cd,rname,isFriend); } else if (!((rootNav->parent()->section() & Entry::COMPOUND_MASK) || rootNav->parent()->section()==Entry::OBJCIMPL_SEC ) && !isMember && (root->relates.isEmpty() || root->relatesType == Duplicate) && root->type.left(7)!="extern " && root->type.left(8)!="typedef " ) // no member => unrelated function { /* check the uniqueness of the function name in the file. * A file could contain a function prototype and a function definition * or even multiple function prototypes. */ bool found=FALSE; MemberName *mn; MemberDef *md=0; if ((mn=Doxygen::functionNameSDict->find(rname))) { Debug::print(Debug::Functions,0," --> function %s already found!\n",rname.data()); MemberNameIterator mni(*mn); for (mni.toFirst();(!found && (md=mni.current()));++mni) { NamespaceDef *mnd = md->getNamespaceDef(); NamespaceDef *rnd = 0; //printf("root namespace=%s\n",rootNav->parent()->name().data()); QCString fullScope = scope; QCString parentScope = rootNav->parent()->name(); if (!parentScope.isEmpty() && !leftScopeMatch(parentScope,scope)) { if (!scope.isEmpty()) fullScope.prepend("::"); fullScope.prepend(parentScope); } //printf("fullScope=%s\n",fullScope.data()); rnd = getResolvedNamespace(fullScope); FileDef *mfd = md->getFileDef(); QCString nsName,rnsName; if (mnd) nsName = mnd->name().copy(); if (rnd) rnsName = rnd->name().copy(); //printf("matching arguments for %s%s %s%s\n", // md->name().data(),md->argsString(),rname.data(),argListToString(root->argList).data()); LockingPtr<ArgumentList> mdAl = md->argumentList(); if ( matchArguments2(md->getOuterScope(),mfd,mdAl.pointer(), rnd ? rnd : Doxygen::globalScope,rfd,root->argList, FALSE) ) { GroupDef *gd=0; if (root->groups->first()!=0) { gd = Doxygen::groupSDict->find(root->groups->first()->groupname.data()); } //printf("match!\n"); //printf("mnd=%p rnd=%p nsName=%s rnsName=%s\n",mnd,rnd,nsName.data(),rnsName.data()); // see if we need to create a new member found=(mnd && rnd && nsName==rnsName) || // members are in the same namespace ((mnd==0 && rnd==0 && mfd!=0 && // no external reference and mfd->absFilePath()==root->fileName // prototype in the same file ) ); // otherwise, allow a duplicate global member with the same argument list if (!found && gd && gd==md->getGroupDef()) { // member is already in the group, so we don't want to add it again. found=TRUE; } //printf("combining function with prototype found=%d in namespace %s\n", // found,nsName.data()); if (found) { // merge argument lists mergeArguments(mdAl.pointer(),root->argList,!root->doc.isEmpty()); // merge documentation if (md->documentation().isEmpty() && !root->doc.isEmpty()) { ArgumentList *argList = new ArgumentList; stringToArgumentList(root->args,argList); if (root->proto) { //printf("setDeclArgumentList to %p\n",argList); md->setDeclArgumentList(argList); } else { md->setArgumentList(argList); } } md->setDocumentation(root->doc,root->docFile,root->docLine); md->setInbodyDocumentation(root->inbodyDocs,root->inbodyFile,root->inbodyLine); md->setDocsForDefinition(!root->proto); if (md->briefDescription().isEmpty() && !root->brief.isEmpty()) { md->setArgsString(root->args); } md->setBriefDescription(root->brief,root->briefFile,root->briefLine); md->addSectionsToDefinition(root->anchors); md->enableCallGraph(md->hasCallGraph() || root->callGraph); md->enableCallerGraph(md->hasCallerGraph() || root->callerGraph); // merge ingroup specifiers if (md->getGroupDef()==0 && root->groups->first()!=0) { addMemberToGroups(root,md); } else if (md->getGroupDef()!=0 && root->groups->count()==0) { //printf("existing member is grouped, new member not\n"); root->groups->append(new Grouping(md->getGroupDef()->name(), md->getGroupPri())); } else if (md->getGroupDef()!=0 && root->groups->first()!=0) { //printf("both members are grouped\n"); } } } } } if (!found) /* global function is unique with respect to the file */ { Debug::print(Debug::Functions,0," --> new function %s found!\n",rname.data()); //printf("New function type=`%s' name=`%s' args=`%s' bodyLine=%d\n", // root->type.data(),rname.data(),root->args.data(),root->bodyLine); // new global function ArgumentList *tArgList = root->tArgLists ? root->tArgLists->last() : 0; QCString name=removeRedundantWhiteSpace(rname); md=new MemberDef( root->fileName,root->startLine, root->type,name,root->args,root->exception, root->protection,root->virt,root->stat,Member, MemberDef::Function,tArgList,root->argList); md->setTagInfo(rootNav->tagInfo()); //md->setDefFile(root->fileName); //md->setDefLine(root->startLine); md->setDocumentation(root->doc,root->docFile,root->docLine); md->setBriefDescription(root->brief,root->briefFile,root->briefLine); md->setInbodyDocumentation(root->inbodyDocs,root->inbodyFile,root->inbodyLine); md->setPrototype(root->proto); md->setDocsForDefinition(!root->proto); md->setTypeConstraints(root->typeConstr); //md->setBody(root->body); md->setBodySegment(root->bodyLine,root->endBodyLine); FileDef *fd=rootNav->fileDef(); md->setBodyDef(fd); md->addSectionsToDefinition(root->anchors); md->setMemberSpecifiers(root->spec); md->setMemberGroupId(root->mGrpId); // see if the function is inside a namespace that was not part of // the name already (in that case nd should be non-zero already) if (nd==0 && rootNav->parent()->section() == Entry::NAMESPACE_SEC ) { QCString nscope=removeAnonymousScopes(rootNav->parent()->name()); if (!nscope.isEmpty()) { nd = getResolvedNamespace(nscope); } } if (!scope.isEmpty()) { if (Config_getBool("OPTIMIZE_OUTPUT_JAVA")) { scope = substitute(scope,"::",".")+"."; } else { scope+="::"; } } QCString def; if (!root->type.isEmpty()) { if (root->argList) { def=root->type+" "+scope+name; } else { def=root->type+" "+scope+name+root->args; } } else { if (root->argList) { def=scope+name.copy(); } else { def=scope+name+root->args; } } Debug::print(Debug::Functions,0, " Global Function:\n" " `%s' `%s'::`%s' `%s' proto=%d\n" " def=`%s'\n", root->type.data(), rootNav->parent()->name().data(), rname.data(), root->args.data(), root->proto, def.data() ); md->setDefinition(def); md->enableCallGraph(root->callGraph); md->enableCallerGraph(root->callerGraph); //if (root->mGrpId!=-1) //{ // md->setMemberGroup(memberGroupDict[root->mGrpId]); //} md->setRefItems(root->sli); if (nd && !nd->name().isEmpty() && nd->name().at(0)!='@') { // add member to namespace md->setNamespace(nd); nd->insertMember(md); } if (fd) { // add member to the file (we do this even if we have already // inserted it into the namespace) md->setFileDef(fd); fd->insertMember(md); } // add member to the list of file members //printf("Adding member=%s\n",md->name().data()); MemberName *mn; if ((mn=Doxygen::functionNameSDict->find(name))) { mn->append(md); } else { mn = new MemberName(name); mn->append(md); Doxygen::functionNameSDict->append(name,mn); } addMemberToGroups(root,md); if (root->relatesType == Simple) // if this is a relatesalso command, // allow find Member to pick it up { rootNav->changeSection(Entry::EMPTY_SEC); // Otherwise we have finished // with this entry. } } else { FileDef *fd=rootNav->fileDef(); if (fd) { // add member to the file (we do this even if we have already // inserted it into the namespace) fd->insertMember(md); } } //printf("unrelated function %d `%s' `%s' `%s'\n", // root->parent->section,root->type.data(),rname.data(),root->args.data()); } else { Debug::print(Debug::Functions,0," --> %s not processed!\n",rname.data()); } } else if (rname.isEmpty()) { warn(root->fileName,root->startLine, "Warning: Illegal member name found." ); } rootNav->releaseEntry(); } RECURSE_ENTRYTREE(buildFunctionList,rootNav); } //---------------------------------------------------------------------- static void findFriends() { //printf("findFriends()\n"); MemberNameSDict::Iterator fnli(*Doxygen::functionNameSDict); MemberName *fn; for (;(fn=fnli.current());++fnli) // for each global function name { //printf("Function name=`%s'\n",fn->memberName()); MemberName *mn; if ((mn=Doxygen::memberNameSDict->find(fn->memberName()))) { // there are members with the same name //printf("Function name is also a member name\n"); MemberNameIterator fni(*fn); MemberDef *fmd; for (;(fmd=fni.current());++fni) // for each function with that name { MemberNameIterator mni(*mn); MemberDef *mmd; for (;(mmd=mni.current());++mni) // for each member with that name { //printf("Checking for matching arguments // mmd->isRelated()=%d mmd->isFriend()=%d mmd->isFunction()=%d\n", // mmd->isRelated(),mmd->isFriend(),mmd->isFunction()); LockingPtr<ArgumentList> mmdAl = mmd->argumentList(); LockingPtr<ArgumentList> fmdAl = fmd->argumentList(); if ((mmd->isFriend() || (mmd->isRelated() && mmd->isFunction())) && matchArguments2(mmd->getOuterScope(), mmd->getFileDef(), mmdAl.pointer(), fmd->getOuterScope(), fmd->getFileDef(), fmdAl.pointer(), TRUE ) ) // if the member is related and the arguments match then the // function is actually a friend. { mergeArguments(mmdAl.pointer(),fmdAl.pointer()); if (!fmd->documentation().isEmpty()) { mmd->setDocumentation(fmd->documentation(),fmd->docFile(),fmd->docLine()); } else if (!mmd->documentation().isEmpty()) { fmd->setDocumentation(mmd->documentation(),mmd->docFile(),mmd->docLine()); } if (mmd->briefDescription().isEmpty() && !fmd->briefDescription().isEmpty()) { mmd->setBriefDescription(fmd->briefDescription(),fmd->briefFile(),fmd->briefLine()); } else if (!mmd->briefDescription().isEmpty() && !fmd->briefDescription().isEmpty()) { fmd->setBriefDescription(mmd->briefDescription(),mmd->briefFile(),mmd->briefLine()); } if (!fmd->inbodyDocumentation().isEmpty()) { mmd->setInbodyDocumentation(fmd->inbodyDocumentation(),fmd->inbodyFile(),fmd->inbodyLine()); } else if (!mmd->inbodyDocumentation().isEmpty()) { fmd->setInbodyDocumentation(mmd->inbodyDocumentation(),mmd->inbodyFile(),mmd->inbodyLine()); } //printf("body mmd %d fmd %d\n",mmd->getStartBodyLine(),fmd->getStartBodyLine()); if (mmd->getStartBodyLine()==-1 && fmd->getStartBodyLine()!=-1) { mmd->setBodySegment(fmd->getStartBodyLine(),fmd->getEndBodyLine()); mmd->setBodyDef(fmd->getBodyDef()); //mmd->setBodyMember(fmd); } else if (mmd->getStartBodyLine()!=-1 && fmd->getStartBodyLine()==-1) { fmd->setBodySegment(mmd->getStartBodyLine(),mmd->getEndBodyLine()); fmd->setBodyDef(mmd->getBodyDef()); //fmd->setBodyMember(mmd); } mmd->setDocsForDefinition(fmd->isDocsForDefinition()); mmd->enableCallGraph(mmd->hasCallGraph() || fmd->hasCallGraph()); mmd->enableCallerGraph(mmd->hasCallerGraph() || fmd->hasCallerGraph()); fmd->enableCallGraph(mmd->hasCallGraph() || fmd->hasCallGraph()); fmd->enableCallerGraph(mmd->hasCallerGraph() || fmd->hasCallerGraph()); } } } } } } //---------------------------------------------------------------------- static void transferArgumentDocumentation(ArgumentList *decAl,ArgumentList *defAl) { if (decAl && defAl) { ArgumentListIterator decAli(*decAl); ArgumentListIterator defAli(*defAl); Argument *decA,*defA; for (decAli.toFirst(),defAli.toFirst(); (decA=decAli.current()) && (defA=defAli.current()); ++decAli,++defAli) { //printf("Argument decA->name=%s (doc=%s) defA->name=%s (doc=%s)\n", // decA->name.data(),decA->docs.data(), // defA->name.data(),defA->docs.data() // ); if (decA->docs.isEmpty() && !defA->docs.isEmpty()) { decA->docs = defA->docs.copy(); } else if (defA->docs.isEmpty() && !decA->docs.isEmpty()) { defA->docs = decA->docs.copy(); } } } } static void transferFunctionDocumentation() { //printf("transferFunctionDocumentation()\n"); // find matching function declaration and definitions. MemberNameSDict::Iterator mnli(*Doxygen::functionNameSDict); MemberName *mn; for (;(mn=mnli.current());++mnli) { //printf("memberName=%s count=%d\n",mn->memberName(),mn->count()); MemberDef *mdef=0,*mdec=0; MemberNameIterator mni1(*mn); /* find a matching function declaration and definition for this function */ for (;(mdec=mni1.current());++mni1) { if (mdec->isPrototype() || (mdec->isVariable() && mdec->isExternal()) ) { MemberNameIterator mni2(*mn); for (;(mdef=mni2.current());++mni2) { if ( (mdef->isFunction() && !mdef->isStatic() && !mdef->isPrototype()) || (mdef->isVariable() && !mdef->isExternal() && !mdef->isStatic()) ) { //printf("mdef=(%p,%s) mdec=(%p,%s)\n", // mdef, mdef ? mdef->name().data() : "", // mdec, mdec ? mdec->name().data() : ""); LockingPtr<ArgumentList> mdefAl = mdef->argumentList(); LockingPtr<ArgumentList> mdecAl = mdec->argumentList(); if (matchArguments2(mdef->getOuterScope(),mdef->getFileDef(),mdefAl.pointer(), mdec->getOuterScope(),mdec->getFileDef(),mdecAl.pointer(), TRUE ) ) /* match found */ { //printf("Found member %s: definition in %s (doc=`%s') and declaration in %s (doc=`%s')\n", // mn->memberName(), // mdef->getFileDef()->name().data(),mdef->documentation().data(), // mdec->getFileDef()->name().data(),mdec->documentation().data() // ); // first merge argument documentation transferArgumentDocumentation(mdecAl.pointer(),mdefAl.pointer()); /* copy documentation between function definition and declaration */ if (!mdec->briefDescription().isEmpty()) { mdef->setBriefDescription(mdec->briefDescription(),mdec->briefFile(),mdec->briefLine()); } else if (!mdef->briefDescription().isEmpty()) { mdec->setBriefDescription(mdef->briefDescription(),mdef->briefFile(),mdef->briefLine()); } if (!mdef->documentation().isEmpty()) { //printf("transfering docs mdef->mdec (%s->%s)\n",mdef->argsString(),mdec->argsString()); mdec->setDocumentation(mdef->documentation(),mdef->docFile(),mdef->docLine()); mdec->setDocsForDefinition(mdef->isDocsForDefinition()); if (mdefAl!=0) { ArgumentList *mdefAlComb = new ArgumentList; stringToArgumentList(mdef->argsString(),mdefAlComb); transferArgumentDocumentation(mdefAl.pointer(),mdefAlComb); mdec->setArgumentList(mdefAlComb); } } else if (!mdec->documentation().isEmpty()) { //printf("transfering docs mdec->mdef (%s->%s)\n",mdec->argsString(),mdef->argsString()); mdef->setDocumentation(mdec->documentation(),mdec->docFile(),mdec->docLine()); mdef->setDocsForDefinition(mdec->isDocsForDefinition()); if (mdecAl!=0) { ArgumentList *mdecAlComb = new ArgumentList; stringToArgumentList(mdec->argsString(),mdecAlComb); transferArgumentDocumentation(mdecAl.pointer(),mdecAlComb); mdef->setDeclArgumentList(mdecAlComb); } } if (!mdef->inbodyDocumentation().isEmpty()) { mdec->setInbodyDocumentation(mdef->inbodyDocumentation(),mdef->inbodyFile(),mdef->inbodyLine()); } else if (!mdec->inbodyDocumentation().isEmpty()) { mdef->setInbodyDocumentation(mdec->inbodyDocumentation(),mdec->inbodyFile(),mdec->inbodyLine()); } if (mdec->getStartBodyLine()!=-1 && mdef->getStartBodyLine()==-1) { //printf("body mdec->mdef %d-%d\n",mdec->getStartBodyLine(),mdef->getEndBodyLine()); mdef->setBodySegment(mdec->getStartBodyLine(),mdec->getEndBodyLine()); mdef->setBodyDef(mdec->getBodyDef()); //mdef->setBodyMember(mdec); } else if (mdef->getStartBodyLine()!=-1 && mdec->getStartBodyLine()==-1) { //printf("body mdef->mdec %d-%d\n",mdef->getStartBodyLine(),mdec->getEndBodyLine()); mdec->setBodySegment(mdef->getStartBodyLine(),mdef->getEndBodyLine()); mdec->setBodyDef(mdef->getBodyDef()); //mdec->setBodyMember(mdef); } mdec->mergeMemberSpecifiers(mdef->getMemberSpecifiers()); mdef->mergeMemberSpecifiers(mdec->getMemberSpecifiers()); // copy group info. if (mdec->getGroupDef()==0 && mdef->getGroupDef()!=0) { mdec->setGroupDef(mdef->getGroupDef(), mdef->getGroupPri(), mdef->docFile(), mdef->docLine(), mdef->hasDocumentation(), mdef ); } else if (mdef->getGroupDef()==0 && mdec->getGroupDef()!=0) { mdef->setGroupDef(mdec->getGroupDef(), mdec->getGroupPri(), mdec->docFile(), mdec->docLine(), mdec->hasDocumentation(), mdec ); } mdec->mergeRefItems(mdef); mdef->mergeRefItems(mdec); mdef->setMemberDeclaration(mdec); mdec->setMemberDefinition(mdef); mdef->enableCallGraph(mdec->hasCallGraph() || mdef->hasCallGraph()); mdef->enableCallerGraph(mdec->hasCallerGraph() || mdef->hasCallerGraph()); mdec->enableCallGraph(mdec->hasCallGraph() || mdef->hasCallGraph()); mdec->enableCallerGraph(mdec->hasCallerGraph() || mdef->hasCallerGraph()); } } } } } } } //---------------------------------------------------------------------- static void transferFunctionReferences() { MemberNameSDict::Iterator mnli(*Doxygen::functionNameSDict); MemberName *mn; for (;(mn=mnli.current());++mnli) { MemberDef *md,*mdef=0,*mdec=0; MemberNameIterator mni(*mn); /* find a matching function declaration and definition for this function */ for (;(md=mni.current());++mni) { if (md->isPrototype()) mdec=md; else if (md->isVariable() && md->isExternal()) mdec=md; if (md->isFunction() && !md->isStatic() && !md->isPrototype()) mdef=md; else if (md->isVariable() && !md->isExternal() && !md->isStatic()) mdef=md; } if (mdef && mdec) { LockingPtr<ArgumentList> mdefAl = mdef->argumentList(); LockingPtr<ArgumentList> mdecAl = mdec->argumentList(); if ( matchArguments2(mdef->getOuterScope(),mdef->getFileDef(),mdefAl.pointer(), mdec->getOuterScope(),mdec->getFileDef(),mdecAl.pointer(), TRUE ) ) /* match found */ { LockingPtr<MemberSDict> defDict = mdef->getReferencesMembers(); LockingPtr<MemberSDict> decDict = mdec->getReferencesMembers(); if (defDict!=0) { MemberSDict::Iterator msdi(*defDict); MemberDef *rmd; for (msdi.toFirst();(rmd=msdi.current());++msdi) { if (decDict==0 || decDict->find(rmd->name())==0) { mdec->addSourceReferences(rmd); } } } if (decDict!=0) { MemberSDict::Iterator msdi(*decDict); MemberDef *rmd; for (msdi.toFirst();(rmd=msdi.current());++msdi) { if (defDict==0 || defDict->find(rmd->name())==0) { mdef->addSourceReferences(rmd); } } } defDict = mdef->getReferencedByMembers(); decDict = mdec->getReferencedByMembers(); if (defDict!=0) { MemberSDict::Iterator msdi(*defDict); MemberDef *rmd; for (msdi.toFirst();(rmd=msdi.current());++msdi) { if (decDict==0 || decDict->find(rmd->name())==0) { mdec->addSourceReferencedBy(rmd); } } } if (decDict!=0) { MemberSDict::Iterator msdi(*decDict); MemberDef *rmd; for (msdi.toFirst();(rmd=msdi.current());++msdi) { if (defDict==0 || defDict->find(rmd->name())==0) { mdef->addSourceReferencedBy(rmd); } } } } } } } //---------------------------------------------------------------------- static void transferRelatedFunctionDocumentation() { // find match between function declaration and definition for // related functions MemberNameSDict::Iterator mnli(*Doxygen::functionNameSDict); MemberName *mn; for (mnli.toFirst();(mn=mnli.current());++mnli) { MemberDef *md; MemberNameIterator mni(*mn); /* find a matching function declaration and definition for this function */ for (mni.toFirst();(md=mni.current());++mni) // for each global function { //printf(" Function `%s'\n",md->name().data()); MemberName *rmn; if ((rmn=Doxygen::memberNameSDict->find(md->name()))) // check if there is a member with the same name { //printf(" Member name found\n"); MemberDef *rmd; MemberNameIterator rmni(*rmn); for (rmni.toFirst();(rmd=rmni.current());++rmni) // for each member with the same name { LockingPtr<ArgumentList> mdAl = md->argumentList(); LockingPtr<ArgumentList> rmdAl = rmd->argumentList(); //printf(" Member found: related=`%d'\n",rmd->isRelated()); if ((rmd->isRelated() || rmd->isForeign()) && // related function matchArguments2( md->getOuterScope(), md->getFileDef(), mdAl.pointer(), rmd->getOuterScope(),rmd->getFileDef(),rmdAl.pointer(), TRUE ) ) { //printf(" Found related member `%s'\n",md->name().data()); if (rmd->relatedAlso()) md->setRelatedAlso(rmd->relatedAlso()); else if (rmd->isForeign()) md->makeForeign(); else md->makeRelated(); } } } } } } //---------------------------------------------------------------------- /*! make a dictionary of all template arguments of class cd * that are part of the base class name. * Example: A template class A with template arguments <R,S,T> * that inherits from B<T,T,S> will have T and S in the dictionary. */ static QDict<int> *getTemplateArgumentsInName(ArgumentList *templateArguments,const QCString &name) { QDict<int> *templateNames = new QDict<int>(17); templateNames->setAutoDelete(TRUE); static QRegExp re("[a-z_A-Z][a-z_A-Z0-9:]*"); if (templateArguments) { ArgumentListIterator ali(*templateArguments); Argument *arg; int count=0; for (ali.toFirst();(arg=ali.current());++ali,count++) { int i,p=0,l; while ((i=re.match(name,p,&l))!=-1) { QCString n = name.mid(i,l); if (n==arg->name) { if (templateNames->find(n)==0) { templateNames->insert(n,new int(count)); } } p=i+l; } } } return templateNames; } /*! Searches a class from within \a context and \a cd and returns its * definition if found (otherwise 0 is returned). */ static ClassDef *findClassWithinClassContext(Definition *context,ClassDef *cd,const QCString &name) { FileDef *fd=cd->getFileDef(); ClassDef *result=0; if (context && cd!=context) { result = getResolvedClass(context,0,name,0,0,TRUE,TRUE); } if (result==0) { result = getResolvedClass(cd,fd,name,0,0,TRUE,TRUE); } //printf("** Trying to find %s within context %s class %s result=%s lookup=%p\n", // name.data(), // context ? context->name().data() : "<none>", // cd ? cd->name().data() : "<none>", // result ? result->name().data() : "<none>", // Doxygen::classSDict.find(name) // ); return result; } enum FindBaseClassRelation_Mode { TemplateInstances, DocumentedOnly, Undocumented }; static bool findClassRelation( EntryNav *rootNav, Definition *context, ClassDef *cd, BaseInfo *bi, QDict<int> *templateNames, /*bool insertUndocumented*/ FindBaseClassRelation_Mode mode, bool isArtificial ); static void findUsedClassesForClass(EntryNav *rootNav, Definition *context, ClassDef *masterCd, ClassDef *instanceCd, bool isArtificial, ArgumentList *actualArgs=0, QDict<int> *templateNames=0 ) { masterCd->visited=TRUE; ArgumentList *formalArgs = masterCd->templateArguments(); if (masterCd->memberNameInfoSDict()) { MemberNameInfoSDict::Iterator mnili(*masterCd->memberNameInfoSDict()); MemberNameInfo *mni; for (;(mni=mnili.current());++mnili) { MemberNameInfoIterator mnii(*mni); MemberInfo *mi; for (mnii.toFirst();(mi=mnii.current());++mnii) { MemberDef *md=mi->memberDef; if (md->isVariable()) // for each member variable in this class { //printf(" Found variable %s in class %s\n",md->name().data(),masterCd->name().data()); QCString type=removeRedundantWhiteSpace(md->typeString()); QCString typedefValue = resolveTypeDef(masterCd,type); if (!typedefValue.isEmpty()) { type = typedefValue; } int pos=0; QCString usedClassName; QCString templSpec; bool found=FALSE; // the type can contain template variables, replace them if present if (actualArgs) { type = substituteTemplateArgumentsInString(type,formalArgs,actualArgs); } //printf(" template substitution gives=%s\n",type.data()); while (!found && extractClassNameFromType(type,pos,usedClassName,templSpec)!=-1) { // find the type (if any) that matches usedClassName ClassDef *typeCd = getResolvedClass(masterCd, masterCd->getFileDef(), usedClassName, 0,0, FALSE,TRUE ); //printf("====> usedClassName=%s -> typeCd=%s\n", // usedClassName.data(),typeCd?typeCd->name().data():"<none>"); if (typeCd) { usedClassName = typeCd->name(); } int sp=usedClassName.find('<'); if (sp==-1) sp=0; int si=usedClassName.findRev("::",sp); if (si!=-1) { // replace any namespace aliases replaceNamespaceAliases(usedClassName,si); } // add any template arguments to the class QCString usedName = removeRedundantWhiteSpace(usedClassName+templSpec); //printf(" usedName=%s\n",usedName.data()); bool delTempNames=FALSE; if (templateNames==0) { templateNames = getTemplateArgumentsInName(formalArgs,usedName); delTempNames=TRUE; } BaseInfo bi(usedName,Public,Normal); findClassRelation(rootNav,context,instanceCd,&bi,templateNames,TemplateInstances,isArtificial); if (masterCd->templateArguments()) { ArgumentListIterator ali(*masterCd->templateArguments()); Argument *arg; int count=0; for (ali.toFirst();(arg=ali.current());++ali,++count) { if (arg->name==usedName) // type is a template argument { found=TRUE; Debug::print(Debug::Classes,0," New used class `%s'\n", usedName.data()); ClassDef *usedCd = Doxygen::hiddenClasses->find(usedName); if (usedCd==0) { usedCd = new ClassDef( masterCd->getDefFileName(),masterCd->getDefLine(), usedName,ClassDef::Class); //printf("making %s a template argument!!!\n",usedCd->name().data()); usedCd->makeTemplateArgument(); usedCd->setUsedOnly(TRUE); Doxygen::hiddenClasses->append(usedName,usedCd); } if (usedCd) { if (isArtificial) usedCd->setArtificial(TRUE); Debug::print(Debug::Classes,0," Adding used class `%s' (1)\n", usedCd->name().data()); instanceCd->addUsedClass(usedCd,md->name()); usedCd->addUsedByClass(instanceCd,md->name()); } } } } if (!found) { ClassDef *usedCd=findClassWithinClassContext(context,masterCd,usedName); //printf("Looking for used class %s: result=%s master=%s\n", // usedName.data(),usedCd?usedCd->name().data():"<none>",masterCd?masterCd->name().data():"<none>"); if (usedCd) { found=TRUE; Debug::print(Debug::Classes,0," Adding used class `%s' (2)\n", usedCd->name().data()); instanceCd->addUsedClass(usedCd,md->name()); // class exists usedCd->addUsedByClass(instanceCd,md->name()); } } if (delTempNames) { delete templateNames; templateNames=0; } } if (!found && !type.isEmpty()) // used class is not documented in any scope { ClassDef *usedCd = Doxygen::hiddenClasses->find(type); if (usedCd==0 && !Config_getBool("HIDE_UNDOC_RELATIONS")) { if (type.right(2)=="(*") // type is a function pointer { type+=md->argsString(); } Debug::print(Debug::Classes,0," New undocumented used class `%s'\n", type.data()); usedCd = new ClassDef( masterCd->getDefFileName(),masterCd->getDefLine(), type,ClassDef::Class); usedCd->setUsedOnly(TRUE); Doxygen::hiddenClasses->append(type,usedCd); } if (usedCd) { if (isArtificial) usedCd->setArtificial(TRUE); Debug::print(Debug::Classes,0," Adding used class `%s' (3)\n", usedCd->name().data()); instanceCd->addUsedClass(usedCd,md->name()); usedCd->addUsedByClass(instanceCd,md->name()); } } } } } } else { //printf("no members for class %s (%p)\n",masterCd->name().data(),masterCd); } } static void findBaseClassesForClass( EntryNav *rootNav, Definition *context, ClassDef *masterCd, ClassDef *instanceCd, FindBaseClassRelation_Mode mode, bool isArtificial, ArgumentList *actualArgs=0, QDict<int> *templateNames=0 ) { Entry *root = rootNav->entry(); //if (masterCd->visited) return; masterCd->visited=TRUE; // The base class could ofcouse also be a non-nested class ArgumentList *formalArgs = masterCd->templateArguments(); QListIterator<BaseInfo> bii(*root->extends); BaseInfo *bi=0; for (bii.toFirst();(bi=bii.current());++bii) { //printf("masterCd=%s bi->name=%s #actualArgs=%d\n", // masterCd->localName().data(),bi->name.data(),actualArgs?(int)actualArgs->count():-1); bool delTempNames=FALSE; if (templateNames==0) { templateNames = getTemplateArgumentsInName(formalArgs,bi->name); delTempNames=TRUE; } BaseInfo tbi(bi->name,bi->prot,bi->virt); if (actualArgs) // substitute the formal template arguments of the base class { tbi.name = substituteTemplateArgumentsInString(bi->name,formalArgs,actualArgs); } //printf("bi->name=%s tbi.name=%s\n",bi->name.data(),tbi.name.data()); if (mode==DocumentedOnly) { // find a documented base class in the correct scope if (!findClassRelation(rootNav,context,instanceCd,&tbi,templateNames,DocumentedOnly,isArtificial)) { if (!Config_getBool("HIDE_UNDOC_RELATIONS")) { // no documented base class -> try to find an undocumented one findClassRelation(rootNav,context,instanceCd,&tbi,templateNames,Undocumented,isArtificial); } } } else if (mode==TemplateInstances) { findClassRelation(rootNav,context,instanceCd,&tbi,templateNames,TemplateInstances,isArtificial); } if (delTempNames) { delete templateNames; templateNames=0; } } } //---------------------------------------------------------------------- static bool findTemplateInstanceRelation(Entry *root, Definition *context, ClassDef *templateClass,const QCString &templSpec, QDict<int> *templateNames, bool isArtificial) { Debug::print(Debug::Classes,0," derived from template %s with parameters %s\n", templateClass->name().data(),templSpec.data()); //printf("findTemplateInstanceRelation(base=%s templSpec=%s templateNames=", // templateClass->name().data(),templSpec.data()); //if (templateNames) //{ // QDictIterator<int> qdi(*templateNames); // int *tempArgIndex; // for (;(tempArgIndex=qdi.current());++qdi) // { // printf("(%s->%d) ",qdi.currentKey().data(),*tempArgIndex); // } //} //printf("\n"); bool existingClass = (templSpec==tempArgListToString(templateClass->templateArguments())); if (existingClass) return TRUE; bool freshInstance=FALSE; ClassDef *instanceClass = templateClass->insertTemplateInstance( root->fileName,root->startLine,templSpec,freshInstance); if (isArtificial) instanceClass->setArtificial(TRUE); instanceClass->setIsObjectiveC(root->objc); if (freshInstance) { Debug::print(Debug::Classes,0," found fresh instance '%s'!\n",instanceClass->name().data()); Doxygen::classSDict->append(instanceClass->name(),instanceClass); instanceClass->setTemplateBaseClassNames(templateNames); // search for new template instances caused by base classes of // instanceClass EntryNav *templateRootNav = classEntries.find(templateClass->name()); if (templateRootNav) { bool unloadNeeded=FALSE; Entry *templateRoot = templateRootNav->entry(); if (templateRoot==0) // not yet loaded { templateRootNav->loadEntry(g_storage); templateRoot = templateRootNav->entry(); ASSERT(templateRoot!=0); // now it should really be loaded unloadNeeded=TRUE; } Debug::print(Debug::Classes,0," template root found %s templSpec=%s!\n", templateRoot->name.data(),templSpec.data()); ArgumentList *templArgs = new ArgumentList; stringToArgumentList(templSpec,templArgs); findBaseClassesForClass(templateRootNav,context,templateClass,instanceClass, TemplateInstances,isArtificial,templArgs,templateNames); findUsedClassesForClass(templateRootNav,context,templateClass,instanceClass, isArtificial,templArgs,templateNames); delete templArgs; if (unloadNeeded) // still cleanup to do { templateRootNav->releaseEntry(); } } else { Debug::print(Debug::Classes,0," no template root entry found!\n"); // TODO: what happened if we get here? } //Debug::print(Debug::Classes,0," Template instance %s : \n",instanceClass->name().data()); //ArgumentList *tl = templateClass->templateArguments(); } else { Debug::print(Debug::Classes,0," instance already exists!\n"); } return TRUE; } static bool isRecursiveBaseClass(const QCString &scope,const QCString &name) { QCString n=name; int index=n.find('<'); if (index!=-1) { n=n.left(index); } bool result = rightScopeMatch(scope,n); return result; } /*! Searches for the end of a template in prototype \a s starting from * character position \a startPos. If the end was found the position * of the closing \> is returned, otherwise -1 is returned. * * Handles exotic cases such as * \code * Class<(id<0)> * Class<bits<<2> * Class<"<"> * Class<'<'> * Class<(")<")> * \endcode */ static int findEndOfTemplate(const QCString &s,int startPos) { // locate end of template int e=startPos; int brCount=1; int roundCount=0; int len = s.length(); bool insideString=FALSE; bool insideChar=FALSE; char pc = 0; while (e<len && brCount!=0) { char c=s.at(e); switch(c) { case '<': if (!insideString && !insideChar) { if (e<len-1 && s.at(e+1)=='<') e++; else if (roundCount==0) brCount++; } break; case '>': if (!insideString && !insideChar) { if (e<len-1 && s.at(e+1)=='>') e++; else if (roundCount==0) brCount--; } break; case '(': if (!insideString && !insideChar) roundCount++; break; case ')': if (!insideString && !insideChar) roundCount--; break; case '"': if (!insideChar) { if (insideString && pc!='\\') insideString=FALSE; else insideString=TRUE; } break; case '\'': if (!insideString) { if (insideChar && pc!='\\') insideChar=FALSE; else insideChar=TRUE; } break; } pc = c; e++; } return brCount==0 ? e : -1; } static bool findClassRelation( EntryNav *rootNav, Definition *context, ClassDef *cd, BaseInfo *bi, QDict<int> *templateNames, FindBaseClassRelation_Mode mode, bool isArtificial ) { //printf("findClassRelation(class=%s base=%s templateNames=", // cd->name().data(),bi->name.data()); //if (templateNames) //{ // QDictIterator<int> qdi(*templateNames); // int *tempArgIndex; // for (;(tempArgIndex=qdi.current());++qdi) // { // printf("(%s->%d) ",qdi.currentKey(),*tempArgIndex); // } //} //printf("\n"); Entry *root = rootNav->entry(); QCString biName=bi->name; bool explicitGlobalScope=FALSE; if (biName.left(2)=="::") // explicit global scope { biName=biName.right(biName.length()-2); explicitGlobalScope=TRUE; } //printf("biName=`%s'\n",biName.data()); EntryNav *parentNode=rootNav->parent(); bool lastParent=FALSE; do // for each parent scope, starting with the largest scope // (in case of nested classes) { QCString scopeName= parentNode ? parentNode->name().data() : ""; int scopeOffset=explicitGlobalScope ? 0 : scopeName.length(); do // try all parent scope prefixes, starting with the largest scope { //printf("scopePrefix=`%s' biName=`%s'\n", // scopeName.left(scopeOffset).data(),biName.data()); QCString baseClassName=biName; if (scopeOffset>0) { baseClassName.prepend(scopeName.left(scopeOffset)+"::"); } //QCString stripped; //baseClassName=stripTemplateSpecifiersFromScope // (removeRedundantWhiteSpace(baseClassName),TRUE, // &stripped); MemberDef *baseClassTypeDef=0; QCString templSpec; ClassDef *baseClass=getResolvedClass(explicitGlobalScope ? 0 : cd, cd->getFileDef(), baseClassName, &baseClassTypeDef, &templSpec, mode==Undocumented, TRUE ); //printf("baseClassName=%s baseClass=%p cd=%p explicitGlobalScope=%d\n", // baseClassName.data(),baseClass,cd,explicitGlobalScope); //printf(" scope=`%s' baseClassName=`%s' baseClass=%s templSpec=%s\n", // cd ? cd->name().data():"<none>", // baseClassName.data(), // baseClass?baseClass->name().data():"<none>", // templSpec.data() // ); //if (baseClassName.left(root->name.length())!=root->name || // baseClassName.at(root->name.length())!='<' // ) // Check for base class with the same name. // // If found then look in the outer scope for a match // // and prevent recursion. if (!isRecursiveBaseClass(rootNav->name(),baseClassName) || explicitGlobalScope) { Debug::print( Debug::Classes,0," class relation %s inherited/used by %s found (%s and %s) templSpec='%s'\n", baseClassName.data(), rootNav->name().data(), (bi->prot==Private)?"private":((bi->prot==Protected)?"protected":"public"), (bi->virt==Normal)?"normal":"virtual", templSpec.data() ); int i=baseClassName.find('<'); int si=baseClassName.findRev("::",i==-1 ? baseClassName.length() : i); if (si==-1) si=0; if (baseClass==0 && i!=-1) // base class has template specifiers { // TODO: here we should try to find the correct template specialization // but for now, we only look for the unspecializated base class. int e=findEndOfTemplate(baseClassName,i+1); //printf("baseClass==0 i=%d e=%d\n",i,e); if (e!=-1) // end of template was found at e { templSpec=baseClassName.mid(i,e-i); baseClassName=baseClassName.left(i)+baseClassName.right(baseClassName.length()-e); baseClass=getResolvedClass(cd, cd->getFileDef(), baseClassName, &baseClassTypeDef, 0, //&templSpec, mode==Undocumented, TRUE ); //printf("baseClass=%p -> baseClass=%s templSpec=%s\n", // baseClass,baseClassName.data(),templSpec.data()); } } else if (baseClass && !templSpec.isEmpty()) // we have a known class, but also // know it is a template, so see if // we can also link to the explicit // instance (for instance if a class // derived from a template argument) { //printf("baseClass=%p templSpec=%s\n",baseClass,templSpec.data()); ClassDef *templClass=getClass(baseClass->name()+templSpec); if (templClass) { // use the template instance instead of the template base. baseClass = templClass; templSpec.resize(0); } } //printf("cd=%p baseClass=%p\n",cd,baseClass); bool found=baseClass!=0 && (baseClass!=cd || mode==TemplateInstances); //printf("1. found=%d\n",found); if (!found && si!=-1) { QCString tmpTemplSpec; // replace any namespace aliases replaceNamespaceAliases(baseClassName,si); baseClass=getResolvedClass(cd, cd->getFileDef(), baseClassName, &baseClassTypeDef, &tmpTemplSpec, mode==Undocumented, TRUE ); found=baseClass!=0 && baseClass!=cd; if (found) templSpec = tmpTemplSpec; } //printf("2. found=%d\n",found); //printf("root->name=%s biName=%s baseClassName=%s\n", // root->name.data(),biName.data(),baseClassName.data()); if (!found) { baseClass=findClassWithinClassContext(context,cd,baseClassName); //printf("findClassWithinClassContext(%s,%s)=%p\n", // cd->name().data(),baseClassName.data(),baseClass); found = baseClass!=0 && baseClass!=cd; } bool isATemplateArgument = templateNames!=0 && templateNames->find(biName)!=0; // make templSpec canonical templSpec = getCanonicalTemplateSpec(cd, cd->getFileDef(), templSpec); //printf("3. found=%d\n",found); if (found) { Debug::print(Debug::Classes,0," Documented base class `%s' templSpec=%s\n",biName.data(),templSpec.isEmpty()?"":templSpec.data()); // add base class to this class // if templSpec is not empty then we should "instantiate" // the template baseClass. A new ClassDef should be created // to represent the instance. To be able to add the (instantiated) // members and documentation of a template class // (inserted in that template class at a later stage), // the template should know about its instances. // the instantiation process, should be done in a recursive way, // since instantiating a template may introduce new inheritance // relations. if (!templSpec.isEmpty() && mode==TemplateInstances) { //printf(" => findTemplateInstanceRelation\n"); findTemplateInstanceRelation(root,context,baseClass,templSpec,templateNames,isArtificial); } else if (mode==DocumentedOnly || mode==Undocumented) { //printf(" => insert base class\n"); QCString usedName; if (baseClassTypeDef) { usedName=biName; //printf("***** usedName=%s templSpec=%s\n",usedName.data(),templSpec.data()); } if (Config_getBool("SIP_SUPPORT")) bi->prot=Public; cd->insertBaseClass(baseClass,usedName,bi->prot,bi->virt,templSpec); // add this class as super class to the base class baseClass->insertSubClass(cd,bi->prot,bi->virt,templSpec); } return TRUE; } else if (mode==Undocumented && (scopeOffset==0 || isATemplateArgument)) { Debug::print(Debug::Classes,0, " New undocumented base class `%s' baseClassName=%s\n", biName.data(),baseClassName.data() ); baseClass=0; if (isATemplateArgument) { baseClass=Doxygen::hiddenClasses->find(baseClassName); if (baseClass==0) { baseClass=new ClassDef(root->fileName,root->startLine, baseClassName,ClassDef::Class); Doxygen::hiddenClasses->append(baseClassName,baseClass); if (isArtificial) baseClass->setArtificial(TRUE); } } else { baseClass=Doxygen::classSDict->find(baseClassName); //printf("*** classDDict->find(%s)=%p biName=%s templSpec=%s\n", // baseClassName.data(),baseClass,biName.data(),templSpec.data()); if (baseClass==0) { baseClass=new ClassDef(root->fileName,root->startLine, baseClassName,ClassDef::Class); Doxygen::classSDict->append(baseClassName,baseClass); if (isArtificial) baseClass->setArtificial(TRUE); } } // add base class to this class cd->insertBaseClass(baseClass,biName,bi->prot,bi->virt,templSpec); // add this class as super class to the base class baseClass->insertSubClass(cd,bi->prot,bi->virt,templSpec); // the undocumented base was found in this file baseClass->insertUsedFile(root->fileName); baseClass->setOuterScope(Doxygen::globalScope); return TRUE; } else { Debug::print(Debug::Classes,0," Base class `%s' not found\n",biName.data()); } } else { if (mode!=TemplateInstances) { warn(root->fileName,root->startLine, "Detected potential recursive class relation " "between class %s and base class %s!\n", root->name.data(),baseClassName.data() ); } // for mode==TemplateInstance this case is quite common and // indicates a relation between a template class and a template // instance with the same name. } if (scopeOffset==0) { scopeOffset=-1; } else if ((scopeOffset=scopeName.findRev("::",scopeOffset-1))==-1) { scopeOffset=0; } //printf("new scopeOffset=`%d'",scopeOffset); } while (scopeOffset>=0); if (parentNode==0) { lastParent=TRUE; } else { parentNode=parentNode->parent(); } } while (lastParent); return FALSE; } //---------------------------------------------------------------------- // Computes the base and super classes for each class in the tree static bool isClassSection(EntryNav *rootNav) { if ( !rootNav->name().isEmpty() ) { if (rootNav->section() & Entry::COMPOUND_MASK) // is it a compound (class, struct, union, interface ...) { return TRUE; } else if (rootNav->section() & Entry::COMPOUNDDOC_MASK) // is it a documentation block with inheritance info. { rootNav->loadEntry(g_storage); Entry *root = rootNav->entry(); bool extends = root->extends->count()>0; rootNav->releaseEntry(); if (extends) return TRUE; } } return FALSE; } /*! Builds a dictionary of all entry nodes in the tree starting with \a root */ static void findClassEntries(EntryNav *rootNav) { if (isClassSection(rootNav)) { classEntries.insert(rootNav->name(),rootNav); } RECURSE_ENTRYTREE(findClassEntries,rootNav); } /*! Using the dictionary build by findClassEntries(), this * function will look for additional template specialization that * exists as inheritance relations only. These instances will be * added to the template they are derived from. */ static void findInheritedTemplateInstances() { ClassSDict::Iterator cli(*Doxygen::classSDict); for (cli.toFirst();cli.current();++cli) cli.current()->visited=FALSE; QDictIterator<EntryNav> edi(classEntries); EntryNav *rootNav; for (;(rootNav=edi.current());++edi) { ClassDef *cd; // strip any annonymous scopes first QCString bName=stripAnonymousNamespaceScope(rootNav->name()); bName=stripTemplateSpecifiersFromScope(bName); Debug::print(Debug::Classes,0," Inheritance: Class %s : \n",bName.data()); if ((cd=getClass(bName))) { rootNav->loadEntry(g_storage); //printf("Class %s %d\n",cd->name().data(),root->extends->count()); findBaseClassesForClass(rootNav,cd,cd,cd,TemplateInstances,FALSE); rootNav->releaseEntry(); } } } static void findUsedTemplateInstances() { ClassSDict::Iterator cli(*Doxygen::classSDict); for (cli.toFirst();cli.current();++cli) cli.current()->visited=FALSE; QDictIterator<EntryNav> edi(classEntries); EntryNav *rootNav; for (;(rootNav=edi.current());++edi) { ClassDef *cd; // strip any annonymous scopes first QCString bName=stripAnonymousNamespaceScope(rootNav->name()); bName=stripTemplateSpecifiersFromScope(bName); Debug::print(Debug::Classes,0," Usage: Class %s : \n",bName.data()); if ((cd=getClass(bName))) { rootNav->loadEntry(g_storage); findUsedClassesForClass(rootNav,cd,cd,cd,TRUE); rootNav->releaseEntry(); } } } static void computeClassRelations() { ClassSDict::Iterator cli(*Doxygen::classSDict); for (cli.toFirst();cli.current();++cli) cli.current()->visited=FALSE; QDictIterator<EntryNav> edi(classEntries); EntryNav *rootNav; for (;(rootNav=edi.current());++edi) { ClassDef *cd; rootNav->loadEntry(g_storage); Entry *root = rootNav->entry(); // strip any annonymous scopes first QCString bName=stripAnonymousNamespaceScope(rootNav->name()); bName=stripTemplateSpecifiersFromScope(bName); Debug::print(Debug::Classes,0," Relations: Class %s : \n",bName.data()); if ((cd=getClass(bName))) { findBaseClassesForClass(rootNav,cd,cd,cd,DocumentedOnly,FALSE); } if ((cd==0 || (!cd->hasDocumentation() && !cd->isReference())) && bName.right(2)!="::") { if (!root->name.isEmpty() && root->name.find('@')==-1 && // normal name (guessSection(root->fileName)==Entry::HEADER_SEC || Config_getBool("EXTRACT_LOCAL_CLASSES")) && // not defined in source file (root->protection!=Private || Config_getBool("EXTRACT_PRIVATE")) && // hidden by protection !Config_getBool("HIDE_UNDOC_CLASSES") // undocumented class are visible ) warn_undoc( root->fileName,root->startLine, "Warning: Compound %s is not documented.", root->name.data() ); } rootNav->releaseEntry(); } } static void computeTemplateClassRelations() { QDictIterator<EntryNav> edi(classEntries); EntryNav *rootNav; for (;(rootNav=edi.current());++edi) { rootNav->loadEntry(g_storage); Entry *root = rootNav->entry(); QCString bName=stripAnonymousNamespaceScope(root->name); bName=stripTemplateSpecifiersFromScope(bName); ClassDef *cd=getClass(bName); // strip any annonymous scopes first QDict<ClassDef> *templInstances = 0; if (cd && (templInstances=cd->getTemplateInstances())) { Debug::print(Debug::Classes,0," Template class %s : \n",cd->name().data()); QDictIterator<ClassDef> tdi(*templInstances); ClassDef *tcd; for (tdi.toFirst();(tcd=tdi.current());++tdi) // for each template instance { Debug::print(Debug::Classes,0," Template instance %s : \n",tcd->name().data()); QCString templSpec = tdi.currentKey(); ArgumentList *templArgs = new ArgumentList; stringToArgumentList(templSpec,templArgs); QList<BaseInfo> *baseList=root->extends; BaseInfo *bi=baseList->first(); while (bi) // for each base class of the template { // check if the base class is a template argument BaseInfo tbi(bi->name,bi->prot,bi->virt); ArgumentList *tl = cd->templateArguments(); if (tl) { QDict<int> *baseClassNames = tcd->getTemplateBaseClassNames(); QDict<int> *templateNames = getTemplateArgumentsInName(tl,bi->name); // for each template name that we inherit from we need to // substitute the formal with the actual arguments QDict<int> *actualTemplateNames = new QDict<int>(17); actualTemplateNames->setAutoDelete(TRUE); QDictIterator<int> qdi(*templateNames); for (qdi.toFirst();qdi.current();++qdi) { int templIndex = *qdi.current(); Argument *actArg = 0; if (templIndex<(int)templArgs->count()) { actArg=templArgs->at(templIndex); } if (actArg!=0 && baseClassNames!=0 && baseClassNames->find(actArg->type)!=0 && actualTemplateNames->find(actArg->type)==0 ) { actualTemplateNames->insert(actArg->type,new int(templIndex)); } } delete templateNames; tbi.name = substituteTemplateArgumentsInString(bi->name,tl,templArgs); // find a documented base class in the correct scope if (!findClassRelation(rootNav,cd,tcd,&tbi,actualTemplateNames,DocumentedOnly,FALSE)) { // no documented base class -> try to find an undocumented one findClassRelation(rootNav,cd,tcd,&tbi,actualTemplateNames,Undocumented,FALSE); } delete actualTemplateNames; } bi=baseList->next(); } delete templArgs; } // class has no base classes } rootNav->releaseEntry(); } } //----------------------------------------------------------------------- // compute the references (anchors in HTML) for each function in the file static void computeMemberReferences() { ClassSDict::Iterator cli(*Doxygen::classSDict); ClassDef *cd=0; for (cli.toFirst();(cd=cli.current());++cli) { cd->computeAnchors(); } FileName *fn=Doxygen::inputNameList->first(); while (fn) { FileDef *fd=fn->first(); while (fd) { fd->computeAnchors(); fd=fn->next(); } fn=Doxygen::inputNameList->next(); } NamespaceSDict::Iterator nli(*Doxygen::namespaceSDict); NamespaceDef *nd=0; for (nli.toFirst();(nd=nli.current());++nli) { nd->computeAnchors(); } GroupSDict::Iterator gli(*Doxygen::groupSDict); GroupDef *gd; for (gli.toFirst();(gd=gli.current());++gli) { gd->computeAnchors(); } } //---------------------------------------------------------------------- static void addListReferences() { MemberNameSDict::Iterator mnli(*Doxygen::memberNameSDict); MemberName *mn=0; for (mnli.toFirst();(mn=mnli.current());++mnli) { MemberNameIterator mni(*mn); MemberDef *md=0; for (mni.toFirst();(md=mni.current());++mni) { md->visited=FALSE; } } MemberNameSDict::Iterator fnli(*Doxygen::functionNameSDict); for (fnli.toFirst();(mn=fnli.current());++fnli) { MemberNameIterator mni(*mn); MemberDef *md=0; for (mni.toFirst();(md=mni.current());++mni) { md->visited=FALSE; } } ClassSDict::Iterator cli(*Doxygen::classSDict); ClassDef *cd=0; for (cli.toFirst();(cd=cli.current());++cli) { cd->addListReferences(); } FileName *fn=Doxygen::inputNameList->first(); while (fn) { FileDef *fd=fn->first(); while (fd) { fd->addListReferences(); fd=fn->next(); } fn=Doxygen::inputNameList->next(); } NamespaceSDict::Iterator nli(*Doxygen::namespaceSDict); NamespaceDef *nd=0; for (nli.toFirst();(nd=nli.current());++nli) { nd->addListReferences(); } GroupSDict::Iterator gli(*Doxygen::groupSDict); GroupDef *gd; for (gli.toFirst();(gd=gli.current());++gli) { gd->addListReferences(); } PageSDict::Iterator pdi(*Doxygen::pageSDict); PageDef *pd=0; for (pdi.toFirst();(pd=pdi.current());++pdi) { QCString name = pd->name(); if (pd->getGroupDef()) { name = pd->getGroupDef()->getOutputFileBase(); } { LockingPtr< QList<ListItemInfo> > xrefItems = pd->xrefListItems(); addRefItem(xrefItems.pointer(), theTranslator->trPage(TRUE,TRUE), name,pd->title()); } } DirSDict::Iterator ddi(*Doxygen::directories); DirDef *dd = 0; for (ddi.toFirst();(dd=ddi.current());++ddi) { QCString name = dd->getOutputFileBase(); //if (dd->getGroupDef()) //{ // name = dd->getGroupDef()->getOutputFileBase(); //} LockingPtr< QList<ListItemInfo> > xrefItems = dd->xrefListItems(); addRefItem(xrefItems.pointer(), theTranslator->trDir(TRUE,TRUE), name,dd->displayName()); } } //---------------------------------------------------------------------- // Copy the documentation in entry `root' to member definition `md' and // set the function declaration of the member to `funcDecl'. If the boolean // over_load is set the standard overload text is added. static void addMemberDocs(EntryNav *rootNav, MemberDef *md, const char *funcDecl, ArgumentList *al, bool over_load, NamespaceSDict * ) { Entry *root = rootNav->entry(); //printf("addMemberDocs: `%s'::`%s' `%s' funcDecl=`%s' mSpec=%d\n", // root->parent->name.data(),md->name().data(),md->argsString(),funcDecl,root->spec); QCString fDecl=funcDecl; // strip extern specifier fDecl.stripPrefix("extern "); md->setDefinition(fDecl); md->enableCallGraph(root->callGraph); md->enableCallerGraph(root->callerGraph); ClassDef *cd=md->getClassDef(); NamespaceDef *nd=md->getNamespaceDef(); QCString fullName; if (cd) fullName = cd->name(); else if (nd) fullName = nd->name(); if (!fullName.isEmpty()) fullName+="::"; fullName+=md->name(); FileDef *rfd=rootNav->fileDef(); // TODO determine scope based on root not md Definition *rscope = md->getOuterScope(); LockingPtr<ArgumentList> mdAl = md->argumentList(); if (al) { //printf("merging arguments (1) docs=%d\n",root->doc.isEmpty()); mergeArguments(mdAl.pointer(),al,!root->doc.isEmpty()); } else { if ( matchArguments2( md->getOuterScope(), md->getFileDef(), mdAl.pointer(), rscope,rfd,root->argList, TRUE ) ) { //printf("merging arguments (2)\n"); mergeArguments(mdAl.pointer(),root->argList,!root->doc.isEmpty()); } } if (over_load) // the \overload keyword was used { QCString doc=getOverloadDocs(); if (!root->doc.isEmpty()) { doc+="<p>"; doc+=root->doc; } md->setDocumentation(doc,root->docFile,root->docLine); md->setInbodyDocumentation(root->inbodyDocs,root->inbodyFile,root->inbodyLine); md->setDocsForDefinition(!root->proto); } else { //printf("Adding docs md->docs=`%s' root->docs=`%s'!\n", // md->documentation().data(),root->doc.data()); // documentation outside a compound overrides the documentation inside it #if 0 if ( /* !md->isStatic() && !root->stat && do not replace doc of a static */ ( md->documentation().isEmpty() || /* no docs yet */ (rootNav->parent()->name().isEmpty() && /* or overwrite prototype docs */ !root->proto && md->isPrototype() /* with member definition docs */ ) ) && !root->doc.isEmpty() ) #endif { //printf("overwrite!\n"); md->setDocumentation(root->doc,root->docFile,root->docLine); md->setDocsForDefinition(!root->proto); } //printf("Adding brief md->brief=`%s' root->brief=`%s'!\n", // md->briefDescription().data(),root->brief.data()); // brief descriptions inside a compound override the documentation // outside it #if 0 if ( /* !md->isStatic() && !root->stat && do not replace doc of static */ ( md->briefDescription().isEmpty() || /* no docs yet */ !rootNav->parent()->name().isEmpty() /* member of a class */ ) && !root->brief.isEmpty() ) #endif { //printf("overwrite!\n"); md->setBriefDescription(root->brief,root->briefFile,root->briefLine); } if ( (md->inbodyDocumentation().isEmpty() || !rootNav->parent()->name().isEmpty() ) && !root->inbodyDocs.isEmpty() ) { md->setInbodyDocumentation(root->inbodyDocs,root->inbodyFile,root->inbodyLine); } } //printf("initializer: '%s'(isEmpty=%d) '%s'(isEmpty=%d)\n", // md->initializer().data(),md->initializer().isEmpty(), // root->initializer.data(),root->initializer.isEmpty() // ); if (md->initializer().isEmpty() && !root->initializer.isEmpty()) { //printf("setInitializer\n"); md->setInitializer(root->initializer); } md->setMaxInitLines(root->initLines); if (rfd) { if ((md->getStartBodyLine()==-1 && root->bodyLine!=-1) // || (md->isVariable() && !root->explicitExternal) ) { //printf("Setting new body segment [%d,%d]\n",root->bodyLine,root->endBodyLine); md->setBodySegment(root->bodyLine,root->endBodyLine); md->setBodyDef(rfd); } md->setRefItems(root->sli); } md->enableCallGraph(md->hasCallGraph() || root->callGraph); md->enableCallerGraph(md->hasCallerGraph() || root->callerGraph); md->mergeMemberSpecifiers(root->spec); md->addSectionsToDefinition(root->anchors); addMemberToGroups(root,md); if (cd) cd->insertUsedFile(root->fileName); //printf("root->mGrpId=%d\n",root->mGrpId); if (root->mGrpId!=-1) { if (md->getMemberGroupId()!=-1) { if (md->getMemberGroupId()!=root->mGrpId) { warn( root->fileName,root->startLine, "Warning: member %s belongs to two different groups. The second " "one found here will be ignored.", md->name().data() ); } } else // set group id { //printf("setMemberGroupId=%d md=%s\n",root->mGrpId,md->name().data()); md->setMemberGroupId(root->mGrpId); } } } //---------------------------------------------------------------------- // find a class definition given the scope name and (optionally) a // template list specifier static ClassDef *findClassDefinition(FileDef *fd,NamespaceDef *nd, const char *scopeName) { ClassDef *tcd = getResolvedClass(nd,fd,scopeName,0,0,TRUE,TRUE); return tcd; } //---------------------------------------------------------------------- // Adds the documentation contained in `root' to a global function // with name `name' and argument list `args' (for overloading) and // function declaration `decl' to the corresponding member definition. static bool findGlobalMember(EntryNav *rootNav, const QCString &namespaceName, const char *name, const char *tempArg, const char *, const char *decl) { Entry *root = rootNav->entry(); Debug::print(Debug::FindMembers,0, "2. findGlobalMember(namespace=%s,name=%s,tempArg=%s,decl=%s)\n", namespaceName.data(),name,tempArg,decl); QCString n=name; if (n.isEmpty()) return FALSE; if (n.find("::")!=-1) return FALSE; // skip undefined class members MemberName *mn=Doxygen::functionNameSDict->find(n+tempArg); // look in function dictionary if (mn==0) { mn=Doxygen::functionNameSDict->find(n); // try without template arguments } if (mn) // function name defined { Debug::print(Debug::FindMembers,0,"3. Found function scope\n"); //int count=0; MemberNameIterator mni(*mn); MemberDef *md; bool found=FALSE; for (mni.toFirst();(md=mni.current()) && !found;++mni) { NamespaceDef *nd=md->getNamespaceDef(); //printf("Namespace namespaceName=%s nd=%s\n", // namespaceName.data(),nd ? nd->name().data() : "<none>"); FileDef *fd=rootNav->fileDef(); //printf("File %s\n",fd ? fd->name().data() : "<none>"); NamespaceSDict *nl = fd ? fd->getUsedNamespaces() : 0; //SDict<Definition> *cl = fd ? fd->getUsedClasses() : 0; //printf("NamespaceList %p\n",nl); // search in the list of namespaces that are imported via a // using declaration bool viaUsingDirective = nl && nd && nl->find(nd->qualifiedName())!=0; if ((namespaceName.isEmpty() && nd==0) || // not in a namespace (nd && nd->name()==namespaceName) || // or in the same namespace viaUsingDirective // member in `using' namespace ) { Debug::print(Debug::FindMembers,0,"4. Try to add member `%s' to scope `%s'\n", md->name().data(),namespaceName.data()); QCString nsName = nd ? nd->name().data() : ""; NamespaceDef *rnd = 0; if (!namespaceName.isEmpty()) rnd = Doxygen::namespaceSDict->find(namespaceName); LockingPtr<ArgumentList> mdAl = md->argumentList(); bool matching= (mdAl==0 && root->argList->count()==0) || md->isVariable() || md->isTypedef() || /* in case of function pointers */ matchArguments2(md->getOuterScope(),md->getFileDef(),mdAl.pointer(), rnd ? rnd : Doxygen::globalScope,fd,root->argList, FALSE); //printf("%s<->%s\n", // argListToString(md->argumentList()).data(), // argListToString(root->argList).data()); // for static members we also check if the comment block was found in // the same file. This is needed because static members with the same // name can be in different files. Thus it would be wrong to just // put the comment block at the first syntactically matching member. if (matching && md->isStatic() && md->getDefFileName()!=root->fileName && mn->count()>1) { matching = FALSE; } if (matching) // add docs to the member { Debug::print(Debug::FindMembers,0,"5. Match found\n"); addMemberDocs(rootNav,md,decl,root->argList,FALSE); found=TRUE; } } } if (!found && root->relatesType != Duplicate) // no match { QCString fullFuncDecl=decl; if (root->argList) fullFuncDecl+=argListToString(root->argList,TRUE); warn(root->fileName,root->startLine, "Warning: no matching file member found for \n%s",fullFuncDecl.data()); if (mn->count()>0) { warn_cont("Possible candidates:\n"); for (mni.toFirst();(md=mni.current());++mni) { warn_cont(" %s\n",md->declaration()); } } } } else // got docs for an undefined member! { if (root->type!="friend class" && root->type!="friend struct" && root->type!="friend union") { warn(root->fileName,root->startLine, "Warning: documented function `%s' was not declared or defined.",decl ); } } return TRUE; } static bool isSpecialization( const QList<ArgumentList> &srcTempArgLists, const QList<ArgumentList> &dstTempArgLists ) { QListIterator<ArgumentList> srclali(srcTempArgLists); QListIterator<ArgumentList> dstlali(dstTempArgLists); for (;srclali.current();++srclali,++dstlali) { ArgumentList *sal = srclali.current(); ArgumentList *dal = dstlali.current(); if (!(sal && dal && sal->count()==dal->count())) return TRUE; } return FALSE; } static QCString substituteTemplatesInString( const QList<ArgumentList> &srcTempArgLists, const QList<ArgumentList> &dstTempArgLists, ArgumentList *funcTempArgList, // can be used to match template specializations const QCString &src ) { QCString dst; QRegExp re(idMask); //printf("type=%s\n",sa->type.data()); int i,p=0,l; while ((i=re.match(src,p,&l))!=-1) // for each word in srcType { bool found=FALSE; dst+=src.mid(p,i-p); QCString name=src.mid(i,l); QListIterator<ArgumentList> srclali(srcTempArgLists); QListIterator<ArgumentList> dstlali(dstTempArgLists); for (;srclali.current() && !found;++srclali,++dstlali) { ArgumentListIterator tsali(*srclali.current()); ArgumentListIterator tdali(*dstlali.current()); Argument *tsa =0,*tda=0, *fa=0; if (funcTempArgList) { fa=funcTempArgList->first(); } for (tsali.toFirst();(tsa=tsali.current()) && !found;++tsali) { tda = tdali.current(); if (name==tsa->name) { if (tda) { name=tda->name; // substitute found=TRUE; } else if (fa) { name=fa->type; found=TRUE; } } if (tda) ++tdali; else if (fa) fa=funcTempArgList->next(); } } dst+=name; p=i+l; } dst+=src.right(src.length()-p); return dst; } static void substituteTemplatesInArgList( const QList<ArgumentList> &srcTempArgLists, const QList<ArgumentList> &dstTempArgLists, ArgumentList *src, ArgumentList *dst, ArgumentList *funcTempArgs = 0 ) { ArgumentListIterator sali(*src); Argument *sa=0; Argument *da=dst->first(); for (sali.toFirst();(sa=sali.current());++sali) // for each member argument { QCString dstType = substituteTemplatesInString( srcTempArgLists,dstTempArgLists,funcTempArgs, sa->type); QCString dstArray = substituteTemplatesInString( srcTempArgLists,dstTempArgLists,funcTempArgs, sa->array); if (da==0) { da=new Argument(*sa); dst->append(da); da->type=dstType; da->array=dstArray; da=0; } else { da->type=dstType; da->type=dstArray; da=dst->next(); } } dst->constSpecifier = src->constSpecifier; dst->volatileSpecifier = src->volatileSpecifier; dst->pureSpecifier = src->pureSpecifier; //printf("substituteTemplatesInArgList: replacing %s with %s\n", // argListToString(src).data(),argListToString(dst).data()); } /*! This function tries to find a member (in a documented class/file/namespace) * that corresponds to the function/variable declaration given in \a funcDecl. * * The boolean \a overloaded is used to specify whether or not a standard * overload documentation line should be generated. * * The boolean \a isFunc is a hint that indicates that this is a function * instead of a variable or typedef. */ static void findMember(EntryNav *rootNav, QCString funcDecl, bool overloaded, bool isFunc ) { Entry *root = rootNav->entry(); Debug::print(Debug::FindMembers,0, "findMember(root=%p,funcDecl=`%s',related=`%s',overload=%d," "isFunc=%d mGrpId=%d tArgList=%p (#=%d) " "spec=%d isObjC=%d\n", root,funcDecl.data(),root->relates.data(),overloaded,isFunc,root->mGrpId, root->tArgLists,root->tArgLists ? root->tArgLists->count() : 0, root->spec,root->objc ); QCString scopeName; QCString className; QCString namespaceName; QCString funcType; QCString funcName; QCString funcArgs; QCString funcTempList; QCString exceptions; QCString funcSpec; bool isRelated=FALSE; bool isMemberOf=FALSE; bool isFriend=FALSE; bool done; do { done=TRUE; if (funcDecl.stripPrefix("friend ")) // treat friends as related members { isFriend=TRUE; done=FALSE; } if (funcDecl.stripPrefix("inline ")) { root->spec|=Entry::Inline; done=FALSE; } if (funcDecl.stripPrefix("explicit ")) { root->spec|=Entry::Explicit; done=FALSE; } if (funcDecl.stripPrefix("mutable ")) { root->spec|=Entry::Mutable; done=FALSE; } if (funcDecl.stripPrefix("virtual ")) { done=FALSE; } } while (!done); // delete any ; from the function declaration int sep; while ((sep=funcDecl.find(';'))!=-1) { funcDecl=(funcDecl.left(sep)+funcDecl.right(funcDecl.length()-sep-1)).stripWhiteSpace(); } // make sure the first character is a space to simplify searching. if (!funcDecl.isEmpty() && funcDecl[0]!=' ') funcDecl.prepend(" "); // remove some superfluous spaces funcDecl= substitute( substitute( substitute(funcDecl,"~ ","~"), ":: ","::" ), " ::","::" ).stripWhiteSpace(); //printf("funcDecl=`%s'\n",funcDecl.data()); if (isFriend && funcDecl.left(6)=="class ") { //printf("friend class\n"); funcDecl=funcDecl.right(funcDecl.length()-6); funcName = funcDecl.copy(); } else if (isFriend && funcDecl.left(7)=="struct ") { funcDecl=funcDecl.right(funcDecl.length()-7); funcName = funcDecl.copy(); } else { // extract information from the declarations parseFuncDecl(funcDecl,root->objc,scopeName,funcType,funcName, funcArgs,funcTempList,exceptions ); } //printf("scopeName=`%s' funcType=`%s' funcName=`%s' funcArgs=`%s'\n", // scopeName.data(),funcType.data(),funcName.data(),funcArgs.data()); // the class name can also be a namespace name, we decide this later. // if a related class name is specified and the class name could // not be derived from the function declaration, then use the // related field. //printf("scopeName=`%s' className=`%s' namespaceName=`%s'\n", // scopeName.data(),className.data(),namespaceName.data()); if (!root->relates.isEmpty()) { // related member, prefix user specified scope isRelated=TRUE; isMemberOf=(root->relatesType == MemberOf); if (getClass(root->relates)==0 && !scopeName.isEmpty()) { scopeName= mergeScopes(scopeName,root->relates); } else { scopeName = root->relates; } } if (root->relates.isEmpty() && rootNav->parent() && ((rootNav->parent()->section()&Entry::SCOPE_MASK) || (rootNav->parent()->section()==Entry::OBJCIMPL_SEC) ) && !rootNav->parent()->name().isEmpty()) // see if we can combine scopeName // with the scope in which it was found { QCString joinedName = rootNav->parent()->name()+"::"+scopeName; if (!scopeName.isEmpty() && (getClass(joinedName) || Doxygen::namespaceSDict->find(joinedName))) { scopeName = joinedName; } else { scopeName = mergeScopes(rootNav->parent()->name(),scopeName); } } else // see if we can prefix a namespace or class that is used from the file { FileDef *fd=rootNav->fileDef(); if (fd) { NamespaceSDict *fnl = fd->getUsedNamespaces(); if (fnl) { QCString joinedName; NamespaceDef *fnd; NamespaceSDict::Iterator nsdi(*fnl); for (nsdi.toFirst();(fnd=nsdi.current());++nsdi) { joinedName = fnd->name()+"::"+scopeName; if (Doxygen::namespaceSDict->find(joinedName)) { scopeName=joinedName; break; } } } } } scopeName=stripTemplateSpecifiersFromScope( removeRedundantWhiteSpace(scopeName),FALSE,&funcSpec); // funcSpec contains the last template specifiers of the given scope. // If this method does not have any template arguments or they are // empty while funcSpec is not empty we assume this is a // specialization of a method. If not, we clear the funcSpec and treat // this as a normal method of a template class. if (!(root->tArgLists && root->tArgLists->count()>0 && root->tArgLists->first()->count()==0 ) ) { funcSpec.resize(0); } // split scope into a namespace and a class part extractNamespaceName(scopeName,className,namespaceName,TRUE); //printf("scopeName=`%s' className=`%s' namespaceName=`%s'\n", // scopeName.data(),className.data(),namespaceName.data()); namespaceName=removeAnonymousScopes(namespaceName); //printf("namespaceName=`%s' className=`%s'\n",namespaceName.data(),className.data()); // merge class and namespace scopes again scopeName.resize(0); if (!namespaceName.isEmpty()) { if (className.isEmpty()) { scopeName=namespaceName; } else if (!root->relates.isEmpty() || // relates command with explicit scope !getClass(className)) // class name only exists in a namespace { scopeName=namespaceName+"::"+className; } else { scopeName=className; } } else if (!className.isEmpty()) { scopeName=className; } //printf("new scope=`%s'\n",scopeName.data()); QCString tempScopeName=scopeName; ClassDef *cd=getClass(scopeName); if (cd) { if (root->tArgLists) root->tArgLists->first(); if (funcSpec.isEmpty()) { tempScopeName=cd->qualifiedNameWithTemplateParameters(root->tArgLists); } else { tempScopeName=scopeName+funcSpec; } } //printf("scopeName=%s cd=%p root->tArgLists=%p result=%s\n", // scopeName.data(),cd,root->tArgLists,tempScopeName.data()); //printf("scopeName=`%s' className=`%s'\n",scopeName.data(),className.data()); // rebuild the function declaration (needed to get the scope right). if (!scopeName.isEmpty() && !isRelated && !isFriend && !Config_getBool("HIDE_SCOPE_NAMES")) { if (!funcType.isEmpty()) { if (isFunc) // a function -> we use argList for the arguments { funcDecl=funcType+" "+tempScopeName+"::"+funcName+funcTempList; } else { funcDecl=funcType+" "+tempScopeName+"::"+funcName+funcArgs; } } else { if (isFunc) // a function => we use argList for the arguments { funcDecl=tempScopeName+"::"+funcName+funcTempList; } else // variable => add `argument' list { funcDecl=tempScopeName+"::"+funcName+funcArgs; } } } else // build declaration without scope { if (!funcType.isEmpty()) // but with a type { if (isFunc) // function => omit argument list { funcDecl=funcType+" "+funcName+funcTempList; } else // variable => add `argument' list { funcDecl=funcType+" "+funcName+funcArgs; } } else // no type { if (isFunc) { funcDecl=funcName+funcTempList; } else { funcDecl=funcName+funcArgs; } } } if (funcType=="template class" && !funcTempList.isEmpty()) return; // ignore explicit template instantiations Debug::print(Debug::FindMembers,0, "findMember() Parse results:\n" " namespaceName=`%s'\n" " className=`%s`\n" " funcType=`%s'\n" " funcSpec=`%s'\n" " funcName=`%s'\n" " funcArgs=`%s'\n" " funcTempList=`%s'\n" " funcDecl=`%s'\n" " related=`%s'\n" " exceptions=`%s'\n" " isRelated=%d\n" " isMemberOf=%d\n" " isFriend=%d\n" " isFunc=%d\n\n", namespaceName.data(),className.data(), funcType.data(),funcSpec.data(),funcName.data(),funcArgs.data(),funcTempList.data(), funcDecl.data(),root->relates.data(),exceptions.data(),isRelated,isMemberOf,isFriend, isFunc ); MemberName *mn=0; if (!funcName.isEmpty()) // function name is valid { Debug::print(Debug::FindMembers,0, "1. funcName=`%s'\n",funcName.data()); if (funcName.left(9)=="operator ") // strip class scope from cast operator { funcName = substitute(funcName,className+"::",""); } if (!funcTempList.isEmpty()) // try with member specialization { mn=Doxygen::memberNameSDict->find(funcName+funcTempList); } if (mn==0) // try without specialization { mn=Doxygen::memberNameSDict->find(funcName); } if (!isRelated && mn) // function name already found { Debug::print(Debug::FindMembers,0, "2. member name exists (%d members with this name)\n",mn->count()); if (!className.isEmpty()) // class name is valid { if (funcSpec.isEmpty()) // not a member specialization { int count=0; int noMatchCount=0; MemberNameIterator mni(*mn); MemberDef *md; bool memFound=FALSE; for (mni.toFirst();!memFound && (md=mni.current());++mni) { ClassDef *cd=md->getClassDef(); Debug::print(Debug::FindMembers,0, "3. member definition found, " "scope needed=`%s' scope=`%s' args=`%s' fileName=%s\n", scopeName.data(),cd ? cd->name().data() : "<none>", md->argsString(), root->fileName.data()); //printf("Member %s (member scopeName=%s) (this scopeName=%s) classTempList=%s\n",md->name().data(),cd->name().data(),scopeName.data(),classTempList.data()); FileDef *fd=rootNav->fileDef(); NamespaceDef *nd=0; if (!namespaceName.isEmpty()) nd=getResolvedNamespace(namespaceName); ClassDef *tcd=findClassDefinition(fd,nd,scopeName); if (tcd==0 && stripAnonymousNamespaceScope(cd->name())==scopeName) { // don't be fooled by anonymous scopes tcd=cd; } //printf("Looking for %s inside nd=%s result=%p (%s) cd=%p\n", // scopeName.data(),nd?nd->name().data():"<none>",tcd,tcd?tcd->name().data():"",cd); if (cd && tcd==cd) // member's classes match { Debug::print(Debug::FindMembers,0, "4. class definition %s found\n",cd->name().data()); // get the template parameter lists found at the member declaration QList<ArgumentList> declTemplArgs; cd->getTemplateParameterLists(declTemplArgs); LockingPtr<ArgumentList> templAl = md->templateArguments(); if (templAl!=0) { declTemplArgs.append(templAl.pointer()); } // get the template parameter lists found at the member definition QList<ArgumentList> *defTemplArgs = root->tArgLists; //printf("defTemplArgs=%p\n",defTemplArgs); // do we replace the decl argument lists with the def argument lists? bool substDone=FALSE; ArgumentList *argList=0; /* substitute the occurrences of class template names in the * argument list before matching */ LockingPtr<ArgumentList> mdAl = md->argumentList(); if (declTemplArgs.count()>0 && defTemplArgs && declTemplArgs.count()==defTemplArgs->count() && mdAl.pointer() ) { /* the function definition has template arguments * and the class definition also has template arguments, so * we must substitute the template names of the class by that * of the function definition before matching. */ argList = new ArgumentList; substituteTemplatesInArgList(declTemplArgs,*defTemplArgs, mdAl.pointer(),argList); substDone=TRUE; } else /* no template arguments, compare argument lists directly */ { argList = mdAl.pointer(); } Debug::print(Debug::FindMembers,0, "5. matching `%s'<=>`%s' className=%s namespaceName=%s\n", argListToString(argList,TRUE).data(),argListToString(root->argList,TRUE).data(), className.data(),namespaceName.data() ); bool matching= md->isVariable() || md->isTypedef() || // needed for function pointers (mdAl.pointer()==0 && root->argList->count()==0) || matchArguments2( md->getClassDef(),md->getFileDef(),argList, cd,fd,root->argList, TRUE); Debug::print(Debug::FindMembers,0, "6. match results of matchArguments2 = %d\n",matching); if (substDone) // found a new argument list { if (matching) // replace member's argument list { md->setDefinitionTemplateParameterLists(root->tArgLists); md->setArgumentList(argList); // new owner of the list => no delete } else // no match { if (!funcTempList.isEmpty() && isSpecialization(declTemplArgs,*defTemplArgs)) { // check if we are dealing with a partial template // specialization. In this case we add it to the class // even though the member arguments do not match. // TODO: copy other aspects? root->protection=md->protection(); // copy protection level addMethodToClass(rootNav,cd,md->name(),isFriend); return; } delete argList; } } if (matching) { addMemberDocs(rootNav,md,funcDecl,0,overloaded,0/* TODO */); count++; memFound=TRUE; } } else if (cd && cd!=tcd) // we did find a class with the same name as cd // but in a different namespace { noMatchCount++; } } if (count==0 && rootNav->parent() && rootNav->parent()->section()==Entry::OBJCIMPL_SEC) { goto localObjCMethod; } if (count==0 && !(isFriend && funcType=="class")) { int candidates=0; if (mn->count()>0) { //printf("Assume template class\n"); for (mni.toFirst();(md=mni.current());++mni) { ClassDef *cd=md->getClassDef(); //printf("cd->name()==%s className=%s\n",cd->name().data(),className.data()); if (cd!=0 && rightScopeMatch(cd->name(),className)) { LockingPtr<ArgumentList> templAl = md->templateArguments(); if (root->tArgLists && templAl!=0 && root->tArgLists->getLast()->count()<=templAl->count()) { addMethodToClass(rootNav,cd,md->name(),isFriend); return; } candidates++; } } } warn(root->fileName,root->startLine, "Warning: no %smatching class member found for", noMatchCount>1 ? "uniquely " : "" ); if (root->tArgLists) { QListIterator<ArgumentList> alli(*root->tArgLists); ArgumentList *al; for (;(al=alli.current());++alli) { warn_cont(" template %s\n",tempArgListToString(al).data()); } } QCString fullFuncDecl=funcDecl.copy(); if (isFunc) fullFuncDecl+=argListToString(root->argList,TRUE); warn_cont(" %s\n",fullFuncDecl.data()); if (candidates>0) { warn_cont("Possible candidates:\n"); for (mni.toFirst();(md=mni.current());++mni) { ClassDef *cd=md->getClassDef(); if (cd!=0 && rightScopeMatch(cd->name(),className)) { LockingPtr<ArgumentList> templAl = md->templateArguments(); if (templAl!=0) { warn_cont(" template %s\n",tempArgListToString(templAl.pointer()).data()); } warn_cont(" "); if (md->typeString()) { warn_cont("%s ",md->typeString()); } QCString qScope = cd->qualifiedNameWithTemplateParameters(); if (!qScope.isEmpty()) warn_cont("%s::%s",qScope.data(),md->name().data()); if (md->argsString()) warn_cont("%s",md->argsString()); if (noMatchCount>1) warn_cont(" at line %d of file %s",md->getDefLine(),md->getDefFileName().data()); warn_cont("\n"); } } } } } else if (cd) // member specialization { MemberDef::MemberType mtype=MemberDef::Function; ArgumentList *tArgList = new ArgumentList; // getTemplateArgumentsFromName(cd->name()+"::"+funcName,root->tArgLists); MemberDef *md=new MemberDef( root->fileName,root->startLine, funcType,funcName,funcArgs,exceptions, root->protection,root->virt,root->stat,Member, mtype,tArgList,root->argList); //printf("new specialized member %s args=`%s'\n",md->name().data(),funcArgs.data()); md->setTagInfo(rootNav->tagInfo()); md->setMemberClass(cd); md->setTemplateSpecialization(TRUE); md->setTypeConstraints(root->typeConstr); md->setDefinition(funcDecl); md->enableCallGraph(root->callGraph); md->enableCallerGraph(root->callerGraph); md->setDocumentation(root->doc,root->docFile,root->docLine); md->setInbodyDocumentation(root->inbodyDocs,root->inbodyFile,root->inbodyLine); md->setDocsForDefinition(!root->proto); md->setPrototype(root->proto); md->addSectionsToDefinition(root->anchors); md->setBodySegment(root->bodyLine,root->endBodyLine); FileDef *fd=rootNav->fileDef(); md->setBodyDef(fd); md->setMemberSpecifiers(root->spec); md->setMemberGroupId(root->mGrpId); mn->append(md); cd->insertMember(md); md->setRefItems(root->sli); delete tArgList; } else { //printf("*** Specialized member %s of unknown scope %s%s found!\n", // scopeName.data(),funcName.data(),funcArgs.data()); } } else if (overloaded) // check if the function belongs to only one class { // for unique overloaded member we allow the class to be // omitted, this is to be Qt compatable. Using this should // however be avoided, because it is error prone MemberNameIterator mni(*mn); MemberDef *md=mni.toFirst(); ASSERT(md); ClassDef *cd=md->getClassDef(); ASSERT(cd); QCString className=cd->name().copy(); ++mni; bool unique=TRUE; for (;(md=mni.current());++mni) { ClassDef *cd=md->getClassDef(); if (className!=cd->name()) unique=FALSE; } if (unique) { MemberDef::MemberType mtype; if (root->mtype==Signal) mtype=MemberDef::Signal; else if (root->mtype==Slot) mtype=MemberDef::Slot; else if (root->mtype==DCOP) mtype=MemberDef::DCOP; else mtype=MemberDef::Function; // new overloaded member function ArgumentList *tArgList = getTemplateArgumentsFromName(cd->name()+"::"+funcName,root->tArgLists); //printf("new related member %s args=`%s'\n",md->name().data(),funcArgs.data()); MemberDef *md=new MemberDef( root->fileName,root->startLine, funcType,funcName,funcArgs,exceptions, root->protection,root->virt,root->stat,Related, mtype,tArgList,root->argList); md->setTagInfo(rootNav->tagInfo()); md->setTypeConstraints(root->typeConstr); md->setMemberClass(cd); md->setDefinition(funcDecl); md->enableCallGraph(root->callGraph); md->enableCallerGraph(root->callerGraph); QCString doc=getOverloadDocs(); doc+="<p>"; doc+=root->doc; md->setDocumentation(doc,root->docFile,root->docLine); md->setInbodyDocumentation(root->inbodyDocs,root->inbodyFile,root->inbodyLine); md->setDocsForDefinition(!root->proto); md->setPrototype(root->proto); md->addSectionsToDefinition(root->anchors); md->setBodySegment(root->bodyLine,root->endBodyLine); FileDef *fd=rootNav->fileDef(); md->setBodyDef(fd); md->setMemberSpecifiers(root->spec); md->setMemberGroupId(root->mGrpId); mn->append(md); cd->insertMember(md); cd->insertUsedFile(root->fileName); md->setRefItems(root->sli); } } else // unrelated function with the same name as a member { if (!findGlobalMember(rootNav,namespaceName,funcName,funcTempList,funcArgs,funcDecl)) { QCString fullFuncDecl=funcDecl.copy(); if (isFunc) fullFuncDecl+=argListToString(root->argList,TRUE); warn(root->fileName,root->startLine, "Warning: Cannot determine class for function\n%s", fullFuncDecl.data() ); } } } else if (isRelated && !root->relates.isEmpty()) { Debug::print(Debug::FindMembers,0,"2. related function\n" " scopeName=%s className=%s\n",scopeName.data(),className.data()); if (className.isEmpty()) className=root->relates; ClassDef *cd; //printf("scopeName=`%s' className=`%s'\n",scopeName.data(),className.data()); if ((cd=getClass(scopeName))) { bool newMember=TRUE; // assume we have a new member bool newMemberName=FALSE; bool isDefine=FALSE; { MemberName *mn = Doxygen::functionNameSDict->find(funcName); if (mn) { MemberDef *md = mn->first(); while (md && !isDefine) { isDefine = isDefine || md->isDefine(); md = mn->next(); } } } FileDef *fd=rootNav->fileDef(); if ((mn=Doxygen::memberNameSDict->find(funcName))==0) { mn=new MemberName(funcName); newMemberName=TRUE; // we create a new member name } else { MemberDef *rmd=mn->first(); while (rmd && newMember) // see if we got another member with matching arguments { LockingPtr<ArgumentList> rmdAl = rmd->argumentList(); newMember=newMember && !matchArguments2(rmd->getOuterScope(),rmd->getFileDef(),rmdAl.pointer(), cd,fd,root->argList, TRUE); if (newMember) rmd=mn->next(); } if (!newMember && rmd) // member already exists as rmd -> add docs { //printf("addMemberDocs for related member %s\n",root->name.data()); //rmd->setMemberDefTemplateArguments(root->mtArgList); addMemberDocs(rootNav,rmd,funcDecl,0,overloaded); } } if (newMember) // need to create a new member { MemberDef::MemberType mtype; if (isDefine) mtype=MemberDef::Define; else if (root->mtype==Signal) mtype=MemberDef::Signal; else if (root->mtype==Slot) mtype=MemberDef::Slot; else if (root->mtype==DCOP) mtype=MemberDef::DCOP; else mtype=MemberDef::Function; //printf("New related name `%s' `%d'\n",funcName.data(), // root->argList ? (int)root->argList->count() : -1); // new related (member) function #if 0 // removed as it doesn't handle related template functions correctly ArgumentList *tArgList = getTemplateArgumentsFromName(scopeName+"::"+funcName,root->tArgLists); MemberDef *md=new MemberDef( root->fileName,root->startLine, funcType,funcName,funcArgs,exceptions, root->protection,root->virt,root->stat,TRUE, mtype,tArgList,funcArgs.isEmpty() ? 0 : root->argList); #endif // first note that we pass: // (root->tArgLists ? root->tArgLists->last() : 0) // for the template arguments fo the new "member." // this accurately reflects the template arguments of // the related function, which don't have to do with // those of the related class. MemberDef *md=new MemberDef( root->fileName,root->startLine, funcType,funcName,funcArgs,exceptions, root->protection,root->virt, root->stat && !isMemberOf, isMemberOf ? Foreign : isRelated ? Related : Member, mtype, (root->tArgLists ? root->tArgLists->last() : 0), funcArgs.isEmpty() ? 0 : root->argList); // // we still have the problem that // MemberDef::writeDocumentation() in memberdef.cpp // writes the template argument list for the class, // as if this member is a member of the class. // fortunately, MemberDef::writeDocumentation() has // a special mechanism that allows us to totally // override the set of template argument lists that // are printed. We use that and set it to the // template argument lists of the related function. // md->setDefinitionTemplateParameterLists(root->tArgLists); md->setTagInfo(rootNav->tagInfo()); //printf("Related member name=`%s' decl=`%s' bodyLine=`%d'\n", // funcName.data(),funcDecl.data(),root->bodyLine); // try to find the matching line number of the body from the // global function list bool found=FALSE; if (root->bodyLine==-1) { MemberName *rmn=Doxygen::functionNameSDict->find(funcName); if (rmn) { MemberDef *rmd=rmn->first(); while (rmd && !found) // see if we got another member with matching arguments { LockingPtr<ArgumentList> rmdAl = rmd->argumentList(); // check for matching argument lists if ( matchArguments2(rmd->getOuterScope(),rmd->getFileDef(),rmdAl.pointer(), cd,fd,root->argList, TRUE) ) { found=TRUE; } if (!found) rmd=rmn->next(); } if (rmd) // member found -> copy line number info { md->setBodySegment(rmd->getStartBodyLine(),rmd->getEndBodyLine()); md->setBodyDef(rmd->getBodyDef()); //md->setBodyMember(rmd); } } } if (!found) // line number could not be found or is available in this // entry { md->setBodySegment(root->bodyLine,root->endBodyLine); md->setBodyDef(fd); } //if (root->mGrpId!=-1) //{ // md->setMemberGroup(memberGroupDict[root->mGrpId]); //} md->setMemberClass(cd); md->setMemberSpecifiers(root->spec); md->setDefinition(funcDecl); md->enableCallGraph(root->callGraph); md->enableCallerGraph(root->callerGraph); md->setDocumentation(root->doc,root->docFile,root->docLine); md->setInbodyDocumentation(root->inbodyDocs,root->inbodyFile,root->inbodyLine); md->setDocsForDefinition(!root->proto); md->setPrototype(root->proto); md->setBriefDescription(root->brief,root->briefFile,root->briefLine); md->addSectionsToDefinition(root->anchors); md->setMemberGroupId(root->mGrpId); //md->setMemberDefTemplateArguments(root->mtArgList); mn->append(md); cd->insertMember(md); cd->insertUsedFile(root->fileName); md->setRefItems(root->sli); if (root->relatesType == Duplicate) md->setRelatedAlso(cd); addMemberToGroups(root,md); //printf("Adding member=%s\n",md->name().data()); if (newMemberName) { //Doxygen::memberNameList.append(mn); //Doxygen::memberNameDict.insert(funcName,mn); Doxygen::memberNameSDict->append(funcName,mn); } } if (root->relatesType == Duplicate) { if (!findGlobalMember(rootNav,namespaceName,funcName,funcTempList,funcArgs,funcDecl)) { QCString fullFuncDecl=funcDecl.copy(); if (isFunc) fullFuncDecl+=argListToString(root->argList,TRUE); warn(root->fileName,root->startLine, "Warning: Cannot determine file/namespace for relatedalso function\n%s", fullFuncDecl.data() ); } } } else { warn_undoc(root->fileName,root->startLine, "Warning: class `%s' for related function `%s' is not " "documented.", className.data(),funcName.data() ); } } else if (rootNav->parent() && rootNav->parent()->section()==Entry::OBJCIMPL_SEC) { localObjCMethod: ClassDef *cd; //printf("scopeName=`%s' className=`%s'\n",scopeName.data(),className.data()); if (Config_getBool("EXTRACT_LOCAL_METHODS") && (cd=getClass(scopeName))) { //printf("Local objective C method `%s' of class `%s' found\n",root->name.data(),cd->name().data()); MemberDef *md=new MemberDef( root->fileName,root->startLine, funcType,funcName,funcArgs,exceptions, root->protection,root->virt,root->stat,Member, MemberDef::Function,0,root->argList); md->setTagInfo(rootNav->tagInfo()); md->makeImplementationDetail(); md->setMemberClass(cd); md->setDefinition(funcDecl); md->enableCallGraph(root->callGraph); md->enableCallerGraph(root->callerGraph); md->setDocumentation(root->doc,root->docFile,root->docLine); md->setBriefDescription(root->brief,root->briefFile,root->briefLine); md->setInbodyDocumentation(root->inbodyDocs,root->inbodyFile,root->inbodyLine); md->setDocsForDefinition(!root->proto); md->setPrototype(root->proto); md->addSectionsToDefinition(root->anchors); md->setBodySegment(root->bodyLine,root->endBodyLine); FileDef *fd=rootNav->fileDef(); md->setBodyDef(fd); md->setMemberSpecifiers(root->spec); md->setMemberGroupId(root->mGrpId); cd->insertMember(md); cd->insertUsedFile(root->fileName); md->setRefItems(root->sli); if ((mn=Doxygen::memberNameSDict->find(root->name))) { mn->append(md); } else { mn = new MemberName(root->name); mn->append(md); Doxygen::memberNameSDict->append(root->name,mn); } } else { // local objective C method found for class without interface } } else // unrelated not overloaded member found { bool globMem = findGlobalMember(rootNav,namespaceName,funcName,funcTempList,funcArgs,funcDecl); if (className.isEmpty() && !globMem) { warn(root->fileName,root->startLine, "Warning: class for member `%s' cannot " "be found.", funcName.data() ); } else if (!className.isEmpty() && !globMem) { warn(root->fileName,root->startLine, "Warning: member `%s' of class `%s' cannot be found", funcName.data(),className.data()); } } } else { // this should not be called warn(root->fileName,root->startLine, "Warning: member with no name found."); } return; } //---------------------------------------------------------------------- // find the members corresponding to the different documentation blocks // that are extracted from the sources. static void filterMemberDocumentation(EntryNav *rootNav) { Entry *root = rootNav->entry(); int i=-1,l; Debug::print(Debug::FindMembers,0, "findMemberDocumentation(): root->type=`%s' root->inside=`%s' root->name=`%s' root->args=`%s' section=%x root->spec=%d root->mGrpId=%d\n", root->type.data(),root->inside.data(),root->name.data(),root->args.data(),root->section,root->spec,root->mGrpId ); //printf("rootNav->parent()->name()=%s\n",rootNav->parent()->name().data()); bool isFunc=TRUE; if (root->relatesType == Duplicate && !root->relates.isEmpty()) { QCString tmp = root->relates; root->relates.resize(0); filterMemberDocumentation(rootNav); root->relates = tmp; } if ( // detect func variable/typedef to func ptr (i=findFunctionPtr(root->type,&l))!=-1 ) { //printf("Fixing function pointer!\n"); // fix type and argument root->args.prepend(root->type.right(root->type.length()-i-l)); root->type=root->type.left(i+l); //printf("Results type=%s,name=%s,args=%s\n",root->type.data(),root->name.data(),root->args.data()); isFunc=FALSE; } else if ((root->type.left(8)=="typedef " && root->args.find('(')!=-1)) // detect function types marked as functions { isFunc=FALSE; } //printf("Member %s isFunc=%d\n",root->name.data(),isFunc); if (root->section==Entry::MEMBERDOC_SEC) { //printf("Documentation for inline member `%s' found args=`%s'\n", // root->name.data(),root->args.data()); //if (root->relates.length()) printf(" Relates %s\n",root->relates.data()); if (root->type.isEmpty()) { findMember(rootNav,root->name+root->args+root->exception,FALSE,isFunc); } else { findMember(rootNav,root->type+" "+root->name+root->args+root->exception,FALSE,isFunc); } } else if (root->section==Entry::OVERLOADDOC_SEC) { //printf("Overloaded member %s found\n",root->name.data()); findMember(rootNav,root->name,TRUE,isFunc); } else if ((root->section==Entry::FUNCTION_SEC // function || (root->section==Entry::VARIABLE_SEC && // variable !root->type.isEmpty() && // with a type compoundKeywordDict.find(root->type)==0 // that is not a keyword // (to skip forward declaration of class etc.) ) ) ) { //printf("Documentation for member `%s' found args=`%s' excp=`%s'\n", // root->name.data(),root->args.data(),root->exception.data()); //if (root->relates.length()) printf(" Relates %s\n",root->relates.data()); //printf("Inside=%s\n Relates=%s\n",root->inside.data(),root->relates.data()); if (root->type=="friend class" || root->type=="friend struct" || root->type=="friend union") { findMember(rootNav, root->type+" "+ root->name, FALSE,FALSE); } else if (!root->type.isEmpty()) { findMember(rootNav, root->type+" "+ root->inside+ root->name+ root->args+ root->exception, FALSE,isFunc); } else { findMember(rootNav, root->inside+ root->name+ root->args+ root->exception, FALSE,isFunc); } } else if (root->section==Entry::DEFINE_SEC && !root->relates.isEmpty()) { findMember(rootNav,root->name+root->args,FALSE,!root->args.isEmpty()); } else if (root->section==Entry::VARIABLEDOC_SEC) { //printf("Documentation for variable %s found\n",root->name.data()); //if (!root->relates.isEmpty()) printf(" Relates %s\n",root->relates.data()); findMember(rootNav,root->name,FALSE,FALSE); } else { // skip section //printf("skip section\n"); } } static void findMemberDocumentation(EntryNav *rootNav) { if (rootNav->section()==Entry::MEMBERDOC_SEC || rootNav->section()==Entry::OVERLOADDOC_SEC || rootNav->section()==Entry::FUNCTION_SEC || rootNav->section()==Entry::VARIABLE_SEC || rootNav->section()==Entry::VARIABLEDOC_SEC || rootNav->section()==Entry::DEFINE_SEC ) { rootNav->loadEntry(g_storage); filterMemberDocumentation(rootNav); rootNav->releaseEntry(); } if (rootNav->children()) { EntryNavListIterator eli(*rootNav->children()); EntryNav *e; for (;(e=eli.current());++eli) { if (e->section()!=Entry::ENUM_SEC) findMemberDocumentation(e); } } } //---------------------------------------------------------------------- static void findObjCMethodDefinitions(EntryNav *rootNav) { if (rootNav->children()) { EntryNavListIterator eli(*rootNav->children()); EntryNav *objCImplNav; for (;(objCImplNav=eli.current());++eli) { if (objCImplNav->section()==Entry::OBJCIMPL_SEC && objCImplNav->children()) { EntryNavListIterator seli(*objCImplNav->children()); EntryNav *objCMethodNav; for (;(objCMethodNav=seli.current());++seli) { if (objCMethodNav->section()==Entry::FUNCTION_SEC) { objCMethodNav->loadEntry(g_storage); Entry *objCMethod = objCMethodNav->entry(); //Printf(" Found ObjC method definition %s\n",objCMethod->name.data()); findMember(objCMethodNav, objCMethod->type+" "+objCImplNav->name()+"::"+ objCMethod->name+" "+objCMethod->args, FALSE,TRUE); objCMethod->section=Entry::EMPTY_SEC; objCMethodNav->releaseEntry(); } } } } } } //---------------------------------------------------------------------- // find and add the enumeration to their classes, namespaces or files static void findEnums(EntryNav *rootNav) { if (rootNav->section()==Entry::ENUM_SEC) // non anonymous enumeration { rootNav->loadEntry(g_storage); Entry *root = rootNav->entry(); MemberDef *md=0; ClassDef *cd=0; FileDef *fd=0; NamespaceDef *nd=0; MemberNameSDict *mnsd=0; bool isGlobal; bool isRelated=FALSE; bool isMemberOf=FALSE; //printf("Found enum with name `%s' relates=%s\n",root->name.data(),root->relates.data()); int i; QCString name; QCString scope; if ((i=root->name.findRev("::"))!=-1) // scope is specified { scope=root->name.left(i); // extract scope name=root->name.right(root->name.length()-i-2); // extract name if ((cd=getClass(scope))==0) nd=getResolvedNamespace(scope); } else // no scope, check the scope in which the docs where found { if (( rootNav->parent()->section() & Entry::SCOPE_MASK ) && !rootNav->parent()->name().isEmpty() ) // found enum docs inside a compound { scope=rootNav->parent()->name(); if ((cd=getClass(scope))==0) nd=getResolvedNamespace(scope); } name=root->name; } if (!root->relates.isEmpty()) { // related member, prefix user specified scope isRelated=TRUE; isMemberOf=(root->relatesType == MemberOf); if (getClass(root->relates)==0 && !scope.isEmpty()) scope=mergeScopes(scope,root->relates); else scope=root->relates.copy(); if ((cd=getClass(scope))==0) nd=getResolvedNamespace(scope); } if (cd && !name.isEmpty()) // found a enum inside a compound { //printf("Enum `%s'::`%s'\n",cd->name(),name.data()); fd=0; mnsd=Doxygen::memberNameSDict; isGlobal=FALSE; } else if (nd && !nd->name().isEmpty() && nd->name().at(0)!='@') // found enum inside namespace { mnsd=Doxygen::functionNameSDict; isGlobal=TRUE; } else // found a global enum { fd=rootNav->fileDef(); mnsd=Doxygen::functionNameSDict; isGlobal=TRUE; } if (!name.isEmpty()) { // new enum type md = new MemberDef( root->fileName,root->startLine, 0,name,0,0, root->protection,Normal,FALSE, isMemberOf ? Foreign : isRelated ? Related : Member, MemberDef::Enumeration, 0,0); md->setTagInfo(rootNav->tagInfo()); if (!isGlobal) md->setMemberClass(cd); else md->setFileDef(fd); md->setBodySegment(root->bodyLine,root->endBodyLine); md->setBodyDef(rootNav->fileDef()); //printf("Enum %s definition at line %d of %s: protection=%d\n", // root->name.data(),root->bodyLine,root->fileName.data(),root->protection); md->addSectionsToDefinition(root->anchors); md->setMemberGroupId(root->mGrpId); md->enableCallGraph(root->callGraph); md->enableCallerGraph(root->callerGraph); md->setRefItems(root->sli); //printf("found enum %s nd=%p\n",name.data(),nd); bool defSet=FALSE; if (nd && !nd->name().isEmpty() && nd->name().at(0)!='@') { if (isRelated || Config_getBool("HIDE_SCOPE_NAMES")) { md->setDefinition(name); } else { md->setDefinition(nd->name()+"::"+name); } //printf("definition=%s\n",md->definition()); defSet=TRUE; md->setNamespace(nd); nd->insertMember(md); } // even if we have already added the enum to a namespace, we still // also want to add it to other appropriate places such as file // or class. if (isGlobal) { if (!defSet) md->setDefinition(name); if (fd==0 && rootNav->parent()) { fd=rootNav->parent()->fileDef(); } if (fd) { md->setFileDef(fd); fd->insertMember(md); } } else if (cd) { if (isRelated || Config_getBool("HIDE_SCOPE_NAMES")) { md->setDefinition(name); } else { md->setDefinition(cd->name()+"::"+name); } cd->insertMember(md); cd->insertUsedFile(root->fileName); } md->setDocumentation(root->doc,root->docFile,root->docLine); md->setDocsForDefinition(!root->proto); md->setBriefDescription(root->brief,root->briefFile,root->briefLine); md->setInbodyDocumentation(root->inbodyDocs,root->inbodyFile,root->inbodyLine); //printf("Adding member=%s\n",md->name().data()); MemberName *mn; if ((mn=(*mnsd)[name])) { // this is used if the same enum is in multiple namespaces/classes mn->append(md); } else // new enum name { mn = new MemberName(name); mn->append(md); mnsd->append(name,mn); //printf("add %s to new memberName. Now %d members\n", // name.data(),mn->count()); } addMemberToGroups(root,md); #if 0 if (rootNav->children()) { EntryNavListIterator eli(*rootNav->children()); EntryNav *e; for (;(e=eli.current());++eli) { //printf("e->name=%s isRelated=%d\n",e->name.data(),isRelated); MemberName *fmn=0; MemberNameSDict *emnsd = isRelated ? Doxygen::functionNameSDict : mnsd; if (!e->name().isEmpty() && (fmn=(*emnsd)[e->name()])) // get list of members with the same name as the field { MemberNameIterator fmni(*fmn); MemberDef *fmd; for (fmni.toFirst(); (fmd=fmni.current()) ; ++fmni) { if (fmd->isEnumValue()) { //printf("found enum value with same name\n"); if (nd && !nd->name().isEmpty() && nd->name().at(0)!='@') { NamespaceDef *fnd=fmd->getNamespaceDef(); if (fnd==nd) // enum value is inside a namespace { md->insertEnumField(fmd); fmd->setEnumScope(md); } } else if (isGlobal) { FileDef *ffd=fmd->getFileDef(); if (ffd==fd) // enum value has file scope { md->insertEnumField(fmd); fmd->setEnumScope(md); } } else if (isRelated && cd) // reparent enum value to // match the enum's scope { md->insertEnumField(fmd); // add field def to list fmd->setEnumScope(md); // cross ref with enum name fmd->setEnumClassScope(cd); // cross ref with enum name fmd->setOuterScope(cd); fmd->makeRelated(); cd->insertMember(fmd); } else { ClassDef *fcd=fmd->getClassDef(); if (fcd==cd) // enum value is inside a class { //printf("Inserting enum field %s in enum scope %s\n", // fmd->name().data(),md->name().data()); md->insertEnumField(fmd); // add field def to list fmd->setEnumScope(md); // cross ref with enum name } } } } } } } #endif } rootNav->releaseEntry(); } else { RECURSE_ENTRYTREE(findEnums,rootNav); } } //---------------------------------------------------------------------- static void addEnumValuesToEnums(EntryNav *rootNav) { if (rootNav->section()==Entry::ENUM_SEC) // non anonymous enumeration { rootNav->loadEntry(g_storage); Entry *root = rootNav->entry(); ClassDef *cd=0; FileDef *fd=0; NamespaceDef *nd=0; MemberNameSDict *mnsd=0; bool isGlobal; bool isRelated=FALSE; //printf("Found enum with name `%s' relates=%s\n",root->name.data(),root->relates.data()); int i; QCString name; QCString scope; if ((i=root->name.findRev("::"))!=-1) // scope is specified { scope=root->name.left(i); // extract scope name=root->name.right(root->name.length()-i-2); // extract name if ((cd=getClass(scope))==0) nd=getResolvedNamespace(scope); } else // no scope, check the scope in which the docs where found { if (( rootNav->parent()->section() & Entry::SCOPE_MASK ) && !rootNav->parent()->name().isEmpty() ) // found enum docs inside a compound { scope=rootNav->parent()->name(); if ((cd=getClass(scope))==0) nd=getResolvedNamespace(scope); } name=root->name; } if (!root->relates.isEmpty()) { // related member, prefix user specified scope isRelated=TRUE; if (getClass(root->relates)==0 && !scope.isEmpty()) scope=mergeScopes(scope,root->relates); else scope=root->relates.copy(); if ((cd=getClass(scope))==0) nd=getResolvedNamespace(scope); } if (cd && !name.isEmpty()) // found a enum inside a compound { //printf("Enum in class `%s'::`%s'\n",cd->name().data(),name.data()); fd=0; mnsd=Doxygen::memberNameSDict; isGlobal=FALSE; } else if (nd && !nd->name().isEmpty() && nd->name().at(0)!='@') // found enum inside namespace { //printf("Enum in namespace `%s'::`%s'\n",nd->name().data(),name.data()); mnsd=Doxygen::functionNameSDict; isGlobal=TRUE; } else // found a global enum { fd=rootNav->fileDef(); //printf("Enum in file `%s': `%s'\n",fd->name().data(),name.data()); mnsd=Doxygen::functionNameSDict; isGlobal=TRUE; } if (!name.isEmpty()) { MemberName *mn = mnsd->find(name); // for all members with this name if (mn) { MemberNameIterator mni(*mn); MemberDef *md; for (mni.toFirst(); (md=mni.current()) ; ++mni) // for each enum in this list { if (md->isEnumerate() && rootNav->children()) { EntryNavListIterator eli(*rootNav->children()); // for each enum value EntryNav *e; for (;(e=eli.current());++eli) { SrcLangExt sle; if (rootNav->fileDef() && ( (sle=getLanguageFromFileName(rootNav->fileDef()->name()))==SrcLangExt_CSharp || sle==SrcLangExt_Java ) ) { // For C# enum value are only inside the enum scope, so we // must create them here e->loadEntry(g_storage); MemberDef *fmd = addVariableToFile(e,MemberDef::EnumValue, md->getOuterScope() ? md->getOuterScope()->name() : QCString(), e->name(),FALSE,0); md->insertEnumField(fmd); fmd->setEnumScope(md); e->releaseEntry(); } else { //printf("e->name=%s isRelated=%d\n",e->name().data(),isRelated); MemberName *fmn=0; MemberNameSDict *emnsd = isRelated ? Doxygen::functionNameSDict : mnsd; if (!e->name().isEmpty() && (fmn=(*emnsd)[e->name()])) // get list of members with the same name as the field { MemberNameIterator fmni(*fmn); MemberDef *fmd; for (fmni.toFirst(); (fmd=fmni.current()) ; ++fmni) { if (fmd->isEnumValue() && fmd->getOuterScope()==md->getOuterScope()) // in same scope { //printf("found enum value with same name %s in scope %s\n", // fmd->name().data(),fmd->getOuterScope()->name().data()); if (nd && !nd->name().isEmpty() && nd->name().at(0)!='@') { NamespaceDef *fnd=fmd->getNamespaceDef(); if (fnd==nd) // enum value is inside a namespace { md->insertEnumField(fmd); fmd->setEnumScope(md); } } else if (isGlobal) { FileDef *ffd=fmd->getFileDef(); if (ffd==fd) // enum value has file scope { md->insertEnumField(fmd); fmd->setEnumScope(md); } } else if (isRelated && cd) // reparent enum value to // match the enum's scope { md->insertEnumField(fmd); // add field def to list fmd->setEnumScope(md); // cross ref with enum name fmd->setEnumClassScope(cd); // cross ref with enum name fmd->setOuterScope(cd); fmd->makeRelated(); cd->insertMember(fmd); } else { ClassDef *fcd=fmd->getClassDef(); if (fcd==cd) // enum value is inside a class { //printf("Inserting enum field %s in enum scope %s\n", // fmd->name().data(),md->name().data()); md->insertEnumField(fmd); // add field def to list fmd->setEnumScope(md); // cross ref with enum name } } } } } } } } } } } rootNav->releaseEntry(); } else { RECURSE_ENTRYTREE(addEnumValuesToEnums,rootNav); } } //---------------------------------------------------------------------- // find the documentation blocks for the enumerations static void findEnumDocumentation(EntryNav *rootNav) { if (rootNav->section()==Entry::ENUMDOC_SEC && !rootNav->name().isEmpty() && rootNav->name().at(0)!='@' // skip anonymous enums ) { rootNav->loadEntry(g_storage); Entry *root = rootNav->entry(); //printf("Found docs for enum with name `%s' in context %s\n", // root->name.data(),root->parent->name.data()); int i; QCString name; QCString scope; if ((i=root->name.findRev("::"))!=-1) // scope is specified as part of the name { name=root->name.right(root->name.length()-i-2); // extract name scope=root->name.left(i); // extract scope //printf("Scope=`%s' Name=`%s'\n",scope.data(),name.data()); } else // just the name { name=root->name; } if (( rootNav->parent()->section() & Entry::SCOPE_MASK ) && !rootNav->parent()->name().isEmpty() ) // found enum docs inside a compound { if (!scope.isEmpty()) scope.prepend("::"); scope.prepend(rootNav->parent()->name()); } ClassDef *cd=getClass(scope); if (!name.isEmpty()) { bool found=FALSE; if (cd) { //printf("Enum: scope=`%s' name=`%s'\n",cd->name(),name.data()); QCString className=cd->name().copy(); MemberName *mn=Doxygen::memberNameSDict->find(name); if (mn) { MemberNameIterator mni(*mn); MemberDef *md; for (mni.toFirst();(md=mni.current()) && !found;++mni) { ClassDef *cd=md->getClassDef(); if (cd && cd->name()==className && md->isEnumerate()) { // documentation outside a compound overrides the documentation inside it #if 0 if (!md->documentation() || rootNav->parent()->name().isEmpty()) #endif { md->setDocumentation(root->doc,root->docFile,root->docLine); md->setDocsForDefinition(!root->proto); } // brief descriptions inside a compound override the documentation // outside it #if 0 if (!md->briefDescription() || !rootNav->parent()->name().isEmpty()) #endif { md->setBriefDescription(root->brief,root->briefFile,root->briefLine); } if (!md->inbodyDocumentation() || !rootNav->parent()->name().isEmpty()) { md->setInbodyDocumentation(root->inbodyDocs,root->inbodyFile,root->inbodyLine); } if (root->mGrpId!=-1 && md->getMemberGroupId()==-1) { md->setMemberGroupId(root->mGrpId); } md->addSectionsToDefinition(root->anchors); GroupDef *gd=md->getGroupDef(); if (gd==0 &&root->groups->first()!=0) // member not grouped but out-of-line documentation is { addMemberToGroups(root,md); } found=TRUE; } } } else { //printf("MemberName %s not found!\n",name.data()); } } else // enum outside class { //printf("Enum outside class: %s grpId=%d\n",name.data(),root->mGrpId); MemberName *mn=Doxygen::functionNameSDict->find(name); if (mn) { MemberNameIterator mni(*mn); MemberDef *md; for (mni.toFirst();(md=mni.current()) && !found;++mni) { if (md->isEnumerate()) { md->setDocumentation(root->doc,root->docFile,root->docLine); md->setDocsForDefinition(!root->proto); md->setBriefDescription(root->brief,root->briefFile,root->briefLine); md->setInbodyDocumentation(root->inbodyDocs,root->inbodyFile,root->inbodyLine); md->addSectionsToDefinition(root->anchors); md->setMemberGroupId(root->mGrpId); GroupDef *gd=md->getGroupDef(); if (gd==0 && root->groups->first()!=0) // member not grouped but out-of-line documentation is { addMemberToGroups(root,md); } found=TRUE; } } } } if (!found) { warn(root->fileName,root->startLine, "Warning: Documentation for undefined enum `%s' found.", name.data() ); } } rootNav->releaseEntry(); } RECURSE_ENTRYTREE(findEnumDocumentation,rootNav); } // seach for each enum (member or function) in mnl if it has documented // enum values. static void findDEV(const MemberNameSDict &mnsd) { MemberName *mn; MemberNameSDict::Iterator mnli(mnsd); // for each member name for (mnli.toFirst();(mn=mnli.current());++mnli) { MemberDef *md; MemberNameIterator mni(*mn); // for each member definition for (mni.toFirst();(md=mni.current());++mni) { if (md->isEnumerate()) // member is an enum { LockingPtr<MemberList> fmdl = md->enumFieldList(); int documentedEnumValues=0; if (fmdl!=0) // enum has values { MemberListIterator fmni(*fmdl); MemberDef *fmd; // for each enum value for (fmni.toFirst();(fmd=fmni.current());++fmni) { if (fmd->isLinkableInProject()) documentedEnumValues++; } } // at least one enum value is documented if (documentedEnumValues>0) md->setDocumentedEnumValues(TRUE); } } } } // seach for each enum (member or function) if it has documented enum // values. static void findDocumentedEnumValues() { findDEV(*Doxygen::memberNameSDict); findDEV(*Doxygen::functionNameSDict); } //---------------------------------------------------------------------- static void addMembersToIndex() { MemberName *mn; MemberNameSDict::Iterator mnli(*Doxygen::memberNameSDict); // for each member name for (mnli.toFirst();(mn=mnli.current());++mnli) { MemberDef *md; MemberNameIterator mni(*mn); // for each member definition for (mni.toFirst();(md=mni.current());++mni) { addClassMemberNameToIndex(md); } } MemberNameSDict::Iterator fnli(*Doxygen::functionNameSDict); // for each member name for (fnli.toFirst();(mn=fnli.current());++fnli) { MemberDef *md; MemberNameIterator mni(*mn); // for each member definition for (mni.toFirst();(md=mni.current());++mni) { if (md->getNamespaceDef()) { addNamespaceMemberNameToIndex(md); } else { addFileMemberNameToIndex(md); } } } } //---------------------------------------------------------------------- // computes the relation between all members. For each member `m' // the members that override the implementation of `m' are searched and // the member that `m' overrides is searched. static void computeMemberRelations() { MemberNameSDict::Iterator mnli(*Doxygen::memberNameSDict); MemberName *mn; for ( ; (mn=mnli.current()) ; ++mnli ) // for each member name { MemberNameIterator mdi(*mn); MemberDef *md; for ( ; (md=mdi.current()) ; ++mdi ) // for each member with a specific name { MemberDef *bmd = mn->first(); // for each other member with the same name while (bmd) { ClassDef *mcd = md->getClassDef(); if (mcd && mcd->baseClasses()) { ClassDef *bmcd = bmd->getClassDef(); //printf("Check relation between `%s'::`%s' (%p) and `%s'::`%s' (%p)\n", // mcd->name().data(),md->name().data(),md, // bmcd->name().data(),bmd->name().data(),bmd // ); if (md!=bmd && bmcd && mcd && bmcd!=mcd && mcd->isBaseClass(bmcd,TRUE)) { //printf(" Base argList=`%s'\n Super argList=`%s'\n", // argListToString(bmd->argumentList()).data(), // argListToString(md->argumentList()).data() // ); LockingPtr<ArgumentList> bmdAl = bmd->argumentList(); LockingPtr<ArgumentList> mdAl = md->argumentList(); if ( matchArguments2(bmd->getOuterScope(),bmd->getFileDef(),bmdAl.pointer(), md->getOuterScope(), md->getFileDef(), mdAl.pointer(), TRUE ) ) { //printf(" match found!\n"); if (mcd && bmcd && mcd->isLinkable() && bmcd->isLinkable() ) { MemberDef *rmd; if ((rmd=md->reimplements())==0 || minClassDistance(mcd,bmcd)<minClassDistance(mcd,rmd->getClassDef()) ) { //printf("setting (new) reimplements member\n"); md->setReimplements(bmd); } //printf("%s: add reimplements member %s\n",mcd->name().data(),bmcd->name().data()); //md->setImplements(bmd); //printf("%s: add reimplementedBy member %s\n",bmcd->name().data(),mcd->name().data()); bmd->insertReimplementedBy(md); } } } } bmd = mn->next(); } } } } //---------------------------------------------------------------------------- //static void computeClassImplUsageRelations() //{ // ClassDef *cd; // ClassSDict::Iterator cli(*Doxygen::classSDict); // for (;(cd=cli.current());++cli) // { // cd->determineImplUsageRelation(); // } //} //---------------------------------------------------------------------------- static void createTemplateInstanceMembers() { ClassSDict::Iterator cli(*Doxygen::classSDict); ClassDef *cd; // for each class for (cli.toFirst();(cd=cli.current());++cli) { // that is a template QDict<ClassDef> *templInstances = cd->getTemplateInstances(); if (templInstances) { QDictIterator<ClassDef> qdi(*templInstances); ClassDef *tcd=0; // for each instance of the template for (qdi.toFirst();(tcd=qdi.current());++qdi) { tcd->addMembersToTemplateInstance(cd,qdi.currentKey()); } } } } //---------------------------------------------------------------------------- // builds the list of all members for each class static void buildCompleteMemberLists() { ClassDef *cd; // merge members of categories into the class they extend ClassSDict::Iterator cli(*Doxygen::classSDict); for (cli.toFirst();(cd=cli.current());++cli) { int i=cd->name().find('('); if (i!=-1) // it is an Objective-C category { QCString baseName=cd->name().left(i); ClassDef *baseClass=Doxygen::classSDict->find(baseName); if (baseClass) { //printf("*** merging members of category %s into %s\n", // cd->name().data(),baseClass->name().data()); baseClass->mergeCategory(cd); } } } // merge the member list of base classes into the inherited classes. for (cli.toFirst();(cd=cli.current());++cli) { if (// !cd->isReference() && // not an external class cd->subClasses()==0 && // is a root of the hierarchy cd->baseClasses()) // and has at least one base class { //printf("*** merging members for %s\n",cd->name().data()); cd->mergeMembers(); } } // now sort the member list of all classes. for (cli.toFirst();(cd=cli.current());++cli) { if (cd->memberNameInfoSDict()) cd->memberNameInfoSDict()->sort(); } } //---------------------------------------------------------------------------- static void generateFileSources() { if (documentedHtmlFiles==0) return; if (Doxygen::inputNameList->count()>0) { FileNameListIterator fnli(*Doxygen::inputNameList); FileName *fn; for (;(fn=fnli.current());++fnli) { FileNameIterator fni(*fn); FileDef *fd; for (;(fd=fni.current());++fni) { if (fd->generateSourceFile()) // sources need to be shown in the output { msg("Generating code for file %s...\n",fd->docName().data()); fd->writeSource(*outputList); } else if (!fd->isReference() && Doxygen::parseSourcesNeeded) // we needed to parse the sources even if we do not show them { msg("Parsing code for file %s...\n",fd->docName().data()); fd->parseSource(); } } } } } //---------------------------------------------------------------------------- static void generateFileDocs() { if (documentedHtmlFiles==0) return; if (Doxygen::inputNameList->count()>0) { FileNameListIterator fnli(*Doxygen::inputNameList); FileName *fn; for (fnli.toFirst();(fn=fnli.current());++fnli) { FileNameIterator fni(*fn); FileDef *fd; for (fni.toFirst();(fd=fni.current());++fni) { bool doc = fd->isLinkableInProject(); if (doc) { msg("Generating docs for file %s...\n",fd->docName().data()); fd->writeDocumentation(*outputList); } } } } } //---------------------------------------------------------------------------- static void addSourceReferences() { // add source references for class definitions ClassSDict::Iterator cli(*Doxygen::classSDict); ClassDef *cd=0; for (cli.toFirst();(cd=cli.current());++cli) { FileDef *fd=cd->getBodyDef(); if (fd && cd->isLinkableInProject() && cd->getStartBodyLine()!=-1) { fd->addSourceRef(cd->getStartBodyLine(),cd,0); } } // add source references for namespace definitions NamespaceSDict::Iterator nli(*Doxygen::namespaceSDict); NamespaceDef *nd=0; for (nli.toFirst();(nd=nli.current());++nli) { FileDef *fd=nd->getBodyDef(); if (fd && nd->isLinkableInProject() && nd->getStartBodyLine()!=-1) { fd->addSourceRef(nd->getStartBodyLine(),nd,0); } } // add source references for member names MemberNameSDict::Iterator mnli(*Doxygen::memberNameSDict); MemberName *mn=0; for (mnli.toFirst();(mn=mnli.current());++mnli) { MemberNameIterator mni(*mn); MemberDef *md=0; for (mni.toFirst();(md=mni.current());++mni) { //printf("class member %s\n",md->name().data()); FileDef *fd=md->getBodyDef(); if (fd && md->getStartBodyLine()!=-1 && md->isLinkableInProject() && (fd->generateSourceFile() || Doxygen::parseSourcesNeeded) ) { //printf("Found member `%s' in file `%s' at line `%d' def=%s\n", // md->name().data(),fd->name().data(),md->getStartBodyLine(),md->getOuterScope()->name().data()); fd->addSourceRef(md->getStartBodyLine(),md->getOuterScope(),md); } } } MemberNameSDict::Iterator fnli(*Doxygen::functionNameSDict); for (fnli.toFirst();(mn=fnli.current());++fnli) { MemberNameIterator mni(*mn); MemberDef *md=0; for (mni.toFirst();(md=mni.current());++mni) { FileDef *fd=md->getBodyDef(); //printf("member %s body=[%d,%d] fd=%p link=%d parseSources=%d\n", // md->name().data(), // md->getStartBodyLine(),md->getEndBodyLine(),fd, // md->isLinkableInProject(), // Doxygen::parseSourcesNeeded); if (fd && md->getStartBodyLine()!=-1 && md->isLinkableInProject() && (fd->generateSourceFile() || Doxygen::parseSourcesNeeded) ) { //printf("Found member `%s' in file `%s' at line `%d' def=%s\n", // md->name().data(),fd->name().data(),md->getStartBodyLine(),md->getOuterScope()->name().data()); fd->addSourceRef(md->getStartBodyLine(),md->getOuterScope(),md); } } } } //---------------------------------------------------------------------------- // generate the documentation of all classes static void generateClassList(ClassSDict &classSDict) { ClassSDict::Iterator cli(classSDict); for ( ; cli.current() ; ++cli ) { ClassDef *cd=cli.current(); //printf("cd=%s getOuterScope=%p global=%p\n",cd->name().data(),cd->getOuterScope(),Doxygen::globalScope); if ((cd->getOuterScope()==0 || // <-- should not happen, but can if we read an old tag file cd->getOuterScope()==Doxygen::globalScope // only look at global classes ) && !cd->isHidden() ) { // skip external references, anonymous compounds and // template instances if ( cd->isLinkableInProject() && cd->templateMaster()==0) { msg("Generating docs for compound %s...\n",cd->name().data()); cd->writeDocumentation(*outputList); cd->writeMemberList(*outputList); } // even for undocumented classes, the inner classes can be documented. cd->writeDocumentationForInnerClasses(*outputList); } } } static void generateClassDocs() { // write the installdox script if necessary if (Config_getBool("GENERATE_HTML") && (Config_getList("TAGFILES").count()>0 || Config_getBool("SEARCHENGINE") ) ) { writeInstallScript(); } msg("Generating annotated compound index...\n"); writeAnnotatedIndex(*outputList); //if (Config_getBool("ALPHABETICAL_INDEX")) //{ msg("Generating alphabetical compound index...\n"); writeAlphabeticalIndex(*outputList); //} msg("Generating hierarchical class index...\n"); writeHierarchicalIndex(*outputList); msg("Generating member index...\n"); writeClassMemberIndex(*outputList); if (Doxygen::exampleSDict->count()>0) { msg("Generating example index...\n"); } generateClassList(*Doxygen::classSDict); generateClassList(*Doxygen::hiddenClasses); } //---------------------------------------------------------------------------- static void inheritDocumentation() { MemberNameSDict::Iterator mnli(*Doxygen::memberNameSDict); MemberName *mn; //int count=0; for (;(mn=mnli.current());++mnli) { MemberNameIterator mni(*mn); MemberDef *md; for (;(md=mni.current());++mni) { //printf("%04d Member `%s'\n",count++,md->name().data()); if (md->documentation().isEmpty() && md->briefDescription().isEmpty()) { // no documentation yet MemberDef *bmd = md->reimplements(); while (bmd && bmd->documentation().isEmpty() && bmd->briefDescription().isEmpty() ) { // search up the inheritance tree for a documentation member //printf("bmd=%s class=%s\n",bmd->name().data(),bmd->getClassDef()->name().data()); bmd = bmd->reimplements(); } if (bmd) // copy the documentation from the reimplemented member { md->setInheritsDocsFrom(bmd); md->setDocumentation(bmd->documentation(),bmd->docFile(),bmd->docLine()); md->setDocsForDefinition(bmd->isDocsForDefinition()); md->setBriefDescription(bmd->briefDescription(),bmd->briefFile(),bmd->briefLine()); md->copyArgumentNames(bmd); md->setInbodyDocumentation(bmd->inbodyDocumentation(),bmd->inbodyFile(),bmd->inbodyLine()); } } } } } //---------------------------------------------------------------------------- static void combineUsingRelations() { // for each file FileNameListIterator fnli(*Doxygen::inputNameList); FileName *fn; for (fnli.toFirst();(fn=fnli.current());++fnli) { FileNameIterator fni(*fn); FileDef *fd; for (fni.toFirst();(fd=fni.current());++fni) { fd->visited=FALSE; } } for (fnli.toFirst();(fn=fnli.current());++fnli) { FileNameIterator fni(*fn); FileDef *fd; for (fni.toFirst();(fd=fni.current());++fni) { fd->combineUsingRelations(); } } // for each namespace NamespaceSDict::Iterator nli(*Doxygen::namespaceSDict); NamespaceDef *nd; for (nli.toFirst() ; (nd=nli.current()) ; ++nli ) { nd->visited=FALSE; } for (nli.toFirst() ; (nd=nli.current()) ; ++nli ) { nd->combineUsingRelations(); } } //---------------------------------------------------------------------------- static void addMembersToMemberGroup() { // for each class ClassSDict::Iterator cli(*Doxygen::classSDict); ClassDef *cd; for ( ; (cd=cli.current()) ; ++cli ) { cd->addMembersToMemberGroup(); } // for each file FileName *fn=Doxygen::inputNameList->first(); while (fn) { FileDef *fd=fn->first(); while (fd) { fd->addMembersToMemberGroup(); fd=fn->next(); } fn=Doxygen::inputNameList->next(); } // for each namespace NamespaceSDict::Iterator nli(*Doxygen::namespaceSDict); NamespaceDef *nd; for ( ; (nd=nli.current()) ; ++nli ) { nd->addMembersToMemberGroup(); } // for each group GroupSDict::Iterator gli(*Doxygen::groupSDict); GroupDef *gd; for (gli.toFirst();(gd=gli.current());++gli) { gd->addMembersToMemberGroup(); } } //---------------------------------------------------------------------------- static void distributeMemberGroupDocumentation() { // for each class ClassSDict::Iterator cli(*Doxygen::classSDict); ClassDef *cd; for ( ; (cd=cli.current()) ; ++cli ) { cd->distributeMemberGroupDocumentation(); } // for each file FileName *fn=Doxygen::inputNameList->first(); while (fn) { FileDef *fd=fn->first(); while (fd) { fd->distributeMemberGroupDocumentation(); fd=fn->next(); } fn=Doxygen::inputNameList->next(); } // for each namespace NamespaceSDict::Iterator nli(*Doxygen::namespaceSDict); NamespaceDef *nd; for ( ; (nd=nli.current()) ; ++nli ) { nd->distributeMemberGroupDocumentation(); } // for each group GroupSDict::Iterator gli(*Doxygen::groupSDict); GroupDef *gd; for (gli.toFirst();(gd=gli.current());++gli) { gd->distributeMemberGroupDocumentation(); } } //---------------------------------------------------------------------------- static void findSectionsInDocumentation() { // for each class ClassSDict::Iterator cli(*Doxygen::classSDict); ClassDef *cd; for ( ; (cd=cli.current()) ; ++cli ) { cd->findSectionsInDocumentation(); } // for each file FileName *fn=Doxygen::inputNameList->first(); while (fn) { FileDef *fd=fn->first(); while (fd) { fd->findSectionsInDocumentation(); fd=fn->next(); } fn=Doxygen::inputNameList->next(); } // for each namespace NamespaceSDict::Iterator nli(*Doxygen::namespaceSDict); NamespaceDef *nd; for ( ; (nd=nli.current()) ; ++nli ) { nd->findSectionsInDocumentation(); } // for each group GroupSDict::Iterator gli(*Doxygen::groupSDict); GroupDef *gd; for (gli.toFirst();(gd=gli.current());++gli) { gd->findSectionsInDocumentation(); } // for each page PageSDict::Iterator pdi(*Doxygen::pageSDict); PageDef *pd=0; for (pdi.toFirst();(pd=pdi.current());++pdi) { pd->findSectionsInDocumentation(); } if (Doxygen::mainPage) Doxygen::mainPage->findSectionsInDocumentation(); } static void flushCachedTemplateRelations() { // remove all references to classes from the cache // as there can be new template instances in the inheritance path // to this class. Optimization: only remove those classes that // have inheritance instances as direct or indirect sub classes. QCacheIterator<LookupInfo> ci(Doxygen::lookupCache); LookupInfo *li=0; for (ci.toFirst();(li=ci.current());++ci) { if (li->classDef) { Doxygen::lookupCache.remove(ci.currentKey()); } } // remove all cached typedef resolutions whose target is a // template class as this may now be a template instance MemberNameSDict::Iterator fnli(*Doxygen::functionNameSDict); MemberName *fn; for (;(fn=fnli.current());++fnli) // for each global function name { MemberNameIterator fni(*fn); MemberDef *fmd; for (;(fmd=fni.current());++fni) // for each function with that name { if (fmd->isTypedefValCached()) { ClassDef *cd = fmd->getCachedTypedefVal(); if (cd->isTemplate()) fmd->invalidateTypedefValCache(); } } } MemberNameSDict::Iterator mnli(*Doxygen::memberNameSDict); for (;(fn=mnli.current());++mnli) // for each class method name { MemberNameIterator mni(*fn); MemberDef *fmd; for (;(fmd=mni.current());++mni) // for each function with that name { if (fmd->isTypedefValCached()) { ClassDef *cd = fmd->getCachedTypedefVal(); if (cd->isTemplate()) fmd->invalidateTypedefValCache(); } } } } //---------------------------------------------------------------------------- static void flushUnresolvedRelations() { // Remove all unresolved references to classes from the cache. // This is needed before resolving the inheritance relations, since // it would otherwise not find the inheritance relation // for C in the example below, as B::I was already found to be unresolvable // (which is correct if you igore the inheritance relation between A and B). // // class A { class I {} }; // class B : public A {}; // class C : public B::I {}; // QCacheIterator<LookupInfo> ci(Doxygen::lookupCache); LookupInfo *li=0; for (ci.toFirst();(li=ci.current());++ci) { if (li->classDef==0 && li->typeDef==0) { Doxygen::lookupCache.remove(ci.currentKey()); } } } //---------------------------------------------------------------------------- static void findDefineDocumentation(EntryNav *rootNav) { if ((rootNav->section()==Entry::DEFINEDOC_SEC || rootNav->section()==Entry::DEFINE_SEC) && !rootNav->name().isEmpty() ) { rootNav->loadEntry(g_storage); Entry *root = rootNav->entry(); //printf("found define `%s' `%s' brief=`%s' doc=`%s'\n", // root->name.data(),root->args.data(),root->brief.data(),root->doc.data()); if (rootNav->tagInfo() && !root->name.isEmpty()) // define read from a tag file { MemberDef *md=new MemberDef("<tagfile>",1, "#define",root->name,root->args,0, Public,Normal,FALSE,Member,MemberDef::Define,0,0); md->setTagInfo(rootNav->tagInfo()); //printf("Searching for `%s' fd=%p\n",filePathName.data(),fd); md->setFileDef(rootNav->parent()->fileDef()); //printf("Adding member=%s\n",md->name().data()); MemberName *mn; if ((mn=Doxygen::functionNameSDict->find(root->name))) { mn->append(md); } else { mn = new MemberName(root->name); mn->append(md); Doxygen::functionNameSDict->append(root->name,mn); } } MemberName *mn=Doxygen::functionNameSDict->find(root->name); if (mn) { int count=0; MemberDef *md=mn->first(); while (md) { if (md->memberType()==MemberDef::Define) count++; md=mn->next(); } if (count==1) { md=mn->first(); while (md) { if (md->memberType()==MemberDef::Define) { #if 0 if (md->documentation().isEmpty()) #endif { md->setDocumentation(root->doc,root->docFile,root->docLine); md->setDocsForDefinition(!root->proto); } #if 0 if (md->briefDescription().isEmpty()) #endif { md->setBriefDescription(root->brief,root->briefFile,root->briefLine); } if (md->inbodyDocumentation().isEmpty()) { md->setInbodyDocumentation(root->inbodyDocs,root->inbodyFile,root->inbodyLine); } md->setBodySegment(root->bodyLine,root->endBodyLine); md->setBodyDef(rootNav->fileDef()); md->addSectionsToDefinition(root->anchors); md->setMaxInitLines(root->initLines); md->setRefItems(root->sli); if (root->mGrpId!=-1) md->setMemberGroupId(root->mGrpId); addMemberToGroups(root,md); } md=mn->next(); } } else if (count>1 && (!root->doc.isEmpty() || !root->brief.isEmpty() || root->bodyLine!=-1 ) ) // multiple defines don't know where to add docs // but maybe they are in different files together with their documentation { md=mn->first(); while (md) { if (md->memberType()==MemberDef::Define) { FileDef *fd=md->getFileDef(); if (fd && fd->absFilePath()==root->fileName) // doc and define in the same file assume they belong together. { #if 0 if (md->documentation().isEmpty()) #endif { md->setDocumentation(root->doc,root->docFile,root->docLine); md->setDocsForDefinition(!root->proto); } #if 0 if (md->briefDescription().isEmpty()) #endif { md->setBriefDescription(root->brief,root->briefFile,root->briefLine); } if (md->inbodyDocumentation().isEmpty()) { md->setInbodyDocumentation(root->inbodyDocs,root->inbodyFile,root->inbodyLine); } md->setBodySegment(root->bodyLine,root->endBodyLine); md->setBodyDef(rootNav->fileDef()); md->addSectionsToDefinition(root->anchors); md->setRefItems(root->sli); if (root->mGrpId!=-1) md->setMemberGroupId(root->mGrpId); addMemberToGroups(root,md); } } md=mn->next(); } //warn("Warning: define %s found in the following files:\n",root->name.data()); //warn("Cannot determine where to add the documentation found " // "at line %d of file %s. \n", // root->startLine,root->fileName.data()); } } else if (!root->doc.isEmpty() || !root->brief.isEmpty()) // define not found { static bool preEnabled = Config_getBool("ENABLE_PREPROCESSING"); if (preEnabled) { warn(root->fileName,root->startLine, "Warning: documentation for unknown define %s found.\n", root->name.data() ); } else { warn(root->fileName,root->startLine, "Warning: found documented #define but ignoring it because " "ENABLE_PREPROCESSING is NO.\n", root->name.data() ); } } rootNav->releaseEntry(); } RECURSE_ENTRYTREE(findDefineDocumentation,rootNav); } //---------------------------------------------------------------------------- static void findDirDocumentation(EntryNav *rootNav) { if (rootNav->section() == Entry::DIRDOC_SEC) { rootNav->loadEntry(g_storage); Entry *root = rootNav->entry(); QCString normalizedName = root->name; normalizedName = substitute(normalizedName,"\\","/"); if (normalizedName.at(normalizedName.length()-1)!='/') { normalizedName+='/'; } DirDef *dir,*matchingDir=0; SDict<DirDef>::Iterator sdi(*Doxygen::directories); for (sdi.toFirst();(dir=sdi.current());++sdi) { //printf("Dir: %s<->%s\n",dir->name().data(),normalizedName.data()); if (dir->name().right(normalizedName.length())==normalizedName) { if (matchingDir) { warn(root->fileName,root->startLine, "Warning: \\dir command matches multiple directories.\n" " Applying the command for directory %s\n" " Ignoring the command for directory %s\n", matchingDir->name().data(),dir->name().data() ); } else { matchingDir=dir; } } } if (matchingDir) { //printf("Match for with dir %s\n",matchingDir->name().data()); matchingDir->setBriefDescription(root->brief,root->briefFile,root->briefLine); matchingDir->setDocumentation(root->doc,root->docFile,root->docLine); matchingDir->setRefItems(root->sli); addDirToGroups(root,matchingDir); } else { warn(root->fileName,root->startLine,"Warning: No matching " "directory found for command \\dir %s\n",root->name.data()); } rootNav->releaseEntry(); } RECURSE_ENTRYTREE(findDirDocumentation,rootNav); } //---------------------------------------------------------------------------- // create a (sorted) list of separate documentation pages static void buildPageList(EntryNav *rootNav) { if (rootNav->section() == Entry::PAGEDOC_SEC) { rootNav->loadEntry(g_storage); Entry *root = rootNav->entry(); if (!root->name.isEmpty()) { addRelatedPage(rootNav); } rootNav->releaseEntry(); } else if (rootNav->section() == Entry::MAINPAGEDOC_SEC) { rootNav->loadEntry(g_storage); Entry *root = rootNav->entry(); QCString title=root->args.stripWhiteSpace(); if (title.isEmpty()) title=theTranslator->trMainPage(); addRefItem(root->sli,"page", usingTreeIndex()?"main":"index", title ); rootNav->releaseEntry(); } RECURSE_ENTRYTREE(buildPageList,rootNav); } static void findMainPage(EntryNav *rootNav) { if (rootNav->section() == Entry::MAINPAGEDOC_SEC) { rootNav->loadEntry(g_storage); Entry *root = rootNav->entry(); if (Doxygen::mainPage==0) { //printf("Found main page! \n======\n%s\n=======\n",root->doc.data()); QCString title=root->args.stripWhiteSpace(); QCString indexName=usingTreeIndex()?"main":"index"; Doxygen::mainPage = new PageDef(root->fileName,root->startLine, indexName, root->brief+root->doc,title); //setFileNameForSections(root->anchors,"index",Doxygen::mainPage); Doxygen::mainPage->setFileName(indexName); addPageToContext(Doxygen::mainPage,rootNav); // a page name is a label as well! SectionInfo *si=new SectionInfo( indexName, Doxygen::mainPage->name(), Doxygen::mainPage->title(), SectionInfo::Page); Doxygen::sectionDict.insert(indexName,si); Doxygen::mainPage->addSectionsToDefinition(root->anchors); } else { warn(root->fileName,root->startLine, "Warning: found more than one \\mainpage comment block! Skipping this " "block." ); } rootNav->releaseEntry(); } RECURSE_ENTRYTREE(findMainPage,rootNav); } static void computePageRelations(EntryNav *rootNav) { if ((rootNav->section()==Entry::PAGEDOC_SEC || rootNav->section()==Entry::MAINPAGEDOC_SEC ) && !rootNav->name().isEmpty() ) { rootNav->loadEntry(g_storage); Entry *root = rootNav->entry(); PageDef *pd = root->section==Entry::PAGEDOC_SEC ? Doxygen::pageSDict->find(root->name) : Doxygen::mainPage; if (pd) { QListIterator<BaseInfo> bii(*root->extends); BaseInfo *bi; for (bii.toFirst();(bi=bii.current());++bii) { PageDef *subPd = Doxygen::pageSDict->find(bi->name); if (subPd) { pd->addInnerCompound(subPd); //printf("*** Added subpage relation: %s->%s\n", // pd->name().data(),subPd->name().data()); } } } rootNav->releaseEntry(); } RECURSE_ENTRYTREE(computePageRelations,rootNav); } static void checkPageRelations() { PageSDict::Iterator pdi(*Doxygen::pageSDict); PageDef *pd=0; for (pdi.toFirst();(pd=pdi.current());++pdi) { Definition *ppd = pd->getOuterScope(); while (ppd) { if (ppd==pd) { err("Warning: page defined at line %d of file %s with label %s is a subpage " "of itself! Please remove this cyclic dependency.\n", pd->docLine(),pd->docFile().data(),pd->name().data()); exit(1); } ppd=ppd->getOuterScope(); } } } //---------------------------------------------------------------------------- static void resolveUserReferences() { QDictIterator<SectionInfo> sdi(Doxygen::sectionDict); SectionInfo *si; for (;(si=sdi.current());++sdi) { //printf("si->label=`%s' si->definition=%s si->fileName=`%s'\n", // si->label.data(),si->definition?si->definition->name().data():"<none>", // si->fileName.data()); PageDef *pd=0; // hack: the items of a todo/test/bug/deprecated list are all fragments from // different files, so the resulting section's all have the wrong file // name (not from the todo/test/bug/deprecated list, but from the file in // which they are defined). We correct this here by looking at the // generated section labels! QDictIterator<RefList> rli(*Doxygen::xrefLists); RefList *rl; for (rli.toFirst();(rl=rli.current());++rli) { QCString label="_"+rl->listName(); // "_todo", "_test", ... if (si->label.left(label.length())==label) { si->fileName=rl->listName(); si->generated=TRUE; break; } } //printf("start: si->label=%s si->fileName=%s\n",si->label.data(),si->fileName.data()); if (!si->generated) { // if this section is in a page and the page is in a group, then we // have to adjust the link file name to point to the group. if (!si->fileName.isEmpty() && (pd=Doxygen::pageSDict->find(si->fileName)) && pd->getGroupDef()) { si->fileName=pd->getGroupDef()->getOutputFileBase().copy(); } if (si->definition) { // TODO: there should be one function in Definition that returns // the file to link to, so we can avoid the following tests. GroupDef *gd=0; if (si->definition->definitionType()==Definition::TypeMember) { gd = ((MemberDef *)si->definition)->getGroupDef(); } if (gd) { si->fileName=gd->getOutputFileBase().copy(); } else { //si->fileName=si->definition->getOutputFileBase().copy(); //printf("Setting si->fileName to %s\n",si->fileName.data()); } } } //printf("end: si->label=%s si->fileName=%s\n",si->label.data(),si->fileName.data()); } } //---------------------------------------------------------------------------- // generate all separate documentation pages static void generatePageDocs() { //printf("documentedPages=%d real=%d\n",documentedPages,Doxygen::pageSDict->count()); if (documentedPages==0) return; PageSDict::Iterator pdi(*Doxygen::pageSDict); PageDef *pd=0; for (pdi.toFirst();(pd=pdi.current());++pdi) { if (!pd->getGroupDef() && !pd->isReference()) { msg("Generating docs for page %s...\n",pd->name().data()); Doxygen::insideMainPage=TRUE; pd->writeDocumentation(*outputList); Doxygen::insideMainPage=FALSE; } } } //---------------------------------------------------------------------------- // create a (sorted) list & dictionary of example pages static void buildExampleList(EntryNav *rootNav) { if (rootNav->section()==Entry::EXAMPLE_SEC && !rootNav->name().isEmpty()) { rootNav->loadEntry(g_storage); Entry *root = rootNav->entry(); if (Doxygen::exampleSDict->find(root->name)) { warn(root->fileName,root->startLine, "Warning: Example %s was already documented. Ignoring " "documentation found here.", root->name.data() ); } else { PageDef *pd=new PageDef(root->fileName,root->startLine, root->name,root->brief+root->doc,root->args); pd->setFileName(convertNameToFile(pd->name()+"-example")); pd->addSectionsToDefinition(root->anchors); //pi->addSections(root->anchors); Doxygen::exampleSDict->inSort(root->name,pd); //we don't add example to groups //addExampleToGroups(root,pd); } rootNav->releaseEntry(); } RECURSE_ENTRYTREE(buildExampleList,rootNav); } //---------------------------------------------------------------------------- // prints the Entry tree (for debugging) void printNavTree(EntryNav *rootNav,int indent) { QCString indentStr; indentStr.fill(' ',indent); msg("%s%s (sec=0x%x)\n", indentStr.isEmpty()?"":indentStr.data(), rootNav->name().isEmpty()?"<empty>":rootNav->name().data(), rootNav->section()); if (rootNav->children()) { EntryNavListIterator eli(*rootNav->children()); for (;eli.current();++eli) printNavTree(eli.current(),indent+2); } } //---------------------------------------------------------------------------- // generate the example documentation static void generateExampleDocs() { outputList->disable(OutputGenerator::Man); PageSDict::Iterator pdi(*Doxygen::exampleSDict); PageDef *pd=0; for (pdi.toFirst();(pd=pdi.current());++pdi) { msg("Generating docs for example %s...\n",pd->name().data()); resetCCodeParserState(); QCString n=pd->getOutputFileBase(); startFile(*outputList,n,n,pd->name()); startTitle(*outputList,n); outputList->docify(pd->name()); endTitle(*outputList,n,0); outputList->parseDoc(pd->docFile(), // file pd->docLine(), // startLine pd, // context 0, // memberDef pd->documentation()+"\n\n\\include "+pd->name(), // docs TRUE, // index words TRUE, // is example pd->name() ); endFile(*outputList); } outputList->enable(OutputGenerator::Man); } //---------------------------------------------------------------------------- // generate module pages static void generateGroupDocs() { GroupSDict::Iterator gli(*Doxygen::groupSDict); GroupDef *gd; for (gli.toFirst();(gd=gli.current());++gli) { if (!gd->isReference()) { gd->writeDocumentation(*outputList); } } } //---------------------------------------------------------------------------- //static void generatePackageDocs() //{ // writePackageIndex(*outputList); // // if (Doxygen::packageDict.count()>0) // { // PackageSDict::Iterator pdi(Doxygen::packageDict); // PackageDef *pd; // for (pdi.toFirst();(pd=pdi.current());++pdi) // { // pd->writeDocumentation(*outputList); // } // } //} //---------------------------------------------------------------------------- // generate module pages static void generateNamespaceDocs() { writeNamespaceIndex(*outputList); NamespaceSDict::Iterator nli(*Doxygen::namespaceSDict); NamespaceDef *nd; // for each namespace... for (;(nd=nli.current());++nli) { if (nd->isLinkableInProject()) { msg("Generating docs for namespace %s\n",nd->name().data()); nd->writeDocumentation(*outputList); } // for each class in the namespace... ClassSDict::Iterator cli(*nd->getClassSDict()); for ( ; cli.current() ; ++cli ) { ClassDef *cd=cli.current(); if ( ( cd->isLinkableInProject() && cd->templateMaster()==0 ) // skip external references, anonymous compounds and // template instances and nested classes && !cd->isHidden() ) { msg("Generating docs for compound %s...\n",cd->name().data()); cd->writeDocumentation(*outputList); cd->writeMemberList(*outputList); } cd->writeDocumentationForInnerClasses(*outputList); } } } #if defined(_WIN32) static QCString fixSlashes(QCString &s) { QCString result; uint i; for (i=0;i<s.length();i++) { switch(s.at(i)) { case '/': case '\\': result+="\\\\"; break; default: result+=s.at(i); } } return result; } #endif //---------------------------------------------------------------------------- // generate files for the search engine //static void generateSearchIndex() //{ // if (Config_getBool("SEARCHENGINE") && Config_getBool("GENERATE_HTML")) // { // // create search index // QCString fileName; // writeSearchButton(Config_getString("HTML_OUTPUT")); // //#if !defined(_WIN32) // // create cgi script // fileName = Config_getString("HTML_OUTPUT")+"/"+Config_getString("CGI_NAME"); // QFile f(fileName); // if (f.open(IO_WriteOnly)) // { // QTextStream t(&f); // t << "#!/bin/sh" << endl // << "DOXYSEARCH=" << Config_getString("BIN_ABSPATH") << "/doxysearch" << endl // << "DOXYPATH=\"" << Config_getString("DOC_ABSPATH") << " "; // // QStrList &extDocPaths=Config_getList("EXT_DOC_PATHS"); // char *s= extDocPaths.first(); // while (s) // { // t << s << " "; // s=extDocPaths.next(); // } // // t << "\"" << endl // << "if [ -f $DOXYSEARCH ]" << endl // << "then" << endl // << " $DOXYSEARCH $DOXYPATH" << endl // << "else" << endl // << " echo \"Content-Type: text/html\"" << endl // << " echo \"\"" << endl // << " echo \"<h2>Error: $DOXYSEARCH not found. Check cgi script!</h2>\"" << endl // << "fi" << endl; // // f.close(); // struct stat stat_struct; // stat(fileName,&stat_struct); // chmod(fileName,stat_struct.st_mode|S_IXUSR|S_IXGRP|S_IXOTH); // } // else // { // err("Error: Cannot open file %s for writing\n",fileName.data()); // } //#else /* Windows platform */ // // create cgi program // fileName = Config_getString("CGI_NAME").copy(); // if (fileName.right(4)==".cgi") // fileName=fileName.left(fileName.length()-4); // fileName+=".c"; // fileName.prepend(Config_getString("HTML_OUTPUT")+"/"); // QFile f(fileName); // if (f.open(IO_WriteOnly)) // { // QTextStream t(&f); // t << "#include <stdio.h>" << endl; // t << "#include <stdlib.h>" << endl; // t << "#include <process.h>" << endl; // t << endl; // t << "const char *DOXYSEARCH = \"" << // fixSlashes(Config_getString("BIN_ABSPATH")) << "\\\\doxysearch.exe\";" << endl; // t << "const char *DOXYPATH = \"" << // fixSlashes(Config_getString("DOC_ABSPATH")) << "\";" << endl; // t << endl; // t << "int main(void)" << endl; // t << "{" << endl; // t << " char buf[1024];" << endl; // t << " sprintf(buf,\"%s %s\",DOXYSEARCH,DOXYPATH);" << endl; // t << " if (system(buf))" << endl; // t << " {" << endl; // t << " printf(\"Content-Type: text/html\\n\\n\");" << endl; // t << " printf(\"<h2>Error: failed to execute %s</h2>\\n\",DOXYSEARCH);" << endl; // t << " exit(1);" << endl; // t << " }" << endl; // t << " return 0;" << endl; // t << "}" << endl; // f.close(); // } // else // { // err("Error: Cannot open file %s for writing\n",fileName.data()); // } //#endif /* !defined(_WIN32) */ // // // create config file // fileName = Config_getString("HTML_OUTPUT")+"/search.cfg"; // f.setName(fileName); // if (f.open(IO_WriteOnly)) // { // QTextStream t(&f); // t << Config_getString("DOC_URL") << "/" << endl // << Config_getString("CGI_URL") << "/" << Config_getString("CGI_NAME") << endl; // f.close(); // } // else // { // err("Error: Cannot open file %s for writing\n",fileName.data()); // } // //outputList->generateExternalIndex(); // outputList->pushGeneratorState(); // outputList->disableAllBut(OutputGenerator::Html); // startFile(*outputList,"header"+Doxygen::htmlFileExtension,0,"Search Engine",TRUE); // outputList->endPlainFile(); // outputList->startPlainFile("footer"+Doxygen::htmlFileExtension); // endFile(*outputList,TRUE); // outputList->popGeneratorState(); // } //} //---------------------------------------------------------------------------- static bool openOutputFile(const char *outFile,QFile &f) { bool fileOpened=FALSE; bool writeToStdout=(outFile[0]=='-' && outFile[1]=='\0'); if (writeToStdout) // write to stdout { fileOpened = f.open(IO_WriteOnly,stdout); } else // write to file { QFileInfo fi(outFile); if (fi.exists()) // create a backup { QDir dir=fi.dir(); QFileInfo backup(fi.fileName()+".bak"); if (backup.exists()) // remove existing backup dir.remove(backup.fileName()); dir.rename(fi.fileName(),fi.fileName()+".bak"); } f.setName(outFile); fileOpened = f.open(IO_WriteOnly|IO_Translate); } return fileOpened; } /*! Generate a template version of the configuration file. * If the \a shortList parameter is TRUE a configuration file without * comments will be generated. */ static void generateConfigFile(const char *configFile,bool shortList, bool updateOnly=FALSE) { QFile f; bool fileOpened=openOutputFile(configFile,f); bool writeToStdout=(configFile[0]=='-' && configFile[1]=='\0'); if (fileOpened) { QTextStream t(&f); t.setEncoding(QTextStream::UnicodeUTF8); Config::instance()->writeTemplate(t,shortList,updateOnly); if (!writeToStdout) { if (!updateOnly) { msg("\n\nConfiguration file `%s' created.\n\n",configFile); msg("Now edit the configuration file and enter\n\n"); if (strcmp(configFile,"Doxyfile") || strcmp(configFile,"doxyfile")) msg(" doxygen %s\n\n",configFile); else msg(" doxygen\n\n"); msg("to generate the documentation for your project\n\n"); } else { msg("\n\nConfiguration file `%s' updated.\n\n",configFile); } } } else { err("Error: Cannot open file %s for writing\n",configFile); exit(1); } } //---------------------------------------------------------------------------- // read and parse a tag file //static bool readLineFromFile(QFile &f,QCString &s) //{ // char c=0; // s.resize(0); // while (!f.atEnd() && (c=f.getch())!='\n') s+=c; // return f.atEnd(); //} //---------------------------------------------------------------------------- static void readTagFile(Entry *root,const char *tl) { QCString tagLine = tl; QCString fileName; QCString destName; int eqPos = tagLine.find('='); if (eqPos!=-1) // tag command contains a destination { fileName = tagLine.left(eqPos).stripWhiteSpace(); destName = tagLine.right(tagLine.length()-eqPos-1).stripWhiteSpace(); QFileInfo fi(fileName); Doxygen::tagDestinationDict.insert(fi.fileName(),new QCString(destName)); //printf("insert tagDestination %s->%s\n",fi.fileName().data(),destName.data()); } else { fileName = tagLine; } QFileInfo fi(fileName); if (!fi.exists() || !fi.isFile()) { err("Error: Tag file `%s' does not exist or is not a file. Skipping it...\n", fileName.data()); return; } if (!destName.isEmpty()) msg("Reading tag file `%s', location `%s'...\n",fileName.data(),destName.data()); else msg("Reading tag file `%s'...\n",fileName.data()); parseTagFile(root,fi.absFilePath(),fi.fileName()); } //---------------------------------------------------------------------------- // returns TRUE if the name of the file represented by `fi' matches // one of the file patterns in the `patList' list. static bool patternMatch(QFileInfo *fi,QStrList *patList) { bool found=FALSE; if (patList) { QCString pattern=patList->first(); while (!pattern.isEmpty() && !found) { int i=pattern.find('='); if (i!=-1) pattern=pattern.left(i); // strip of the extension specific filter name #if defined(_WIN32) // windows QRegExp re(pattern,FALSE,TRUE); // case insensitive match #else // unix QRegExp re(pattern,TRUE,TRUE); // case sensitive match #endif found = found || re.match(fi->fileName())!=-1 || re.match(fi->filePath())!=-1 || re.match(fi->absFilePath())!=-1; //printf("Matching `%s' against pattern `%s' found=%d\n", // fi->fileName().data(),pattern.data(),found); pattern=patList->next(); } } return found; } static int transcodeCharacterBuffer(BufStr &srcBuf,int size, const char *inputEncoding,const char *outputEncoding) { if (inputEncoding==0 || outputEncoding==0) return size; if (qstricmp(inputEncoding,outputEncoding)==0) return size; void *cd = portable_iconv_open(outputEncoding,inputEncoding); if (cd==(void *)(-1)) { err("Error: unsupported character conversion: '%s'->'%s': %s\n" "Check the INPUT_ENCODING setting in the config file!\n", inputEncoding,outputEncoding,strerror(errno)); exit(1); } int tmpBufSize=size*4+1; BufStr tmpBuf(tmpBufSize); size_t iLeft=size; size_t oLeft=tmpBufSize; const char *srcPtr = srcBuf.data(); char *dstPtr = tmpBuf.data(); uint newSize=0; if (!portable_iconv(cd, &srcPtr, &iLeft, &dstPtr, &oLeft)) { newSize = tmpBufSize-oLeft; srcBuf.shrink(newSize); strncpy(srcBuf.data(),tmpBuf.data(),newSize); //printf("iconv: input size=%d output size=%d\n[%s]\n",size,newSize,srcBuf.data()); } else { err("Error: failed to translate characters from %s to %s: check INPUT_ENCODING\n", inputEncoding,outputEncoding); exit(1); } portable_iconv_close(cd); return newSize; } //---------------------------------------------------------------------------- // reads a file into an array and filters out any 0x00 and 0x06 bytes, // because these are special for the parser. void copyAndFilterFile(const char *fileName,BufStr &dest) { // try to open file int size=0; //uint oldPos = dest.curPos(); //printf(".......oldPos=%d\n",oldPos); QFileInfo fi(fileName); if (!fi.exists()) return; QCString filterName = getFileFilter(fileName); if (filterName.isEmpty()) { QFile f(fileName); if (!f.open(IO_ReadOnly)) { err("Error: could not open file %s\n",fileName); return; } size=fi.size(); // read the file dest.skip(size); if (f.readBlock(dest.data()/*+oldPos*/,size)!=size) { err("Error while reading file %s\n",fileName); return; } } else { QCString cmd=filterName+" \""+fileName+"\""; Debug::print(Debug::ExtCmd,0,"Executing popen(`%s`)\n",cmd.data()); FILE *f=portable_popen(cmd,"r"); if (!f) { err("Error: could not execute filter %s\n",filterName.data()); return; } const int bufSize=1024; char buf[bufSize]; int numRead; while ((numRead=fread(buf,1,bufSize,f))>0) { //printf(">>>>>>>>Reading %d bytes\n",numRead); dest.addArray(buf,numRead),size+=numRead; } portable_pclose(f); } // filter unwanted bytes from the resulting data uchar conv[256]; int i; for (i=0;i<256;i++) conv[i]=i; conv[0x06]=0x20; // replace the offending characters with spaces conv[0x00]=0x20; // remove any special markers from the input uchar *p=(uchar *)dest.data()/*+oldPos*/; for (i=0;i<size;i++,p++) *p=conv[*p]; // and translate CR's int newSize=filterCRLF(dest.data()/*+oldPos*/,size); //printf("filter char at %p size=%d newSize=%d\n",dest.data()+oldPos,size,newSize); if (newSize!=size) // we removed chars { dest.shrink(/*oldPos+*/newSize); // resize the array //printf(".......resizing from %d to %d result=[%s]\n",oldPos+size,oldPos+newSize,dest.data()); } } //---------------------------------------------------------------------------- static void copyStyleSheet() { QCString &htmlStyleSheet = Config_getString("HTML_STYLESHEET"); if (!htmlStyleSheet.isEmpty()) { QFile cssf(htmlStyleSheet); QFileInfo cssfi(htmlStyleSheet); if (cssf.open(IO_ReadOnly)) { QCString destFileName = Config_getString("HTML_OUTPUT")+"/"+cssfi.fileName().data(); QFile df(destFileName); if (df.open(IO_WriteOnly)) { char *buffer = new char[cssf.size()]; cssf.readBlock(buffer,cssf.size()); df.writeBlock(buffer,cssf.size()); df.flush(); delete[] buffer; } else { err("Error: could not write to style sheet %s\n",destFileName.data()); } } else { err("Error: could not open user specified style sheet %s\n",Config_getString("HTML_STYLESHEET").data()); htmlStyleSheet.resize(0); // revert to the default } } } static void parseFiles(Entry *root,EntryNav *rootNav) { void *cd = 0; QCString inpEncoding = Config_getString("INPUT_ENCODING"); bool needsTranscoding = !inpEncoding.isEmpty(); if (needsTranscoding) { if (!(cd = portable_iconv_open("UTF-8", inpEncoding))) { err("Error: unsupported character enconding: '%s'",inpEncoding.data()); exit(1); } } QCString *s=inputFiles.first(); while (s) { QCString fileName=*s; QCString extension; int ei = fileName.findRev('.'); if (ei!=-1) extension=fileName.right(fileName.length()-ei); ParserInterface *parser = Doxygen::parserManager->getParser(extension); QFileInfo fi(fileName); BufStr preBuf(fi.size()+4096); //BufStr *bufPtr = &preBuf; if (Config_getBool("ENABLE_PREPROCESSING") && parser->needsPreprocessing(extension)) { msg("Preprocessing %s...\n",s->data()); preprocessFile(fileName,preBuf); } else { msg("Reading %s...\n",s->data()); copyAndFilterFile(fileName,preBuf); } preBuf.addChar('\n'); /* to prevent problems under Windows ? */ // do character transcoding if needed. transcodeCharacterBuffer(preBuf,preBuf.curPos(), Config_getString("INPUT_ENCODING"),"UTF-8"); BufStr convBuf(preBuf.curPos()+1024); // convert multi-line C++ comments to C style comments convertCppComments(&preBuf,&convBuf,fileName); convBuf.addChar('\0'); // use language parse to parse the file parser->parseInput(fileName,convBuf.data(),root); // store the Entry tree in a file and create an index to // navigate/load entries bool ambig; FileDef *fd=findFileDef(Doxygen::inputNameDict,fileName,ambig); ASSERT(fd!=0); root->createNavigationIndex(rootNav,g_storage,fd); s=inputFiles.next(); } } //---------------------------------------------------------------------------- // Read all files matching at least one pattern in `patList' in the // directory represented by `fi'. // The directory is read iff the recusiveFlag is set. // The contents of all files is append to the input string int readDir(QFileInfo *fi, FileNameList *fnList, FileNameDict *fnDict, StringDict *exclDict, QStrList *patList, QStrList *exclPatList, StringList *resultList, StringDict *resultDict, bool errorIfNotExist, bool recursive, QDict<void> *killDict ) { QDir dir((const char *)fi->absFilePath()); dir.setFilter( QDir::Files | QDir::Dirs | QDir::Hidden ); int totalSize=0; msg("Searching for files in directory %s\n", fi->absFilePath().data()); //printf("killDict=%p count=%d\n",killDict,killDict->count()); const QFileInfoList *list = dir.entryInfoList(); QFileInfoListIterator it( *list ); QFileInfo *cfi; while ((cfi=it.current())) { if (exclDict==0 || exclDict->find(cfi->absFilePath())==0) { // file should not be excluded //printf("killDict->find(%s)\n",cfi->absFilePath().data()); if (!cfi->exists() || !cfi->isReadable()) { if (errorIfNotExist) { err("Warning: source %s is not a readable file or directory... skipping.\n",cfi->absFilePath().data()); } } else if (cfi->isFile() && (!Config_getBool("EXCLUDE_SYMLINKS") || !cfi->isSymLink()) && (patList==0 || patternMatch(cfi,patList)) && !patternMatch(cfi,exclPatList) && (killDict==0 || killDict->find(cfi->absFilePath())==0) ) { totalSize+=cfi->size()+cfi->absFilePath().length()+4; QCString name=convertToQCString(cfi->fileName()); //printf("New file %s\n",name.data()); if (fnDict) { FileDef *fd=new FileDef(cfi->dirPath()+"/",name); FileName *fn=0; if (!name.isEmpty() && (fn=(*fnDict)[name])) { fn->append(fd); } else { fn = new FileName(cfi->absFilePath(),name); fn->append(fd); if (fnList) fnList->inSort(fn); fnDict->insert(name,fn); } } QCString *rs=0; if (resultList || resultDict) { rs=new QCString(cfi->absFilePath()); } if (resultList) resultList->append(rs); if (resultDict) resultDict->insert(cfi->absFilePath(),rs); if (killDict) killDict->insert(cfi->absFilePath(),(void *)0x8); } else if (recursive && (!Config_getBool("EXCLUDE_SYMLINKS") || !cfi->isSymLink()) && cfi->isDir() && cfi->fileName()!="." && !patternMatch(cfi,exclPatList) && cfi->fileName()!="..") { cfi->setFile(cfi->absFilePath()); totalSize+=readDir(cfi,fnList,fnDict,exclDict, patList,exclPatList,resultList,resultDict,errorIfNotExist, recursive,killDict); } } ++it; } return totalSize; } //---------------------------------------------------------------------------- // read a file or all files in a directory and append their contents to the // input string. The names of the files are appended to the `fiList' list. int readFileOrDirectory(const char *s, FileNameList *fnList, FileNameDict *fnDict, StringDict *exclDict, QStrList *patList, QStrList *exclPatList, StringList *resultList, StringDict *resultDict, bool recursive, bool errorIfNotExist, QDict<void> *killDict ) { //printf("killDict=%p count=%d\n",killDict,killDict->count()); // strip trailing slashes if (s==0) return 0; QCString fs = s; char lc = fs.at(fs.length()-1); if (lc=='/' || lc=='\\') fs = fs.left(fs.length()-1); QFileInfo fi(fs); //printf("readFileOrDirectory(%s)\n",s); int totalSize=0; { if (exclDict==0 || exclDict->find(fi.absFilePath())==0) { if (!fi.exists() || !fi.isReadable()) { if (errorIfNotExist) { err("Warning: source %s is not a readable file or directory... skipping.\n",s); } } else if (!Config_getBool("EXCLUDE_SYMLINKS") || !fi.isSymLink()) { if (fi.isFile()) { //printf("killDict->find(%s)\n",fi.absFilePath().data()); if (killDict==0 || killDict->find(fi.absFilePath())==0) { totalSize+=fi.size()+fi.absFilePath().length()+4; //readFile(&fi,fiList,input); //fiList->inSort(new FileInfo(fi)); QCString name=convertToQCString(fi.fileName()); //printf("New file %s\n",name.data()); if (fnDict) { FileDef *fd=new FileDef(fi.dirPath(TRUE)+"/",name); FileName *fn=0; if (!name.isEmpty() && (fn=(*fnDict)[name])) { fn->append(fd); } else { fn = new FileName(fi.absFilePath(),name); fn->append(fd); if (fnList) fnList->inSort(fn); fnDict->insert(name,fn); } } QCString *rs=0; if (resultList || resultDict) { rs=new QCString(fi.absFilePath()); if (resultList) resultList->append(rs); if (resultDict) resultDict->insert(fi.absFilePath(),rs); } if (killDict) killDict->insert(fi.absFilePath(),(void *)0x8); } } else if (fi.isDir()) // readable dir { totalSize+=readDir(&fi,fnList,fnDict,exclDict,patList, exclPatList,resultList,resultDict,errorIfNotExist, recursive,killDict); } } } } return totalSize; } //---------------------------------------------------------------------------- void readFormulaRepository() { QFile f(Config_getString("HTML_OUTPUT")+"/formula.repository"); if (f.open(IO_ReadOnly)) // open repository { msg("Reading formula repository...\n"); QTextStream t(&f); QCString line; while (!t.eof()) { line=t.readLine(); int se=line.find(':'); // find name and text separator. if (se==-1) { err("Warning: formula.repository is corrupted!\n"); break; } else { QCString formName = line.left(se); QCString formText = line.right(line.length()-se-1); Formula *f=new Formula(formText); Doxygen::formulaList.append(f); Doxygen::formulaDict.insert(formText,f); Doxygen::formulaNameDict.insert(formName,f); } } } } //---------------------------------------------------------------------------- static void expandAliases() { QDictIterator<QCString> adi(Doxygen::aliasDict); QCString *s; for (adi.toFirst();(s=adi.current());++adi) { *s = expandAlias(adi.currentKey(),*s); } } //---------------------------------------------------------------------------- static void escapeAliases() { QDictIterator<QCString> adi(Doxygen::aliasDict); QCString *s; for (adi.toFirst();(s=adi.current());++adi) { QCString value=*s,newValue; int in,p=0; // for each \n in the alias command value while ((in=value.find("\\n",p))!=-1) { newValue+=value.mid(p,in-p); // expand \n's except if \n is part of a built-in command. if (value.mid(in,5)!="\\note" && value.mid(in,5)!="\\name" && value.mid(in,10)!="\\namespace" && value.mid(in,14)!="\\nosubgrouping" ) { newValue+="\\_linebr "; } else { newValue+="\\n"; } p=in+2; } newValue+=value.mid(p,value.length()-p); *s=newValue; //printf("Alias %s has value %s\n",adi.currentKey().data(),s->data()); } } //---------------------------------------------------------------------------- void readAliases() { // add aliases to a dictionary Doxygen::aliasDict.setAutoDelete(TRUE); QStrList &aliasList = Config_getList("ALIASES"); const char *s=aliasList.first(); while (s) { if (Doxygen::aliasDict[s]==0) { QCString alias=s; int i=alias.find('='); if (i>0) { QCString name=alias.left(i).stripWhiteSpace(); QCString value=alias.right(alias.length()-i-1); //printf("Alias: found name=`%s' value=`%s'\n",name.data(),value.data()); if (!name.isEmpty()) { QCString *dn=Doxygen::aliasDict[name]; if (dn==0) // insert new alias { Doxygen::aliasDict.insert(name,new QCString(value)); } else // overwrite previous alias { *dn=value; } } } } s=aliasList.next(); } expandAliases(); escapeAliases(); } //---------------------------------------------------------------------------- static void dumpSymbol(QTextStream &t,Definition *d) { QCString anchor; if (d->definitionType()==Definition::TypeMember) { MemberDef *md = (MemberDef *)d; anchor=":"+md->anchor(); } QCString scope; if (d->getOuterScope() && d->getOuterScope()!=Doxygen::globalScope) { scope = d->getOuterScope()->getOutputFileBase()+Doxygen::htmlFileExtension; } t << "REPLACE INTO symbols (symbol_id,scope_id,name,file,line) VALUES('" << d->getOutputFileBase()+Doxygen::htmlFileExtension+anchor << "','" << scope << "','" << d->name() << "','" << d->getDefFileName() << "','" << d->getDefLine() << "');" << endl; } static void dumpSymbolMap() { QFile f("symbols.sql"); if (f.open(IO_WriteOnly)) { QTextStream t(&f); QDictIterator<DefinitionIntf> di(*Doxygen::symbolMap); DefinitionIntf *intf; for (;(intf=di.current());++di) { if (intf->definitionType()==DefinitionIntf::TypeSymbolList) // list of symbols { DefinitionListIterator dli(*(DefinitionList*)intf); Definition *d; // for each symbol for (dli.toFirst();(d=dli.current());++dli) { dumpSymbol(t,d); } } else // single symbol { Definition *d = (Definition *)intf; if (d!=Doxygen::globalScope) dumpSymbol(t,d); } } } } //---------------------------------------------------------------------------- // print the usage of doxygen static void usage(const char *name) { msg("Doxygen version %s\nCopyright Dimitri van Heesch 1997-2008\n\n",versionString); msg("You can use doxygen in a number of ways:\n\n"); msg("1) Use doxygen to generate a template configuration file:\n"); msg(" %s [-s] -g [configName]\n\n",name); msg(" If - is used for configName doxygen will write to standard output.\n\n"); msg("2) Use doxygen to update an old configuration file:\n"); msg(" %s [-s] -u [configName]\n\n",name); msg("3) Use doxygen to generate documentation using an existing "); msg("configuration file:\n"); msg(" %s [configName]\n\n",name); msg(" If - is used for configName doxygen will read from standard input.\n\n"); msg("4) Use doxygen to generate a template file controlling the layout of the\n"); msg(" generated documentation:\n"); msg(" %s -l layoutFileName.xml\n\n",name); msg("5) Use doxygen to generate a template style sheet file for RTF, HTML or Latex.\n"); msg(" RTF: %s -w rtf styleSheetFile\n",name); msg(" HTML: %s -w html headerFile footerFile styleSheetFile [configFile]\n",name); msg(" LaTeX: %s -w latex headerFile styleSheetFile [configFile]\n\n",name); msg("6) Use doxygen to generate an rtf extensions file\n"); msg(" RTF: %s -e rtf extensionsFile\n\n",name); msg("If -s is specified the comments in the config file will be omitted.\n"); msg("If configName is omitted `Doxyfile' will be used as a default.\n\n"); exit(1); } //---------------------------------------------------------------------------- // read the argument of option `c' from the comment argument list and // update the option index `optind'. static const char *getArg(int argc,char **argv,int &optind) { char *s=0; if (strlen(&argv[optind][2])>0) s=&argv[optind][2]; else if (optind+1<argc && argv[optind+1][0]!='-') s=argv[++optind]; return s; } //---------------------------------------------------------------------------- extern void commentScanTest(); void initDoxygen() { setlocale(LC_ALL,""); setlocale(LC_CTYPE,"C"); // to get isspace(0xA0)==0, needed for UTF-8 setlocale(LC_NUMERIC,"C"); //Doxygen::symbolMap->setAutoDelete(TRUE); Doxygen::runningTime.start(); initPreprocessor(); ParserInterface *defaultParser = new CLanguageScanner; Doxygen::parserManager = new ParserManager(defaultParser); Doxygen::parserManager->registerParser(".py", new PythonLanguageScanner); Doxygen::parserManager->registerParser(".f", new FortranLanguageScanner); Doxygen::parserManager->registerParser(".f90", new FortranLanguageScanner); Doxygen::parserManager->registerParser(".vhd", new VHDLLanguageScanner); // register any additional parsers here... initClassMemberIndices(); initNamespaceMemberIndices(); initFileMemberIndices(); } void cleanUpDoxygen() { delete Doxygen::inputNameDict; delete Doxygen::includeNameDict; delete Doxygen::exampleNameDict; delete Doxygen::imageNameDict; delete Doxygen::dotFileNameDict; delete Doxygen::mainPage; delete Doxygen::pageSDict; delete Doxygen::exampleSDict; delete Doxygen::globalScope; delete Doxygen::xrefLists; delete Doxygen::parserManager; cleanUpPreprocessor(); delete theTranslator; delete outputList; Mappers::freeMappers(); codeFreeScanner(); if (Doxygen::symbolMap) { // iterate through Doxygen::symbolMap and delete all // DefinitionList objects, since they have no owner QDictIterator<DefinitionIntf> dli(*Doxygen::symbolMap); DefinitionIntf *di; for (dli.toFirst();(di=dli.current());) { if (di->definitionType()==DefinitionIntf::TypeSymbolList) { DefinitionIntf *tmp = Doxygen::symbolMap->take(dli.currentKey()); delete (DefinitionList *)tmp; } else { ++dli; } } } delete Doxygen::inputNameList; delete Doxygen::memberNameSDict; delete Doxygen::functionNameSDict; delete Doxygen::groupSDict; delete Doxygen::classSDict; delete Doxygen::hiddenClasses; delete Doxygen::namespaceSDict; delete Doxygen::directories; //delete Doxygen::symbolMap; <- we cannot do this unless all static lists // (such as Doxygen::namespaceSDict) // with objects based on Definition are made // dynamic first } void readConfiguration(int argc, char **argv) { /************************************************************************** * Handle arguments * **************************************************************************/ int optind=1; const char *configName=0; const char *layoutName=0; const char *debugLabel; const char *formatName; bool genConfig=FALSE; bool shortList=FALSE; bool updateConfig=FALSE; bool genLayout=FALSE; while (optind<argc && argv[optind][0]=='-' && (isalpha(argv[optind][1]) || argv[optind][1]=='?' || argv[optind][1]=='-') ) { switch(argv[optind][1]) { case 'g': genConfig=TRUE; configName=getArg(argc,argv,optind); if (strcmp(argv[optind+1],"-")==0) { configName="-"; optind++; } if (!configName) { configName="Doxyfile"; } break; case 'l': genLayout=TRUE; layoutName=getArg(argc,argv,optind); if (!layoutName) { layoutName="DoxygenLayout.xml"; } break; case 'd': debugLabel=getArg(argc,argv,optind); Debug::setFlag(debugLabel); break; case 's': shortList=TRUE; break; case 'u': updateConfig=TRUE; break; case 'e': formatName=getArg(argc,argv,optind); if (!formatName) { err("Error:option -e is missing format specifier rtf.\n"); cleanUpDoxygen(); exit(1); } if (stricmp(formatName,"rtf")==0) { if (optind+1>=argc) { err("Error: option \"-e rtf\" is missing an extensions file name\n"); cleanUpDoxygen(); exit(1); } QFile f; if (openOutputFile(argv[optind+1],f)) { RTFGenerator::writeExtensionsFile(f); } cleanUpDoxygen(); exit(1); } err("Error: option \"-e\" has invalid format specifier.\n"); cleanUpDoxygen(); exit(1); break; case 'w': formatName=getArg(argc,argv,optind); if (!formatName) { err("Error: option -w is missing format specifier rtf, html or latex\n"); cleanUpDoxygen(); exit(1); } if (stricmp(formatName,"rtf")==0) { if (optind+1>=argc) { err("Error: option \"-w rtf\" is missing a style sheet file name\n"); cleanUpDoxygen(); exit(1); } QFile f; if (openOutputFile(argv[optind+1],f)) { RTFGenerator::writeStyleSheetFile(f); } cleanUpDoxygen(); exit(1); } else if (stricmp(formatName,"html")==0) { if (optind+4<argc) { if (!Config::instance()->parse(argv[optind+4])) { err("Error opening or reading configuration file %s!\n",argv[optind+4]); cleanUpDoxygen(); exit(1); } Config::instance()->substituteEnvironmentVars(); Config::instance()->convertStrToVal(); Config::instance()->check(); } else { Config::instance()->init(); } if (optind+3>=argc) { err("Error: option \"-w html\" does not have enough arguments\n"); cleanUpDoxygen(); exit(1); } QCString outputLanguage=Config_getEnum("OUTPUT_LANGUAGE"); if (!setTranslator(outputLanguage)) { err("Warning: Output language %s not supported! Using English instead.\n", outputLanguage.data()); } QFile f; if (openOutputFile(argv[optind+1],f)) { HtmlGenerator::writeHeaderFile(f); } f.close(); if (openOutputFile(argv[optind+2],f)) { HtmlGenerator::writeFooterFile(f); } f.close(); if (openOutputFile(argv[optind+3],f)) { HtmlGenerator::writeStyleSheetFile(f); } cleanUpDoxygen(); exit(0); } else if (stricmp(formatName,"latex")==0) { if (optind+3<argc) // use config file to get settings { if (!Config::instance()->parse(argv[optind+3])) { err("Error opening or reading configuration file %s!\n",argv[optind+3]); exit(1); } Config::instance()->substituteEnvironmentVars(); Config::instance()->convertStrToVal(); Config::instance()->check(); } else // use default config { Config::instance()->init(); } if (optind+2>=argc) { err("Error: option \"-w latex\" does not have enough arguments\n"); cleanUpDoxygen(); exit(1); } QCString outputLanguage=Config_getEnum("OUTPUT_LANGUAGE"); if (!setTranslator(outputLanguage)) { err("Warning: Output language %s not supported! Using English instead.\n", outputLanguage.data()); } QFile f; if (openOutputFile(argv[optind+1],f)) { LatexGenerator::writeHeaderFile(f); } f.close(); if (openOutputFile(argv[optind+2],f)) { LatexGenerator::writeStyleSheetFile(f); } cleanUpDoxygen(); exit(0); } else { err("Error: Illegal format specifier %s: should be one of rtf, html, or latex\n",formatName); cleanUpDoxygen(); exit(1); } break; case 'm': g_dumpSymbolMap = TRUE; break; case '-': if (strcmp(&argv[optind][2],"help")==0) { usage(argv[0]); } else if (strcmp(&argv[optind][2],"version")==0) { msg("%s\n",versionString); cleanUpDoxygen(); exit(0); } break; case 'b': setvbuf(stdout,NULL,_IONBF,0); Doxygen::outputToWizard=TRUE; break; case 'h': case '?': usage(argv[0]); break; default: err("Unknown option -%c\n",argv[optind][1]); usage(argv[0]); } optind++; } /************************************************************************** * Parse or generate the config file * **************************************************************************/ Config::instance()->init(); if (genConfig) { generateConfigFile(configName,shortList); cleanUpDoxygen(); exit(0); } if (genLayout) { writeDefaultLayoutFile(layoutName); cleanUpDoxygen(); exit(0); } QFileInfo configFileInfo1("Doxyfile"),configFileInfo2("doxyfile"); if (optind>=argc) { if (configFileInfo1.exists()) { configName="Doxyfile"; } else if (configFileInfo2.exists()) { configName="doxyfile"; } else { err("Doxyfile not found and no input file specified!\n"); usage(argv[0]); } } else { QFileInfo fi(argv[optind]); if (fi.exists() || strcmp(argv[optind],"-")==0) { configName=argv[optind]; } else { err("Error: configuration file %s not found!\n",argv[optind]); usage(argv[0]); } } if (!Config::instance()->parse(configName)) { err("Error: could not open or read configuration file %s!\n",configName); cleanUpDoxygen(); exit(1); } if (updateConfig) { generateConfigFile(configName,shortList,TRUE); cleanUpDoxygen(); exit(0); } /* Perlmod wants to know the path to the config file.*/ QFileInfo configFileInfo(configName); setPerlModDoxyfile(configFileInfo.absFilePath()); } void checkConfiguration() { Config::instance()->substituteEnvironmentVars(); Config::instance()->convertStrToVal(); Config::instance()->check(); initWarningFormat(); QCString outputLanguage=Config_getEnum("OUTPUT_LANGUAGE"); if (!setTranslator(outputLanguage)) { err("Warning: Output language %s not supported! Using English instead.\n", outputLanguage.data()); } QStrList &includePath = Config_getList("INCLUDE_PATH"); char *s=includePath.first(); while (s) { QFileInfo fi(s); addSearchDir(fi.absFilePath()); s=includePath.next(); } /* Set the global html file extension. */ Doxygen::htmlFileExtension = Config_getString("HTML_FILE_EXTENSION"); Doxygen::xrefLists->setAutoDelete(TRUE); Doxygen::parseSourcesNeeded = Config_getBool("CALL_GRAPH") || Config_getBool("CALLER_GRAPH") || Config_getBool("REFERENCES_RELATION") || Config_getBool("REFERENCED_BY_RELATION"); } #ifdef HAS_SIGNALS static void stopDoxygen(int) { QDir thisDir; msg("Cleaning up...\n"); if (!Doxygen::entryDBFileName.isEmpty()) { thisDir.remove(Doxygen::entryDBFileName); } if (!Doxygen::objDBFileName.isEmpty()) { thisDir.remove(Doxygen::objDBFileName); } exit(1); } #endif static void exitDoxygen() { if (!g_successfulRun) // premature exit { QDir thisDir; msg("Exiting...\n"); if (!Doxygen::entryDBFileName.isEmpty()) { thisDir.remove(Doxygen::entryDBFileName); } if (!Doxygen::objDBFileName.isEmpty()) { thisDir.remove(Doxygen::objDBFileName); } } } static QCString createOutputDirectory(const QCString &baseDirName, const char *formatDirOption, const char *defaultDirName) { // Note the & on the next line, we modify the formatDirOption! QCString &formatDirName = Config_getString(formatDirOption); if (formatDirName.isEmpty()) { formatDirName = baseDirName + defaultDirName; } else if (formatDirName[0]!='/' && (formatDirName.length()==1 || formatDirName[1]!=':')) { formatDirName.prepend(baseDirName+'/'); } QDir formatDir(formatDirName); if (!formatDir.exists() && !formatDir.mkdir(formatDirName)) { err("Could not create output directory %s\n", formatDirName.data()); cleanUpDoxygen(); exit(1); } return formatDirName; } static QCString getQchFileName() { QCString const & qchFile = Config_getString("QCH_FILE"); if (!qchFile.isEmpty()) { return qchFile; } QCString const & projectName = Config_getString("PROJECT_NAME"); QCString const & versionText = Config_getString("PROJECT_NUMBER"); return QCString("../qch/") + (projectName.isEmpty() ? QCString("index") : projectName) + (versionText.isEmpty() ? QCString("") : QCString("-") + versionText) + QCString(".qch"); } void parseInput() { atexit(exitDoxygen); /************************************************************************** * Make sure the output directory exists **************************************************************************/ QCString &outputDirectory = Config_getString("OUTPUT_DIRECTORY"); if (outputDirectory.isEmpty()) { outputDirectory=QDir::currentDirPath(); } else { QDir dir(outputDirectory); if (!dir.exists()) { dir.setPath(QDir::currentDirPath()); if (!dir.mkdir(outputDirectory)) { err("Error: tag OUTPUT_DIRECTORY: Output directory `%s' does not " "exist and cannot be created\n",outputDirectory.data()); cleanUpDoxygen(); exit(1); } else if (!Config_getBool("QUIET")) { err("Notice: Output directory `%s' does not exist. " "I have created it for you.\n", outputDirectory.data()); } dir.cd(outputDirectory); } outputDirectory=dir.absPath(); } /************************************************************************** * Initialize global lists and dictionaries **************************************************************************/ Doxygen::symbolMap = new QDict<DefinitionIntf>(1000); int cacheSize = Config_getInt("SYMBOL_CACHE_SIZE"); if (cacheSize<0) cacheSize=0; if (cacheSize>9) cacheSize=9; Doxygen::symbolCache = new ObjCache(16+cacheSize); // 16 -> room for 65536 elements, // ~2.0 MByte "overhead" Doxygen::symbolStorage = new Store; #ifdef HAS_SIGNALS signal(SIGINT, stopDoxygen); #endif uint pid = portable_pid(); Doxygen::objDBFileName.sprintf("doxygen_objdb_%d.tmp",pid); Doxygen::objDBFileName.prepend(outputDirectory+"/"); Doxygen::entryDBFileName.sprintf("doxygen_entrydb_%d.tmp",pid); Doxygen::entryDBFileName.prepend(outputDirectory+"/"); if (Doxygen::symbolStorage->open(Doxygen::objDBFileName)==-1) { err("Failed to open temporary file %s\n",Doxygen::objDBFileName.data()); exit(1); } Doxygen::inputNameList = new FileNameList; Doxygen::inputNameList->setAutoDelete(TRUE); Doxygen::memberNameSDict = new MemberNameSDict(10000); Doxygen::memberNameSDict->setAutoDelete(TRUE); Doxygen::functionNameSDict = new MemberNameSDict(10000); Doxygen::functionNameSDict->setAutoDelete(TRUE); Doxygen::groupSDict = new GroupSDict(17); Doxygen::groupSDict->setAutoDelete(TRUE); Doxygen::globalScope = new NamespaceDef("<globalScope>",1,"<globalScope>"); Doxygen::namespaceSDict = new NamespaceSDict(20); Doxygen::namespaceSDict->setAutoDelete(TRUE); Doxygen::classSDict = new ClassSDict(1009); Doxygen::classSDict->setAutoDelete(TRUE); Doxygen::hiddenClasses = new ClassSDict(257); Doxygen::hiddenClasses->setAutoDelete(TRUE); Doxygen::directories = new DirSDict(17); Doxygen::directories->setAutoDelete(TRUE); Doxygen::pageSDict = new PageSDict(1009); // all doc pages Doxygen::pageSDict->setAutoDelete(TRUE); Doxygen::exampleSDict = new PageSDict(1009); // all examples Doxygen::exampleSDict->setAutoDelete(TRUE); Doxygen::inputNameDict = new FileNameDict(10007); Doxygen::includeNameDict = new FileNameDict(10007); Doxygen::exampleNameDict = new FileNameDict(1009); Doxygen::exampleNameDict->setAutoDelete(TRUE); Doxygen::imageNameDict = new FileNameDict(257); Doxygen::dotFileNameDict = new FileNameDict(257); Doxygen::sectionDict.setAutoDelete(TRUE); Doxygen::memGrpInfoDict.setAutoDelete(TRUE); Doxygen::tagDestinationDict.setAutoDelete(TRUE); Doxygen::lookupCache.setAutoDelete(TRUE); Doxygen::dirRelations.setAutoDelete(TRUE); excludeNameDict.setAutoDelete(TRUE); /************************************************************************** * Initialize some global constants **************************************************************************/ int &tabSize = Config_getInt("TAB_SIZE"); spaces.resize(tabSize+1); int sp;for (sp=0;sp<tabSize;sp++) spaces.at(sp)=' '; spaces.at(tabSize)='\0'; compoundKeywordDict.insert("template class",(void *)8); compoundKeywordDict.insert("template struct",(void *)8); compoundKeywordDict.insert("class",(void *)8); compoundKeywordDict.insert("struct",(void *)8); compoundKeywordDict.insert("union",(void *)8); compoundKeywordDict.insert("interface",(void *)8); compoundKeywordDict.insert("exception",(void *)8); bool alwaysRecursive = Config_getBool("RECURSIVE"); /************************************************************************** * Check/create output directorties * **************************************************************************/ QCString htmlOutput; bool &generateHtml = Config_getBool("GENERATE_HTML"); if (generateHtml) htmlOutput = createOutputDirectory(outputDirectory,"HTML_OUTPUT","/html"); QCString xmlOutput; bool &generateXml = Config_getBool("GENERATE_XML"); if (generateXml) xmlOutput = createOutputDirectory(outputDirectory,"XML_OUTPUT","/xml"); QCString latexOutput; bool &generateLatex = Config_getBool("GENERATE_LATEX"); if (generateLatex) latexOutput = createOutputDirectory(outputDirectory,"LATEX_OUTPUT","/latex"); QCString rtfOutput; bool &generateRtf = Config_getBool("GENERATE_RTF"); if (generateRtf) rtfOutput = createOutputDirectory(outputDirectory,"RTF_OUTPUT","/rtf"); QCString manOutput; bool &generateMan = Config_getBool("GENERATE_MAN"); if (generateMan) manOutput = createOutputDirectory(outputDirectory,"MAN_OUTPUT","/man"); /************************************************************************** * Handle layout file * **************************************************************************/ LayoutDocManager::instance().init(); QCString layoutFileName = Config_getString("LAYOUT_FILE"); bool defaultLayoutUsed = FALSE; if (layoutFileName.isEmpty()) { layoutFileName = "DoxygenLayout.xml"; defaultLayoutUsed = TRUE; } QFile layoutFile(layoutFileName); if (layoutFile.open(IO_ReadOnly)) { msg("Parsing layout file %s...\n",layoutFileName.data()); QTextStream t(&layoutFile); LayoutDocManager::instance().parse(t); } else if (!defaultLayoutUsed) { err("Warning: failed to open layout file '%s' for reading!\n",layoutFileName.data()); } /************************************************************************** * Read and preprocess input * **************************************************************************/ QStrList &exclPatterns = Config_getList("EXCLUDE_PATTERNS"); // prevent search in the output directories if (generateHtml) exclPatterns.append(htmlOutput); if (generateXml) exclPatterns.append(xmlOutput); if (generateLatex) exclPatterns.append(latexOutput); if (generateRtf) exclPatterns.append(rtfOutput); if (generateMan) exclPatterns.append(manOutput); // gather names of all files in the include path msg("Searching for include files...\n"); QStrList &includePathList = Config_getList("INCLUDE_PATH"); char *s=includePathList.first(); while (s) { QStrList &pl = Config_getList("INCLUDE_FILE_PATTERNS"); if (pl.count()==0) { pl = Config_getList("FILE_PATTERNS"); } readFileOrDirectory(s,0,Doxygen::includeNameDict,0,&pl, &exclPatterns,0,0, alwaysRecursive); s=includePathList.next(); } msg("Searching for example files...\n"); QStrList &examplePathList = Config_getList("EXAMPLE_PATH"); s=examplePathList.first(); while (s) { readFileOrDirectory(s,0,Doxygen::exampleNameDict,0, &Config_getList("EXAMPLE_PATTERNS"), 0,0,0, (alwaysRecursive || Config_getBool("EXAMPLE_RECURSIVE"))); s=examplePathList.next(); } msg("Searching for images...\n"); QStrList &imagePathList=Config_getList("IMAGE_PATH"); s=imagePathList.first(); while (s) { readFileOrDirectory(s,0,Doxygen::imageNameDict,0,0, 0,0,0, alwaysRecursive); s=imagePathList.next(); } msg("Searching for dot files...\n"); QStrList &dotFileList=Config_getList("DOTFILE_DIRS"); s=dotFileList.first(); while (s) { readFileOrDirectory(s,0,Doxygen::dotFileNameDict,0,0, 0,0,0, alwaysRecursive); s=dotFileList.next(); } msg("Searching for files to exclude\n"); QStrList &excludeList = Config_getList("EXCLUDE"); s=excludeList.first(); while (s) { readFileOrDirectory(s,0,0,0,&Config_getList("FILE_PATTERNS"), 0,0,&excludeNameDict, alwaysRecursive, FALSE); s=excludeList.next(); } /************************************************************************** * Determine Input Files * **************************************************************************/ msg("Searching for files to process...\n"); QDict<void> *killDict = new QDict<void>(10007); int inputSize=0; QStrList &inputList=Config_getList("INPUT"); inputFiles.setAutoDelete(TRUE); s=inputList.first(); while (s) { QCString path=s; uint l = path.length(); // strip trailing slashes if (path.at(l-1)=='\\' || path.at(l-1)=='/') path=path.left(l-1); inputSize+=readFileOrDirectory( path, Doxygen::inputNameList, Doxygen::inputNameDict, &excludeNameDict, &Config_getList("FILE_PATTERNS"), &exclPatterns, &inputFiles,0, alwaysRecursive, TRUE, killDict); s=inputList.next(); } delete killDict; // add predefined macro name to a dictionary QStrList &expandAsDefinedList =Config_getList("EXPAND_AS_DEFINED"); s=expandAsDefinedList.first(); while (s) { if (Doxygen::expandAsDefinedDict[s]==0) { Doxygen::expandAsDefinedDict.insert(s,(void *)666); } s=expandAsDefinedList.next(); } // read aliases and store them in a dictionary readAliases(); // Notice: the order of the function calls below is very important! if (Config_getBool("GENERATE_HTML")) { readFormulaRepository(); } /************************************************************************** * Handle Tag Files * **************************************************************************/ g_storage = new FileStorage; g_storage->setName(Doxygen::entryDBFileName); if (!g_storage->open(IO_WriteOnly)) { err("Failed to create temporary storage file %s\n", Doxygen::entryDBFileName.data()); exit(1); } Entry *root=new Entry; EntryNav *rootNav = new EntryNav(0,root); rootNav->setEntry(root); msg("Reading and parsing tag files\n"); QStrList &tagFileList = Config_getList("TAGFILES"); s=tagFileList.first(); while (s) { readTagFile(root,s); root->createNavigationIndex(rootNav,g_storage,0); s=tagFileList.next(); } /************************************************************************** * Parse source files * **************************************************************************/ parseFiles(root,rootNav); g_storage->close(); if (!g_storage->open(IO_ReadOnly)) { err("Failed to open temporary storage file %s for reading", Doxygen::entryDBFileName.data()); exit(1); } //printNavTree(rootNav,0); // we are done with input scanning now, so free up the buffers used by flex // (can be around 4MB) preFreeScanner(); scanFreeScanner(); pyscanFreeScanner(); //delete rootNav; //g_storage.close(); //exit(1); /************************************************************************** * Gather information * **************************************************************************/ msg("Building group list...\n"); buildGroupList(rootNav); organizeSubGroups(rootNav); msg("Building directory list...\n"); buildDirectories(); findDirDocumentation(rootNav); if (Config_getBool("BUILTIN_STL_SUPPORT")) { addSTLClasses(rootNav); } msg("Building namespace list...\n"); buildNamespaceList(rootNav); findUsingDirectives(rootNav); msg("Building file list...\n"); buildFileList(rootNav); //generateFileTree(); msg("Searching for included using directives...\n"); findIncludedUsingDirectives(); msg("Building class list...\n"); buildClassList(rootNav); msg("Associating documentation with classes...\n"); buildClassDocList(rootNav); // build list of using declarations here (global list) buildListOfUsingDecls(rootNav); msg("Computing nesting relations for classes...\n"); resolveClassNestingRelations(); // calling buildClassList may result in cached relations that // become invalid after resolveClassNestingRelation(), that's why // we need to clear the cache here Doxygen::lookupCache.clear(); // we don't need the list of using declaration anymore g_usingDeclarations.clear(); msg("Searching for members imported via using declarations...\n"); findUsingDeclImports(rootNav); findUsingDeclarations(rootNav); msg("Building example list...\n"); buildExampleList(rootNav); msg("Searching for enumerations...\n"); findEnums(rootNav); // Since buildVarList calls isVarWithConstructor // and this calls getResolvedClass we need to process // typedefs first so the relations between classes via typedefs // are properly resolved. See bug 536385 for an example. msg("Searching for documented typedefs...\n"); buildTypedefList(rootNav); msg("Searching for documented variables...\n"); buildVarList(rootNav); msg("Building member list...\n"); // using class info only ! buildFunctionList(rootNav); msg("Searching for friends...\n"); findFriends(); msg("Searching for documented defines...\n"); findDefineDocumentation(rootNav); findClassEntries(rootNav); msg("Computing class inheritance relations...\n"); findInheritedTemplateInstances(); msg("Computing class usage relations...\n"); findUsedTemplateInstances(); msg("Flushing cached template relations that have become invalid...\n"); flushCachedTemplateRelations(); msg("Creating members for template instances...\n"); createTemplateInstanceMembers(); msg("Computing class relations...\n"); computeTemplateClassRelations(); flushUnresolvedRelations(); //if (Config_getBool("OPTIMIZE_OUTPUT_VHDL")) //{ // VhdlDocGen::computeVhdlComponentRelations(classEntries,g_storage); //} //else //{ computeClassRelations(); //} classEntries.clear(); msg("Add enum values to enums...\n"); addEnumValuesToEnums(rootNav); findEnumDocumentation(rootNav); msg("Searching for member function documentation...\n"); findObjCMethodDefinitions(rootNav); findMemberDocumentation(rootNav); // may introduce new members ! transferRelatedFunctionDocumentation(); transferFunctionDocumentation(); msg("Building page list...\n"); buildPageList(rootNav); msg("Search for main page...\n"); findMainPage(rootNav); msg("Computing page relations...\n"); computePageRelations(rootNav); checkPageRelations(); msg("Determining the scope of groups...\n"); findGroupScope(rootNav); msg("Sorting lists...\n"); Doxygen::memberNameSDict->sort(); Doxygen::functionNameSDict->sort(); Doxygen::hiddenClasses->sort(); Doxygen::classSDict->sort(); msg("Freeing entry tree\n"); delete rootNav; g_storage->close(); delete g_storage; g_storage=0; QDir thisDir; thisDir.remove(Doxygen::entryDBFileName); msg("Determining which enums are documented\n"); findDocumentedEnumValues(); msg("Computing member relations...\n"); computeMemberRelations(); msg("Building full member lists recursively...\n"); buildCompleteMemberLists(); msg("Adding members to member groups.\n"); addMembersToMemberGroup(); if (Config_getBool("DISTRIBUTE_GROUP_DOC")) { msg("Distributing member group documentation.\n"); distributeMemberGroupDocumentation(); } msg("Computing member references...\n"); computeMemberReferences(); if (Config_getBool("INHERIT_DOCS")) { msg("Inheriting documentation...\n"); inheritDocumentation(); } // compute the shortest possible names of all files // without loosing the uniqueness of the file names. msg("Generating disk names...\n"); Doxygen::inputNameList->generateDiskNames(); msg("Adding source references...\n"); addSourceReferences(); msg("Adding todo/test/bug list items...\n"); addListReferences(); if (Config_getBool("SHOW_DIRECTORIES") && Config_getBool("DIRECTORY_GRAPH")) { msg("Computing dependencies between directories...\n"); computeDirDependencies(); } msg("Counting data structures...\n"); countDataStructures(); msg("Resolving user defined references...\n"); resolveUserReferences(); msg("Finding anchors and sections in the documentation...\n"); findSectionsInDocumentation(); transferFunctionReferences(); msg("Combining using relations...\n"); combineUsingRelations(); msg("Adding members to index pages...\n"); addMembersToIndex(); } void generateOutput() { /************************************************************************** * Initialize output generators * **************************************************************************/ //// dump all symbols //SDict<DefinitionList>::Iterator sdi(Doxygen::symbolMap); //DefinitionList *dl; //for (sdi.toFirst();(dl=sdi.current());++sdi) //{ // DefinitionListIterator dli(*dl); // Definition *d; // printf("Symbol: "); // for (dli.toFirst();(d=dli.current());++dli) // { // printf("%s ",d->qualifiedName().data()); // } // printf("\n"); //} if (g_dumpSymbolMap) { dumpSymbolMap(); exit(0); } initDocParser(); outputList = new OutputList(TRUE); if (Config_getBool("GENERATE_HTML")) { outputList->add(new HtmlGenerator); HtmlGenerator::init(); if (Config_getBool("GENERATE_HTMLHELP")) Doxygen::indexList.addIndex(new HtmlHelp); if (Config_getBool("GENERATE_QHP")) Doxygen::indexList.addIndex(new Qhp); #if 0 if (Config_getBool("GENERATE_INDEXLOG")) Doxygen::indexList.addIndex(new IndexLog); #endif if (usingTreeIndex()) Doxygen::indexList.addIndex(new FTVHelp); if (Config_getBool("GENERATE_DOCSET")) Doxygen::indexList.addIndex(new DocSets); Doxygen::indexList.initialize(); Doxygen::indexList.addImageFile("tab_r.gif"); Doxygen::indexList.addImageFile("tab_l.gif"); Doxygen::indexList.addImageFile("tab_b.gif"); Doxygen::indexList.addStyleSheetFile("tabs.css"); Doxygen::indexList.addImageFile("doxygen.png"); if (Config_getBool("HTML_DYNAMIC_SECTIONS")) HtmlGenerator::generateSectionImages(); copyStyleSheet(); } if (Config_getBool("GENERATE_LATEX")) { outputList->add(new LatexGenerator); LatexGenerator::init(); } if (Config_getBool("GENERATE_MAN")) { outputList->add(new ManGenerator); ManGenerator::init(); } if (Config_getBool("GENERATE_RTF")) { outputList->add(new RTFGenerator); RTFGenerator::init(); } if (Config_getBool("USE_HTAGS")) { Htags::useHtags = TRUE; QCString htmldir = Config_getString("HTML_OUTPUT"); if (!Htags::execute(htmldir)) err("Error: USE_HTAGS is YES but htags(1) failed. \n"); if (!Htags::loadFilemap(htmldir)) err("Error: htags(1) ended normally but failed to load the filemap. \n"); } /************************************************************************** * Generate documentation * **************************************************************************/ QFile *tag=0; QCString &generateTagFile = Config_getString("GENERATE_TAGFILE"); if (!generateTagFile.isEmpty()) { tag=new QFile(generateTagFile); if (!tag->open(IO_WriteOnly)) { err("Error: cannot open tag file %s for writing\n", generateTagFile.data() ); cleanUpDoxygen(); exit(1); } Doxygen::tagFile.setDevice(tag); Doxygen::tagFile.setEncoding(QTextStream::UnicodeUTF8); Doxygen::tagFile << "<?xml version='1.0' encoding='ISO-8859-1' standalone='yes' ?>" << endl; Doxygen::tagFile << "<tagfile>" << endl; } if (Config_getBool("GENERATE_HTML")) writeDoxFont(Config_getString("HTML_OUTPUT")); if (Config_getBool("GENERATE_LATEX")) writeDoxFont(Config_getString("LATEX_OUTPUT")); if (Config_getBool("GENERATE_RTF")) writeDoxFont(Config_getString("RTF_OUTPUT")); msg("Generating style sheet...\n"); //printf("writing style info\n"); QCString genString = theTranslator->trGeneratedAt(dateToString(TRUE),Config_getString("PROJECT_NAME")); outputList->writeStyleInfo(0); // write first part outputList->disableAllBut(OutputGenerator::Latex); outputList->parseText(genString); outputList->writeStyleInfo(1); // write second part //parseText(*outputList,theTranslator->trWrittenBy()); outputList->writeStyleInfo(2); // write third part outputList->parseText(genString); outputList->writeStyleInfo(3); // write fourth part //parseText(*outputList,theTranslator->trWrittenBy()); outputList->writeStyleInfo(4); // write last part outputList->enableAll(); //statistics(); // count the number of documented elements in the lists we have built. // If the result is 0 we do not generate the lists and omit the // corresponding links in the index. msg("Generating index page...\n"); writeIndex(*outputList); msg("Generating page index...\n"); writePageIndex(*outputList); msg("Generating example documentation...\n"); generateExampleDocs(); msg("Generating file sources...\n"); if (!Htags::useHtags) { generateFileSources(); } msg("Generating file documentation...\n"); generateFileDocs(); msg("Generating page documentation...\n"); generatePageDocs(); msg("Generating group documentation...\n"); generateGroupDocs(); msg("Generating group index...\n"); writeGroupIndex(*outputList); msg("Generating class documentation...\n"); generateClassDocs(); if (Config_getBool("HAVE_DOT") && Config_getBool("GRAPHICAL_HIERARCHY")) { msg("Generating graphical class hierarchy...\n"); writeGraphicalClassHierarchy(*outputList); } msg("Generating namespace index...\n"); generateNamespaceDocs(); msg("Generating namespace member index...\n"); writeNamespaceMemberIndex(*outputList); if (Config_getBool("GENERATE_LEGEND")) { msg("Generating graph info page...\n"); writeGraphInfo(*outputList); } if (Config_getBool("SHOW_DIRECTORIES")) { msg("Generating directory documentation...\n"); generateDirDocs(*outputList); } msg("Generating file index...\n"); writeFileIndex(*outputList); if (Config_getBool("SHOW_DIRECTORIES")) { msg("Generating directory index...\n"); writeDirIndex(*outputList); } msg("Generating example index...\n"); writeExampleIndex(*outputList); msg("Generating file member index...\n"); writeFileMemberIndex(*outputList); //writeDirDependencyGraph(Config_getString("HTML_OUTPUT")); if (Config_getBool("GENERATE_RTF")) { msg("Combining RTF output...\n"); if (!RTFGenerator::preProcessFileInplace(Config_getString("RTF_OUTPUT"),"refman.rtf")) { err("An error occurred during post-processing the RTF files!\n"); } } if (Doxygen::formulaList.count()>0 && Config_getBool("GENERATE_HTML")) { msg("Generating bitmaps for formulas in HTML...\n"); Doxygen::formulaList.generateBitmaps(Config_getString("HTML_OUTPUT")); } //if (Config_getBool("GENERATE_HTML") && Config_getBool("GENERATE_HTMLHELP")) //{ // HtmlHelp::getInstance()->finalize(); //} //if (Config_getBool("GENERATE_HTML") && Config_getBool("GENERATE_TREEVIEW")) //{ // FTVHelp::getInstance()->finalize(); //} Doxygen::indexList.finalize(); if (!Config_getString("GENERATE_TAGFILE").isEmpty()) { Doxygen::tagFile << "</tagfile>" << endl; delete tag; } if (Config_getBool("GENERATE_HTML") && Config_getBool("DOT_CLEANUP")) removeDoxFont(Config_getString("HTML_OUTPUT")); if (Config_getBool("GENERATE_RTF") && Config_getBool("DOT_CLEANUP")) removeDoxFont(Config_getString("RTF_OUTPUT")); if (Config_getBool("GENERATE_XML")) { msg("Generating XML output...\n"); generateXML(); } if (Config_getBool("GENERATE_AUTOGEN_DEF")) { msg("Generating AutoGen DEF output...\n"); generateDEF(); } if (Config_getBool("GENERATE_PERLMOD")) { msg("Generating Perl module output...\n"); generatePerlMod(); } if (Config_getBool("GENERATE_HTML") && Config_getBool("GENERATE_HTMLHELP") && !Config_getString("HHC_LOCATION").isEmpty()) { msg("Running html help compiler...\n"); QString oldDir = QDir::currentDirPath(); QDir::setCurrent(Config_getString("HTML_OUTPUT")); if (portable_system(Config_getString("HHC_LOCATION"), "index.hhp", FALSE)) { err("Error: failed to run html help compiler on index.hhp\n"); } QDir::setCurrent(oldDir); } #if 0 if ( Config_getBool("GENERATE_HTMLHELP") && !Config_getString("DOXYGEN2QTHELP_LOC").isEmpty() && !Config_getString("QTHELP_CONFIG").isEmpty()) { msg("Running doxygen2qthelp...\n"); const QCString qtHelpFile = Config_getString("QTHELP_FILE"); const QCString args = QCString().sprintf("--config=%s index.hhp%s%s", Config_getString("QTHELP_CONFIG").data(), (qtHelpFile.isEmpty() ? "" : " "), (qtHelpFile.isEmpty() ? "" : qtHelpFile.data())); const QString oldDir = QDir::currentDirPath(); QDir::setCurrent(Config_getString("HTML_OUTPUT")); if (portable_system(Config_getString("DOXYGEN2QTHELP_LOC"), args.data(), FALSE)) { err("Error: failed to run doxygen2qthelp on index.hhp\n"); } QDir::setCurrent(oldDir); } #endif if ( Config_getBool("GENERATE_HTML") && Config_getBool("GENERATE_QHP") && !Config_getString("QHG_LOCATION").isEmpty()) { msg("Running qhelpgenerator...\n"); QCString const qhpFileName = Qhp::getQhpFileName(); QCString const qchFileName = getQchFileName(); QCString const args = QCString().sprintf("%s -o %s", qhpFileName.data(), qchFileName.data()); QString const oldDir = QDir::currentDirPath(); QDir::setCurrent(Config_getString("HTML_OUTPUT")); if (portable_system(Config_getString("QHG_LOCATION"), args.data(), FALSE)) { err("Error: failed to run qhelpgenerator on index.qhp\n"); } QDir::setCurrent(oldDir); } if (Config_getBool("SEARCHENGINE")) { msg("Generating search index\n"); HtmlGenerator::writeSearchPage(); Doxygen::searchIndex->write(Config_getString("HTML_OUTPUT")+"/search.idx"); } if (Debug::isFlagSet(Debug::Time)) { msg("Total elapsed time: %.3f seconds\n(of which %.3f seconds waiting for external tools to finish)\n", ((double)Doxygen::runningTime.elapsed())/1000.0, Doxygen::sysElapsedTime ); } /************************************************************************** * Start cleaning up * **************************************************************************/ //Doxygen::symbolCache->printStats(); //Doxygen::symbolStorage->printStats(); cleanUpDoxygen(); finializeDocParser(); Doxygen::symbolStorage->close(); QDir thisDir; thisDir.remove(Doxygen::objDBFileName); Config::deleteInstance(); QTextCodec::deleteAllCodecs(); delete Doxygen::symbolCache; delete Doxygen::symbolMap; delete Doxygen::symbolStorage; g_successfulRun=TRUE; }