1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
|
/***************************************************************************
cppcodecompletion.cpp - description
-------------------
begin : Sat Jul 21 2001
copyright : (C) 2001 by Victor R�er
email : [email protected]
copyright : (C) 2002,2003 by Roberto Raggi
email : [email protected]
copyright : (C) 2005 by Adam Treat
email : [email protected]
copyright : (C) 2006,2007 by David Nolden
email : [email protected]
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "cppcodecompletion.h"
#include "cppcodecompletionconfig.h"
#include "backgroundparser.h"
#include "ast.h"
#include "ast_utils.h"
#include "codeinformationrepository.h"
#include "parser.h"
#include "lexer.h"
#include "tree_parser.h"
#include "cpp_tags.h"
#include "cppsupport_utils.h"
#include "tag_creator.h"
#include <typeinfo>
#include <tqpopupmenu.h>
#include <kapplication.h>
#include <kdebug.h>
#include <klocale.h>
#include <kmainwindow.h>
#include <kmessagebox.h>
#include <kparts/part.h>
#include <kstatusbar.h>
#include <ktexteditor/document.h>
#include <kaction.h>
#include <tqdatastream.h>
#include <tqfile.h>
#include <tqmap.h>
#include <tqregexp.h>
#include <tqstatusbar.h>
#include <tqstring.h>
#include <tqstringlist.h>
#include <tqpair.h>
#include <tqvaluestack.h>
#include <kdevpartcontroller.h>
#include <kdevmainwindow.h>
#include <kdevproject.h>
#include <kdevcoderepository.h>
#include <codemodel_utils.h>
#include <codemodel.h>
#include <codebrowserfrontend.h>
#include "codecompletionentry.h"
#include "typedesc.h"
#include "computerecoverypoints.h"
#include "completiondebug.h"
#include "bithelpers.h"
#include "stringhelpers.h"
#include "simpletype.h"
#include "simpletypecachebinder.h"
#include "safetycounter.h"
#include "cppevaluation.h"
#include "simplecontext.h"
#include "simpletypefunction.h"
//#define DISABLE_TRACING
CppCodeCompletion* CppCodeCompletion::m_instance = 0;
const bool disableVerboseForCompletionList = false;
const bool disableVerboseForContextMenu = false;
const bool contextMenuEntriesAtTop = false;
bool showNamespaceAppearances = true;
const char* constructorPrefix = "<constructor>";
const char* destructorPrefix = "<destructor>";
///This enables-disables the automatic processing of the expression under the mouse-cursor
//#define DISABLETOOLTIPS
/**
-- TODO: Does not yet correctly search for overloaded functions and select the right one
-- TODO: The documentation shown in the calltips looks very bad, a better solution must be found(maybe an additional tooltip)
*/
void statusBarText( const TQString& str, int time ) {
CppCodeCompletion* c = CppCodeCompletion::instance();
if( c )
c->addStatusText( str, time );
}
TypePointer CppCodeCompletion::createGlobalNamespace() {
KSharedPtr<SimpleTypeCachedNamespace> n = new SimpleTypeCachedNamespace( TQStringList(), TQStringList() );
n->addAliases(m_pSupport->codeCompletionConfig()->namespaceAliases() );
return n.data();
}
template <class Item>
class ItemLocker {
public:
ItemLocker( Item& it ) : item( it ) {
it.lock();
}
~ItemLocker() {
item.unlock();
}
private:
Item& item;
};
ParsedFilePointer getParsedFile( CodeModelItem* i ) {
if( !i || !i->file() || !i->file()->parseResult() ) return 0;
return dynamic_cast<ParsedFile*>( i->file()->parseResult().data());
}
SafetyCounter safetyCounter;
CppCodeCompletion* cppCompletionInstance = 0;
//file global functions, must be before any "using namespace"
TQString cleanForMenu( TQString txt ) {
return txt.tqreplace( "&", "&&" ).tqreplace( " ", " " );
}
TQString buildSignature( TypePointer currType ) {
SimpleTypeFunctionInterface * f = currType->asFunction();
if ( !f )
return "";
TQString ret;
LocateResult rtt = currType->locateDecType( f->getReturnType() );
if ( rtt->resolved() || rtt.resolutionCount() > 1 )
ret = rtt->fullNameChain();
else
ret = f->getReturnType().fullNameChain();
TypeDesc desc = currType->desc();
desc.decreaseFunctionDepth();
TQString sig = ret + " " + desc.fullNameChain() + f->signature();
if ( f->isConst() )
sig += " const";
return sig;
}
uint PopupTracker::pendingPopups = 0;
PopupTracker* PopupTracker::pt = 0;
/** Multiple empty lines are reduced to one, too long lines wrapped over, and the beginnings of the lines are normalized
*/
TQStringList maximumLength( const TQStringList& in, int length ) {
TQStringList ret;
uint firstNonSpace = 50000;
for ( TQStringList::const_iterator it = in.begin(); it != in.end(); ++it )
for ( uint a = 0; a < ( *it ).length(); a++ )
if ( !( *it ) [ a ].isSpace() ) {
if ( firstNonSpace > a )
firstNonSpace = a;
break;
}
if ( firstNonSpace == 50000 )
return TQStringList();
bool hadEmptyLine = false;
for ( TQStringList::const_iterator it = in.begin(); it != in.end(); ++it ) {
if ( ( *it ).length() <= firstNonSpace ) {
if ( !hadEmptyLine )
ret << " ";
hadEmptyLine = true;
} else {
hadEmptyLine = false;
TQString str = ( *it ).mid( firstNonSpace );
while ( !str.isEmpty() ) {
if ( (int)str.length() < length ) {
ret << str;
break;
} else {
ret << str.left( length ) + "\\";
str = str.mid( length );
}
}
}
}
return ret;
}
TQStringList prepareTextForMenu( const TQString& comment, int maxLines, int maxLength ) {
TQStringList in = TQStringList::split( "\n", comment );
TQStringList out;
for ( TQStringList::iterator it = in.begin(); it != in.end(); ++it ) {
out << cleanForMenu( *it );
if ( (int)out.count() >= maxLines ) {
out << "[...]";
break;
}
}
return maximumLength( out, maxLength );
}
TQStringList formatComment( const TQString& comment, int maxCols = 120 ) {
TQStringList ret;
SafetyCounter s( 14 ); ///maximum of 14 lines
TQStringList lines = TQStringList::split( "\n", comment );
for ( TQStringList::iterator it = lines.begin(); it != lines.end(); ++it ) {
TQStringList words = TQStringList::split( " ", *it );
while ( !words.isEmpty() && s ) {
TQString line = "? ";
int len = 0;
while ( !words.isEmpty() && len < maxCols ) {
len += words.front().length();
line += words.front() + " ";
words.pop_front();
}
ret << line;
}
}
if ( !s )
ret << "? comment has too many lines";
return ret;
}
bool operator < ( const CodeCompletionEntry& e1, const CodeCompletionEntry& e2 ) {
return e1.text < e2.text;
}
template <class ItemType>
static TQValueList<ItemType> unique( const TQValueList<ItemType>& entryList ) {
TQValueList< ItemType > l;
TQMap<TQString, bool> map;
typename TQValueList< ItemType >::ConstIterator it = entryList.begin();
while ( it != entryList.end() ) {
CodeCompletionEntry e = *it++;
TQString key = ( e.type + " " +
e.prefix + " " +
e.text + " " +
e.postfix + " " ).simplifyWhiteSpace().stripWhiteSpace();
if ( map.tqfind( key ) == map.end() ) {
map[ key ] = TRUE;
l << e;
}
}
return l;
}
static TQStringList unique( const TQStringList& entryList ) {
TQStringList l;
TQMap<TQString, bool> map;
TQStringList::ConstIterator it = entryList.begin();
while ( it != entryList.end() ) {
TQString e = *it++;
if ( map.tqfind( e ) == map.end() ) {
map[ e ] = TRUE;
l << e;
}
}
return l;
}
static TQStringList unique( const TQValueList<TQStringList>& entryList ) {
TQStringList l;
TQMap<TQString, bool> map;
TQValueList<TQStringList>::ConstIterator it = entryList.begin();
while ( it != entryList.end() ) {
TQStringList li = ( *it++ );
TQString e = li.join( "\n" );
if ( map.tqfind( e ) == map.end() ) {
map[ e ] = TRUE;
l += li;
}
}
return l;
}
bool tokenAt( const TQString& text, const TQString& token, int textPos ) {
if ( text.isEmpty() )
return false;
int tokenPos = token.length() - 1;
if ( tokenPos <= 0 || textPos <= 0 )
return false;
while ( text[ textPos ] == token[ tokenPos ] ) {
--tokenPos;
--textPos;
if ( tokenPos == 0 || textPos == 0 ) {
if ( tokenPos == 0 ) {
if ( textPos >= 1 && text[ textPos ] == token[ tokenPos ] ) {
TQChar c = text[ textPos - 1 ];
return c.isSpace() || c == '{' || c == '}' || c == ';';
} else {
return false;
}
} else {
return false;
}
}
}
return false;
}
CppSupportPart* CppCodeCompletion::cppSupport() const {
return m_pSupport;
}
using namespace CompletionDebug;
using namespace StringHelpers;
using namespace BitHelpers;
using namespace CppEvaluation;
struct PopupFillerHelpStruct {
CppCodeCompletion* receiver;
FileList files;
CppCodeCompletion::PopupActions& m_popupActions;
PopupFillerHelpStruct( CppCodeCompletion* rec ) : m_popupActions( rec->m_popupActions ) {
receiver = rec;
files = receiver->cppSupport()->codeModel()->fileList();
}
bool shouldShowIncludeMenu() const {
return true;
}
TQMap<TQString, TQPopupMenu*> m_namespacePopupCache;
void insertItem( TQPopupMenu* tqparent, SimpleTypeImpl::MemberInfo d , TQString prefix ) {
Q_UNUSED(prefix);
TQString memType = d.memberTypeToString();
if ( d.memberType == SimpleTypeImpl::MemberInfo::Typedef && d.type->fullName() == "const int" )
memType = "enum";
TQString txt = i18n( "Jump to %1 %2" ).tqarg( memType ).tqarg( cleanForMenu( d.name ) );
int id = tqparent->insertItem( txt, receiver, TQT_SLOT( popupAction( int ) ) );
receiver->m_popupActions.insert( id, d.decl );
}
void insertItem ( TQPopupMenu* tqparent, TypeDesc d , TQString prefix ) {
Debug dbg( "#insert# ", 10 );
TQString txt1, txt2;
if ( d.resolved() && d.resolved() ->isNamespace() ) {
SimpleTypeCachedNamespace * ns = dynamic_cast<SimpleTypeCachedNamespace*>( d.resolved().data() );
if ( ns ) {
SimpleTypeNamespace::SlaveList slaves = ns->getSlaves( receiver->getIncludeFiles() );
for ( SimpleTypeNamespace::SlaveList::iterator it = slaves.begin(); it != slaves.end(); ++it ) {
SimpleTypeCodeModel* cm = dynamic_cast<SimpleTypeCodeModel*>( ( *it ).first.first.resolved().data() );
if ( cm && cm->item() ) {
TQPopupMenu * m = PopupTracker::createPopup( tqparent );
TQString scope = cm->scope().join("::");
TQMap< TQString, TQPopupMenu* >::iterator it = m_namespacePopupCache.tqfind( scope );
if( it != m_namespacePopupCache.end() ) {
tqparent->insertItem( "Imported Namespace " + scope, *it );
delete m;
} else {
tqparent->insertItem( "Imported Namespace " + scope, m );
insertItem( m, ( new SimpleTypeCachedCodeModel( cm->item() ) ) ->desc(), prefix );
m_namespacePopupCache.insert( scope, m );
}
} else {
SimpleTypeNamespace* cn = dynamic_cast<SimpleTypeNamespace*>( ( *it ).first.first.resolved().data() );
if( cn ) {
TypePointer t = new SimpleTypeNamespace( cn ); //To avoid endless recursion, this needs to be done(the dynamic-cast above fails)
insertItem( tqparent, t->desc(), prefix );
}
}
}
return ;
}
}
if ( d.resolved() && receiver->cppSupport() ->codeCompletionConfig() ->showNamespaceAppearances() ) {
if ( SimpleTypeCachedCodeModel * item = dynamic_cast<SimpleTypeCachedCodeModel*>( d.resolved().data() ) ) { ///(1)
if ( item->item() && item->item() ->isNamespace() ) {
NamespaceModel* ns = dynamic_cast<NamespaceModel*>( item->item().data() );
TQStringList wholeScope = ns->scope();
wholeScope << ns->name();
for( FileList::iterator it = files.begin(); it != files.end(); ++it ) {
// if( !safetyCounter ) break;
NamespaceModel* ns = (*it).data();
for( TQStringList::iterator it2 = wholeScope.begin(); it2 != wholeScope.end(); ++it2 ) {
if( ns->hasNamespace( (*it2) ) ) {
ns = ns->namespaceByName( *it2 );
if( !ns ) break;
} else {
ns = 0;
break;
}
}
if( ns ) {
ItemDom i(ns);
int sLine, sCol, eLine, eCol;
i->getStartPosition( &sLine, &sCol );
i->getEndPosition( &eLine, &eCol );
insertItem( tqparent, (new SimpleTypeCodeModel( i ))->desc(), prefix + " " + (*it)->name() + TQString(" (%1 Lines): ").tqarg( eLine - sLine ) ); ///SimpleTypeCodeModel is used instead of SimpleTypeCachedNodeModel, so the detection at (1) does not trigger, this avoids endless recursion.
}
}
return;
}
}
}
if ( d.resolved() ) {
if ( d.resolved() ->asFunction() ) {
txt1 = prefix + i18n( "Jump to declaration of %1(...)" ).tqarg( d.resolved() ->scope().join( "::" ) );
txt2 = prefix + i18n( "Jump to definition of %1(...)" ).tqarg( d.resolved() ->scope().join( "::" ) );
} else {
txt1 = prefix + i18n( "Jump to %1" ).tqarg( cleanForMenu( d.resolved() ->scope().join( "::" ) ) );
}
} else {
if( !BuiltinTypes::isBuiltin( d ) ) {
txt1 = prefix + d.name() + i18n( " is unresolved" );
} else {
txt1 = prefix + d.name() + i18n( " (builtin " ) + BuiltinTypes::comment( d ) + ")";
}
}
int id = tqparent->insertItem( txt1, receiver, TQT_SLOT( popupAction( int ) ) );
if ( d.resolved() )
receiver->m_popupActions.insert( id, d.resolved() ->getDeclarationInfo() );
if ( !txt2.isEmpty() ) {
int id2 = tqparent->insertItem( txt2, receiver, TQT_SLOT( popupDefinitionAction( int ) ) );
if ( d.resolved() )
receiver->m_popupDefinitionActions.insert( id2, d.resolved() ->getDeclarationInfo() );
}
}
};
ItemDom itemFromScope( const TQStringList& scope, NamespaceDom startNamespace ) {
if ( scope.isEmpty() )
return ItemDom();
NamespaceDom glob = startNamespace;
if ( !glob )
return ItemDom();
ClassModel* curr = glob ;
TQStringList::const_iterator mit = scope.begin();
while ( curr->isNamespace() && mit != scope.end() && ( ( NamespaceModel* ) curr ) ->hasNamespace( *mit ) ) {
curr = &( *( ( ( NamespaceModel* ) curr ) ->namespaceByName( *mit ) ) );
++mit;
}
while ( ( curr->isNamespace() || curr->isClass() ) && mit != scope.end() && curr->hasClass( *mit ) ) {
ClassList cl = curr->classByName( *mit );
curr = &( **cl.begin() );
++mit;
}
if ( mit != --scope.end() )
return ItemDom();
TypeAliasList l = curr->typeAliasByName( *mit );
if ( !l.isEmpty() )
return model_cast<ItemDom>( l.front() );
VariableDom v = curr->variableByName( *mit );
if ( v )
return model_cast<ItemDom>( v );
ClassList c = curr->classByName( *mit );
if ( !c.isEmpty() )
return model_cast<ItemDom>( c.front() );
EnumDom en = curr->enumByName( *mit );
if ( en )
return model_cast<ItemDom>( en );
FunctionList f = curr->functionByName( *mit );
if ( !f.isEmpty() )
return model_cast<ItemDom>( f.front() );
FunctionDefinitionList fd = curr->functionDefinitionByName( *mit );
if ( !fd.isEmpty() )
return model_cast<ItemDom>( fd.front() );
return ItemDom();
}
struct PopupClassViewFillerHelpStruct {
CppCodeCompletion* receiver;
CppCodeCompletion::PopupActions& m_popupActions;
PopupClassViewFillerHelpStruct( CppCodeCompletion* rec ) : m_popupActions( rec->m_popupActions ) {
receiver = rec;
}
bool shouldShowIncludeMenu() const {
return false;
}
void insertItem( TQPopupMenu* tqparent, SimpleTypeImpl::MemberInfo d , TQString prefix ) {
Q_UNUSED(prefix);
FileDom f = receiver->m_pSupport->codeModel() ->fileByName( d.decl.file );
if ( !f )
return ;
ItemDom dom = itemFromScope( TQStringList::split( "::", d.name ), model_cast<NamespaceDom>( f ) );
TQString memType = d.memberTypeToString();
if ( d.memberType == SimpleTypeImpl::MemberInfo::Typedef && d.type->fullName() == "const int" )
memType = "enum";
TQString txt = i18n( "Show %1 %2" ).tqarg( memType ).tqarg( cleanForMenu( d.name ) );
int id = tqparent->insertItem( txt, receiver, TQT_SLOT( popupClassViewAction( int ) ) );
receiver->m_popupClassViewActions.insert( id, dom );
}
void insertItem ( TQPopupMenu* tqparent, TypeDesc d , TQString prefix ) {
Debug dbg( "#insert# ", 10 );
TQString txt;
if ( !d.resolved() )
return ;
ItemDom dom;
if ( d.resolved() ) {
SimpleTypeCodeModel * cm = dynamic_cast<SimpleTypeCodeModel*>( d.resolved().data() );
if ( cm )
dom = cm->item();
}
if ( d.resolved() ) {
if ( !dom && d.resolved() ->isNamespace() ) {
SimpleTypeCachedNamespace * ns = dynamic_cast<SimpleTypeCachedNamespace*>( d.resolved().data() );
if ( ns ) {
SimpleTypeNamespace::SlaveList slaves = ns->getSlaves( receiver->getIncludeFiles() );
for ( SimpleTypeNamespace::SlaveList::iterator it = slaves.begin(); it != slaves.end(); ++it ) {
SimpleTypeCodeModel* cm = dynamic_cast<SimpleTypeCodeModel*>( ( *it ).first.first.resolved().data() );
if ( cm && cm->item() ) {
insertItem( tqparent, ( new SimpleTypeCachedCodeModel( cm->item() ) ) ->desc(), prefix );
} else {
SimpleTypeNamespace* cn = dynamic_cast<SimpleTypeNamespace*>( ( *it ).first.first.resolved().data() );
if( cn ) {
TypePointer t = new SimpleTypeNamespace( cn ); //to avoid endless recursion (caching would be better)
insertItem( tqparent, t->desc(), prefix );
}
}
}
return ;
}
} else {
if ( dom ) {
TQString n = d.resolved() ->scope().join( "::" );
//TQString n = d.fullNameChain();
if ( d.resolved() ->asFunction() ) {
n = buildSignature( d.resolved() );
}
txt = prefix + i18n( "Show %1" ).tqarg( cleanForMenu( n ) );
} else {
txt = prefix + d.name() + " not in code-model";
}
}
} else {
if( !BuiltinTypes::isBuiltin( d ) ) {
txt = prefix + d.name() + i18n( " is unresolved" );
} else {
txt = prefix + d.name() + i18n( " (builtin " ) + BuiltinTypes::comment( d ) + ")";
}
}
int id = tqparent->insertItem( txt, receiver, TQT_SLOT( popupClassViewAction( int ) ) );
if ( dom )
receiver->m_popupClassViewActions.insert( id, dom );
}
};
template <class HelpStruct = PopupFillerHelpStruct>
class PopupFiller {
HelpStruct struk;
TQString depthAdd;
SafetyCounter s;
public:
PopupFiller( HelpStruct str , TQString dAdd, int maxCount = 100 ) : struk( str ), depthAdd( dAdd ), s( maxCount ) {}
void fillIncludes( const DeclarationInfo& decl, TQPopupMenu* tqparent, bool& needSeparator ) {
if( !struk.receiver->getIncludeFiles()[ HashedString( decl.file ) ] ) {
TQString file = decl.file;
//The include-file seems to be missing
if( needSeparator ) {
needSeparator = false;
tqparent->insertSeparator();
}
TQString includeFile = file;
TQFileInfo info( file );
Driver* driver = struk.receiver->cppSupport()->driver();
if( driver ) {
TQStringList elements = TQStringList::split( "/", file );
includeFile = elements.back();
elements.pop_back();
Dependence d;
d.first = includeFile;
d.second = Dep_Local;
while( driver->findIncludeFile( d, struk.receiver->activeFileName() ) != file && !elements.empty() ) {
//kdDebug( 9007 ) << "could not find include-file \"" << d.first << "\"" << endl;
includeFile = elements.back() + "/" + includeFile;
d.first = includeFile;
elements.pop_back();
}
if( elements.empty() )
includeFile = "/" + includeFile;
//kdDebug( 9007 ) << "found include-file \"" << includeFile << "\"" << endl;
}
int id = tqparent->insertItem( i18n( "#include \"%1\" ( defines %2 )" ).tqarg ( includeFile ).tqarg( decl.name ), struk.receiver, TQT_SLOT( popupAction( int ) ) );
DeclarationInfo fakeDec;
fakeDec.name = decl.name;
fakeDec.file = includeFile;
fakeDec.startLine = -1; //Use startline -1 to indicate that instead of jumping to the file, the file should be included.
struk.m_popupActions.insert( id, fakeDec );
}
}
void fill( TQPopupMenu * tqparent, LocateResult d, TQString prefix = "", const DeclarationInfo & sourceVariable = DeclarationInfo() ) {
Debug dbg( "#fl# ", 10 )
;
if ( !s || !dbg ) {
//dbgMajor() << "safety-counter triggered while filling \"" << d.fullNameChain() << "\"" << endl;
return ;
}
if ( !sourceVariable.name.isEmpty() && sourceVariable.name != "this" ) {
SimpleTypeImpl::MemberInfo f;
f.decl = sourceVariable;
f.name = sourceVariable.name;
f.type = d.desc();
f.memberType = SimpleTypeImpl::MemberInfo::Variable;
/*int id = m->insertItem( i18n("jump to variable-declaration \"%1\"").tqarg( type.sourceVariable.name ) , this, TQT_SLOT( popupAction( int ) ) );
m_popupActions.insert( id, type.sourceVariable );*/
struk.insertItem( tqparent, f, prefix );
tqparent->insertSeparator();
if ( !sourceVariable.comment.isEmpty() ) {
TQPopupMenu * m = PopupTracker::createPopup( tqparent );
tqparent->insertItem( i18n( "Comment on %1" ).tqarg( sourceVariable.name ), m );
TQStringList ls = prepareTextForMenu( sourceVariable.comment, 15, 100 );
for ( TQStringList::iterator it = ls.begin(); it != ls.end(); ++it ) {
m->insertItem( *it, 0, TQT_SLOT( popupClassViewAction( int ) ) );
}
tqparent->insertSeparator();
}
}
struk.insertItem( tqparent, d, prefix );
if( d->resolved() && !d->resolved()->specialization().isEmpty() ) {
SimpleType p = d->resolved()->tqparent();
LocateResult r = p->locateDecType( d->name() );
if( r ) {
TQPopupMenu * m = PopupTracker::createPopup( tqparent );
tqparent->insertItem( i18n( "Specialized from \"%1\"" ).tqarg( cleanForMenu( r->fullNameChain() ) ), m );
fill( m, r );
}
}
TypeDesc::TemplateParams p = d->templateParams();
for ( TypeDesc::TemplateParams::iterator it = p.begin(); it != p.end(); ++it ) {
//if( (*it)->resolved() ) {
TQPopupMenu * m = PopupTracker::createPopup( tqparent );
tqparent->insertItem( i18n( "Template-param \"%1\"" ).tqarg( cleanForMenu( ( *it ) ->fullNameChain() ) ), m );
fill( m, **it );
/*} else {
fill( tqparent, **it, prefix + depthAdd );
}*/
}
if ( d->resolved() ) {
if ( d->resolved() ->asFunction() ) {
LocateResult rt = d->resolved() ->locateDecType( d->resolved() ->asFunction() ->getReturnType() );
if ( rt ) {
TQPopupMenu * m = PopupTracker::createPopup( tqparent );
tqparent->insertItem( i18n( "Return-type \"%1\"" ).tqarg( cleanForMenu( rt->fullNameChain() ) ), m );
fill( m, rt );
}
TQValueList<TypeDesc> args = d->resolved() ->asFunction() ->getArgumentTypes();
TQStringList argNames = d->resolved() ->asFunction() ->getArgumentNames();
if ( !args.isEmpty() ) {
TQPopupMenu * m = PopupTracker::createPopup( tqparent );
tqparent->insertItem( i18n( "Argument-types" ), m );
TQStringList::iterator it2 = argNames.begin();
for ( TQValueList<TypeDesc>::iterator it = args.begin(); it != args.end(); ++it ) {
LocateResult at = d->resolved() ->locateDecType( *it );
TQString name = "";
if ( it2 != argNames.end() ) {
name = *it2;
++it2;
}
TQPopupMenu * mo = PopupTracker::createPopup( m );
m->insertItem( i18n( "Argument \"%1\"" ).tqarg( cleanForMenu( at->fullNameChain() + " " + name ) ), mo );
fill( mo, at );
}
}
}
}
#ifndef DISABLE_TRACING
if ( d.trace() ) {
TQValueList<TQPair<SimpleTypeImpl::MemberInfo, TypeDesc> > trace = d.trace() ->trace();
if ( !trace.isEmpty() ) {
TQPopupMenu * m = PopupTracker::createPopup( tqparent );
tqparent->insertItem( i18n( "Trace" ), m );
for ( TQValueList<TQPair<SimpleTypeImpl::MemberInfo, TypeDesc> >::iterator it = trace.begin(); it != trace.end(); ++it ) {
TQPopupMenu * mo = PopupTracker::createPopup( m );
TQString tail = ( *it ).second.fullNameChain();
if ( !tail.isEmpty() )
tail = "::" + tail;
m->insertItem( i18n( "%1 -> %2" ).tqarg( cleanForMenu( ( *it ).first.name + tail ) ).tqarg( cleanForMenu( ( *it ).first.type->fullNameChain() + tail ) ), mo );
struk.insertItem( mo, ( *it ).first, prefix );
if ( !( *it ).first.decl.comment.isEmpty() ) {
mo->insertSeparator();
TQPopupMenu * m = PopupTracker::createPopup( mo );
mo->insertItem( i18n( "Comment" ), m );
TQStringList ls = prepareTextForMenu( ( *it ).first.decl.comment, 15, 100 );
for ( TQStringList::iterator it = ls.begin(); it != ls.end(); ++it ) {
m->insertItem( *it, 0, TQT_SLOT( popupClassViewAction( int ) ) );
}
}
/*bool needSeparator = true;
if( struk.shouldShowIncludeMenu() && struk.receiver->cppSupport()->codeCompletionConfig()->preProcessAllHeaders() && !(*it).first.decl.file.operator TQString().isEmpty() )
fillIncludes( (*it).first.decl, mo, needSeparator );*/
}
}
}
#endif
if ( d->resolved() ) {
TQValueList<LocateResult> bases = d->resolved() ->getBases();
for ( TQValueList<LocateResult>::iterator it = bases.begin(); it != bases.end(); ++it ) {
TQPopupMenu * m = PopupTracker::createPopup( tqparent );
tqparent->insertItem( i18n( "Base-class \"%1\"" ).tqarg( cleanForMenu( ( *it ) ->fullNameChain() ) ), m );
fill( m, *it );
}
if ( d->resolved() ->tqparent() && d->resolved() ->tqparent() ->desc() ) {
TQPopupMenu * m = PopupTracker::createPopup( tqparent );
tqparent->insertItem( i18n( "Nested in \"%1\"" ).tqarg( cleanForMenu( d->resolved() ->tqparent() ->fullTypeResolved() ) ), m );
fill( m, d->resolved() ->tqparent() ->desc() );
}
if ( !d->resolved() ->comment().isEmpty() ) {
tqparent->insertSeparator();
TQPopupMenu * m = PopupTracker::createPopup( tqparent );
tqparent->insertItem( i18n( "Comment on %1" ).tqarg( cleanForMenu( d->name() ) ), m );
TQStringList ls = prepareTextForMenu( d->resolved() ->comment(), 15, 100 );
for ( TQStringList::iterator it = ls.begin(); it != ls.end(); ++it ) {
m->insertItem( *it, 0, TQT_SLOT( popupClassViewAction( int ) ) );
}
}
}
//Add entries for including missing include-files
if( struk.shouldShowIncludeMenu() && struk.receiver->cppSupport()->codeCompletionConfig()->preProcessAllHeaders() ) {
bool needSeparator = true;
//Show the include-files for the whole trace, because usually the first in the trace should be the one to include
if ( d.trace() ) {
TQValueList<TQPair<SimpleTypeImpl::MemberInfo, TypeDesc> > trace = d.trace() ->trace();
if ( !trace.isEmpty() ) {
for ( TQValueList<TQPair<SimpleTypeImpl::MemberInfo, TypeDesc> >::iterator it = trace.begin(); it != trace.end(); ++it ) {
if( struk.shouldShowIncludeMenu() && struk.receiver->cppSupport()->codeCompletionConfig()->preProcessAllHeaders() && !(*it).first.decl.file.operator TQString().isEmpty() )
fillIncludes( (*it).first.decl, tqparent, needSeparator );
}
}
}
//Show the include-file for the item itself
if( d->resolved() && !d->resolved()->isNamespace() && struk.receiver->cppSupport() ) {
fillIncludes( d->resolved()->getDeclarationInfo(), tqparent, needSeparator );
}
}
}
};
struct CompTypeProcessor : public TypeProcessor {
SimpleType m_scope;
bool m_processArguments;
CompTypeProcessor( SimpleType scope, bool processArguments ) : m_scope( scope ), m_processArguments( processArguments ) {}
virtual TQString tqparentType() {
return m_scope->fullType();
}
virtual TQString processType( const TQString& type ) {
if ( !m_processArguments )
return type;
LocateResult t = m_scope->locateDecType( type );
if ( t )
return t->fullNameChain();
else
return type;
}
};
struct CppCodeCompletionData {
TQPtrList<RecoveryPoint> recoveryPoints;
//TQStringList classNameList;
CppCodeCompletionData() {
recoveryPoints.setAutoDelete( true );
}
RecoveryPoint* findRecoveryPoint( int line, int column ) {
if ( recoveryPoints.count() == 0 )
return 0;
TQPair<int, int> pt = tqMakePair( line, column );
TQPtrListIterator<RecoveryPoint> it( recoveryPoints );
RecoveryPoint* recPt = 0;
while ( it.current() ) {
TQPair<int, int> startPt = tqMakePair( it.current() ->startLine, it.current() ->startColumn );
TQPair<int, int> endPt = tqMakePair( it.current() ->endLine, it.current() ->endColumn );
if ( pt < startPt ) {
break;
}
if ( startPt < pt && pt < endPt )
recPt = it.current();
++it;
}
return recPt;
}
};
CppCodeCompletion::CppCodeCompletion( CppSupportPart* part )
: d( new CppCodeCompletionData ),
//Matches on includes
m_includeRx( "^\\s*#\\s*include\\s+[\"<]" ),
//Matches on C++ and C style comments as well as literal strings
m_cppCodeCommentsRx( "(//([^\n]*)(\n|$)|/\\*.*\\*/|\"([^\\\\]|\\\\.)*\")" ),
//Matches on alpha chars and '.'
m_codeCompleteChRx( "([A-Z])|([a-z])|(\\.)" ),
//Matches on "->" and "::"
m_codeCompleteCh2Rx( "(->)|(\\:\\:)" ) {
m_instance = this;
cppCompletionInstance = this;
m_cppCodeCommentsRx.setMinimal( true );
m_pSupport = part;
connect( m_pSupport->codeCompletionConfig(), TQT_SIGNAL( stored() ), this, TQT_SLOT( emptyCache() ) );
m_activeCursor = 0;
m_activeEditor = 0;
m_activeCompletion = 0;
m_activeHintInterface = 0;
m_activeView = 0;
m_ccTimer = new TQTimer( this );
m_showStatusTextTimer = new TQTimer( this );
m_ccLine = 0;
m_ccColumn = 0;
connect( m_ccTimer, TQT_SIGNAL( timeout() ), this, TQT_SLOT( slotTimeout() ) );
connect( m_showStatusTextTimer, TQT_SIGNAL( timeout() ), this, TQT_SLOT( slotStatusTextTimeout() ) );
computeFileEntryList();
CppSupportPart* cppSupport = m_pSupport;
connect( cppSupport->project(), TQT_SIGNAL( addedFilesToProject( const TQStringList& ) ),
this, TQT_SLOT( computeFileEntryList() ) );
connect( cppSupport->project(), TQT_SIGNAL( removedFilesFromProject( const TQStringList& ) ),
this, TQT_SLOT( computeFileEntryList() ) );
connect( cppSupport, TQT_SIGNAL( synchronousParseReady( const TQString&, ParsedFilePointer ) ), this, TQT_SLOT( synchronousParseReady( const TQString&, ParsedFilePointer ) ) );
m_bArgHintShow = false;
m_bCompletionBoxShow = false;
m_blockForKeyword = false;
m_demandCompletion = false;
m_completionMode = NormalCompletion;
m_repository = new CodeInformationRepository( cppSupport->codeRepository() );
connect( cppSupport->codeRepository(), TQT_SIGNAL(catalogRegistered( Catalog* )), this, TQT_SLOT( emptyCache() ) );
connect( cppSupport->codeRepository(), TQT_SIGNAL(catalogUnregistered( Catalog* )), this, TQT_SLOT( emptyCache() ) );
connect( cppSupport->codeRepository(), TQT_SIGNAL(catalogChanged( Catalog* )), this, TQT_SLOT( emptyCache() ) );
setupCodeInformationRepository();
if ( part->partController() ->parts() ) {
TQPtrListIterator<KParts::Part> it( *part->partController() ->parts() );
while ( KParts::Part * part = it.current() ) {
integratePart( part );
++it;
}
}
if ( part->partController() ->activePart() )
slotActivePartChanged( part->partController() ->activePart() );
connect( part->partController( ), TQT_SIGNAL( partAdded( KParts::Part* ) ),
this, TQT_SLOT( slotPartAdded( KParts::Part* ) ) );
connect( part->partController( ), TQT_SIGNAL( activePartChanged( KParts::Part* ) ),
this, TQT_SLOT( slotActivePartChanged( KParts::Part* ) ) );
connect( part, TQT_SIGNAL( fileParsed( const TQString& ) ),
this, TQT_SLOT( slotFileParsed( const TQString& ) ) );
connect( part, TQT_SIGNAL( codeModelUpdated( const TQString& ) ),
this, TQT_SLOT( slotCodeModelUpdated( const TQString& ) ) );
KAction * action = new KAction( i18n("Jump to declaration under cursor"), 0, CTRL + Key_Comma,
this, TQT_SLOT(slotJumpToDeclCursorContext()), part->actionCollection(), "jump_to_declaration_cursor_context" );
action->plug( &m_DummyActionWidget );
action = new KAction( i18n("Jump to definition under cursor"), 0, CTRL + Key_Period,
this, TQT_SLOT(slotJumpToDefCursorContext()), part->actionCollection(), "jump_to_defintion_cursor_context" );
action->plug( &m_DummyActionWidget );
}
CppCodeCompletion::~CppCodeCompletion( ) {
delete m_repository;
delete d;
}
void CppCodeCompletion::addStatusText( TQString text, int timeout ) {
m_statusTextList.append( TQPair<int, TQString>( timeout, text ) );
if ( !m_showStatusTextTimer->isActive() ) {
slotStatusTextTimeout();
}
}
void CppCodeCompletion::clearStatusText() {
m_statusTextList.clear();
m_showStatusTextTimer->stop();
}
void CppCodeCompletion::slotStatusTextTimeout() {
if ( m_statusTextList.isEmpty() || !m_pSupport )
return ;
// m_pSupport->mainWindow() ->statusBar() ->message( m_statusTextList.front().second, m_statusTextList.front().first );
m_showStatusTextTimer->start( m_statusTextList.front().first , true );
m_statusTextList.pop_front();
}
void CppCodeCompletion::slotTimeout() {
if ( !m_activeCursor || !m_activeEditor || !m_activeCompletion )
return ;
uint nLine, nCol;
m_activeCursor->cursorPositionReal( &nLine, &nCol );
if ( nLine != m_ccLine || nCol != m_ccColumn )
return ;
TQString textLine = m_activeEditor->textLine( nLine );
TQChar ch = textLine[ nCol ];
if ( ch.isLetterOrNumber() || ch == '_' )
return ;
completeText();
}
void CppCodeCompletion::slotArgHintHidden() {
//kdDebug(9007) << "CppCodeCompletion::slotArgHintHidden()" << endl;
m_bArgHintShow = false;
}
void CppCodeCompletion::slotCompletionBoxHidden() {
//kdDebug( 9007 ) << "CppCodeCompletion::slotCompletionBoxHidden()" << endl;
m_bCompletionBoxShow = false;
}
void CppCodeCompletion::integratePart( KParts::Part * part ) {
if ( !part || !part->widget() )
return ;
KTextEditor::Document* doc = dynamic_cast<KTextEditor::Document*>( part );
if ( doc ) {
kdDebug( 9007 ) << k_funcinfo << "integrate document: " << doc << endl;
if ( m_pSupport ) { //The slot should connected even when automatic completion is disabled, so it can be enabled any time
kdDebug( 9007 ) << k_funcinfo << "enabling code completion" << endl;
connect( part, TQT_SIGNAL( textChanged() ), this, TQT_SLOT( slotTextChanged() ) );
connect( part->widget(), TQT_SIGNAL( completionDone() ), this,
TQT_SLOT( slotCompletionBoxHidden() ) );
connect( part->widget(), TQT_SIGNAL( completionAborted() ), this,
TQT_SLOT( slotCompletionBoxHidden() ) );
connect( part->widget(), TQT_SIGNAL( argHintHidden() ), this,
TQT_SLOT( slotArgHintHidden() ) );
}
}
}
void CppCodeCompletion::slotPartAdded( KParts::Part * part ) {
integratePart( part );
}
void CppCodeCompletion::slotActivePartChanged( KParts::Part * part ) {
emptyCache();
this->d->recoveryPoints.clear();
if ( m_activeHintInterface && m_activeView ) {
disconnect( m_activeView , TQT_SIGNAL( needTextHint( int, int, TQString & ) ), this, TQT_SLOT( slotTextHint( int, int, TQString& ) ) );
m_activeHintInterface = 0;
}
if ( !part )
return ;
kdDebug( 9007 ) << k_funcinfo << endl;
m_activeFileName = TQString();
KTextEditor::Document* doc = dynamic_cast<KTextEditor::Document*>( part );
if ( !doc )
return ;
m_activeFileName = doc->url().path();
// if the interface stuff fails we should disable codecompletion automatically
m_activeEditor = dynamic_cast<KTextEditor::EditInterface*>( part );
if ( !m_activeEditor ) {
kdDebug( 9007 ) << "Editor doesn't support the EditDocumentIface" << endl;
return ;
}
m_activeCursor = dynamic_cast<KTextEditor::ViewCursorInterface*>( part->widget() );
if ( !m_activeCursor ) {
kdDebug( 9007 ) << "The editor doesn't support the CursorDocumentIface!" << endl;
return ;
}
m_activeCompletion = dynamic_cast<KTextEditor::CodeCompletionInterface*>( part->widget() );
if ( !m_activeCompletion ) {
kdDebug( 9007 ) << "Editor doesn't support the CompletionIface" << endl;
return ;
}
m_activeView = part ? dynamic_cast<KTextEditor::View*>( part->widget() ) : 0;
if ( m_activeView )
m_activeHintInterface = dynamic_cast<KTextEditor::TextHintInterface*>( m_activeView );
char* q = 0;
kdDebug() << q << endl;
if ( m_activeHintInterface ) {
#ifndef DISABLETOOLTIPS
m_activeHintInterface->enableTextHints( 500 );
connect( m_activeView, TQT_SIGNAL( needTextHint( int, int, TQString & ) ), this, TQT_SLOT( slotTextHint( int, int, TQString& ) ) );
#endif
} else {
kdDebug( 9007 ) << "editor has no text-hint-interface" << endl;
}
kdDebug( 9007 ) << k_funcinfo << "-- end" << endl;
}
void CppCodeCompletion::slotTextChanged() {
m_ccTimer->stop();
if ( !m_activeCursor )
return ;
unsigned int nLine, nCol;
m_activeCursor->cursorPositionReal( &nLine, &nCol );
TQString strCurLine = m_activeEditor->textLine( nLine );
TQString ch = strCurLine.mid( nCol - 1, 1 );
TQString ch2 = strCurLine.mid( nCol - 2, 2 );
// Tell the completion box to _go_away_ when the completion char
// becomes empty or whitespace and the box is already showing.
// !!WARNING!! This is very hackish, but KTE doesn't offer a way
// to tell the completion box to _go_away_
if ( ch.simplifyWhiteSpace().isEmpty() &&
!strCurLine.simplifyWhiteSpace().tqcontains( "virtual" ) &&
m_bCompletionBoxShow ) {
TQValueList<KTextEditor::CompletionEntry> entryList;
m_bCompletionBoxShow = true;
m_activeCompletion->showCompletionBox( entryList, 0 );
}
m_ccLine = 0;
m_ccColumn = 0;
bool argsHint = m_pSupport->codeCompletionConfig() ->automaticArgumentsHint();
bool codeComplete = m_pSupport->codeCompletionConfig() ->automaticCodeCompletion();
bool headComplete = codeComplete; //m_pSupport->codeCompletionConfig() ->automaticHeaderCompletion();
// m_codeCompleteChRx completes on alpha chars and '.'
// m_codeCompleteCh2Rx completes on "->" and "::"
if ( ( argsHint && ch == "(" ) ||
( codeComplete && strCurLine.simplifyWhiteSpace().tqcontains( "virtual" ) ) ||
( codeComplete && ( m_codeCompleteChRx.search( ch ) != -1 ||
m_codeCompleteCh2Rx.search( ch2 ) != -1 ) ) ||
( headComplete && ( ch == "\"" || ch == "<" ) && m_includeRx.search( strCurLine ) != -1 ) ) {
int time;
m_ccLine = nLine;
m_ccColumn = nCol;
if ( ch == "(" )
time = m_pSupport->codeCompletionConfig() ->argumentsHintDelay();
else
time = m_pSupport->codeCompletionConfig() ->codeCompletionDelay();
m_ccTimer->start( time, true );
}
fitContextItem( nLine, nCol );
}
void CppCodeCompletion::fitContextItem( int nLine, int nCol ) {
if( !SimpleType::globalNamespace() ) {
kdDebug( 9007 ) << "no global namespace was set, clearing cache" << endl;
emptyCache();
}
///Find out whether the cache may be used on, or has to be cleared.
if ( m_cachedFromContext ) {
int sLine, sCol, eLine, eCol;
m_cachedFromContext->getStartPosition( &sLine, &sCol );
m_cachedFromContext->getEndPosition( &eLine, &eCol );
if ( ( nLine < sLine || ( nLine == sLine && nCol < sCol ) ) || ( nLine > eLine || ( nLine == eLine && nCol >= eCol ) ) ) {
///The stored item was left. First check whether the item was expanded.
FileDom file = m_pSupport->codeModel() ->fileByName( m_activeFileName );
if ( file ) {
CodeModelUtils::CodeModelHelper fileModel( m_pSupport->codeModel(), file );
if ( m_cachedFromContext->isClass() ) {
ClassDom klass = fileModel.classAt( nLine, nCol );
if ( klass ) {
ClassDom oldClass = dynamic_cast<ClassModel*>( m_cachedFromContext.data() );
if ( oldClass && oldClass->name() == klass->name() && oldClass->scope() == klass->scope() ) {
m_cachedFromContext = klass.data();
} else {
emptyCache();
}
} else {
emptyCache();
}
} else if ( m_cachedFromContext->isFunction() ) {
FunctionDom function = fileModel.functionAt( nLine, nCol );
if ( function ) {
FunctionDom oldFunction = dynamic_cast<FunctionModel*>( m_cachedFromContext.data() );
if ( oldFunction && oldFunction->name() == function->name() && function->scope() == oldFunction->scope() && oldFunction->argumentList().count() == function->argumentList().count() ) {
ArgumentList l1 = oldFunction->argumentList();
ArgumentList l2 = function->argumentList();
ArgumentList::iterator it = l1.begin();
ArgumentList::iterator it2 = l2.begin();
bool match = true;
while ( it != l1.end() ) {
if ( ( *it ) ->type() != ( *it2 ) ->type() ) {
match = false;
break;
}
++it;
++it2;
}
if ( match ) {
m_cachedFromContext = function.data();
} else {
emptyCache();
}
} else {
emptyCache();
}
} else {
emptyCache();
}
} else {
emptyCache();
}
} else {
emptyCache();
}
}
}
}
enum { T_ACCESS, T_PAREN, T_BRACKET, T_IDE, T_UNKNOWN, T_TEMP };
TQString CppCodeCompletion::replaceCppComments( const TQString& contents ) {
TQString text = contents;
int pos = 0;
while ( ( pos = m_cppCodeCommentsRx.search( text, pos ) ) != -1 ) {
if ( m_cppCodeCommentsRx.cap( 1 ).startsWith( "//" ) ) {
TQString before = m_cppCodeCommentsRx.cap( 1 );
TQString after;
after.fill( ' ', before.length() - 5 );
after.prepend( "/*" );
after.append( "*/" );
text.tqreplace( pos, before.length() - 1, after );
pos += after.length();
} else {
pos += m_cppCodeCommentsRx.matchedLength();
}
}
return text;
}
int CppCodeCompletion::expressionAt( const TQString& contents, int index ) {
kdDebug( 9007 ) << k_funcinfo << endl;
/* C++ style comments present issues with finding the expr so I'm
matching for them and replacing them with empty C style comments
of the same length for purposes of finding the expr. */
TQString text = clearComments( contents );
int last = T_UNKNOWN;
int start = index;
--index;
while ( index > 0 ) {
while ( index > 0 && text[ index ].isSpace() ) {
--index;
}
TQChar ch = text[ index ];
TQString ch2 = text.mid( index - 1, 2 );
if ( ( last != T_IDE ) && ( ch.isLetterOrNumber() || ch == '_' ) ) {
while ( index > 0 && ( text[ index ].isLetterOrNumber() || text[ index ] == '_' ) ) {
--index;
}
last = T_IDE;
} else if ( last != T_IDE && ch == ')' ) {
int count = 0;
while ( index > 0 ) {
TQChar ch = text[ index ];
if ( ch == '(' ) {
++count;
} else if ( ch == ')' ) {
--count;
} else if ( count == 0 ) {
//index;
last = T_PAREN;
break;
}
--index;
}
} else if ( last != T_IDE && ch == '>' && ch2 != "->" ) {
int count = 0;
while ( index > 0 ) {
TQChar ch = text[ index ];
if ( ch == '<' ) {
++count;
} else if ( ch == '>' ) {
--count;
} else if ( count == 0 ) {
//--index;
last = T_TEMP;
break;
}
--index;
}
} else if ( ch == ']' ) {
int count = 0;
while ( index > 0 ) {
TQChar ch = text[ index ];
if ( ch == '[' ) {
++count;
} else if ( ch == ']' ) {
--count;
} else if ( count == 0 ) {
//--index;
last = T_BRACKET;
break;
}
--index;
}
} else if ( ch == '.' ) {
--index;
last = T_ACCESS;
} else if ( ch2 == "::" ) {
index -= 2;
last = T_ACCESS;
} else if ( ch2 == "->" ) {
index -= 2;
last = T_ACCESS;
} else {
if ( start > index ) {
++index;
}
last = T_UNKNOWN;
break;
}
}
///If we're at the first item, the above algorithm cannot be used safely,
///so just determine whether the sign is valid for the beginning of an expression, if it isn't reject it.
if ( index == 0 && start > index && !( text[ index ].isLetterOrNumber() || text[ index ] == '_' || text[ index ] == ':' ) ) {
++index;
}
return index;
}
TQStringList CppCodeCompletion::splitExpression( const TQString& text ) {
#define ADD_CURRENT()\
if( current.length() ) { l << current; /*kdDebug(9007) << "add word " << current << endl;*/ current = ""; }
TQStringList l;
uint index = 0;
TQString current;
while ( index < text.length() ) {
TQChar ch = text[ index ];
TQString ch2 = text.mid( index, 2 );
if ( ch == '.' ) {
current += ch;
ADD_CURRENT();
++index;
} else if ( ch == '(' ) {
int count = 0;
while ( index < text.length() ) {
TQChar ch = text[ index ];
if ( ch == '(' ) {
++count;
} else if ( ch == ')' ) {
--count;
} else if ( count == 0 ) {
break;
}
current += ch;
++index;
}
} else if ( ch == '[' ) {
int count = 0;
while ( index < text.length() ) {
TQChar ch = text[ index ];
if ( ch == '[' ) {
++count;
} else if ( ch == ']' ) {
--count;
} else if ( count == 0 ) {
break;
}
current += ch;
++index;
}
} else if ( ch2 == "->" ) {
current += ch2;
ADD_CURRENT();
index += 2;
} /*else if ( ch2 == "::" )
{
current += ch2;
ADD_CURRENT();
index += 2;
}*/
else {
current += text[ index ];
++index;
}
}
ADD_CURRENT();
return l;
}
///Before calling this, a SimpleTypeConfiguration-object should be created, so that the ressources will be freed when that object is destroyed
EvaluationResult CppCodeCompletion::evaluateExpressionAt( int line, int column , SimpleTypeConfiguration& conf, bool ifUnknownSetType ) {
kdDebug( 9007 ) << "CppCodeCompletion::evaluateExpressionAt( " << line << ", " << column << " )" << endl;
if ( !m_pSupport || !m_activeEditor )
return EvaluationResult();
if ( line < 0 || line >= ( int ) m_activeEditor->numLines() )
return EvaluationResult();
if ( column < 0 || column >= m_activeEditor->lineLength( line ) )
return EvaluationResult();
{
TQString curLine = m_activeEditor->textLine( line );
///move column to the last letter of the pointed word
while ( column + 1 < ( int ) curLine.length() && isValidIdentifierSign( curLine[ column ] ) && isValidIdentifierSign( curLine[ column + 1 ] ) )
column++;
//if( column > 0 ) column--;
if ( column >= ( int ) curLine.length() || curLine[ column ].isSpace() )
return EvaluationResult();
TQString expr = curLine.left( column + 1 );
kdDebug( 9007 ) << "evaluating line \"" << expr.stripWhiteSpace() << "\"" << endl;
if ( curLine[ column ] == '-' || curLine[ column ] == ';' )
--column;
EvaluationResult type = evaluateExpressionType( line, column + 1, conf, ifUnknownSetType ? addFlag( DefaultEvaluationOptions, DefaultAsTypeExpression ) : DefaultEvaluationOptions );
kdDebug( 9007 ) << "type: " << type->fullNameChain() << endl;
return type;
}
}
void CppCodeCompletion::popupAction( int number ) {
PopupActions::iterator it = m_popupActions.tqfind( number );
if ( it != m_popupActions.end() ) {
TQString fileName = ( *it ).file == "current_file" ? m_activeFileName : ( *it ).file.operator TQString();
if( (*it).startLine == -1 ) {
//startLine -1 indicates that the file should be added to the include-files
m_activeEditor->insertLine( 0, TQString("#include \"%1\" /* defines %2 */").tqarg( fileName ).tqarg( (*it).name ) );
} else {
m_pSupport->partController() ->editDocument( fileName, ( *it ).startLine );
}
} else {
kdDebug( 9007 ) << "error" << endl;
}
}
void CppCodeCompletion::popupDefinitionAction( int number ) {
PopupActions::iterator it = m_popupDefinitionActions.tqfind( number );
if ( it != m_popupDefinitionActions.end() ) {
TQString fileName = ( *it ).file == "current_file" ? m_activeFileName : ( *it ).file.operator TQString();
if ( !m_pSupport->switchHeaderImpl( fileName, ( *it ).startLine, ( *it ).startCol ) )
m_pSupport->partController() ->editDocument( fileName, ( *it ).startLine );
} else {
kdDebug( 9007 ) << "error" << endl;
}
}
void CppCodeCompletion::selectItem( ItemDom item ) {
Extensions::KDevCodeBrowserFrontend * f = m_pSupport->extension< Extensions::KDevCodeBrowserFrontend > ( "KDevelop/CodeBrowserFrontend" );
if ( f != 0 ) {
ItemDom itemDom( &( *item ) );
f->jumpedToItem( itemDom );
} else {
kdDebug() << "could not find the proper extension" << endl;
}
}
void CppCodeCompletion::popupClassViewAction( int number ) {
PopupClassViewActions::iterator it = m_popupClassViewActions.tqfind( number );
if ( it != m_popupClassViewActions.end() ) {
if ( ( *it ) )
selectItem( *it );
} else {
kdDebug( 9007 ) << "error" << endl;
}
}
void CppCodeCompletion::contextEvaluationMenus ( TQPopupMenu *popup, const Context *context, int line, int column ) {
clearStatusText();
Q_UNUSED(context);
if ( !m_pSupport->codeCompletionConfig() ->showEvaluationContextMenu() )
return ;
kdDebug( 9007 ) << "CppCodeCompletion::contextEvaluationMenu()" << endl;
PopupTracker::print();
m_popupActions.clear();
m_popupDefinitionActions.clear();
m_popupClassViewActions.clear();
if ( !m_pSupport || !m_activeEditor )
return ;
struct SetDbgState {
DBGStreamType& st;
bool oldState;
SetDbgState( DBGStreamType& targ, bool state ) : st( targ ) {
oldState = targ.state();
targ.setState( state );
}
~SetDbgState() {
st.setState( oldState );
}
};
int cpos = 0;
SetDbgState stt( dbgState, disableVerboseForContextMenu );
SimpleTypeConfiguration conf( m_activeFileName );
EvaluationResult type = evaluateExpressionAt( line, column, conf );
///Test if it is a macro
if( type.isMacro ) {
TQPopupMenu * m = PopupTracker::createPopup( popup );
int gid;
if ( contextMenuEntriesAtTop )
gid = popup->insertItem( i18n( "Navigate by Macro \"%1\"" ).tqarg( cleanForMenu( type.macro.name() ) ), m, 5, cpos++ );
else
gid = popup->insertItem( i18n( "Navigate by Macro \"%1\"" ).tqarg( cleanForMenu( type.macro.name() ) ), m );
int id = m->insertItem( i18n( "Jump to %1" ).tqarg( cleanForMenu( type.macro.name() ) ), this, TQT_SLOT( popupAction( int ) ) );
TQPopupMenu * b = PopupTracker::createPopup( m );
m->insertItem( i18n( "Body" ), b );
DeclarationInfo i;
i.file = type.macro.fileName();
i.startCol = type.macro.column();
i.startLine = type.macro.line();
i.endCol = type.macro.column();
i.endLine = type.macro.line();
m_popupActions.insert( id, i );
TQStringList ls = prepareTextForMenu( type.macro.body(), 20, 100 );
for ( TQStringList::iterator it = ls.begin(); it != ls.end(); ++it ) {
b->insertItem( *it, 0, TQT_SLOT( popupClassViewAction( int ) ) );
}
}
///Test if it is an include-directive
TQString includeFileName, includeFilePath;
bool simpleAlgorithm = false;
bool isIncludeDirective = getIncludeInfo( line, includeFileName, includeFilePath, simpleAlgorithm );
if( isIncludeDirective ) {
///Add menu entry
if( !includeFilePath.isEmpty() ) {
int gid;
TQPopupMenu * m = PopupTracker::createPopup( popup );
if ( contextMenuEntriesAtTop )
gid = popup->insertItem( i18n( "Goto Include File: %1" ).tqarg( cleanForMenu( includeFileName ) ), m, 5, cpos++ );
else
gid = popup->insertItem( i18n( "Goto Include File: %1" ).tqarg( cleanForMenu( includeFileName ) ), m );
int id = m->insertItem( i18n( "Jump to %1" ).tqarg( cleanForMenu( includeFilePath ) ), this, TQT_SLOT( popupAction( int ) ) );
DeclarationInfo i;
i.file = includeFilePath;
i.startCol = 0;
i.startLine = 0;
i.endCol = 0;
i.endLine = 0;
m_popupActions.insert( id, i );
if( simpleAlgorithm && cppSupport()->codeCompletionConfig()->resolveIncludePaths() ) {
//Add a notification that the correct algorithm failed in finding the include-file correctly
m->insertItem( i18n( "This include-file could not be located regularly, and was selected from the project file list." ) );
}
} else {
///Could not find include-file
if ( contextMenuEntriesAtTop )
popup->insertItem( i18n( "Not Found: \"%1\"" ).tqarg( includeFileName ), 5, cpos++ );
else
popup->insertItem( i18n( "Not Found: \"%1\"" ).tqarg( includeFileName ) );
}
}
///Break if we cannot show additional information
if ( isIncludeDirective || (!type->resolved() && !type.sourceVariable && ( !type.resultType.trace() || type.resultType.trace() ->trace().isEmpty() ) && !BuiltinTypes::isBuiltin( type.resultType ) ) )
return ;
TQString name = type->fullNameChain();
if ( type.sourceVariable )
name += " " + type.sourceVariable.name;
if ( type.resultType->resolved() && type.resultType->resolved() ->asFunction() )
name = buildSignature( type.resultType->resolved() );
///Fill the jump-menu
{
PopupFillerHelpStruct h( this );
PopupFiller<PopupFillerHelpStruct> filler( h, "" );
TQPopupMenu * m = PopupTracker::createPopup( popup );
int gid;
if ( contextMenuEntriesAtTop )
gid = popup->insertItem( i18n( "Navigate by \"%1\"" ).tqarg( cleanForMenu( name ) ), m, 5, cpos++ );
else
gid = popup->insertItem( i18n( "Navigate by \"%1\"" ).tqarg( cleanForMenu( name ) ), m );
popup->tqsetWhatsThis( gid, i18n( "<b>Navigation</b><p>Provides a menu to navigate to positions of items that are involved in this expression" ) );
/*if( type.sourceVariable && type.sourceVariable.name != "this" ) {
int id = m->insertItem( i18n("jump to variable-declaration \"%1\"").tqarg( type.sourceVariable.name ) , this, TQT_SLOT( popupAction( int ) ) );
m_popupActions.insert( id, type.sourceVariable );
}*/
filler.fill( m, type, "", type.sourceVariable );
}
if ( type->resolved() ) {
///Now fill the class-view-browsing-stuff
{
TQPopupMenu * m = PopupTracker::createPopup( popup );
int gid;
if ( contextMenuEntriesAtTop )
gid = popup->insertItem( i18n( "Navigate Class-View by \"%1\"" ).tqarg( cleanForMenu( name ) ), m, 6, cpos++ );
else
gid = popup->insertItem( i18n( "Navigate Class-View by \"%1\"" ).tqarg( cleanForMenu( name ) ), m );
popup->tqsetWhatsThis( gid, i18n( "<b>Navigation</b><p>Provides a menu to show involved items in the class-view " ) );
PopupClassViewFillerHelpStruct h( this );
PopupFiller<PopupClassViewFillerHelpStruct> filler( h, "" );
filler.fill( m, type );
}
}
if ( contextMenuEntriesAtTop )
popup->insertSeparator( cpos );
}
void CppCodeCompletion::slotTextHint( int line, int column, TQString &text ) {
if ( ! m_pSupport->codeCompletionConfig() ->statusBarTypeEvaluation() )
return ;
kdDebug( 9007 ) << "CppCodeCompletion::slotTextHint()" << endl;
clearStatusText();
if ( m_lastHintTime.msecsTo( TQTime::currentTime() ) < 300 ) {
kdDebug( 9007 ) << "slotNeedTextHint called too often" << endl;
return ;
}
m_lastHintTime = TQTime::currentTime();
clearStatusText();
text = "";
if ( !m_pSupport || !m_activeEditor )
return ;
SimpleTypeConfiguration conf( m_activeFileName );
EvaluationResult type = evaluateExpressionAt( line, column, conf );
if ( type.expr.expr().stripWhiteSpace().isEmpty() )
return ; ///Expression could not be found
if ( type.sourceVariable ) {
text += type.sourceVariable.toText() + "\n";
}
if ( type->resolved() ) {
/*SimpleTypeFunctionInterface* f = type->resolved()->asFunction();
if( f ) {
text += "function: \"" + buildSignature( type->resolved() ) + "\"";
} else {
TQValueList<TypeDesc> trace = type.resultType->trace();
if( !trace.isEmpty() ) {
for( TQValueList<TypeDesc>::iterator it = trace.begin(); it != trace.end(); ++it ) {
text += (*it).fullNameChain() + " --> ";
}
text += "\n";
}
text += "type: \"" + type.resultType->fullTypeResolved() + "\"";
}
if( type.resultType->tqparent()) text += "\nnested in: \"" + type.resultType->tqparent()->fullTypeResolvedWithScope() + "\"";
DeclarationInfo i = type.resultType->getDeclarationInfo();
if( i ) text += "\n" + i.locationToText();
if( !type.resultType->comment().isEmpty() ) text += "\n\n" + type.resultType->comment() + "";*/
} else {}
kdDebug( 9007 ) << "showing: \n" << text << endl;
const int timeout = 2000;
if ( type->resolved() ) {
addStatusText( i18n( "Type of \"%1\" is \"%2\"" ).tqarg( type.expr.expr() ).tqarg( type->fullNameChain() ), timeout );
if ( type.sourceVariable && !type.sourceVariable.comment.isEmpty() ) {
addStatusText( i18n( "Comment on variable \"%1\": \"%2\"" ).tqarg( type.sourceVariable.name ).tqarg( type.sourceVariable.comment ) , 10000 );
}
if ( !type->resolved() ->comment().isEmpty() ) {
addStatusText( i18n( "Comment on \"%1\": \"%2\"" ).tqarg( type->name() ).tqarg( type->resolved() ->comment() ) , 10000 );
}
if ( type->resolved() ->comment().isEmpty() ) {
addStatusText( i18n( "\"%1\" has no comment" ).tqarg( type->name() ) , timeout );
}
} else {
if ( type ) {
if( !BuiltinTypes::isBuiltin( type.resultType ) ) {
addStatusText( i18n( "Type of \"%1\" is unresolved, name: \"%2\"" ).tqarg( type.expr.expr() ).tqarg( type->fullNameChain() ), 2 * timeout );
} else {
addStatusText( i18n( "\"%1\" is of builtin type \"%2\", a %3" ).tqarg( type.expr.expr() ).tqarg( type->fullNameChain() ).tqarg(BuiltinTypes::comment( type.resultType )), 2 * timeout );
}
} else {
addStatusText( i18n( "Type of \"%1\" could not be evaluated: tried to evaluate expression as \"%2\"" ).tqarg( type.expr.expr() ).tqarg( type.expr.typeAsString() ), 2 * timeout );
}
}
text = ""; ///Don't really use tooltips since those are not implemented in katepart, and don't work right in the qt-designer based part
}
///not good..
bool CppCodeCompletion::isTypeExpression( const TQString& expr ) {
TypeDesc d( expr );
if ( !d.isValidType() )
return false;
TQString ex = d.fullNameChain();
TQStringList lex = TQStringList::split( " ", ex );
TQStringList lexpr = TQStringList::split( " ", expr );
return lex.join( " " ) == lexpr.join( " " );
}
bool CppCodeCompletion::mayBeTypeTail( int line, int column, TQString& append, bool inFunction ) {
TQString tail = clearComments( m_activeEditor->text( line, column + 1, line + 10 > ( int ) m_activeEditor->numLines() ? ( int ) m_activeEditor->numLines() : line + 10, 0 ) );
tail.tqreplace( "\n", " " );
SafetyCounter s ( 100 );
bool hadSpace = false;
while ( !tail.isEmpty() && s ) {
if ( tail[ 0 ] == ';' ) {
return false;
} else if ( ( !inFunction && tail[ 0 ] == ',' ) || tail[ 0 ] == '&' || tail[ 0 ] == '*' || tail[ 0 ] == '{' || tail[ 0 ] == ':' ) {
return true;
} else if ( isTypeOpenParen( tail[ 0 ] ) ) {
///TODO: use findClose to make the whole expression include template-params
int to = findClose( tail, 0 );
if ( to != -1 ) {
append = tail.left( to + 1 );
tail = tail.mid( to + 1 );
} else {
return false;
}
} else if ( isTypeCloseParen( tail[ 0 ] ) ) {
return true;
} else if ( tail[ 0 ].isSpace() ) {
tail = tail.mid( 1 );
hadSpace = true;
} else if ( tail[ 0 ].isLetter() ) {
return hadSpace;
} else {
break;
}
}
return false;
}
bool CppCodeCompletion::canBeTypePrefix( const TQString& prefix, bool inFunction ) {
for ( int p = prefix.length() - 1 ; p >= 0; --p ) {
if ( prefix[ p ].isSpace() ) {
continue;
}
if ( prefix[ p ] == ';' || prefix[ p ] == '<' || prefix[ p ] == ':' || ( !inFunction && ( prefix[ p ] == '(' || prefix[ p ] == ',' ) ) || prefix[ p ] == '}' || prefix[ p ] == '{' ) {
return true;
}
///@todo: make this a simple regex
if ( prefix[ p ].isLetterOrNumber() && ( tokenAt( prefix, "class", p ) || tokenAt( prefix, "struct", p ) || tokenAt( prefix, "const", p ) || tokenAt( prefix, "typedef", p ) || tokenAt( prefix, "public", p ) || tokenAt( prefix, "protected", p ) || tokenAt( prefix, "private", p ) || tokenAt( prefix, "virtual", p ) || tokenAt( prefix, "static", p ) || tokenAt( prefix, "virtual", p ) ) )
return true;
else {
return false;
}
}
return true;
}
///This function is just a litte hack und should be remade, it doesn't work for all cases
ExpressionInfo CppCodeCompletion::findExpressionAt( int line, int column, int startLine, int startCol, bool inFunction ) {
ExpressionInfo ret;
TQString contents = clearComments( getText( startLine, startCol, line, column ) );
int start_expr = expressionAt( contents, contents.length() );
if ( start_expr != int( contents.length() ) ) {
TQString str = contents.mid( start_expr, contents.length() - start_expr ).stripWhiteSpace();
if ( str.startsWith( "new " ) ) {
str = str.mid( 4 ).stripWhiteSpace();
}
ret.setExpr( str );
if ( !ret.expr().isEmpty() )
ret.t = ExpressionInfo::NormalExpression;
}
if ( ret ) {
///Check whether it may be a type-expression
bool mayBeType = true;
TQString append;
if ( !mayBeTypeTail( line, column - 1, append, inFunction ) )
mayBeType = false;
if ( mayBeType ) {
if ( !canBeTypePrefix( contents.left( start_expr ), inFunction ) )
mayBeType = false;
}
//make this a regexp
TQString e = ret.expr();
if ( e.tqcontains( "." ) || e.tqcontains( "->" ) || e.tqcontains( "(" ) || e.tqcontains( ")" ) || e.tqcontains( "=" ) || e.tqcontains( "-" ) )
mayBeType = false;
if ( mayBeType ) {
ret.setExpr( ret.expr() + append );
ret.t = ExpressionInfo::TypeExpression;
}
}
return ret;
}
void macrosToDriver( Driver& d, FileDom file ) {
return; //Deactivate this for now, because macros can cause inconsistency of line/column-numbers between processed text and the not-processed text of the buffer
ParseResultPointer p;
if( file )
p = file->parseResult();
ParsedFile* pf = dynamic_cast<ParsedFile*>( p.data() );
if( pf ) {
d.insertMacros( pf->usedMacros() ); ///Add macros
}
}
SimpleContext* CppCodeCompletion::computeFunctionContext( FunctionDom f, int line, int col, SimpleTypeConfiguration& conf ) {
Q_UNUSED(conf);
if ( !f )
return 0;
int modelStartLine, modelStartColumn;
int modelEndLine, modelEndColumn;
f->getStartPosition( &modelStartLine, &modelStartColumn );
f->getEndPosition( &modelEndLine, &modelEndColumn );
TQString textLine = m_activeEditor->textLine( modelStartLine );
kdDebug( 9007 ) << "startLine = " << textLine << endl;
TQString contents = getText( modelStartLine, modelStartColumn, line, col );
Driver d;
Lexer lexer( &d );
macrosToDriver( d, f->file() );
lexer.setSource( contents );
Parser parser( &d, &lexer );
DeclarationAST::Node recoveredDecl;
RecoveryPoint* recoveryPoint = this->d->findRecoveryPoint( line, col );///@todo recovery-points are not needed anymore
parser.parseDeclaration( recoveredDecl );
if ( recoveredDecl.get() ) {
bool isFunDef = recoveredDecl->nodeType() == NodeType_FunctionDefinition;
kdDebug( 9007 ) << "is function definition= " << isFunDef << endl;
int startLine, startColumn;
int endLine, endColumn;
recoveredDecl->getStartPosition( &startLine, &startColumn );
recoveredDecl->getEndPosition( &endLine, &endColumn );
/*if( startLine != modelStartLine || endLine != modelEndLine || startColumn != modelStartColumn || endColumn != modelEndColumn ) {
kdDebug( 9007 ) << "code-model and real file are out of sync \nfunction-bounds in code-model: " << endl;
kdDebug( 9007 ) << "(l " << modelStartLine << ", c " << modelStartColumn << ") - (l " << modelEndLine << ", c " << modelEndColumn << ") " << "parsed function-bounds: " << endl;
kdDebug( 9007 ) << "(l " << startLine << ", c " << startColumn << ") - (l " << endLine << ", c " << endColumn << ") " << endl;
}*/
if ( isFunDef ) {
FunctionDefinitionAST * def = static_cast<FunctionDefinitionAST*>( recoveredDecl.get() );
SimpleContext* ctx = computeContext( def, endLine, endColumn, modelStartLine, modelStartColumn );
if ( !ctx )
return 0;
TQStringList scope = f->scope();
if ( !scope.isEmpty() ) {
SimpleType tqparentType;
/* if( !m_cachedFromContext ) {
TypePointer t = SimpleType(TQStringList())->locateDecType( scope.join("") ).desc().resolved();;
if( t )
tqparentType = SimpleType( t.data() );
else
tqparentType = SimpleType( scope );
} else {*/
tqparentType = SimpleType( scope, getIncludeFiles() );
//}
tqparentType->descForEdit().setTotalPointerDepth( 1 );
ctx->setContainer( tqparentType );
}
SimpleType global = ctx->global();
if( dynamic_cast<SimpleTypeNamespace*>( &(*global) ) ) {
SimpleTypeNamespace* globalNs = static_cast <SimpleTypeNamespace*>( &(*global) );
TQValueList<TQPair<TQString, TQString> > localImports = ctx->imports();
for( TQValueList<TQPair<TQString, TQString> >::const_iterator it = localImports.begin(); it != localImports.end(); ++it )
globalNs->addAliasMap( (*it).first, (*it).second );
}
/* //Should not be necessary any more
if( !getParsedFile( f->file().data() ) || getParsedFile( f->file().data() )->includeFiles().size() <= 1 ) {
if ( !m_cachedFromContext ) {
conf.setGlobalNamespace( &( *global ) );
if ( recoveryPoint ) {
recoveryPoint->registerImports( global, m_pSupport->codeCompletionConfig() ->namespaceAliases() );
} else {
kdDebug( 9007 ) << "no recovery-point, cannot use imports" << endl;
}
}
}*/
///Insert the "this"-type(container) and correctly resolve it using imported namespaces
if ( ctx->container() ) {
if ( !m_cachedFromContext ) {
TypeDesc td = ctx->container() ->desc();
td.setIncludeFiles( getIncludeFiles() );
td.makePrivate();
td.resetResolved( );
TypePointer tt = ctx->container() ->locateDecType( td, SimpleTypeImpl::LocateBase ) ->resolved();
if ( tt ) {
ctx->setContainer( SimpleType( tt ) );
} else {
kdDebug( 9007 ) << "could not resolve local this-type \"" << td.fullNameChain() << "\"" << endl;
}
}
SimpleType this_type = ctx->container();
this_type->descForEdit().setTotalPointerDepth( 1 );
SimpleVariable var;
var.type = this_type->desc();
var.name = "this";
var.comment = this_type->comment();
ctx->add
( var );
ctx->setContainer( this_type );
}
return ctx;
} else {
kdDebug( 9007 ) << "computeFunctionContext: context is no function-definition" << endl;
}
} else {
kdDebug( 9007 ) << "computeFunctionContext: could not find a valid declaration to recover" << endl;
}
return 0;
}
bool CppCodeCompletion::functionContains( FunctionDom f , int line, int col ) {
if ( !f )
return false;
int sl, sc, el, ec;
f->getStartPosition( &sl, &sc );
f->getEndPosition( &el, &ec );
TQString t = clearComments( getText( sl, sc, el, ec ) );
if ( t.isEmpty() )
return false;
//int i = t.tqfind( '{' );
int i = t.tqfind( '(' ); //This now includes the argument-list
if ( i == -1 )
return false;
int lineCols = 0;
for ( int a = 0; a < i; a++ ) {
if ( t[ a ] == '\n' ) {
sl++;
lineCols = 0;
} else {
lineCols++;
}
}
sc += lineCols;
return ( line > sl || ( line == sl && col >= sc ) ) && ( line < el || ( line == el && col < ec ) );
}
void CppCodeCompletion::getFunctionBody( FunctionDom f , int& line, int& col ) {
if ( !f )
return;
int sl, sc, el, ec;
f->getStartPosition( &sl, &sc );
f->getEndPosition( &el, &ec );
TQString t = clearComments( getText( sl, sc, el, ec ) );
if ( t.isEmpty() )
return;
int i = t.tqfind( '{' );
if ( i == -1 )
return;
i++;
if( (uint)i >= t.length() )
return;
int lineCols = 0;
for ( int a = 0; a < i; a++ ) {
if ( t[ a ] == '\n' ) {
sl++;
lineCols = 0;
} else {
lineCols++;
}
}
sc += lineCols;
line = sl;
col = sc;
}
void CppCodeCompletion::emptyCache() {
m_cachedFromContext = 0;
SimpleTypeConfiguration c; ///Will automatically destroy the type-store when the function is closed
kdDebug( 9007 ) << "completion-cache emptied" << endl;
}
void CppCodeCompletion::needRecoveryPoints() {
if ( this->d->recoveryPoints.isEmpty() ) {
kdDebug( 9007 ) << "missing recovery-points for file " << m_activeFileName << " they have to be computed now" << endl;
m_pSupport->backgroundParser() ->lock ()
;
std::vector<CppCodeCompletion> vec;
TranslationUnitAST * ast = *m_pSupport->backgroundParser() ->translationUnit( m_activeFileName );
m_pSupport->backgroundParser() ->unlock();
if ( !ast ) {
kdDebug( 9007 ) << "background-parser is missing the translation-unit. The file needs to be reparsed." << endl;
m_pSupport->parseFileAndDependencies( m_activeFileName, true );
// m_pSupport->mainWindow() ->statusBar() ->message( i18n( "Background-parser is missing the necessary translation-unit. It will be computed, but this completion will fail." ).tqarg( m_activeFileName ), 2000 );
return;
} else {
computeRecoveryPointsLocked();
}
if ( this->d->recoveryPoints.isEmpty() ) {
kdDebug( 9007 ) << "Failed to compute recovery-points for " << m_activeFileName << endl;
// m_pSupport->mainWindow() ->statusBar() ->message( i18n( "Failed to compute recovery-points for %1" ).tqarg( m_activeFileName ), 1000 );
} else {
kdDebug( 9007 ) << "successfully computed recovery-points for " << m_activeFileName << endl;
}
}
}
EvaluationResult CppCodeCompletion::evaluateExpressionType( int line, int column, SimpleTypeConfiguration& conf, EvaluateExpressionOptions opt ) {
EvaluationResult ret;
safetyCounter.init();
FileDom file = m_pSupport->codeModel() ->fileByName( m_activeFileName );
if ( !file ) {
// m_pSupport->mainWindow() ->statusBar() ->message( i18n( "File %1 does not exist in the code-model" ).tqarg( m_activeFileName ), 1000 );
kdDebug( 9007 ) << "Error: file " << m_activeFileName << " could not be located in the code-model, code-completion stopped\n";
return SimpleType();
}
needRecoveryPoints();
CodeModelUtils::CodeModelHelper fileModel( m_pSupport->codeModel(), file );
ItemDom contextItem;
int nLine = line, nCol = column;
// emptyCache();
fitContextItem( line, column );
TQString strCurLine = m_activeEditor->textLine( nLine );
TQString ch = strCurLine.mid( nCol - 1, 1 );
TQString ch2 = strCurLine.mid( nCol - 2, 2 );
while ( ch[ 0 ].isSpace() && nCol >= 3 ) {
nCol -= 1;
ch = strCurLine.mid( nCol - 1, 1 );
ch2 = strCurLine.mid( nCol - 2, 2 );
}
if ( ch2 == "->" || ch == "." || ch == "(" ) {
int pos = ch2 == "->" ? nCol - 3 : nCol - 2;
TQChar c = strCurLine[ pos ];
while ( pos > 0 && c.isSpace() )
c = strCurLine[ --pos ];
if ( !( c.isLetterOrNumber() || c == '_' || c == ')' || c == ']' || c == '>' ) ) {
conf.tqinvalidate();
return SimpleType();
}
}
bool showArguments = false;
if ( ch == "(" ) {
--nCol;
while ( nCol > 0 && strCurLine[ nCol ].isSpace() )
--nCol;
showArguments = true;
}
TQString word;
{
ExpressionInfo exp_ = findExpressionAt( line, column , line, 0 );
if( file->parseResult() ) {
ParsedFilePointer p = dynamic_cast<ParsedFile*>( file->parseResult().data());
if( p ) {
if( p->usedMacros().hasMacro( exp_.expr() ) ) {
//It is a macro, return it
ret.expr = exp_.expr();
ret.isMacro = true;
ret.macro = p->usedMacros().macro( exp_.expr() );
return ret;
}
}
}
}
if ( !m_cachedFromContext )
conf.setGlobalNamespace( createGlobalNamespace() );
ItemLocker<BackgroundParser> block( *m_pSupport->backgroundParser() );
FunctionDom currentFunction = fileModel.functionAt( line, column );
bool functionFailed = true;
if ( opt & SearchInFunctions ) {
//currentFunction = fileModel.functionAt( line, column );
if ( currentFunction && functionContains( currentFunction, line, column ) ) {
///Evaluate the context of the function-body if we're in the argument-list
int realLine = line, realColumn = column;
getFunctionBody( currentFunction, realLine, realColumn );
if( realLine < line || ( realLine == line && realColumn < column ) ) {
realLine = line;
realColumn = column;
}
SimpleContext * ctx = computeFunctionContext( currentFunction, realLine, realColumn, conf );
contextItem = currentFunction.data();
if ( ctx ) {
opt = remFlag( opt, SearchInClasses );
int startLine, endLine;
currentFunction->getStartPosition( &startLine, &endLine );
ExpressionInfo exp = findExpressionAt( line, column , startLine, endLine, true );
if ( ( opt & DefaultAsTypeExpression ) && ( !exp.canBeNormalExpression() && !exp.canBeTypeExpression() ) && !exp.expr().isEmpty() )
exp.t = ExpressionInfo::TypeExpression;
if ( exp.canBeTypeExpression() ) {
{
if ( ! ( opt & IncludeTypeExpression ) ) {
kdDebug( 9007 ) << "recognized a type-expression, but another expression-type is desired" << endl;
} else {
TypeDesc d( exp.expr() );
d.setIncludeFiles( getIncludeFiles() );
ret.resultType = ctx->container() ->locateDecType( d );
ret.expr = exp;
}
}
}
if ( /*exp.canBeNormalExpression() &&*/ !ret.resultType->resolved() ) { ///It is not cleary possible to recognize the kind of an expression from the syntax as long as it's not written completely
{
if ( ! ( opt & IncludeStandardExpressions ) ) {
kdDebug( 9007 ) << "recognized a standard-expression, but another expression-type is desired" << endl;
} else {
///Remove the not completely typed last word while normal completion
if ( !showArguments && ( opt & CompletionOption ) ) {
TQString e = exp.expr();
int idx = e.length() - 1;
while ( e[ idx ].isLetterOrNumber() || e[ idx ] == '_' )
--idx;
if ( idx != int( e.length() ) - 1 ) {
++idx;
word = e.mid( idx ).stripWhiteSpace();
exp.setExpr( e.left( idx ).stripWhiteSpace() );
}
}
functionFailed = false;
ret = evaluateExpression( exp, ctx );
}
}
}
} else {
kdDebug( 9007 ) << "could not compute context" << endl;
}
if ( ctx )
delete ctx;
} else {
kdDebug( 9007 ) << "could not find context-function in code-model" << endl;
}
}
if ( ( opt & SearchInClasses ) && !ret->resolved() && functionFailed ) {
ClassDom currentClass = fileModel.classAt( line, column );
int startLine = 0, startCol = 0;
RecoveryPoint* recoveryPoint = this->d->findRecoveryPoint( line, column );
TQStringList scope;
if ( !currentClass ) {
kdDebug( 9007 ) << "no container-class found" << endl;
if ( !recoveryPoint ) {
kdDebug( 9007 ) << "no recovery-point found" << endl;
} else {
startLine = recoveryPoint->startLine;
startCol = recoveryPoint->startColumn;
scope = recoveryPoint->scope;
}
} else {
contextItem = currentClass.data();
scope = currentClass->scope();
scope << currentClass->name();
currentClass->getStartPosition( &startLine, &startCol );
}
SimpleType container;
if ( m_cachedFromContext ) {
TypeDesc d( scope.join( "::" ) );
d.setIncludeFiles( getIncludeFiles() );
SimpleTypeImpl * i = SimpleType( TQStringList(), getIncludeFiles() ) ->locateDecType( d ).desc().resolved().data();
if ( i )
container = i;
else
container = SimpleType( scope, getIncludeFiles() );
} else {
container = SimpleType( scope, getIncludeFiles() );
}
ExpressionInfo exp = findExpressionAt( line, column , startLine, startCol );
exp.t = ExpressionInfo::TypeExpression; ///Outside of functions, we can only handle type-expressions
ret.expr = exp;
if ( exp && ( exp.t & ExpressionInfo::TypeExpression ) ) {
kdDebug( 9007 ) << "locating \"" << exp.expr() << "\" in " << container->fullTypeResolvedWithScope() << endl;
TypeDesc d( exp.expr() );
d.setIncludeFiles( getIncludeFiles() );
ret.resultType = container->locateDecType( d );
} else {
if ( exp ) {
kdDebug( 9007 ) << "wrong expression-type recognized" << endl;
} else {
kdDebug( 9007 ) << "expression could not be recognized" << endl;
}
}
}
CppCodeCompletionConfig * cfg = m_pSupport->codeCompletionConfig();
if( cfg->usePermanentCaching() && contextItem ) {
conf.tqinvalidate();
m_cachedFromContext = contextItem;
}
return ret;
}
bool isAfterKeyword( const TQString& str, int column ) {
TQStringList keywords;
keywords << "new";
keywords << "throw";
keywords << "return";
keywords << "emit"; ///This could be done even better by only showing signals for completion..
for ( TQStringList::iterator it = keywords.begin(); it != keywords.end(); ++it ) {
int len = ( *it ).length();
if ( column >= len && str.mid( column - len, len ) == *it )
return true;
}
return false;
}
void CppCodeCompletion::setMaxComments( int count ) {
m_maxComments = count;
}
///TODO: make this use findExpressionAt etc. (like the other expression-evaluation-stuff)
void CppCodeCompletion::completeText( bool invokedOnDemand /*= false*/ ) {
kdDebug( 9007 ) << "CppCodeCompletion::completeText()" << endl;
clearStatusText();
if ( !m_pSupport || !m_activeCursor || !m_activeEditor || !m_activeCompletion )
return ;
setMaxComments( 1000 );
needRecoveryPoints();
CppCodeCompletionConfig * cfg = m_pSupport->codeCompletionConfig();
m_demandCompletion = invokedOnDemand;
FileDom file = m_pSupport->codeModel() ->fileByName( m_activeFileName );
if ( !file ) {
// m_pSupport->mainWindow() ->statusBar() ->message( i18n( "File %1 does not exist in the code-model" ).tqarg( m_activeFileName ), 1000 );
kdDebug( 9007 ) << "Error: file " << m_activeFileName << " could not be located in the code-model, code-completion stopped\n";
return ;
}
CodeModelUtils::CodeModelHelper fileModel( m_pSupport->codeModel(), file );
ItemDom contextItem;
unsigned int line, column;
m_activeCursor->cursorPositionReal( &line, &column );
fitContextItem( line, column );
///Check whether the cursor is within a comment
int surroundingStartLine = line - 10, surroundingEndLine = line + 10;
if ( surroundingStartLine < 0 )
surroundingStartLine = 0;
if ( surroundingEndLine > m_activeEditor->numLines() - 1 )
surroundingEndLine = m_activeEditor->numLines() - 1;
int surroundingEndCol = m_activeEditor->lineLength( surroundingEndLine );
TQString pre = getText( surroundingStartLine, 0, line, column );
int pos = pre.length();
pre += getText( line, column, surroundingEndLine, surroundingEndCol );
TQString cleared = clearComments( pre );
if ( cleared[ pos ] != pre[ pos ] ) {
kdDebug( 9007 ) << "stopping completion because we're in a coment" << endl;
return ;
}
int nLine = line, nCol = column;
TQString strCurLine = clearComments( m_activeEditor->textLine( nLine ) );
TQString ch = strCurLine.mid( nCol - 1, 1 );
TQString ch2 = strCurLine.mid( nCol - 2, 2 );
while ( ch[ 0 ].isSpace() && nCol >= 3 ) {
nCol -= 1;
ch = strCurLine.mid( nCol - 1, 1 );
ch2 = strCurLine.mid( nCol - 2, 2 );
}
if ( m_includeRx.search( strCurLine ) != -1 ) {
if ( !m_fileEntryList.isEmpty() ) {
m_bCompletionBoxShow = true;
m_activeCompletion->showCompletionBox( m_fileEntryList, column - m_includeRx.matchedLength() );
}
return ;
}
bool showArguments = false;
bool isInstance = true;
m_completionMode = NormalCompletion;
if ( ch2 == "->" || ch == "." || ch == "(" ) {
int pos = ch2 == "->" ? nCol - 3 : nCol - 2;
TQChar c = strCurLine[ pos ];
while ( pos > 0 && c.isSpace() )
c = strCurLine[ --pos ];
if ( !( c.isLetterOrNumber() || c == '_' || c == ')' || c == ']' || c == '>' ) )
return ;
}
if ( ch == "(" ) {
--nCol;
while ( nCol > 0 && strCurLine[ nCol - 1 ].isSpace() )
--nCol;
///check whether it is a value-definition using constructor
int column = nCol;
bool s1 = false, s2 = false;
while ( column > 0 && isValidIdentifierSign( strCurLine[ column - 1 ] ) ) {
column--;
s1 = true;
}
///skip white space
while ( column > 0 && strCurLine[ column - 1 ].isSpace() ) {
--column;
s2 = true;
}
if ( s1 && s2 && isValidIdentifierSign( strCurLine[ column - 1 ] ) ) {
if ( isAfterKeyword( strCurLine, column ) ) {
///Maybe a constructor using "new", or "throw", "return", ...
} else {
///it is a local constructor like "TQString name("David");"
nCol = column;
}
}
showArguments = TRUE;
}
EvaluationResult type;
SimpleType this_type;
TQString expr, word;
DeclarationAST::Node recoveredDecl;
TypeSpecifierAST::Node recoveredTypeSpec;
SimpleContext* ctx = 0;
SimpleTypeConfiguration conf( m_activeFileName );
if ( !m_cachedFromContext )
conf.setGlobalNamespace( createGlobalNamespace() );
ItemLocker<BackgroundParser> block( *m_pSupport->backgroundParser() );
FunctionDom currentFunction = fileModel.functionAt( line, column );
RecoveryPoint * recoveryPoint = d->findRecoveryPoint( line, column );
if ( recoveryPoint || currentFunction ) {
contextItem = currentFunction.data();
TQStringList scope;
int startLine, startColumn;
if ( currentFunction ) { ///maybe change the priority of these
kdDebug( 9007 ) << "using code-model for completion" << endl;
currentFunction->getStartPosition( &startLine, &startColumn );
scope = currentFunction->scope();
} else {
kdDebug( 9007 ) << "recovery-point, node-kind = " << nodeTypeToString( recoveryPoint->kind ) << endl;
startLine = recoveryPoint->startLine;
startColumn = recoveryPoint->startColumn;
scope = recoveryPoint->scope;
}
TQString textLine = m_activeEditor->textLine( startLine );
kdDebug( 9007 ) << "startLine = " << textLine << endl;
if ( currentFunction || recoveryPoint->kind == NodeType_FunctionDefinition ) {
TQString textToReparse = clearComments( getText( startLine, startColumn, line, showArguments ? nCol : column ) );
kdDebug( 9007 ) << "-------------> reparse text" << endl << textToReparse << endl
<< "--------------------------------------------" << endl;
Driver d;
Lexer lexer( &d );
macrosToDriver( d, file );
lexer.setSource( textToReparse );
Parser parser( &d, &lexer );
parser.parseDeclaration( recoveredDecl );
/* kdDebug(9007) << "recoveredDecl = " << recoveredDecl.get() << endl;*/
if ( recoveredDecl.get() ) {
bool isFunDef = recoveredDecl->nodeType() == NodeType_FunctionDefinition;
kdDebug( 9007 ) << "is function definition= " << isFunDef << endl;
int endLine, endColumn;
recoveredDecl->getEndPosition( &endLine, &endColumn );
kdDebug( 9007 ) << "endLine = " << endLine << ", endColumn " << endColumn << endl;
/// @todo check end position
if ( isFunDef ) {
FunctionDefinitionAST * def = static_cast<FunctionDefinitionAST*>( recoveredDecl.get() );
/// @todo remove code duplication
TQString contents = textToReparse;
int start_expr = expressionAt( contents, contents.length() );
// kdDebug(9007) << "start_expr = " << start_expr << endl;
if ( start_expr != int( contents.length() ) )
expr = contents.mid( start_expr, contents.length() - start_expr ).stripWhiteSpace();
if ( expr.startsWith( "SIGNAL" ) || expr.startsWith( "SLOT" ) ) {
m_completionMode = expr.startsWith( "SIGNAL" ) ? SignalCompletion : SlotCompletion;
showArguments = false;
int end_expr = start_expr - 1;
while ( end_expr > 0 && contents[ end_expr ].isSpace() )
--end_expr;
if ( contents[ end_expr ] != ',' ) {
expr = TQString();
} else {
start_expr = expressionAt( contents, end_expr );
expr = contents.mid( start_expr, end_expr - start_expr ).stripWhiteSpace();
}
} else {
if ( !showArguments ) {
int idx = expr.length() - 1;
while ( expr[ idx ].isLetterOrNumber() || expr[ idx ] == '_' )
--idx;
if ( idx != int( expr.length() ) - 1 ) {
++idx;
word = expr.mid( idx ).stripWhiteSpace();
expr = expr.left( idx ).stripWhiteSpace();
}
}
}
ctx = computeContext( def, endLine, endColumn, startLine, startColumn );
DeclaratorAST* d = def->initDeclarator() ->declarator();
NameAST* name = d->declaratorId();
TQStringList nested;
TQPtrList<ClassOrNamespaceNameAST> l;
if ( name ) {
l = name->classOrNamespaceNameList();
}
// TQPtrList<ClassOrNamespaceNameAST> l = name->classOrNamespaceNameList();
TQPtrListIterator<ClassOrNamespaceNameAST> nameIt( l );
while ( nameIt.current() ) {
if ( nameIt.current() ->name() ) {
nested << nameIt.current() ->name() ->text();
}
++nameIt;
}
if ( currentFunction ) {
scope = currentFunction->scope();
if ( !scope.isEmpty() ) {
//scope.pop_back();
} else {
kdDebug( 9007 ) << "scope is empty" << endl;
}
if( dynamic_cast<SimpleTypeNamespace*>( SimpleType::globalNamespace().data() ) ) {
SimpleTypeNamespace* globalNs = static_cast <SimpleTypeNamespace*>( SimpleType::globalNamespace().data() );
TQValueList<TQPair<TQString, TQString> > localImports = ctx->imports();
for( TQValueList<TQPair<TQString, TQString> >::const_iterator it = localImports.begin(); it != localImports.end(); ++it )
globalNs->addAliasMap( (*it).first, (*it).second );
}
} else {
scope += nested;
}
if ( !scope.isEmpty() ) {
SimpleType tqparentType;
/*if( !m_cachedFromContext ) {
TypePointer t = createGlobalNamespace();
conf.setGlobalNamespace( t );
SimpleTypeNamespace * n = dynamic_cast<SimpleTypeNamespace*>( t.data() );
if ( !n ) {
TQString str = TQString( "the global namespace was not resolved correctly , real type: " ) + typeid( n ).name() + TQString( " name: " ) + n->scope().join( "::" ) + " scope-size: " + n->scope().count();
kdDebug( 9007 ) << str << endl;
m_pSupport->mainWindow() ->statusBar() ->message( str , 1000 );
} else {
}
this_type = SimpleType(t);
}*/
if ( m_cachedFromContext ) {
TypeDesc d( scope.join( "::" ) );
d.setIncludeFiles( getIncludeFiles() );
SimpleTypeImpl * i = SimpleType( TQStringList(), getIncludeFiles() ) ->locateDecType( d ).desc().resolved().data();
if ( i ) {
tqparentType = i;
} else {
tqparentType = SimpleType( scope, getIncludeFiles() );
}
} else {
tqparentType = SimpleType( scope, getIncludeFiles() );
}
this_type = tqparentType;
this_type->descForEdit().setTotalPointerDepth( 1 );
ctx->setContainer( this_type );
}
///Now locate the local type using the imported namespaces
if ( !scope.isEmpty() ) {
if ( !m_cachedFromContext ) {
TypeDesc td = ctx->container() ->desc();
td.makePrivate();
td.resetResolved( );
td.setIncludeFiles( getIncludeFiles() );
TypePointer tt = ctx->container() ->locateDecType( td, SimpleTypeImpl::LocateBase ) ->resolved();
if ( tt ) {
ctx->setContainer( SimpleType( tt ) );
} else {
kdDebug( 9007 ) << "could not resolve local this-type \"" << td.fullNameChain() << "\"" << endl;
}
}
SimpleType this_type = ctx->container();
this_type->descForEdit().setTotalPointerDepth( 1 );
SimpleVariable var;
var.type = this_type->desc();
var.name = "this";
var.comment = this_type->comment();
ctx->add
( var );
ctx->setContainer( this_type );
}
ExpressionInfo exp( expr );
exp.t = ( ExpressionInfo::Type ) ( ExpressionInfo::NormalExpression | ExpressionInfo::TypeExpression );
type = evaluateExpression( exp, ctx );
}
} else {
kdDebug( 9007 ) << "no valid declaration to recover!!!" << endl;
}
} else if ( recoveryPoint->kind == NodeType_ClassSpecifier ) {
TQString textToReparse = getText( recoveryPoint->startLine, recoveryPoint->startColumn,
recoveryPoint->endLine, recoveryPoint->endColumn, line );
// kdDebug(9007) << "-------------> please reparse only text" << endl << textToReparse << endl
// << "--------------------------------------------" << endl;
Driver d;
Lexer lexer( &d );
macrosToDriver( d, file );
lexer.setSource( textToReparse );
Parser parser( &d, &lexer );
parser.parseClassSpecifier( recoveredTypeSpec );
/* kdDebug(9007) << "recoveredDecl = " << recoveredTypeSpec.get() << endl;*/
if ( recoveredTypeSpec.get() ) {
//ClassSpecifierAST * clazz = static_cast<ClassSpecifierAST*>( recoveredTypeSpec.get() );
TQString keyword = getText( line, 0, line, column ).simplifyWhiteSpace();
kdDebug( 9007 ) << "===========================> keyword is: " << keyword << endl;
if ( keyword == "virtual" ) { /*
BaseClauseAST *baseClause = clazz->baseClause();
if ( baseClause )
{
TQPtrList<BaseSpecifierAST> baseList = baseClause->baseSpecifierList();
TQPtrList<BaseSpecifierAST>::iterator it = baseList.begin();
for ( ; it != baseList.end(); ++it )
type.append( ( *it )->name()->text() );
ctx = new SimpleContext();
showArguments = false;
m_completionMode = VirtualDeclCompletion;
kdDebug(9007) << "------> found virtual keyword for class specifier '"
<< clazz->text() << "'" << endl;
}*/
} else if ( TQString( "virtual" ).tqfind( keyword ) != -1 )
m_blockForKeyword = true;
else
m_blockForKeyword = false;
}
}
}
///@todo is all this necessary?
if ( !recoveredDecl.get() && !recoveredTypeSpec.get() ) {
TranslationUnitAST * ast = *m_pSupport->backgroundParser() ->translationUnit( m_activeFileName );
if ( AST * node = findNodeAt( ast, line, column ) ) {
kdDebug( 9007 ) << "------------------- AST FOUND --------------------" << endl;
kdDebug( 9007 ) << "node-kind = " << nodeTypeToString( node->nodeType() ) << endl;
if ( FunctionDefinitionAST * def = functionDefinition( node ) ) {
kdDebug( 9007 ) << "------> found a function definition" << endl;
int startLine, startColumn;
def->getStartPosition( &startLine, &startColumn );
TQString contents = getText( startLine, startColumn, line, showArguments ? nCol : column );
/// @todo remove code duplication
int start_expr = expressionAt( contents, contents.length() );
// kdDebug(9007) << "start_expr = " << start_expr << endl;
if ( start_expr != int( contents.length() ) )
expr = contents.mid( start_expr, contents.length() - start_expr ).stripWhiteSpace();
if ( expr.startsWith( "SIGNAL" ) || expr.startsWith( "SLOT" ) ) {
m_completionMode = expr.startsWith( "SIGNAL" ) ? SignalCompletion : SlotCompletion;
showArguments = false;
int end_expr = start_expr - 1;
while ( end_expr > 0 && contents[ end_expr ].isSpace() )
--end_expr;
if ( contents[ end_expr ] != ',' ) {
expr = TQString();
} else {
start_expr = expressionAt( contents, end_expr );
expr = contents.mid( start_expr, end_expr - start_expr ).stripWhiteSpace();
}
} else {
int idx = expr.length() - 1;
while ( expr[ idx ].isLetterOrNumber() || expr[ idx ] == '_' )
--idx;
if ( idx != int( expr.length() ) - 1 ) {
++idx;
word = expr.mid( idx ).stripWhiteSpace();
expr = expr.left( idx ).stripWhiteSpace();
}
}
ctx = computeContext( def, line, column, startLine, startColumn );
TQStringList scope;
scopeOfNode( def, scope );
this_type = SimpleType( scope, getIncludeFiles() );
if ( scope.size() ) { /*
SimpleVariable var;
var.type = scope;
var.name = "this";
ctx->add( var );*/
//kdDebug(9007) << "add variable " << var.name << " with type " << var.type << endl;
}
ExpressionInfo exp( expr );
exp.t = ( ExpressionInfo::Type ) ( ExpressionInfo::NormalExpression | ExpressionInfo::TypeExpression );
type = evaluateExpression( exp, ctx );
}
}
}
if ( !ctx )
return ;
if ( ch2 == "::" ) {
TQString str = clearComments( expr );
if ( !str.tqcontains( '.' ) && !str.tqcontains( "->" ) ) ///Necessary, because the expression may also be like user->BaseUser::
isInstance = false;
}
TQString resolutionType = "(resolved)";
if( !type->resolved() ) {
if( BuiltinTypes::isBuiltin( type.resultType ) ) {
resolutionType = "(builtin " + BuiltinTypes::comment( type.resultType ) + ")";
} else {
resolutionType = "(unresolved)";
}
}
kdDebug( 9007 ) << "===========================> type is: " << type->fullNameChain() << resolutionType << endl;
kdDebug( 9007 ) << "===========================> word is: " << word << endl;
if ( !showArguments ) {
TQValueList<CodeCompletionEntry> entryList;
if ( !type && this_type && ( expr.isEmpty() || expr.endsWith( ";" ) ) ) {
bool alwaysIncludeNamespaces = cfg->alwaysIncludeNamespaces();
{
SimpleType t = this_type;
///First, all static data.
bool ready = false;
SafetyCounter cnt( 20 );
int depth = 0;
while ( !ready & cnt ) {
if ( t->scope().isEmpty() ) {
ready = true;
}
if( !t->isNamespace() || invokedOnDemand || alwaysIncludeNamespaces )
computeCompletionEntryList( t, entryList, t->scope(), false, depth );
t = t->tqparent();
depth++;
}
}
{
SimpleType t = this_type;
///Now find non-static(if we have an instance) and global data
bool ready = false;
SafetyCounter cnt( 20 );
int depth = 0;
bool first = true;
while ( !ready & cnt ) {
if ( t->scope().isEmpty() ) {
ready = true;
}
if ( ( (t->isNamespace() && invokedOnDemand) || alwaysIncludeNamespaces ) || ( first && isInstance ) )
computeCompletionEntryList( t, entryList, t->scope(), t->isNamespace() ? true : isInstance, depth );
t = t->tqparent();
depth++;
first = false;
}
}
if( ctx ) computeCompletionEntryList( entryList, ctx, isInstance );
} else if ( type->resolved() && expr.isEmpty() ) {
if( ctx ) computeCompletionEntryList( entryList, ctx, isInstance );
// if ( m_pSupport->codeCompletionConfig() ->includeGlobalFunctions() )
// computeCompletionEntryList( type, entryList, TQStringList(), false );
computeCompletionEntryList( type, entryList, TQStringList(), false );
if ( this_type.scope().size() )
computeCompletionEntryList( this_type, entryList, this_type.scope(), isInstance );
computeCompletionEntryList( type, entryList, type->resolved() ->scope() , isInstance );
} else if ( type->resolved() ) {
if ( type->resolved() )
computeCompletionEntryList( type, entryList, type->resolved() ->scope() , isInstance );
}
TQStringList trueMatches;
if ( invokedOnDemand ) {
// find matching words
TQValueList<CodeCompletionEntry>::Iterator it;
for ( it = entryList.begin(); it != entryList.end(); ++it ) {
if ( ( *it ).text.startsWith( word ) ) {
trueMatches << ( *it ).text;
// if more than one entry matches, abort immediately
if ( trueMatches.size() > 1 )
break;
}
}
}
if ( invokedOnDemand && trueMatches.size() == 1 ) {
// erbsland: get the cursor position now, because m_ccLine and m_ccColumn
// are not set until the first typed char.
unsigned int nLine, nCol;
m_activeCursor->cursorPositionReal( &nLine, &nCol );
// there is only one entry -> complete immediately
m_activeEditor->insertText( nLine, nCol,
trueMatches[ 0 ].right( trueMatches[ 0 ].length() - word.length() ) );
} else if ( entryList.size() ) {
entryList = unique( entryList );
qHeapSort( entryList );
m_bCompletionBoxShow = true;
///Warning: the conversion is only possible because CodeCompletionEntry is binary compatible with KTextEditor::CompletionEntry,
///never change that!
m_activeCompletion->showCompletionBox( *( ( TQValueList<KTextEditor::CompletionEntry>* ) ( &entryList ) ), word.length() );
}
} else {
TQValueList<TQStringList> signatureList;
signatureList = computeSignatureList( type );
TQString methodName = type->name();
///Search for variables with ()-operator in the context
if ( ctx ) {
SimpleVariable var = ctx->findVariable( methodName );
if ( !var.name.isEmpty() ) {
signatureList += computeSignatureList( ctx->container() ->locateDecType( var.type ) );
}
}
///search for fitting methods/classes in the current context
SimpleType t = this_type;
bool ready = false;
SafetyCounter s( 20 );
do {
if ( !t )
ready = true;
TypeDesc d( methodName );
d.setIncludeFiles( getIncludeFiles() );
SimpleType method = t->typeOf( d );
if ( method )
signatureList += computeSignatureList( method );
if ( t )
t = t->tqparent();
} while ( !ready && s );
if ( !signatureList.isEmpty() ) {
//signatureList = unique( signatureList );
//qHeapSort( signatureList );
m_bArgHintShow = true;
m_activeCompletion->showArgHint( unique( signatureList ), "()", "," );
}
}
delete( ctx );
ctx = 0;
if ( cfg->usePermanentCaching() ) {
conf.tqinvalidate();
m_cachedFromContext = contextItem;
}
}
TQValueList<TQStringList> CppCodeCompletion::computeSignatureList( EvaluationResult result ) {
SimpleType type = result;
if ( result.expr.t == ExpressionInfo::TypeExpression ) {
TypeDesc d( result->name() );
d.setIncludeFiles( getIncludeFiles() );
type = type->typeOf( d, SimpleTypeImpl::MemberInfo::Function ); ///Compute the signature of the constructor
}
TQValueList<TQStringList> retList;
SimpleTypeFunctionInterface* f = type->asFunction();
SimpleType currType = type;
if ( !f && !type->isNamespace() ) {
SimpleType t = type->typeOf( TypeDesc("operator ( )"), SimpleTypeImpl::MemberInfo::Function );
if ( t ) {
f = t->asFunction();
currType = t;
}
}
while ( f ) {
TQStringList lst;
TQString sig = buildSignature( currType.get() );
TQString comment = currType->comment();
TQStringList commentList;
if ( m_pSupport->codeCompletionConfig() ->showCommentWithArgumentHint() ) {
if ( !comment.isEmpty() ) {
if ( sig.length() + comment.length() < 130 ) {
sig += ": \"" + currType->comment() + "\"";
} else {
commentList = formatComment( comment );
}
}
}
lst << sig;
lst += commentList;
currType = f->nextFunction();
///Maybe try to apply implicit template-params in this place
retList << lst;
f = currType->asFunction();
}
return retList;
}
void CppCodeCompletion::synchronousParseReady( const TQString& file, ParsedFilePointer unit ) {
if ( file == m_activeFileName ) {
computeRecoveryPoints( unit );
}
}
void CppCodeCompletion::slotCodeModelUpdated( const TQString& fileName ) {
if ( fileName != m_activeFileName || !m_pSupport || !m_activeEditor )
return ;
// m_pSupport->mainWindow() ->statusBar() ->message( i18n( "Current file updated %1" ).tqarg( m_activeFileName ), 1000 );
computeRecoveryPointsLocked();
}
void CppCodeCompletion::slotFileParsed( const TQString& fileName ) {
if ( fileName != m_activeFileName || !m_pSupport || !m_activeEditor )
return ;
// m_pSupport->mainWindow() ->statusBar() ->message( i18n( "Current file parsed %1 (cache emptied)" ).tqarg( m_activeFileName ), 1000 );
emptyCache(); ///The cache has to be emptied, because the code-model changed. @todo Better: Only refresh the code-model(tell all code-model-types to refresh themselves on demand)
computeRecoveryPointsLocked();
}
void CppCodeCompletion::setupCodeInformationRepository( ) {}
SimpleContext* CppCodeCompletion::computeContext( FunctionDefinitionAST * ast, int line, int col, int lineOffset, int colOffset ) {
kdDebug( 9007 ) << "CppCodeCompletion::computeContext() -- main" << endl;
SimpleContext* ctx = new SimpleContext();
if ( ast && ast->initDeclarator() && ast->initDeclarator() ->declarator() ) {
DeclaratorAST * d = ast->initDeclarator() ->declarator();
if ( ParameterDeclarationClauseAST * clause = d->parameterDeclarationClause() ) {
if ( ParameterDeclarationListAST * params = clause->parameterDeclarationList() ) {
TQPtrList<ParameterDeclarationAST> l( params->parameterList() );
TQPtrListIterator<ParameterDeclarationAST> it( l );
while ( it.current() ) {
ParameterDeclarationAST * param = it.current();
++it;
SimpleVariable var;
TQStringList ptrList;
TQPtrList<AST> ptrOpList = param->declarator() ->ptrOpList();
TQPtrList<AST>::iterator it = ptrOpList.begin();
for ( ; it != ptrOpList.end(); ++it ) {
ptrList.append( ( *it ) ->text() );
}
var.ptrList = ptrList;
var.type = param->typeSpec() ->text() + ptrList.join( "" );
var.name = declaratorToString( param->declarator(), TQString(), true );
var.comment = param->comment();
param->getStartPosition( &var.startLine, &var.startCol );
param->getEndPosition( &var.endLine, &var.endCol );
if ( var.type ) {
ctx->add
( var );
//kdDebug(9007) << "add argument " << var.name << " with type " << var.type << endl;
}
}
}
}
}
if ( ast )
computeContext( ctx, ast->functionBody(), line, col );
if ( ctx ) {
ctx->offset( lineOffset, colOffset );
}
return ctx;
}
void CppCodeCompletion::computeContext( SimpleContext*& ctx, StatementAST* stmt, int line, int col ) {
if ( !stmt )
return ;
switch ( stmt->nodeType() ) {
case NodeType_IfStatement:
computeContext( ctx, static_cast<IfStatementAST*>( stmt ), line, col );
break;
case NodeType_WhileStatement:
computeContext( ctx, static_cast<WhileStatementAST*>( stmt ), line, col );
break;
case NodeType_DoStatement:
computeContext( ctx, static_cast<DoStatementAST*>( stmt ), line, col );
break;
case NodeType_ForStatement:
computeContext( ctx, static_cast<ForStatementAST*>( stmt ), line, col );
break;
case NodeType_SwitchStatement:
computeContext( ctx, static_cast<SwitchStatementAST*>( stmt ), line, col );
break;
case NodeType_TryBlockStatement:
computeContext( ctx, static_cast<TryBlockStatementAST*>( stmt ), line, col );
break;
case NodeType_DeclarationStatement:
computeContext( ctx, static_cast<DeclarationStatementAST*>( stmt ), line, col );
break;
case NodeType_StatementList:
computeContext( ctx, static_cast<StatementListAST*>( stmt ), line, col );
break;
case NodeType_ExpressionStatement:
break;
}
}
void CppCodeCompletion::computeContext( SimpleContext*& ctx, StatementListAST* ast, int line, int col ) {
if ( !inContextScope( ast, line, col, false, true ) )
return ;
TQPtrList<StatementAST> l( ast->statementList() );
TQPtrListIterator<StatementAST> it( l );
while ( it.current() ) {
StatementAST * stmt = it.current();
++it;
computeContext( ctx, stmt, line, col );
}
}
void CppCodeCompletion::computeContext( SimpleContext*& ctx, IfStatementAST* ast, int line, int col ) {
if ( !inContextScope( ast, line, col ) )
return ;
computeContext( ctx, ast->condition(), line, col );
computeContext( ctx, ast->statement(), line, col );
computeContext( ctx, ast->elseStatement(), line, col );
}
void CppCodeCompletion::computeContext( SimpleContext*& ctx, ForStatementAST* ast, int line, int col ) {
if ( !inContextScope( ast, line, col ) )
return ;
computeContext( ctx, ast->initStatement(), line, col );
computeContext( ctx, ast->condition(), line, col );
computeContext( ctx, ast->statement(), line, col );
}
void CppCodeCompletion::computeContext( SimpleContext*& ctx, DoStatementAST* ast, int line, int col ) {
if ( !inContextScope( ast, line, col ) )
return ;
//computeContext( ctx, ast->condition(), line, col );
computeContext( ctx, ast->statement(), line, col );
}
void CppCodeCompletion::computeContext( SimpleContext*& ctx, WhileStatementAST* ast, int line, int col ) {
if ( !inContextScope( ast, line, col ) )
return ;
computeContext( ctx, ast->condition(), line, col );
computeContext( ctx, ast->statement(), line, col );
}
void CppCodeCompletion::computeContext( SimpleContext*& ctx, SwitchStatementAST* ast, int line, int col ) {
if ( !inContextScope( ast, line, col ) )
return ;
computeContext( ctx, ast->condition(), line, col );
computeContext( ctx, ast->statement(), line, col );
}
void CppCodeCompletion::computeContext( SimpleContext*& ctx, TryBlockStatementAST* ast, int line, int col ) {
if ( !inContextScope( ast, line, col ) )
return ;
computeContext( ctx, ast->statement(), line, col );
computeContext( ctx, ast->catchStatementList(), line, col );
}
void CppCodeCompletion::computeContext( SimpleContext*& ctx, CatchStatementListAST* ast, int line, int col ) {
/*if ( !inContextScope( ast, line, col, false, true ) )
return;*/
TQPtrList<CatchStatementAST> l( ast->statementList() );
TQPtrListIterator<CatchStatementAST> it( l );
while ( it.current() ) {
CatchStatementAST * stmt = it.current();
++it;
computeContext( ctx, stmt, line, col );
}
}
void CppCodeCompletion::computeContext( SimpleContext*& ctx, CatchStatementAST* ast, int line, int col ) {
if ( !ast->statement() )
return ;
if ( !inContextScope( ast->statement(), line, col ) )
return ;
computeContext( ctx, ast->condition(), line, col );
computeContext( ctx, ast->statement(), line, col );
}
void CppCodeCompletion::computeContext( SimpleContext*& ctx, DeclarationStatementAST* ast, int line, int col ) {
///@todo respect NodeType_Typedef
if( ast->declaration() && ast->declaration() ->nodeType() == NodeType_UsingDirective ) {
UsingDirectiveAST* usingDecl = static_cast<UsingDirectiveAST*>( ast->declaration() );
TQString name;
if( usingDecl->name() ) {
name = usingDecl->name()->text();
if( !name.isNull() )
ctx->addImport( TQPair<TQString, TQString>( "", name ) );
}
}
if( ast->declaration() && ast->declaration() ->nodeType() == NodeType_NamespaceAlias ) {
NamespaceAliasAST* namespaceAlias = static_cast<NamespaceAliasAST*>( ast->declaration() );
TQString name;
if( namespaceAlias ->namespaceName() && namespaceAlias->aliasName() ) {
ctx->addImport( TQPair<TQString, TQString>( namespaceAlias->namespaceName()->text(), namespaceAlias->aliasName()->text() ) );
}
}
if ( !ast->declaration() || ast->declaration() ->nodeType() != NodeType_SimpleDeclaration )
return ;
if ( !inContextScope( ast, line, col, true, false ) )
return ;
SimpleDeclarationAST* simpleDecl = static_cast<SimpleDeclarationAST*>( ast->declaration() );
TypeSpecifierAST* typeSpec = simpleDecl->typeSpec();
InitDeclaratorListAST* initDeclListAST = simpleDecl->initDeclaratorList();
if ( !initDeclListAST )
return ;
TQPtrList<InitDeclaratorAST> l = initDeclListAST->initDeclaratorList();
TQPtrListIterator<InitDeclaratorAST> it( l );
while ( it.current() ) {
DeclaratorAST * d = it.current() ->declarator();
++it;
if ( d->declaratorId() ) {
SimpleVariable var;
TQStringList ptrList;
TQPtrList<AST> ptrOpList = d->ptrOpList();
TQPtrList<AST>::iterator it = ptrOpList.begin();
for ( ; it != ptrOpList.end(); ++it ) {
ptrList.append( ( *it ) ->text() );
}
for( int a = 0; a < d->arrayDimensionList().count(); a++ )
ptrList.append("*");
var.ptrList = ptrList;
var.type = typeSpec->text() + ptrList.join( "" );
var.name = toSimpleName( d->declaratorId() );
var.comment = d->comment();
d->getStartPosition( &var.startLine, &var.startCol );
d->getEndPosition( &var.endLine, &var.endCol );
ctx->add
( var );
//kdDebug(9007) << "add variable " << var.name << " with type " << var.type << endl;
}
}
}
void CppCodeCompletion::computeContext( SimpleContext*& ctx, ConditionAST* ast, int line, int col ) {
if ( !ast->typeSpec() || !ast->declarator() || !ast->declarator() ->declaratorId() )
return ;
if ( !inContextScope( ast, line, col, true, false ) )
return ;
SimpleVariable var;
TQStringList ptrList;
TQPtrList<AST> ptrOpList = ast->declarator() ->ptrOpList();
TQPtrList<AST>::iterator it = ptrOpList.begin();
for ( ; it != ptrOpList.end(); ++it ) {
ptrList.append( ( *it ) ->text() );
}
var.ptrList = ptrList;
var.type = ast->typeSpec() ->text() + ptrList.join( "" );
var.name = toSimpleName( ast->declarator() ->declaratorId() );
var.comment = ast->comment();
ast->getStartPosition( &var.startLine, &var.startCol );
ast->getEndPosition( &var.endLine, &var.endCol );
ctx->add
( var );
//kdDebug(9007) << "add variable " << var.name << " with type " << var.type << endl;
}
bool CppCodeCompletion::inContextScope( AST* ast, int line, int col, bool checkStart, bool checkEnd ) {
int startLine, startColumn;
int endLine, endColumn;
ast->getStartPosition( &startLine, &startColumn );
ast->getEndPosition( &endLine, &endColumn );
// kdDebug(9007) << k_funcinfo << endl;
// kdDebug(9007) << "current char line: " << line << " col: " << col << endl;
//
// kdDebug(9007) << nodeTypeToString( ast->nodeType() )
// << " start line: " << startLine
// << " col: " << startColumn << endl;
// kdDebug(9007) << nodeTypeToString( ast->nodeType() )
// << " end line: " << endLine
// << " col: " << endColumn << endl;
bool start = line > startLine || ( line == startLine && col >= startColumn );
bool end = line < endLine || ( line == endLine && col <= endColumn );
if ( checkStart && checkEnd )
return start && end;
else if ( checkStart )
return start;
else if ( checkEnd )
return end;
return false;
}
FunctionDefinitionAST * CppCodeCompletion::functionDefinition( AST* node ) {
while ( node ) {
if ( node->nodeType() == NodeType_FunctionDefinition )
return static_cast<FunctionDefinitionAST*>( node );
node = node->tqparent();
}
return 0;
}
TQString CppCodeCompletion::getText( int startLine, int startColumn, int endLine, int endColumn, int omitLine ) {
if ( startLine == endLine ) {
TQString textLine = m_activeEditor->textLine( startLine );
return textLine.mid( startColumn, endColumn - startColumn );
}
TQStringList contents;
for ( int line = startLine; line <= endLine; ++line ) {
if ( line == omitLine )
continue;
TQString textLine = m_activeEditor->textLine( line );
if ( line == startLine )
textLine = textLine.mid( startColumn );
if ( line == endLine )
textLine = textLine.left( endColumn );
contents << textLine;
}
return contents.join( "\n" );
}
void CppCodeCompletion::computeRecoveryPointsLocked() {
m_pSupport->backgroundParser() ->lock ()
;
ParsedFilePointer unit = m_pSupport->backgroundParser() ->translationUnit( m_activeFileName );
computeRecoveryPoints( unit );
m_pSupport->backgroundParser() ->unlock();
}
void CppCodeCompletion::computeRecoveryPoints( ParsedFilePointer unit ) {
if ( m_blockForKeyword )
return ;
kdDebug( 9007 ) << "CppCodeCompletion::computeRecoveryPoints" << endl;
d->recoveryPoints.clear();
if ( !unit )
return ;
ComputeRecoveryPoints walker( d->recoveryPoints );
walker.parseTranslationUnit( *unit );
}
TQString codeModelAccessToString( CodeModelItem::Access access ) {
switch ( access ) {
case CodeModelItem::Public:
return "public";
case CodeModelItem::Protected:
return "protected";
case CodeModelItem::Private:
return "private";
default:
return "unknown";
}
}
#define MAXCOMMENTCOLUMNS 45
TQString CppCodeCompletion::commentFromItem( const SimpleType& tqparent, const ItemDom& item ) {
--m_maxComments;
static TQString maxReached = " ";
if( m_maxComments < 0 ) {
return maxReached;
}
TQString ret;
int line, col;
item->getStartPosition( &line, &col );
if ( !tqparent->scope().isEmpty() ) {
ret += "Container: " + tqparent->fullTypeResolvedWithScope();
}
if ( item->isEnum() ) {
ret += "\nKind: Enum";
ret += "\nValues:";
const EnumModel* en = dynamic_cast<const EnumModel*>( item.data() );
if ( en ) {
EnumeratorList values = en->enumeratorList();
for ( EnumeratorList::iterator it = values.begin(); it != values.end(); ++it ) {
ret += "\n " + ( *it ) ->name();
if ( !( *it ) ->value().isEmpty() ) {
ret + " = " + ( *it ) ->value();
}
}
ret += "\n\nAccess: " + codeModelAccessToString( ( CodeModelItem::Access ) en->access() );
} else {}
}
if ( item->isFunction() || item->isFunctionDefinition() ) {
const FunctionModel * f = dynamic_cast<const FunctionModel*>( item.data() );
ret += "\nKind: Function";
if ( f ) {
TQString state;
if ( f->isStatic() )
state += "static ";
if ( f->isVirtual() )
state += "virtual ";
if ( f->isAbstract() )
state += "abstract ";
//if( f->isTemplateable() ) state += "template ";
if ( f->isConstant() )
state += "const ";
if ( f->isSlot() )
state += "slot ";
if ( f->isSignal() )
state += "signal ";
if ( !state.isEmpty() )
ret += "\nModifiers: " + state;
ret += "\nAccess: " + codeModelAccessToString( ( CodeModelItem::Access ) f->access() );
}
}
if ( item->isEnumerator() ) {
const EnumeratorModel * f = dynamic_cast<const EnumeratorModel*>( item.data() );
ret += "\nKind: Enumerator";
if ( f ) {
if ( !f->value().isEmpty() )
ret += "\nValue: " + f->value();
//ret += "\nAccess: " + codeModelAccessToString( f->() );
}
} else {
if ( item->isVariable() ) {
const VariableModel * f = dynamic_cast<const VariableModel*>( item.data() );
if ( f ) {
if ( !f->isEnumeratorVariable() ) {
ret += "\nKind: Variable";
if ( f->isStatic() )
ret += "\nModifiers: static";
} else {
ret += "\nKind: Enumerator";
ret += "\nEnum: " + f->type();
}
ret += "\nAccess: " + codeModelAccessToString( ( CodeModelItem::Access ) f->access() );
}
}
}
if ( item->isTypeAlias() ) {
const TypeAliasModel * t = dynamic_cast<const TypeAliasModel*>( item.data() );
ret += "\nKind: Typedef";
if ( t ) {
ret += "\nType: " + t->type();
LocateResult r = tqparent->locateDecType( t->type() );
if ( r.desc().resolved() )
ret += "\nResolved type: " + r.desc().resolved() ->fullTypeResolvedWithScope();
else
ret += "\nPartially resolved type: " + r.desc().fullNameChain();
}
}
if ( item->isClass() ) {
ret += "\nKind: Class";
}
ret += TQString( "\nFile: %1\nLine: %2 Column: %3" ).tqarg( prepareTextForMenu( item->fileName(), 3, MAXCOMMENTCOLUMNS ).join( "\n" ) ).tqarg( line ).tqarg( col );
if ( !item->comment().isEmpty() )
ret += "\n\n" + prepareTextForMenu( item->comment(), 3, MAXCOMMENTCOLUMNS ).join( "\n" );
return ret;
}
TQString CppCodeCompletion::commentFromTag( const SimpleType& tqparent, Tag& tag ) {
--m_maxComments;
static TQString maxReached = " ";
if( m_maxComments < 0 ) {
return maxReached;
}
int line, col;
tag.getStartPosition( &line, &col );
TQString ret; // = tag.comment();
if ( !tqparent->scope().isEmpty() ) {
ret += "Container: " + tqparent->fullTypeResolvedWithScope();
}
/*
if( tag.kind() == Tag::Kind_Enum ) {
ret += "\nKind: Enum";
ret += "\nValues:";
EnumModel* en = dynamic_cast<EnumModel*>( item.data() );
if( en ) {
EnumeratorList values =en->enumeratorList();
for( EnumeratorList::iterator it = values.begin(); it != values.end(); ++it )
{
ret += "\n " + (*it)->name();
if( !(*it)->value().isEmpty() ) {
ret + " = " + (*it)->value();
}
}
ret += "\n\nAccess: " + codeModelAccessToString( (CodeModelItem::Access)en->access() );
} else {
}
}*/
if ( tag.kind() == Tag::Kind_Function || tag.kind() == Tag::Kind_FunctionDeclaration ) {
CppFunction<Tag> function( tag );
ret += "\nKind: Function";
TQString state;
if ( function.isStatic() )
state += "static ";
if ( function.isVirtual() )
state += "virtual ";
//if( function.isVolatile() ) state += "volatile ";
if ( function.isConst() )
state += "const ";
if ( function.isSlot() )
state += "slot ";
if ( function.isSignal() )
state += "signal ";
if ( !state.isEmpty() )
ret += "\nModifiers: " + state;
ret += "\nAccess: " + TagUtils::accessToString( function.access() );
}
/*if( item->isEnumerator() ) {
EnumeratorModel* f = dynamic_cast<EnumeratorModel*>( item.data() );
ret += "\nKind: Enumerator";
if( f ) {
if( !f->value().isEmpty() )
ret += "\nValue: " + f->value();
//ret += "\nAccess: " + codeModelAccessToString( f->() );
}
} else {
if( item->isVariable() ) {
VariableModel* f = dynamic_cast<VariableModel*>( item.data() );
ret += "\nKind: Variable";
if( f ) {
ret += "\nAccess: " + codeModelAccessToString( (CodeModelItem::Access)f->access() );
}
}
}*/
if ( tag.kind() == Tag::Kind_Enum ) {
CppVariable<Tag> var( tag );
ret += "\nKind: Enum";
}
if ( tag.kind() == Tag::Kind_Enumerator ) {
CppVariable<Tag> var( tag );
ret += "\nKind: Enumerator";
if ( tag.hasAttribute( "enum" ) && tag.attribute( "enum" ).asString() != "int" )
ret += "\nEnum: " + tag.attribute( "enum" ).asString();
}
if ( tag.kind() == Tag::Kind_Variable ) {
CppVariable<Tag> var( tag );
ret += "\nKind: Variable";
if ( var.isStatic() )
ret += "\nModifiers: static";
ret += "\nAccess: " + TagUtils::accessToString( var.access() );
}
if ( tag.kind() == Tag::Kind_Typedef ) {
ret += "\nKind: Typedef";
ret += "\nType: " + tagType( tag );
LocateResult r = tqparent->locateDecType( tagType( tag ) );
if ( r.desc().resolved() )
ret += "\nResolved type: " + r.desc().resolved() ->fullTypeResolvedWithScope();
else
ret += "\nPartially resolved type: " + r.desc().fullNameChain();
}
if ( tag.kind() == Tag::Kind_Class ) {
ret += "\nKind: Class";
}
if ( tag.kind() == Tag::Kind_Struct ) {
ret += "\nKind: Struct";
}
ret += TQString( "\nFile: %1\nLine: %2 Column: %3" ).tqarg( prepareTextForMenu( tag.fileName(), 3, MAXCOMMENTCOLUMNS ).join( "\n" ) ).tqarg( line ).tqarg( col );
if ( !tag.comment().isEmpty() ) {
ret += "\n\n" + prepareTextForMenu( tag.comment(), 20, MAXCOMMENTCOLUMNS ).join( "\n" );
}
return ret;
}
void CppCodeCompletion::computeCompletionEntryList( SimpleType typeR, TQValueList<CodeCompletionEntry>& entryList, const TQStringList& type, SimpleTypeNamespace* ns, std::set<HashedString>& ignore, bool isInstance, int depth ) {
HashedString myName = HashedString( ns->scope().join("::") +"%"+typeid(*ns).name() );
if ( ignore.find( myName ) != ignore.end() )
return ;
ignore.insert( myName );
SimpleTypeNamespace::SlaveList slaves = ns->getSlaves( getIncludeFiles() );
for ( SimpleTypeNamespace::SlaveList::iterator it = slaves.begin(); it != slaves.end(); ++it ) {
SimpleTypeNamespace* nns = dynamic_cast<SimpleTypeNamespace*>( (*it).first.first.resolved().data() );
if ( !nns ) {
if( ( *it ).first.first.resolved() ) computeCompletionEntryList( SimpleType((*it).first.first.resolved()), entryList, ( *it ).first.first.resolved()->scope(), isInstance, depth );
} else {
if( ( *it ).first.first.resolved() ) computeCompletionEntryList( SimpleType(( *it ).first.first.resolved()), entryList, ( *it ).first.first.resolved()->scope(), nns, ignore, isInstance, depth );
}
}
}
void CppCodeCompletion::computeCompletionEntryList( SimpleType typeR, TQValueList< CodeCompletionEntry > & entryList, const TQStringList & type, bool isInstance, int depth ) {
dbgState.setState( disableVerboseForCompletionList );
Debug d( "#cel#" );
if ( !safetyCounter || !d )
return ;
SimpleTypeImpl* m = &( *typeR ) ;
if ( SimpleTypeNamespace * ns = dynamic_cast<SimpleTypeNamespace*>( m ) ) {
std::set<HashedString> ignore;
computeCompletionEntryList( typeR, entryList, type, ns, ignore, isInstance, depth );
} else if ( dynamic_cast<SimpleTypeCodeModel*>( m ) ) {
ItemDom item = ( dynamic_cast<SimpleTypeCodeModel*>( m ) ) ->item();
if ( item )
if ( ClassModel * mod = dynamic_cast<ClassModel*> ( &( *item ) ) )
computeCompletionEntryList( typeR, entryList, ClassDom( mod ) , isInstance, depth );
} else {
TQValueList<Catalog::QueryArgument> args;
TQValueList<Tag> tags;
TQStringList ts = type;
if( !ts.isEmpty() ) {
TQString s = ts.back() + typeR->specialization();
ts.pop_back();
ts.push_back( s );
}
args.clear();
args << Catalog::QueryArgument( "kind", Tag::Kind_FunctionDeclaration )
<< Catalog::QueryArgument( "scope", ts );
tags = m_repository->query( args );
computeCompletionEntryList( typeR, entryList, tags, isInstance, depth );
args.clear();
args << Catalog::QueryArgument( "kind", Tag::Kind_Variable )
<< Catalog::QueryArgument( "scope", ts );
tags = m_repository->query( args );
computeCompletionEntryList( typeR, entryList, tags, isInstance, depth );
if ( !isInstance ) {
args.clear();
args << Catalog::QueryArgument( "kind", Tag::Kind_Enumerator )
<< Catalog::QueryArgument( "scope", ts );
tags = m_repository->query( args );
computeCompletionEntryList( typeR, entryList, tags, isInstance, depth );
args.clear();
args << Catalog::QueryArgument( "kind", Tag::Kind_Enum )
<< Catalog::QueryArgument( "scope", ts );
tags = m_repository->query( args );
computeCompletionEntryList( typeR, entryList, tags, isInstance, depth );
args.clear();
args << Catalog::QueryArgument( "kind", Tag::Kind_Typedef )
<< Catalog::QueryArgument( "scope", ts );
tags = m_repository->query( args );
computeCompletionEntryList( typeR, entryList, tags, isInstance, depth );
args.clear();
args << Catalog::QueryArgument( "kind", Tag::Kind_Class )
<< Catalog::QueryArgument( "scope", ts );
tags = m_repository->query( args );
computeCompletionEntryList( typeR, entryList, tags, isInstance, depth );
args.clear();
args << Catalog::QueryArgument( "kind", Tag::Kind_Struct )
<< Catalog::QueryArgument( "scope", ts );
tags = m_repository->query( args );
computeCompletionEntryList( typeR, entryList, tags, isInstance, depth );
}
args.clear();
args << Catalog::QueryArgument( "kind", Tag::Kind_Base_class );
TQString fullname = type.join( "::" )+typeR->specialization();
/* if( fullname.length() >=2 )
args << Catalog::QueryArgument( "prefix", fullname.left(2) );*/
args << Catalog::QueryArgument( "name", fullname );
TQValueList<LocateResult> tqparents = typeR->getBases( );
for ( TQValueList<LocateResult>::Iterator it = tqparents.begin(); it != tqparents.end(); ++it ) {
if ( !( *it ) ->resolved() )
continue;
SimpleType tp = SimpleType( ( *it ) ->resolved() );
if ( tp )
computeCompletionEntryList( tp, entryList, tp.scope(), isInstance, depth + 1 );
}
}
dbgState.setState( true );
}
void CppCodeCompletion::computeCompletionEntryList( SimpleType type, TQValueList< CodeCompletionEntry > & entryList, TQValueList< Tag > & tags, bool isInstance, int depth ) {
Debug d( "#cel#" );
if ( !safetyCounter || !d )
return ;
TQString className = type->desc().name();
bool isNs = type->isNamespace();
CompTypeProcessor proc( type, m_pSupport->codeCompletionConfig() ->processFunctionArguments() && type->usingTemplates() );
bool resolve = m_pSupport->codeCompletionConfig() ->processPrimaryTypes() && type->usingTemplates();
TQValueList<Tag>::Iterator it = tags.begin();
while ( it != tags.end() ) {
Tag & tag = *it;
++it;
int subSorting = 0;
if ( tag.name().isEmpty() ) {
continue;
} else if ( m_completionMode != NormalCompletion ) {
if ( tag.kind() != Tag::Kind_FunctionDeclaration )
continue;
}
if ( tag.kind() == Tag::Kind_Function || tag.kind() == Tag::Kind_FunctionDeclaration ) {
CppFunction<Tag> info( tag );
if ( m_completionMode == SlotCompletion && !info.isSlot() )
continue;
else if ( m_completionMode == SignalCompletion && !info.isSignal() )
continue;
else if ( m_completionMode == VirtualDeclCompletion && !info.isVirtual() )
continue;
if ( info.isConst() )
subSorting = 1;
if ( info.isSlot() )
subSorting = 2;
if ( info.isSignal() )
subSorting = 3;
if ( info.isVirtual() )
subSorting = 4;
if ( info.isStatic() )
subSorting = 5;
}
CodeCompletionEntry e = CodeInformationRepository::toEntry( tag, m_completionMode, &proc );
TagFlags fl;
fl.flags = tag.flags();
int num = fl.data.access;
TQString str = "public";
if ( num != 0 ) {
str = TagUtils::accessToString( num );
} else {
num = 0;
}
// 0 = protected, 1 = public, 2 = private
if ( str == "public" )
num = 0;
else if ( str == "protected" )
num = 1;
else if ( str == "private" )
num = 2;
int sortPosition = 0;
switch ( tag.kind() ) {
case Tag::Kind_Enum:
sortPosition = 3;
if ( isInstance )
continue;
break;
case Tag::Kind_Enumerator:
sortPosition = 4;
if ( isInstance )
continue;
break;
case Tag::Kind_Struct:
case Tag::Kind_Union:
case Tag::Kind_Class:
sortPosition = 5;
if ( isInstance )
continue;
break;
case Tag::Kind_VariableDeclaration:
case Tag::Kind_Variable:
sortPosition = 2;
if ( !isInstance && !CppVariable<Tag>( tag ).isStatic() && !isNs )
continue;
break;
case Tag::Kind_FunctionDeclaration:
case Tag::Kind_Function:
sortPosition = 1;
if ( !isInstance && !CppFunction<Tag>( tag ).isStatic() && !isNs )
continue;
break;
case Tag::Kind_Typedef:
sortPosition = 6;
if ( isInstance )
continue;
break;
}
e.userdata = TQString( "%1%2%3%4%5" ).tqarg( num ).tqarg( depth ).tqarg( className ).tqarg( sortPosition ).tqarg( subSorting );
if ( m_completionMode != SignalCompletion ) {
if ( !type->isNamespace() ) {
if ( num == 1 )
e.postfix += "; (protected)"; // in " + proc.tqparentType() + ")";
if ( num == 2 )
e.postfix += "; (private)"; // in " + proc.tqparentType() + ")";
}
}
TQString prefix = tagType( tag ).stripWhiteSpace();
if ( tag.kind() == Tag::Kind_Enumerator && tag.hasAttribute( "enum" ) ) {
prefix = tag.attribute( "enum" ).asString();
e.userdata += prefix; ///Sort enumerators together
} else if ( tag.kind() == Tag::Kind_Enum ) {
prefix = "enum";
} else {
if ( tag.kind() == Tag::Kind_FunctionDeclaration || tag.kind() == Tag::Kind_Function || tag.kind() == Tag::Kind_Variable || tag.kind() == Tag::Kind_Typedef ) {
if ( !prefix.isEmpty() && resolve ) {
LocateResult et = type->locateDecType( prefix );
if ( et )
prefix = et->fullNameChain();
}
}
if ( tag.kind() == Tag::Kind_FunctionDeclaration || tag.kind() == Tag::Kind_Function ) {
if ( prefix.isEmpty() ) {
if ( tag.name() == className )
prefix = constructorPrefix;
else if ( tag.name().startsWith( "~" ) )
prefix = destructorPrefix;
}
}
if ( tag.kind() == Tag::Kind_Class || tag.kind() == Tag::Kind_Function )
prefix = "";
}
e.comment = commentFromTag( type, tag );
if ( e.prefix.isEmpty() )
e.prefix = prefix;
else
e.prefix += " " + prefix;
e.prefix = e.prefix.stripWhiteSpace();
e.prefix = stringMult( depth, " " ) + e.prefix.stripWhiteSpace();
e.text = e.text.stripWhiteSpace();
if ( str != "private" )
entryList << e;
}
}
void CppCodeCompletion::computeCompletionEntryList( SimpleType type, TQValueList< CodeCompletionEntry > & entryList, ClassDom klass, bool isInstance, int depth ) {
Debug d( "#cel#" );
if ( !safetyCounter || !d )
return ;
computeCompletionEntryList( type, entryList, klass->functionList(), isInstance, depth );
///Find all function-definitions that have no functions. Those may be inlined functions and need to be treated too.
FunctionDefinitionList definitions = klass->functionDefinitionList();
FunctionList l;
TQStringList classScope = klass->scope();
classScope << klass->name();
for ( FunctionDefinitionList::iterator it = definitions.begin(); it != definitions.end(); ++it ) {
FunctionList fl = klass->functionByName( ( *it ) ->name() );
ArgumentList args = ( *it ) ->argumentList();
if ( !l.isEmpty() ) {
bool matched = false;
for ( FunctionList::iterator it = fl.begin(); it != fl.end(); ++it ) {
ArgumentList fArgs = ( *it ) ->argumentList();
if ( fArgs.count() != args.count() )
continue;
ArgumentList::iterator it = args.begin();
ArgumentList::iterator it2 = fArgs.begin();
bool hit = true;
while ( it != args.end() ) {
if ( ( *it ) ->type() != ( *it2 ) ->type() ) {
hit = false;
break;
}
++it;
++it2;
}
if ( hit ) {
matched = true;
break;
}
}
if ( matched )
continue;
}
///The function-definition belongs to some sub-class
if( (*it)->scope() != classScope && !(*it)->scope().isEmpty() ) continue;
l << ( FunctionModel* ) ( *it ).data();
}
if ( !l.isEmpty() )
computeCompletionEntryList( type, entryList, l, isInstance, depth );
if ( m_completionMode == NormalCompletion )
computeCompletionEntryList( type, entryList, klass->variableList(), isInstance, depth );
if ( !isInstance ) {
computeCompletionEntryList( klass->name(), type, entryList, klass->classList(), isInstance, depth );
computeCompletionEntryList( klass->name(), type, entryList, klass->typeAliasList(), isInstance, depth );
}
TQValueList<LocateResult> tqparents = type->getBases( );
for ( TQValueList<LocateResult>::Iterator it = tqparents.begin(); it != tqparents.end(); ++it ) {
if ( !( *it ) ->resolved() )
continue;
SimpleTypeImpl* i = ( *it ) ->resolved();
computeCompletionEntryList( i, entryList, i->scope(), isInstance, depth + 1 );
/*
SimpleTypeCodeModel* m = dynamic_cast<SimpleTypeCodeModel*> ( i );
if ( m ) {
ItemDom item = m->item();
ClassModel* kl = dynamic_cast<ClassModel*> ( &( *item ) );
if ( kl ) {
computeCompletionEntryList( SimpleType( ( *it ) ->resolved() ), entryList, ClassDom ( kl ), isInstance, depth + 1 );
}
}*/
}
}
void CppCodeCompletion::computeCompletionEntryList( SimpleType type, TQValueList< CodeCompletionEntry > & entryList, NamespaceDom scope, bool isInstance, int depth ) {
Debug d( "#cel#" );
if ( !safetyCounter || !d )
return ;
CppCodeCompletionConfig * cfg = m_pSupport->codeCompletionConfig();
computeCompletionEntryList( type, entryList, ClassDom( scope.data() ), isInstance, depth );
if ( !isInstance )
computeCompletionEntryList( type, entryList, scope->namespaceList(), isInstance, depth );
}
void CppCodeCompletion::computeCompletionEntryList( TQString tqparent, SimpleType type, TQValueList< CodeCompletionEntry > & entryList, const ClassList & lst, bool isInstance, int depth ) {
Debug d( "#cel#" );
if ( !safetyCounter || !d )
return ;
ClassList::ConstIterator it = lst.begin();
while ( it != lst.end() ) {
ClassDom klass = *it;
++it;
CodeCompletionEntry entry;
entry.prefix = "class";
entry.prefix = stringMult( depth, " " ) + entry.prefix.stripWhiteSpace();
entry.text = klass->name();
entry.comment = commentFromItem( type, klass.data() );
if ( isInstance )
continue;
entry.userdata = TQString( "%1%2%3%4%5" ).tqarg( CodeModelItem::Public ).tqarg( depth ).tqarg( tqparent ).tqarg( 6 );
entryList << entry;
// if ( cfg->includeTypes() )
/*{
computeCompletionEntryList( type, entryList, klass->classList(), isInstance, depth );
}*/
}
}
void CppCodeCompletion::computeCompletionEntryList( TQString tqparent, SimpleType type, TQValueList< CodeCompletionEntry > & entryList, const TypeAliasList & lst, bool isInstance, int depth ) {
Debug d( "#cel#" );
if ( !safetyCounter || !d )
return ;
TypeAliasList::ConstIterator it = lst.begin();
while ( it != lst.end() ) {
TypeAliasDom klass = *it;
++it;
CodeCompletionEntry entry;
LocateResult et = type->locateDecType( klass->type() );
if ( et )
entry.prefix = "typedef " + et->fullNameChain();
else
entry.prefix = "typedef " + klass->type();
entry.prefix = stringMult( depth, " " ) + entry.prefix.stripWhiteSpace();
entry.text = klass->name();
entry.comment = commentFromItem( type, klass.data() );
entry.userdata = TQString( "%1%2%3%4%5" ).tqarg( CodeModelItem::Public ).tqarg( depth ).tqarg( tqparent ).tqarg( 5 );
entryList << entry;
}
}
void CppCodeCompletion::computeCompletionEntryList( SimpleType type, TQValueList< CodeCompletionEntry > & entryList, const NamespaceList & lst, bool /*isInstance*/, int depth ) {
Debug d( "#cel#" );
if ( !safetyCounter || !d )
return ;
NamespaceList::ConstIterator it = lst.begin();
while ( it != lst.end() ) {
NamespaceDom scope = *it;
++it;
CodeCompletionEntry entry;
entry.prefix = "namespace";
entry.prefix = stringMult( depth, " " ) + entry.prefix.stripWhiteSpace();
entry.text = scope->name();
entry.comment = commentFromItem( type, scope.data() );
entryList << entry;
}
}
void CppCodeCompletion::computeCompletionEntryList( SimpleType type, TQValueList< CodeCompletionEntry > & entryList, const FunctionList & methods, bool isInstance, int depth ) {
Debug d( "#cel#" );
if ( !safetyCounter || !d )
return ;
TQString className = type->desc().name();
bool isNs = type->isNamespace();
bool resolve = type->usingTemplates() && m_pSupport->codeCompletionConfig() ->processPrimaryTypes();
CompTypeProcessor proc( type, m_pSupport->codeCompletionConfig() ->processFunctionArguments() && type->usingTemplates() );
FunctionList::ConstIterator it = methods.begin();
while ( it != methods.end() ) {
FunctionDom meth = *it;
++it;
if ( isInstance && meth->isStatic() )
continue;
else if ( m_completionMode == SignalCompletion && !meth->isSignal() )
continue;
else if ( m_completionMode == SlotCompletion && !meth->isSlot() )
continue;
else if ( m_completionMode == VirtualDeclCompletion && !meth->isVirtual() )
continue;
if ( !isInstance && !meth->isStatic() && !isNs )
continue;
CodeCompletionEntry entry;
entry.comment = commentFromItem( type, model_cast<ItemDom>( meth ) );
if ( ! resolve ) {
entry.prefix = meth->resultType();
} else {
TQString tt = meth->resultType();
LocateResult t = type->locateDecType( tt );
if ( t ) {
entry.prefix = t->fullNameChain();
} else
entry.prefix = meth->resultType();
}
if ( entry.prefix.isEmpty() && meth->name() == className )
entry.prefix = constructorPrefix;
if ( entry.prefix.isEmpty() && meth->name().startsWith( "~" ) )
entry.prefix = destructorPrefix;
entry.prefix = stringMult( depth, " " ) + entry.prefix.stripWhiteSpace();
TQString text;
ArgumentList args = meth->argumentList();
ArgumentList::Iterator argIt = args.begin();
/*
if ( m_completionMode == VirtualDeclCompletion )
{
//Ideally the type info would be a entry.prefix, but we need them to be
//inserted upon completion so they have to be part of entry.text
entry.text = meth->resultType();
entry.text += " ";
entry.text += meth->name();
}
else*/
entry.text = meth->name();
entry.text += formattedOpeningParenthesis( args.size() == 0 );
while ( argIt != args.end() ) {
ArgumentDom arg = *argIt;
++argIt;
text += proc.processType( arg->type() );
if ( m_completionMode == NormalCompletion ||
m_completionMode == VirtualDeclCompletion )
text += TQString( " " ) + arg->name();
if ( argIt != args.end() )
text += ", ";
}
if ( args.size() == 0 ) {
entry.text += formattedClosingParenthesis( true );
} else {
text += formattedClosingParenthesis( false );
}
int subSorting = 0;
if ( meth->isConstant() )
subSorting = 1;
if ( meth->isSlot() )
subSorting = 2;
if ( meth->isSignal() )
subSorting = 3;
if ( meth->isVirtual() )
subSorting = 4;
if ( meth->isStatic() )
subSorting = 5;
entry.userdata += TQString( "%1%2%3%4%5" ).tqarg( meth->access() ).tqarg( depth ).tqarg( className ).tqarg( 1 ).tqarg( subSorting );
if ( m_completionMode == VirtualDeclCompletion )
entry.text += text + ";";
if ( m_completionMode != NormalCompletion )
entry.text += text;
else
entry.postfix = text;
if ( meth->isConstant() )
entry.postfix += " const";
if ( m_completionMode != SignalCompletion ) {
if ( !type->isNamespace() ) {
if ( meth->access() == CodeModelItem::Protected )
entry.postfix += "; (protected)"; // in " + type->fullType() + ")";
if ( meth->access() == CodeModelItem::Private )
entry.postfix += "; (private)"; // in " + type->fullType() + ")";
}
}
entry.text = entry.text.stripWhiteSpace();
entryList << entry;
}
}
void CppCodeCompletion::computeCompletionEntryList( SimpleType type, TQValueList< CodeCompletionEntry > & entryList, const VariableList & attributes, bool isInstance, int depth ) {
Debug d( "#cel#" );
TQString className = type->desc().name();
bool isNs = type->isNamespace();
if ( !safetyCounter || !d )
return ;
if ( m_completionMode != NormalCompletion )
return ;
bool resolve = type->usingTemplates() && m_pSupport->codeCompletionConfig() ->processPrimaryTypes();
VariableList::ConstIterator it = attributes.begin();
while ( it != attributes.end() ) {
VariableDom attr = *it;
++it;
if ( isInstance && attr->isStatic() )
continue;
if ( !isInstance && !attr->isStatic() && !isNs )
continue;
CodeCompletionEntry entry;
entry.text = attr->name();
entry.comment = commentFromItem( type, model_cast<ItemDom>( attr ) );
entry.userdata += TQString( "%1%2%3%4" ).tqarg( attr->access() ).tqarg( depth ).tqarg( className ).tqarg( 2 );
if ( !attr->isEnumeratorVariable() ) {
if ( ! resolve ) {
entry.prefix = attr->type();
} else {
TQString tt = attr->type();
LocateResult t = type->locateDecType( tt );
//SimpleType t = type->typeOf( attr->name() );
if ( t )
entry.prefix = t->fullNameChain();
else
entry.prefix = attr->type();
}
} else {
entry.prefix = attr->type();
entry.userdata += attr->type(); ///Sort enumerators by their enum
}
if ( attr->access() == CodeModelItem::Protected )
entry.postfix += "; (protected)"; // in " + type->fullType() + ")";
if ( attr->access() == CodeModelItem::Private )
entry.postfix += "; (private)"; // in " + type->fullType() + ")";
entry.prefix = stringMult( depth, " " ) + entry.prefix.stripWhiteSpace();
entryList << entry;
}
}
void CppCodeCompletion::computeCompletionEntryList( TQValueList< CodeCompletionEntry > & entryList, SimpleContext * ctx, bool /*isInstance*/, int depth ) {
Debug d( "#cel#" );
if ( !safetyCounter || !d )
return ;
while ( ctx ) {
TQValueList<SimpleVariable> vars = ctx->vars();
TQValueList<SimpleVariable>::ConstIterator it = vars.begin();
while ( it != vars.end() ) {
const SimpleVariable & var = *it;
++it;
CodeCompletionEntry entry;
entry.prefix = var.type.fullNameChain();
entry.text = var.name;
entry.userdata = "000";
entry.comment = "Local variable";
entryList << entry;
}
ctx = ctx->prev();
}
}
EvaluationResult CppCodeCompletion::evaluateExpression( ExpressionInfo expr, SimpleContext* ctx ) {
safetyCounter.init();
//d->classNameList = typeNameList( m_pSupport->codeModel() );
CppEvaluation::ExpressionEvaluation obj( this, expr, AllOperators, getIncludeFiles(), ctx );
EvaluationResult res;
res = obj.evaluate();
TQString resolutionType = "(resolved)";
if( !res->resolved() ) {
if( BuiltinTypes::isBuiltin( res.resultType ) ) {
resolutionType = "(builtin " + BuiltinTypes::comment( res.resultType ) + ")";
} else {
resolutionType = "(unresolved)";
}
}
addStatusText( i18n( "Type of \"%1\" is \"%2\", %3" ).tqarg( expr.expr() ).tqarg( res->fullNameChain() ).tqarg( resolutionType ), 5000 );
return res;
}
void CppCodeCompletion::computeFileEntryList( ) {
m_fileEntryList.clear();
TQStringList fileList = m_pSupport->project() ->allFiles();
for ( TQStringList::Iterator it = fileList.begin(); it != fileList.end(); ++it ) {
if ( !m_pSupport->isHeader( *it ) )
continue;
CodeCompletionEntry entry;
entry.text = TQFileInfo( *it ).fileName();
m_fileEntryList.push_back( entry );
}
m_fileEntryList = unique( m_fileEntryList );
}
HashedStringSet CppCodeCompletion::getIncludeFiles( const TQString& fi ) {
TQString file = fi;
if( file.isEmpty() )
file = m_activeFileName;
FileDom f = m_pSupport->codeModel() ->fileByName( file );
if( f ) {
ParseResultPointer p = f->parseResult();
if( p ) {
ParsedFilePointer pp = dynamic_cast<ParsedFile*>( p.data() );
if( pp ) {
return pp->includeFiles();
}
}
}
return HashedStringSet();
}
void CppCodeCompletion::slotJumpToDeclCursorContext()
{
kdDebug(9007) << k_funcinfo << endl;
jumpCursorContext( Declaration );
}
void CppCodeCompletion::slotJumpToDefCursorContext()
{
kdDebug(9007) << k_funcinfo << endl;
jumpCursorContext( Definition );
}
void CppCodeCompletion::jumpCursorContext( FunctionType f )
{
if ( !m_activeCursor ) return;
SimpleTypeConfiguration conf( m_activeFileName );
unsigned int line;
unsigned int column;
m_activeCursor->cursorPositionReal( &line, &column );
EvaluationResult result = evaluateExpressionAt( line, column, conf );
// Determine the declaration info based on the type of item we are dealing with.
DeclarationInfo d;
TQString includeFileName, includeFilePath;
bool unused;
if ( result.isMacro ) {
d.name = result.macro.name();
d.file = result.macro.fileName();
d.startLine = d.endLine = result.macro.line();
d.startCol = d.endCol = result.macro.column();
} else if ( getIncludeInfo( line, includeFileName, includeFilePath, unused ) ) {
d.name = includeFileName;
d.file = includeFilePath;
} else {
d = result.sourceVariable;
}
if ( !d ) {
LocateResult type = result.resultType;
if ( type && type->resolved() ) {
// Is it a namespace?
if ( type->resolved()->isNamespace() ) {
SimpleTypeCachedNamespace * ns = dynamic_cast<SimpleTypeCachedNamespace*>( type->resolved().data() );
if ( ns ) {
SimpleTypeNamespace::SlaveList slaves = ns->getSlaves( getIncludeFiles() );
if ( slaves.begin() != slaves.end() ) {
SimpleTypeCachedCodeModel * item = dynamic_cast<SimpleTypeCachedCodeModel*>( ( *slaves.begin() ).first.first.resolved().data() );
if ( item && item->item() && item->item()->isNamespace() ) {
NamespaceModel* ns = dynamic_cast<NamespaceModel*>( item->item().data() );
TQStringList wholeScope = ns->scope();
wholeScope << ns->name();
FileList files = cppSupport()->codeModel()->fileList();
for ( FileList::iterator it = files.begin(); it != files.end(); ++it ) {
NamespaceModel* ns = (*it).data();
for ( TQStringList::iterator it2 = wholeScope.begin(); it2 != wholeScope.end(); ++it2 ) {
if ( ns->hasNamespace( (*it2) ) ) {
ns = ns->namespaceByName( *it2 );
if ( !ns ) break;
} else {
ns = 0;
break;
}
}
if ( ns ) {
d.name = ns->name();
ns->getStartPosition( &d.startLine, &d.startCol );
ns->getEndPosition( &d.endLine, &d.endCol );
d.file = ns->fileName();
break;
}
}
}
}
}
} else {
// Not a namespace, we can get the declaration info straight from the type description.
d = type->resolved()->getDeclarationInfo();
}
}
// Unresolved, maybe its a named enumeration?
else if ( type && type.trace() ) {
TQValueList< TQPair<SimpleTypeImpl::MemberInfo, TypeDesc> > trace = type.trace()->trace();
if ( !trace.isEmpty() ) {
if ( trace.begin() != trace.end() ) {
d = ( *trace.begin() ).first.decl;
}
}
}
}
if ( d ) {
TQString fileName = d.file == "current_file" ? m_activeFileName : d.file.operator TQString();
if ( f == Definition && cppSupport()->switchHeaderImpl( fileName, d.startLine, d.startCol ) )
return;
cppSupport()->partController()->editDocument( fileName, d.startLine );
}
}
TQString CppCodeCompletion::createTypeInfoString( int line, int column )
{
TQString typeInfoString;
SimpleTypeConfiguration conf( m_activeFileName );
EvaluationResult type = evaluateExpressionAt( line, column, conf );
if ( type.expr.expr().stripWhiteSpace().isEmpty() )
return typeInfoString;
typeInfoString += type.expr.expr() + TQString(" : " );
if ( type->resolved() )
{
TQString scope = type->resolved()->scope().join("::");
int pos = scope.tqfindRev("::");
if ( scope.isEmpty() || pos == -1 )
{
scope = "::";
}
else
{
scope.truncate( pos + 2 );
}
typeInfoString += scope + type->fullNameChain() + TQString( i18n(" (resolved) ") );
}
else
{
if ( type )
{
if( !BuiltinTypes::isBuiltin( type.resultType ) )
{
typeInfoString += type->fullNameChain() + TQString( i18n(" (unresolved) ") );
}
else
{
typeInfoString += type->fullNameChain() + ", " + BuiltinTypes::comment( type.resultType ) + TQString( i18n(" (builtin type) ") );
}
}
else
{
typeInfoString += TQString( i18n(" (unresolved) ") );
}
}
if( cppSupport() && type->resolved() && cppSupport()->codeCompletionConfig()->preProcessAllHeaders() ) {
DeclarationInfo decl = type->resolved()->getDeclarationInfo();
if( !getIncludeFiles()[ HashedString( decl.file ) ] ) {
typeInfoString += " [header not included] ";
}
}
return typeInfoString;
}
bool CppCodeCompletion::getIncludeInfo( int line, TQString& includeFileName, TQString& includeFilePath, bool& usedProjectFiles )
{
bool isIncludeDirective = false;
TQString lineText = getText( line, 0, line+1, 0 );
TQRegExp includeRx( "(?:#include[\\s]*(?:\\\"|\\<))([^\\n]*)(\\\"|\\>)" );
if( includeRx.search( lineText ) != -1 ) {
//It is an include-directive. The regular expression captures the string, and the closing sign('"' or '>').
isIncludeDirective = true;
usedProjectFiles = false;
TQStringList captured = includeRx.tqcapturedTexts();
if( captured.size() == 3 ) {
Dependence d;
d.first = captured[1];
d.second = captured[2] == "\"" ? Dep_Local : Dep_Global;
includeFilePath = cppSupport()->driver()->findIncludeFile( d, activeFileName() );
if( includeFilePath.isEmpty() ) {
//A simple backup-algorithm that can only find files within the same project
includeFilePath = cppSupport()->findHeaderSimple( d.first );
usedProjectFiles = true;
}
includeFileName = d.first;
} else {
kdDebug( 9007 ) << "wrong count of captured items" << endl;
}
}
return isIncludeDirective;
}
#include "cppcodecompletion.moc"
//kate: indent-mode csands; tab-width 2; space-indent off;
|