aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/cppeditor/quickfixes/cppcodegenerationquickfixes.cpp
blob: 4ecd29d734a8834f94e169e6a9a77d09da7d96a4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
// Copyright (C) 2024 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "cppcodegenerationquickfixes.h"

#include "../cppcodestylesettings.h"
#include "../cppeditortr.h"
#include "../cpprefactoringchanges.h"
#include "../insertionpointlocator.h"
#include "cppquickfix.h"
#include "cppquickfixhelpers.h"
#include "cppquickfixprojectsettings.h"
#include "cppquickfixsettings.h"

#include <cplusplus/Overview.h>
#include <cplusplus/CppRewriter.h>
#include <projectexplorer/projecttree.h>
#include <utils/basetreeview.h>
#include <utils/treemodel.h>

#include <QApplication>
#include <QCheckBox>
#include <QDialog>
#include <QDialogButtonBox>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QMimeData>
#include <QPushButton>
#include <QProxyStyle>
#include <QStyledItemDelegate>
#include <QTableView>
#include <QTreeView>

#ifdef WITH_TESTS
#include "cppquickfix_test.h"
#include <QAbstractItemModelTester>
#include <QTest>
#endif

using namespace CPlusPlus;
using namespace ProjectExplorer;
using namespace TextEditor;
using namespace Utils;

namespace CppEditor::Internal {
namespace {

static QStringList toStringList(const QList<Symbol *> names)
{
    QStringList list;
    list.reserve(names.size());
    for (const auto symbol : names) {
        const Identifier *const id = symbol->identifier();
        list << QString::fromUtf8(id->chars(), id->size());
    }
    return list;
}

static QList<Symbol *> getMemberFunctions(const Class *clazz)
{
    QList<Symbol *> memberFunctions;
    for (auto it = clazz->memberBegin(); it != clazz->memberEnd(); ++it) {
        Symbol *const s = *it;
        if (!s->identifier() || !s->type())
            continue;
        if ((s->asDeclaration() && s->type()->asFunctionType()) || s->asFunction())
            memberFunctions << s;
    }
    return memberFunctions;
}

static QString symbolAtDifferentLocation(
    const CppQuickFixInterface &interface,
    Symbol *symbol,
    const CppRefactoringFilePtr &targetFile,
    InsertionLocation targetLocation)
{
    QTC_ASSERT(symbol, return QString());
    Scope *scopeAtInsertPos = targetFile->cppDocument()->scopeAt(targetLocation.line(),
                                                                 targetLocation.column());

    LookupContext cppContext(targetFile->cppDocument(), interface.snapshot());
    ClassOrNamespace *cppCoN = cppContext.lookupType(scopeAtInsertPos);
    if (!cppCoN)
        cppCoN = cppContext.globalNamespace();
    SubstitutionEnvironment env;
    env.setContext(interface.context());
    env.switchScope(symbol->enclosingScope());
    UseMinimalNames q(cppCoN);
    env.enter(&q);
    Control *control = interface.context().bindings()->control().get();
    Overview oo = CppCodeStyleSettings::currentProjectCodeStyleOverview();
    return oo.prettyName(LookupContext::minimalName(symbol, cppCoN, control));
}

static FullySpecifiedType typeAtDifferentLocation(
    const CppQuickFixInterface &interface,
    FullySpecifiedType type,
    Scope *originalScope,
    const CppRefactoringFilePtr &targetFile,
    InsertionLocation targetLocation,
    const QStringList &newNamespaceNamesAtLoc = {})
{
    Scope *scopeAtInsertPos = targetFile->cppDocument()->scopeAt(targetLocation.line(),
                                                                 targetLocation.column());
    for (const QString &nsName : newNamespaceNamesAtLoc) {
        const QByteArray utf8Name = nsName.toUtf8();
        Control *control = targetFile->cppDocument()->control();
        const Name *name = control->identifier(utf8Name.data(), utf8Name.size());
        Namespace *ns = control->newNamespace(0, name);
        ns->setEnclosingScope(scopeAtInsertPos);
        scopeAtInsertPos = ns;
    }
    LookupContext cppContext(targetFile->cppDocument(), interface.snapshot());
    ClassOrNamespace *cppCoN = cppContext.lookupType(scopeAtInsertPos);
    if (!cppCoN)
        cppCoN = cppContext.globalNamespace();
    SubstitutionEnvironment env;
    env.setContext(interface.context());
    env.switchScope(originalScope);
    UseMinimalNames q(cppCoN);
    env.enter(&q);
    Control *control = interface.context().bindings()->control().get();
    return rewriteType(type, &env, control);
}

static std::optional<FullySpecifiedType> getFirstTemplateParameter(const Name *name)
{
    if (const QualifiedNameId *qualifiedName = name->asQualifiedNameId())
        return getFirstTemplateParameter(qualifiedName->name());

    if (const TemplateNameId *templateName = name->asTemplateNameId()) {
        if (templateName->templateArgumentCount() > 0)
            return templateName->templateArgumentAt(0).type();
    }
    return {};
}

static std::optional<FullySpecifiedType> getFirstTemplateParameter(Type *type)
{
    if (NamedType *namedType = type->asNamedType())
        return getFirstTemplateParameter(namedType->name());

    return {};
}

static std::optional<FullySpecifiedType> getFirstTemplateParameter(FullySpecifiedType type)
{
    return getFirstTemplateParameter(type.type());
}

struct ExistingGetterSetterData
{
    Class *clazz = nullptr;
    Declaration *declarationSymbol = nullptr;
    QString getterName;
    QString setterName;
    QString resetName;
    QString signalName;
    QString qPropertyName;
    QString memberVariableName;
    Document::Ptr doc;

    int computePossibleFlags() const;
};

// FIXME: Should be a member?
static void findExistingFunctions(ExistingGetterSetterData &existing, QStringList memberFunctionNames)
{
    const CppQuickFixSettings *settings = CppQuickFixProjectsSettings::getQuickFixSettings(
        ProjectExplorer::ProjectTree::currentProject());
    const QString lowerBaseName = CppQuickFixSettings::memberBaseName(existing.memberVariableName).toLower();
    const QStringList getterNames{lowerBaseName,
                                  "get_" + lowerBaseName,
                                  "get" + lowerBaseName,
                                  "is_" + lowerBaseName,
                                  "is" + lowerBaseName,
                                  settings->getGetterName(lowerBaseName, existing.memberVariableName)};
    const QStringList setterNames{"set_" + lowerBaseName,
                                  "set" + lowerBaseName,
                                  settings->getSetterName(lowerBaseName, existing.memberVariableName)};
    const QStringList resetNames{"reset_" + lowerBaseName,
                                 "reset" + lowerBaseName,
                                 settings->getResetName(lowerBaseName, existing.memberVariableName)};
    const QStringList signalNames{lowerBaseName + "_changed",
                                  lowerBaseName + "changed",
                                  settings->getSignalName(lowerBaseName, existing.memberVariableName)};
    for (const auto &memberFunctionName : memberFunctionNames) {
        const QString lowerName = memberFunctionName.toLower();
        if (getterNames.contains(lowerName))
            existing.getterName = memberFunctionName;
        else if (setterNames.contains(lowerName))
            existing.setterName = memberFunctionName;
        else if (resetNames.contains(lowerName))
            existing.resetName = memberFunctionName;
        else if (signalNames.contains(lowerName))
            existing.signalName = memberFunctionName;
    }
}

static void extractNames(const CppRefactoringFilePtr &file,
                  QtPropertyDeclarationAST *qtPropertyDeclaration,
                  ExistingGetterSetterData &data)
{
    QtPropertyDeclarationItemListAST *it = qtPropertyDeclaration->property_declaration_item_list;
    for (; it; it = it->next) {
        const char *tokenString = file->tokenAt(it->value->item_name_token).spell();
        if (!qstrcmp(tokenString, "READ")) {
            data.getterName = file->textOf(it->value->expression);
        } else if (!qstrcmp(tokenString, "WRITE")) {
            data.setterName = file->textOf(it->value->expression);
        } else if (!qstrcmp(tokenString, "RESET")) {
            data.resetName = file->textOf(it->value->expression);
        } else if (!qstrcmp(tokenString, "NOTIFY")) {
            data.signalName = file->textOf(it->value->expression);
        } else if (!qstrcmp(tokenString, "MEMBER")) {
            data.memberVariableName = file->textOf(it->value->expression);
        }
    }
}

class GetterSetterRefactoringHelper
{
public:
    GetterSetterRefactoringHelper(CppQuickFixOperation *operation, Class *clazz)
        : m_operation(operation)
        , m_changes(m_operation->snapshot())
        , m_locator(m_changes)
        , m_headerFile(operation->currentFile())
        , m_sourceFile([&] {
            FilePath cppFilePath = correspondingHeaderOrSource(m_headerFile->filePath(),
                                                               &m_isHeaderHeaderFile);
            if (!m_isHeaderHeaderFile || !cppFilePath.exists()) {
                // there is no "source" file
                return m_headerFile;
            } else {
                return m_changes.cppFile(cppFilePath);
            }
        }())
        , m_class(clazz)
    {}

    void performGeneration(ExistingGetterSetterData data, int generationFlags);

    void applyChanges()
    {
        const auto classLayout = {
            InsertionPointLocator::Public,
            InsertionPointLocator::PublicSlot,
            InsertionPointLocator::Signals,
            InsertionPointLocator::Protected,
            InsertionPointLocator::ProtectedSlot,
            InsertionPointLocator::PrivateSlot,
            InsertionPointLocator::Private,
        };
        for (auto spec : classLayout) {
            const auto iter = m_headerFileCode.find(spec);
            if (iter != m_headerFileCode.end()) {
                const InsertionLocation loc = headerLocationFor(spec);
                m_headerFile->setOpenEditor(true, m_headerFile->position(loc.line(), loc.column()));
                insertAndIndent(m_headerFile, loc, *iter);
            }
        }
        if (!m_sourceFileCode.isEmpty() && m_sourceFileInsertionPoint.isValid()) {
            m_sourceFile->setOpenEditor(true, m_sourceFile->position(
                                                  m_sourceFileInsertionPoint.line(),
                                                  m_sourceFileInsertionPoint.column()));
            insertAndIndent(m_sourceFile, m_sourceFileInsertionPoint, m_sourceFileCode);
        }

        m_headerFile->apply(m_headerFileChangeSet);
        m_sourceFile->apply(m_sourceFileChangeSet);
    }

    bool hasSourceFile() const { return m_headerFile != m_sourceFile; }

protected:
    void insertAndIndent(const RefactoringFilePtr &file,
                         const InsertionLocation &loc,
                         const QString &text)
    {
        int targetPosition = file->position(loc.line(), loc.column());
        ChangeSet &changeSet = file == m_headerFile ? m_headerFileChangeSet : m_sourceFileChangeSet;
        changeSet.insert(targetPosition, loc.prefix() + text + loc.suffix());
    }

    FullySpecifiedType makeConstRef(FullySpecifiedType type)
    {
        type.setConst(true);
        return m_operation->currentFile()->cppDocument()->control()->referenceType(type, false);
    }

    FullySpecifiedType addConstToReference(FullySpecifiedType type)
    {
        if (ReferenceType *ref = type.type()->asReferenceType()) {
            FullySpecifiedType elemType = ref->elementType();
            if (elemType.isConst())
                return type;
            elemType.setConst(true);
            return m_operation->currentFile()->cppDocument()->control()->referenceType(elemType,
                                                                                       false);
        }
        return type;
    }

    QString symbolAt(Symbol *symbol,
                     const CppRefactoringFilePtr &targetFile,
                     InsertionLocation targetLocation)
    {
        return symbolAtDifferentLocation(*m_operation, symbol, targetFile, targetLocation);
    }

    FullySpecifiedType typeAt(FullySpecifiedType type,
                              Scope *originalScope,
                              const CppRefactoringFilePtr &targetFile,
                              InsertionLocation targetLocation,
                              const QStringList &newNamespaceNamesAtLoc = {})
    {
        return typeAtDifferentLocation(*m_operation,
                                       type,
                                       originalScope,
                                       targetFile,
                                       targetLocation,
                                       newNamespaceNamesAtLoc);
    }

    /**
     * @brief checks if the type in the enclosing scope in the header is a value type
     * @param type a type in the m_headerFile
     * @param enclosingScope the enclosing scope
     * @param customValueType if not nullptr set to true when value type comes
     * from CppQuickFixSettings::isValueType
     * @return true if it is a pointer, enum, integer, floating point, reference, custom value type
     */
    bool isValueType(FullySpecifiedType type, Scope *enclosingScope, bool *customValueType = nullptr)
    {
        if (customValueType)
            *customValueType = false;
        // a type is a value type if it is one of the following
        const auto isTypeValueType = [](const FullySpecifiedType &t) {
            return t->asPointerType() || t->asEnumType() || t->asIntegerType() || t->asFloatType()
                   || t->asReferenceType();
        };
        if (type->asNamedType()) {
            // we need a recursive search and a lookup context
            LookupContext context(m_headerFile->cppDocument(), m_changes.snapshot());
            auto isValueType = [settings = m_settings,
                                &customValueType,
                                &context,
                                &isTypeValueType](const Name *name,
                                                  Scope *scope,
                                                  auto &isValueType) {
                // maybe the type is a custom value type by name
                if (const Identifier *id = name->identifier()) {
                    if (settings->isValueType(QString::fromUtf8(id->chars(), id->size()))) {
                        if (customValueType)
                            *customValueType = true;
                        return true;
                    }
                }
                // search for the type declaration
                QList<LookupItem> localLookup = context.lookup(name, scope);
                for (auto &&i : localLookup) {
                    if (isTypeValueType(i.type()))
                        return true;
                    if (i.type()->asNamedType()) { // check if we have to search recursively
                        const Name *newName = i.type()->asNamedType()->name();
                        Scope *newScope = i.declaration()->enclosingScope();
                        if (Matcher::match(newName, name)
                            && Matcher::match(newScope->name(), scope->name())) {
                            continue; // we have found the start location of the search
                        }
                        return isValueType(newName, newScope, isValueType);
                    }
                    return false;
                }
                return false;
            };
            // start recursion
            return isValueType(type->asNamedType()->name(), enclosingScope, isValueType);
        }
        return isTypeValueType(type);
    }

    bool isValueType(Symbol *symbol, bool *customValueType = nullptr)
    {
        return isValueType(symbol->type(), symbol->enclosingScope(), customValueType);
    }

    void addHeaderCode(InsertionPointLocator::AccessSpec spec, QString code)
    {
        QString &existing = m_headerFileCode[spec];
        existing += code;
        if (!existing.endsWith('\n'))
            existing += '\n';
    }

    InsertionLocation headerLocationFor(InsertionPointLocator::AccessSpec spec)
    {
        const auto insertionPoint = m_headerInsertionPoints.find(spec);
        if (insertionPoint != m_headerInsertionPoints.end())
            return *insertionPoint;
        const InsertionLocation loc = m_locator.methodDeclarationInClass(
            m_headerFile->filePath(), m_class, spec,
            InsertionPointLocator::ForceAccessSpec::Yes);
        m_headerInsertionPoints.insert(spec, loc);
        return loc;
    }

    InsertionLocation sourceLocationFor(Symbol *symbol, QStringList *insertedNamespaces = nullptr)
    {
        if (m_sourceFileInsertionPoint.isValid())
            return m_sourceFileInsertionPoint;
        m_sourceFileInsertionPoint
            = insertLocationForMethodDefinition(symbol,
                                                false,
                                                m_settings->createMissingNamespacesinCppFile()
                                                    ? NamespaceHandling::CreateMissing
                                                    : NamespaceHandling::Ignore,
                                                m_changes,
                                                m_sourceFile->filePath(),
                                                insertedNamespaces);
        if (m_settings->addUsingNamespaceinCppFile()) {
            // check if we have to insert a using namespace ...
            auto requiredNamespaces = getNamespaceNames(
                symbol->asClass() ? symbol : symbol->enclosingClass());
            NSCheckerVisitor visitor(m_sourceFile.get(),
                                     requiredNamespaces,
                                     m_sourceFile->position(m_sourceFileInsertionPoint.line(),
                                                            m_sourceFileInsertionPoint.column()));
            visitor.accept(m_sourceFile->cppDocument()->translationUnit()->ast());
            if (insertedNamespaces)
                insertedNamespaces->clear();
            if (auto rns = visitor.remainingNamespaces(); !rns.empty()) {
                QString ns = "using namespace ";
                for (auto &n : rns) {
                    if (!n.isEmpty()) { // we have to ignore unnamed namespaces
                        ns += n;
                        ns += "::";
                        if (insertedNamespaces)
                            insertedNamespaces->append(n);
                    }
                }
                ns.resize(ns.size() - 2); // remove last '::'
                ns += ";\n";
                const auto &loc = m_sourceFileInsertionPoint;
                m_sourceFileInsertionPoint = InsertionLocation(loc.filePath(),
                                                               loc.prefix() + ns,
                                                               loc.suffix(),
                                                               loc.line(),
                                                               loc.column());
            }
        }
        return m_sourceFileInsertionPoint;
    }

    void addSourceFileCode(QString code)
    {
        while (!m_sourceFileCode.isEmpty() && !m_sourceFileCode.endsWith("\n\n"))
            m_sourceFileCode += '\n';
        m_sourceFileCode += code;
    }

protected:
    CppQuickFixOperation *const m_operation;
    const CppRefactoringChanges m_changes;
    const InsertionPointLocator m_locator;
    const CppRefactoringFilePtr m_headerFile;
    bool m_isHeaderHeaderFile = false; // the "header" (where the class is defined) can be a source file
    const CppRefactoringFilePtr m_sourceFile;
    CppQuickFixSettings *const m_settings = CppQuickFixProjectsSettings::getQuickFixSettings(
        ProjectTree::currentProject());
    Class *const m_class;

private:
    ChangeSet m_headerFileChangeSet;
    ChangeSet m_sourceFileChangeSet;
    QMap<InsertionPointLocator::AccessSpec, InsertionLocation> m_headerInsertionPoints;
    InsertionLocation m_sourceFileInsertionPoint;
    QString m_sourceFileCode;
    QMap<InsertionPointLocator::AccessSpec, QString> m_headerFileCode;
};

struct ParentClassConstructorInfo;

class ConstructorMemberInfo
{
public:
    ConstructorMemberInfo(const QString &name, Symbol *symbol, int numberOfMember)
        : memberVariableName(name)
        , parameterName(CppQuickFixSettings::memberBaseName(name))
        , symbol(symbol)
        , type(symbol->type())
        , numberOfMember(numberOfMember)
    {}
    ConstructorMemberInfo(const QString &memberName,
                          const QString &paramName,
                          const QString &defaultValue,
                          Symbol *symbol,
                          const ParentClassConstructorInfo *parentClassConstructor)
        : parentClassConstructor(parentClassConstructor)
        , memberVariableName(memberName)
        , parameterName(paramName)
        , defaultValue(defaultValue)
        , init(defaultValue.isEmpty())
        , symbol(symbol)
        , type(symbol->type())
    {}
    const ParentClassConstructorInfo *parentClassConstructor = nullptr;
    QString memberVariableName;
    QString parameterName;
    QString defaultValue;
    bool init = true;
    bool customValueType; // for the generation later
    Symbol *symbol; // for the right type later
    FullySpecifiedType type;
    int numberOfMember; // first member, second member, ...
};

class ConstructorParams : public QAbstractTableModel
{
    Q_OBJECT
    std::list<ConstructorMemberInfo> candidates;
    std::vector<ConstructorMemberInfo *> infos;

    void validateOrder()
    {
        // parameters with default values must be at the end
        bool foundWithDefault = false;
        for (auto info : infos) {
            if (info->init) {
                if (foundWithDefault && info->defaultValue.isEmpty()) {
                    emit validOrder(false);
                    return;
                }
                foundWithDefault |= !info->defaultValue.isEmpty();
            }
        }
        emit validOrder(true);
    }

public:
    enum Column { ShouldInitColumn, MemberNameColumn, ParameterNameColumn, DefaultValueColumn };
    template<typename... _Args>
    void emplaceBackParameter(_Args &&...__args)
    {
        candidates.emplace_back(std::forward<_Args>(__args)...);
        infos.push_back(&candidates.back());
    }
    const std::vector<ConstructorMemberInfo *> &getInfos() const { return infos; }
    void addRow(ConstructorMemberInfo *info)
    {
        beginInsertRows({}, rowCount(), rowCount());
        infos.push_back(info);
        endInsertRows();
        validateOrder();
    }
    void removeRow(ConstructorMemberInfo *info)
    {
        for (auto iter = infos.begin(); iter != infos.end(); ++iter) {
            if (*iter == info) {
                const auto index = iter - infos.begin();
                beginRemoveRows({}, index, index);
                infos.erase(iter);
                endRemoveRows();
                validateOrder();
                return;
            }
        }
    }

    int selectedCount() const
    {
        return Utils::count(infos, [](const ConstructorMemberInfo *mi) {
            return mi->init && !mi->parentClassConstructor;
        });
    }
    int memberCount() const
    {
        return Utils::count(infos, [](const ConstructorMemberInfo *mi) {
            return !mi->parentClassConstructor;
        });
    }

    int rowCount(const QModelIndex & /*parent*/ = {}) const override { return int(infos.size()); }
    int columnCount(const QModelIndex & /*parent*/ = {}) const override { return 4; }
    QVariant data(const QModelIndex &index, int role) const override
    {
        if (index.row() < 0 || index.row() >= rowCount())
            return {};
        if (role == Qt::CheckStateRole && index.column() == ShouldInitColumn
            && !infos[index.row()]->parentClassConstructor)
            return infos[index.row()]->init ? Qt::Checked : Qt::Unchecked;
        if (role == Qt::DisplayRole && index.column() == MemberNameColumn)
            return infos[index.row()]->memberVariableName;
        if ((role == Qt::DisplayRole || role == Qt::EditRole)
            && index.column() == ParameterNameColumn)
            return infos[index.row()]->parameterName;
        if ((role == Qt::DisplayRole || role == Qt::EditRole)
            && index.column() == DefaultValueColumn)
            return infos[index.row()]->defaultValue;
        if ((role == Qt::ToolTipRole) && index.column() > 0)
            return Overview{}.prettyType(infos[index.row()]->symbol->type());
        return {};
    }
    bool setData(const QModelIndex &index, const QVariant &value, int role) override
    {
        if (index.column() == ShouldInitColumn && role == Qt::CheckStateRole) {
            if (infos[index.row()]->parentClassConstructor)
                return false;
            infos[index.row()]->init = value.toInt() == Qt::Checked;
            emit dataChanged(this->index(index.row(), 0), this->index(index.row(), columnCount()));
            validateOrder();
            return true;
        }
        if (index.column() == ParameterNameColumn && role == Qt::EditRole) {
            infos[index.row()]->parameterName = value.toString();
            return true;
        }
        if (index.column() == DefaultValueColumn && role == Qt::EditRole) {
            infos[index.row()]->defaultValue = value.toString();
            validateOrder();
            return true;
        }
        return false;
    }
    Qt::DropActions supportedDropActions() const override { return Qt::MoveAction; }
    Qt::ItemFlags flags(const QModelIndex &index) const override
    {
        if (!index.isValid())
            return Qt::ItemIsSelectable | Qt::ItemIsDropEnabled;

        Qt::ItemFlags f{};
        if (infos[index.row()]->init) {
            f |= Qt::ItemIsDragEnabled;
            f |= Qt::ItemIsSelectable;
        }

        if (index.column() == ShouldInitColumn && !infos[index.row()]->parentClassConstructor)
            return f | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable;
        if (!infos[index.row()]->init)
            return f;
        if (index.column() == MemberNameColumn)
            return f | Qt::ItemIsEnabled;
        if (index.column() == ParameterNameColumn || index.column() == DefaultValueColumn)
            return f | Qt::ItemIsEnabled | Qt::ItemIsEditable;
        return {};
    }

    QVariant headerData(int section, Qt::Orientation orientation, int role) const override
    {
        if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
            switch (section) {
            case ShouldInitColumn:
                return Tr::tr("Initialize in Constructor");
            case MemberNameColumn:
                return Tr::tr("Member Name");
            case ParameterNameColumn:
                return Tr::tr("Parameter Name");
            case DefaultValueColumn:
                return Tr::tr("Default Value");
            }
        }
        return {};
    }
    bool dropMimeData(const QMimeData *data,
                      Qt::DropAction /*action*/,
                      int row,
                      int /*column*/,
                      const QModelIndex & /*parent*/) override
    {
        if (row == -1)
            row = rowCount();
        bool ok;
        int sourceRow = data->data("application/x-qabstractitemmodeldatalist").toInt(&ok);
        if (ok) {
            if (sourceRow == row || row == sourceRow + 1)
                return false;
            beginMoveRows({}, sourceRow, sourceRow, {}, row);
            infos.insert(infos.begin() + row, infos.at(sourceRow));
            if (row < sourceRow)
                ++sourceRow;
            infos.erase(infos.begin() + sourceRow);
            validateOrder();
            return true;
        }
        return false;
    }

    QMimeData *mimeData(const QModelIndexList &indexes) const override
    {
        for (const auto &i : indexes) {
            if (!i.isValid())
                continue;
            auto data = new QMimeData();
            data->setData("application/x-qabstractitemmodeldatalist",
                          QString::number(i.row()).toLatin1());
            return data;
        }
        return nullptr;
    }

    class TableViewStyle : public QProxyStyle
    {
    public:
        TableViewStyle(QStyle *style)
            : QProxyStyle(style)
        {}

        void drawPrimitive(PrimitiveElement element,
                           const QStyleOption *option,
                           QPainter *painter,
                           const QWidget *widget) const override
        {
            if (element == QStyle::PE_IndicatorItemViewItemDrop && !option->rect.isNull()) {
                QStyleOption opt(*option);
                opt.rect.setLeft(0);
                if (widget)
                    opt.rect.setRight(widget->width());
                QProxyStyle::drawPrimitive(element, &opt, painter, widget);
                return;
            }
            QProxyStyle::drawPrimitive(element, option, painter, widget);
        }
    };
signals:
    void validOrder(bool valid);
};

class TopMarginDelegate : public QStyledItemDelegate
{
public:
    TopMarginDelegate(QObject *parent = nullptr)
        : QStyledItemDelegate(parent)
    {}

    void paint(QPainter *painter,
               const QStyleOptionViewItem &option,
               const QModelIndex &index) const override
    {
        Q_ASSERT(index.isValid());
        QStyleOptionViewItem opt = option;
        initStyleOption(&opt, index);
        const QWidget *widget = option.widget;
        QStyle *style = widget ? widget->style() : QApplication::style();
        if (opt.rect.height() > 20)
            opt.rect.adjust(0, 5, 0, 0);
        style->drawControl(QStyle::CE_ItemViewItem, &opt, painter, widget);
    }
};

struct ParentClassConstructorParameter : public ConstructorMemberInfo
{
    QString originalDefaultValue;
    QString declaration; // displayed in the treeView
    ParentClassConstructorParameter(const QString &name,
                                    const QString &defaultValue,
                                    Symbol *symbol,
                                    const ParentClassConstructorInfo *parentClassConstructor);

    ParentClassConstructorParameter(const ParentClassConstructorParameter &) = delete;
    ParentClassConstructorParameter(ParentClassConstructorParameter &&) = default;
};

struct ParentClassConstructorInfo
{
    ParentClassConstructorInfo(const QString &name, ConstructorParams &model)
        : className(name)
        , model(model)
    {}
    bool useInConstructor = false;
    const QString className;
    QString declaration;
    std::vector<ParentClassConstructorParameter> parameters;
    ConstructorParams &model;

    ParentClassConstructorInfo(const ParentClassConstructorInfo &) = delete;
    ParentClassConstructorInfo(ParentClassConstructorInfo &&) = default;

    void addParameter(ParentClassConstructorParameter &param) { model.addRow(&param); }
    void removeParameter(ParentClassConstructorParameter &param) { model.removeRow(&param); }
    void removeAllParameters()
    {
        for (auto &param : parameters)
            model.removeRow(&param);
    }
};

ParentClassConstructorParameter::ParentClassConstructorParameter(
    const QString &name,
    const QString &defaultValue,
    Symbol *symbol,
    const ParentClassConstructorInfo *parentClassConstructor)
    : ConstructorMemberInfo(parentClassConstructor->className + "::" + name,
                            name,
                            defaultValue,
                            symbol,
                            parentClassConstructor)
    , originalDefaultValue(defaultValue)
    , declaration(Overview{}.prettyType(symbol->type(), name)
                  + (defaultValue.isEmpty() ? QString{} : " = " + defaultValue))
{}

using ParentClassConstructors = std::vector<ParentClassConstructorInfo>;

class ParentClassesModel : public QAbstractItemModel
{
    ParentClassConstructors &constructors;

public:
    ParentClassesModel(QObject *parent, ParentClassConstructors &constructors)
        : QAbstractItemModel(parent)
        , constructors(constructors)
    {}
    QModelIndex index(int row, int column, const QModelIndex &parent = {}) const override
    {
        if (!parent.isValid())
            return createIndex(row, column, nullptr);
        if (parent.internalPointer())
            return {};
        auto index = createIndex(row, column, &constructors.at(parent.row()));
        return index;
    }
    QModelIndex parent(const QModelIndex &index) const override
    {
        if (!index.isValid())
            return {};
        auto *parent = static_cast<ParentClassConstructorInfo *>(index.internalPointer());
        if (!parent)
            return {};
        int i = 0;
        for (const auto &info : constructors) {
            if (&info == parent)
                return createIndex(i, 0, nullptr);
            ++i;
        }
        return {};
    }
    int rowCount(const QModelIndex &parent = {}) const override
    {
        if (!parent.isValid())
            return static_cast<int>(constructors.size());
        auto info = static_cast<ParentClassConstructorInfo *>(parent.internalPointer());
        if (!info)
            return static_cast<int>(constructors.at(parent.row()).parameters.size());
        return 0;
    }
    int columnCount(const QModelIndex & /*parent*/ = {}) const override { return 1; }
    QVariant data(const QModelIndex &index, int role) const override
    {
        if (!index.isValid())
            return {};
        auto info = static_cast<ParentClassConstructorInfo *>(index.internalPointer());

        if (info) {
            const auto &parameter = info->parameters.at(index.row());
            if (role == Qt::CheckStateRole)
                return parameter.init ? Qt::Checked : Qt::Unchecked;
            if (role == Qt::DisplayRole)
                return parameter.declaration;
            return {};
        }
        const auto &constructor = constructors.at(index.row());
        if (role == Qt::CheckStateRole)
            return constructor.useInConstructor ? Qt::PartiallyChecked : Qt::Unchecked;
        if (role == Qt::DisplayRole)
            return constructor.declaration;

        // Highlight the selected items
        if (role == Qt::FontRole && constructor.useInConstructor) {
            QFont font = QApplication::font();
            font.setBold(true);
            return font;
        }
        // Create a margin between sets of constructors for base classes
        if (role == Qt::SizeHintRole && index.row() > 0
            && constructor.className != constructors.at(index.row() - 1).className) {
            return QSize(-1, 25);
        }
        return {};
    }
    bool setData(const QModelIndex &index, const QVariant &value, int /*role*/) override
    {
        if (index.isValid() && index.column() == 0) {
            auto info = static_cast<ParentClassConstructorInfo *>(index.internalPointer());
            if (info) {
                const bool nowUse = value.toBool();
                auto &param = info->parameters.at(index.row());
                param.init = nowUse;
                if (nowUse)
                    info->addParameter(param);
                else
                    info->removeParameter(param);
                return true;
            }
            auto &newConstructor = constructors.at(index.row());
            // You have to select a base class constructor
            if (newConstructor.useInConstructor)
                return false;
            auto c = std::find_if(constructors.begin(), constructors.end(), [&](const auto &c) {
                return c.className == newConstructor.className && c.useInConstructor;
            });
            QTC_ASSERT(c == constructors.end(), return false;);
            c->useInConstructor = false;
            newConstructor.useInConstructor = true;
            emit dataChanged(this->index(index.row(), 0), this->index(index.row(), columnCount()));
            auto parentIndex = this->index(index.row(), 0);
            emit dataChanged(this->index(0, 0, parentIndex),
                             this->index(rowCount(parentIndex), columnCount()));
            const int oldIndex = c - constructors.begin();
            emit dataChanged(this->index(oldIndex, 0), this->index(oldIndex, columnCount()));
            parentIndex = this->index(oldIndex, 0);
            emit dataChanged(this->index(0, 0, parentIndex),
                             this->index(rowCount(parentIndex), columnCount()));
            // update other table
            c->removeAllParameters();
            for (auto &p : newConstructor.parameters)
                if (p.init)
                    newConstructor.addParameter(p);
            return true;
        }
        return false;
    }
    QVariant headerData(int section, Qt::Orientation orientation, int role) const override
    {
        if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
            switch (section) {
            case 0:
                return Tr::tr("Base Class Constructors");
            }
        }
        return {};
    }
    Qt::ItemFlags flags(const QModelIndex &index) const override
    {
        if (index.isValid()) {
            Qt::ItemFlags f;
            auto info = static_cast<ParentClassConstructorInfo *>(index.internalPointer());
            if (!info || info->useInConstructor) {
                f |= Qt::ItemIsEnabled;
            }
            f |= Qt::ItemIsUserCheckable;

            return f;
        }
        return {};
    }
};

class GenerateConstructorDialog : public QDialog
{
public:
    GenerateConstructorDialog(ConstructorParams *constructorParamsModel,
                              ParentClassConstructors &constructors)
    {
        setWindowTitle(Tr::tr("Constructor"));

        const auto treeModel = new ParentClassesModel(this, constructors);
        const auto treeView = new QTreeView(this);
        treeView->setModel(treeModel);
        treeView->setItemDelegate(new TopMarginDelegate(this));
        treeView->expandAll();

        const auto view = new QTableView(this);
        view->setModel(constructorParamsModel);
        int optimalWidth = 0;
        for (int i = 0; i < constructorParamsModel->columnCount(QModelIndex{}); ++i) {
            view->resizeColumnToContents(i);
            optimalWidth += view->columnWidth(i);
        }
        view->resizeRowsToContents();
        view->verticalHeader()->setDefaultSectionSize(view->rowHeight(0));
        view->setSelectionBehavior(QAbstractItemView::SelectRows);
        view->setSelectionMode(QAbstractItemView::SingleSelection);
        view->setDragEnabled(true);
        view->setDropIndicatorShown(true);
        view->setDefaultDropAction(Qt::MoveAction);
        view->setDragDropMode(QAbstractItemView::InternalMove);
        view->setDragDropOverwriteMode(false);
        view->horizontalHeader()->setStretchLastSection(true);
        view->setStyle(new ConstructorParams::TableViewStyle(view->style()));

        const auto buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
        connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept);
        connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);

        const auto errorLabel = new QLabel(
            Tr::tr("Parameters without default value must come before parameters with default value."));
        errorLabel->setStyleSheet("color: #ff0000");
        errorLabel->setVisible(false);
        QSizePolicy labelSizePolicy = errorLabel->sizePolicy();
        labelSizePolicy.setRetainSizeWhenHidden(true);
        errorLabel->setSizePolicy(labelSizePolicy);
        connect(constructorParamsModel, &ConstructorParams::validOrder, this,
                [errorLabel, button = buttonBox->button(QDialogButtonBox::Ok)](bool valid) {
                    button->setEnabled(valid);
                    errorLabel->setVisible(!valid);
                });

        // setup select all/none checkbox
        QCheckBox *const checkBox = new QCheckBox(Tr::tr("Initialize all members"));
        checkBox->setChecked(true);
        connect(checkBox, &QCheckBox::stateChanged, this,
                [model = constructorParamsModel](int state) {
                    if (state != Qt::PartiallyChecked) {
                        for (int i = 0; i < model->rowCount(); ++i)
                            model->setData(model->index(i, ConstructorParams::ShouldInitColumn),
                                           state,
                                           Qt::CheckStateRole);
                    }
                });
        connect(checkBox, &QCheckBox::clicked, this, [checkBox] {
            if (checkBox->checkState() == Qt::PartiallyChecked)
                checkBox->setCheckState(Qt::Checked);
        });
        connect(constructorParamsModel,
                &QAbstractItemModel::dataChanged,
                this,
                [model = constructorParamsModel, checkBox] {
                    const auto state = [model, selectedCount = model->selectedCount()]() {
                        if (selectedCount == 0)
                            return Qt::Unchecked;
                        if (static_cast<int>(model->memberCount() == selectedCount))
                            return Qt::Checked;
                        return Qt::PartiallyChecked;
                    }();
                    checkBox->setCheckState(state);
                });

        using A = InsertionPointLocator::AccessSpec;
        auto accessCombo = new QComboBox;
        connect(accessCombo, &QComboBox::currentIndexChanged, this, [this, accessCombo] {
            const auto data = accessCombo->currentData();
            m_accessSpec = static_cast<A>(data.toInt());
        });
        for (auto a : {A::Public, A::Protected, A::Private})
            accessCombo->addItem(InsertionPointLocator::accessSpecToString(a), a);
        const auto row = new QHBoxLayout();
        row->addWidget(new QLabel(Tr::tr("Access") + ":"));
        row->addWidget(accessCombo);
        row->addSpacerItem(new QSpacerItem(1, 1, QSizePolicy::Expanding, QSizePolicy::Minimum));

        const auto mainLayout = new QVBoxLayout(this);
        mainLayout->addWidget(
            new QLabel(Tr::tr("Select the members to be initialized in the constructor.\n"
                              "Use drag and drop to change the order of the parameters.")));
        mainLayout->addLayout(row);
        mainLayout->addWidget(checkBox);
        mainLayout->addWidget(view);
        mainLayout->addWidget(treeView);
        mainLayout->addWidget(errorLabel);
        mainLayout->addWidget(buttonBox);
        int left, right;
        mainLayout->getContentsMargins(&left, nullptr, &right, nullptr);
        optimalWidth += left + right;
        resize(optimalWidth, mainLayout->sizeHint().height());
    }

    InsertionPointLocator::AccessSpec accessSpec() const { return m_accessSpec; }

private:
    InsertionPointLocator::AccessSpec m_accessSpec;
};

class MemberInfo
{
public:
    MemberInfo(ExistingGetterSetterData data, int possibleFlags)
        : data(data)
        , possibleFlags(possibleFlags)
    {}

    ExistingGetterSetterData data;
    int possibleFlags;
    int requestedFlags = 0;
};
using GetterSetterCandidates = std::vector<MemberInfo>;

class GenerateConstructorOperation : public CppQuickFixOperation
{
public:
    GenerateConstructorOperation(const CppQuickFixInterface &interface)
        : CppQuickFixOperation(interface)
    {
        setDescription(Tr::tr("Generate Constructor"));

        m_classAST = astForClassOperations(interface);
        if (!m_classAST)
            return;
        Class *const theClass = m_classAST->symbol;
        if (!theClass)
            return;

        // Go through all members and find member variable declarations
        int memberCounter = 0;
        for (auto it = theClass->memberBegin(); it != theClass->memberEnd(); ++it) {
            Symbol *const s = *it;
            if (!s->identifier() || !s->type() || s->type().isTypedef())
                continue;
            if ((s->asDeclaration() && s->type()->asFunctionType()) || s->asFunction())
                continue;
            if (s->asDeclaration() && (s->isPrivate() || s->isProtected()) && !s->isStatic()) {
                const auto name = QString::fromUtf8(s->identifier()->chars(),
                                                    s->identifier()->size());
                parameterModel.emplaceBackParameter(name, s, memberCounter++);
            }
        }
        Overview o = CppCodeStyleSettings::currentProjectCodeStyleOverview();
        o.showArgumentNames = true;
        o.showReturnTypes = true;
        o.showDefaultArguments = true;
        o.showTemplateParameters = true;
        o.showFunctionSignatures = true;
        LookupContext context(currentFile()->cppDocument(), interface.snapshot());
        for (BaseClass *bc : theClass->baseClasses()) {
            const QString className = o.prettyName(bc->name());

            ClassOrNamespace *localLookupType = context.lookupType(bc);
            QList<LookupItem> localLookup = localLookupType->lookup(bc->name());
            for (auto &li : localLookup) {
                Symbol *d = li.declaration();
                if (!d->asClass())
                    continue;
                for (auto i = d->asClass()->memberBegin(); i != d->asClass()->memberEnd(); ++i) {
                    Symbol *s = *i;
                    if (s->isProtected() || s->isPublic()) {
                        if (s->name()->match(d->name())) {
                            // we have found a constructor
                            Function *func = s->type().type()->asFunctionType();
                            if (!func)
                                continue;
                            const bool isFirst = parentClassConstructors.empty()
                                                 || parentClassConstructors.back().className
                                                        != className;
                            parentClassConstructors.emplace_back(className, parameterModel);
                            ParentClassConstructorInfo &constructor = parentClassConstructors.back();
                            constructor.declaration = className + o.prettyType(func->type());
                            constructor.declaration.replace("std::__1::__get_nullptr_t()",
                                                            "nullptr");
                            constructor.useInConstructor = isFirst;
                            for (auto arg = func->memberBegin(); arg != func->memberEnd(); ++arg) {
                                Symbol *param = *arg;
                                Argument *argument = param->asArgument();
                                if (!argument) // can also be a block
                                    continue;
                                const QString name = o.prettyName(param->name());
                                const StringLiteral *ini = argument->initializer();
                                QString defaultValue;
                                if (ini)
                                    defaultValue = QString::fromUtf8(ini->chars(), ini->size())
                                                       .replace("std::__1::__get_nullptr_t()",
                                                                "nullptr");
                                constructor.parameters.emplace_back(name,
                                                                    defaultValue,
                                                                    param,
                                                                    &constructor);
                                // do not show constructors like QObject(QObjectPrivate & dd, ...)
                                ReferenceType *ref = param->type()->asReferenceType();
                                if (ref && name == "dd") {
                                    auto type = o.prettyType(ref->elementType());
                                    if (type.startsWith("Q") && type.endsWith("Private")) {
                                        parentClassConstructors.pop_back();
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        // add params to parameter lists
        for (auto &c : parentClassConstructors)
            if (c.useInConstructor)
                for (auto &p : c.parameters)
                    if (p.init)
                        c.addParameter(p);
    }

    bool isApplicable() const
    {
        return parameterModel.rowCount() > 0
               || Utils::anyOf(parentClassConstructors,
                               [](const auto &parent) { return !parent.parameters.empty(); });
    }

    void setTest(bool isTest = true) { m_test = isTest; }

private:
    void perform() override
    {
        auto infos = parameterModel.getInfos();

        InsertionPointLocator::AccessSpec accessSpec = InsertionPointLocator::Public;
        if (!m_test) {
            GenerateConstructorDialog dlg(&parameterModel, parentClassConstructors);
            if (dlg.exec() == QDialog::Rejected)
                return;
            accessSpec = dlg.accessSpec();
            infos = parameterModel.getInfos();
        } else {
#ifdef WITH_TESTS
            ParentClassesModel model(nullptr, parentClassConstructors);
            QAbstractItemModelTester tester(&model);
#endif
            if (infos.size() >= 3) {
                // if we are testing and have 3 or more members => change the order
                // move first element to the back
                infos.push_back(infos[0]);
                infos.erase(infos.begin());
            }
            for (auto info : infos) {
                if (info->memberVariableName.startsWith("di_"))
                    info->defaultValue = "42";
            }
            for (auto &c : parentClassConstructors) {
                if (c.useInConstructor) {
                    for (auto &p : c.parameters) {
                        if (!p.init && p.parameterName.startsWith("use_")) {
                            infos.push_back(&p);
                            p.init = true;
                        }
                    }
                }
            }
        }
        if (infos.empty())
            return;
        struct GenerateConstructorRefactoringHelper : public GetterSetterRefactoringHelper
        {
            const ClassSpecifierAST *m_classAST;
            InsertionPointLocator::AccessSpec m_accessSpec;
            GenerateConstructorRefactoringHelper(CppQuickFixOperation *operation,
                                                 Class *clazz,
                                                 const ClassSpecifierAST *classAST,
                                                 InsertionPointLocator::AccessSpec accessSpec)
                : GetterSetterRefactoringHelper(operation, clazz)
                , m_classAST(classAST)
                , m_accessSpec(accessSpec)
            {}
            void generateConstructor(std::vector<ConstructorMemberInfo *> members,
                                     const ParentClassConstructors &parentClassConstructors)
            {
                auto constructorLocation = m_settings->determineSetterLocation(int(members.size()));
                if (constructorLocation == CppQuickFixSettings::FunctionLocation::CppFile
                    && !hasSourceFile())
                    constructorLocation = CppQuickFixSettings::FunctionLocation::OutsideClass;

                Overview overview = CppCodeStyleSettings::currentProjectCodeStyleOverview();
                overview.showTemplateParameters = true;

                InsertionLocation implLoc;
                QString implCode;
                CppRefactoringFilePtr implFile;
                QString className = overview.prettyName(m_class->name());
                QStringList insertedNamespaces;
                if (constructorLocation == CppQuickFixSettings::FunctionLocation::CppFile) {
                    implLoc = sourceLocationFor(m_class, &insertedNamespaces);
                    implFile = m_sourceFile;
                    if (m_settings->rewriteTypesinCppFile())
                        implCode = symbolAt(m_class, m_sourceFile, implLoc);
                    else
                        implCode = className;
                    implCode += "::" + className + "(";
                } else if (constructorLocation
                           == CppQuickFixSettings::FunctionLocation::OutsideClass) {
                    implLoc = insertLocationForMethodDefinition(m_class,
                                                                false,
                                                                NamespaceHandling::Ignore,
                                                                m_changes,
                                                                m_headerFile->filePath(),
                                                                &insertedNamespaces);
                    implFile = m_headerFile;
                    implCode = symbolAt(m_class, m_headerFile, implLoc);
                    implCode += "::" + className + "(";
                }

                QString inClassDeclaration = overview.prettyName(m_class->name()) + "(";
                QString constructorBody = members.empty() ? QString(") {}") : QString(") : ");
                for (auto &member : members) {
                    if (isValueType(member->symbol, &member->customValueType))
                        member->type.setConst(false);
                    else
                        member->type = makeConstRef(member->type);

                    inClassDeclaration += overview.prettyType(member->type, member->parameterName);
                    if (!member->defaultValue.isEmpty())
                        inClassDeclaration += " = " + member->defaultValue;
                    inClassDeclaration += ", ";
                    if (implFile) {
                        FullySpecifiedType type = typeAt(member->type,
                                                         m_class,
                                                         implFile,
                                                         implLoc,
                                                         insertedNamespaces);
                        implCode += overview.prettyType(type, member->parameterName) + ", ";
                    }
                }
                Utils::sort(members, &ConstructorMemberInfo::numberOfMember);
                // first, do the base classes
                for (const auto &parent : parentClassConstructors) {
                    if (!parent.useInConstructor)
                        continue;
                    // Check if we really need a constructor
                    if (Utils::anyOf(parent.parameters, [](const auto &param) {
                            return param.init || param.originalDefaultValue.isEmpty();
                        })) {
                        int defaultAtEndCount = 0;
                        for (auto i = parent.parameters.crbegin(); i != parent.parameters.crend();
                             ++i) {
                            if (i->init || i->originalDefaultValue.isEmpty())
                                break;
                            ++defaultAtEndCount;
                        }
                        const int numberOfParameters = static_cast<int>(parent.parameters.size())
                                                       - defaultAtEndCount;
                        constructorBody += parent.className + "(";
                        int counter = 0;
                        for (const auto &param : parent.parameters) {
                            if (++counter > numberOfParameters)
                                break;
                            if (param.init) {
                                if (param.customValueType)
                                    constructorBody += "std::move(" + param.parameterName + ')';
                                else
                                    constructorBody += param.parameterName;
                            } else if (!param.originalDefaultValue.isEmpty())
                                constructorBody += param.originalDefaultValue;
                            else
                                constructorBody += "/* insert value */";
                            constructorBody += ", ";
                        }
                        constructorBody.resize(constructorBody.size() - 2);
                        constructorBody += "),\n";
                    }
                }
                for (auto &member : members) {
                    if (member->parentClassConstructor)
                        continue;
                    QString param = member->parameterName;
                    if (member->customValueType)
                        param = "std::move(" + member->parameterName + ')';
                    constructorBody += member->memberVariableName + '(' + param + "),\n";
                }
                if (!members.empty()) {
                    inClassDeclaration.resize(inClassDeclaration.size() - 2);
                    constructorBody.remove(constructorBody.size() - 2, 1); // ..),\n => ..)\n
                    constructorBody += "{}";
                    if (!implCode.isEmpty())
                        implCode.resize(implCode.size() - 2);
                }
                implCode += constructorBody;

                if (constructorLocation == CppQuickFixSettings::FunctionLocation::InsideClass)
                    inClassDeclaration += constructorBody;
                else
                    inClassDeclaration += QLatin1String(");");

                TranslationUnit *tu = m_headerFile->cppDocument()->translationUnit();
                insertAndIndent(m_headerFile,
                                m_locator.constructorDeclarationInClass(tu,
                                                                        m_classAST,
                                                                        m_accessSpec,
                                                                        int(members.size())),
                                inClassDeclaration);

                if (constructorLocation == CppQuickFixSettings::FunctionLocation::CppFile) {
                    addSourceFileCode(implCode);
                } else if (constructorLocation
                           == CppQuickFixSettings::FunctionLocation::OutsideClass) {
                    if (m_isHeaderHeaderFile)
                        implCode.prepend("inline ");
                    insertAndIndent(m_headerFile, implLoc, implCode);
                }
            }
        };
        GenerateConstructorRefactoringHelper helper(this,
                                                    m_classAST->symbol,
                                                    m_classAST,
                                                    accessSpec);

        auto members = Utils::filtered(infos, [](const auto mi) {
            return mi->init || mi->parentClassConstructor;
        });
        helper.generateConstructor(std::move(members), parentClassConstructors);
        helper.applyChanges();
    }

    ConstructorParams parameterModel;
    ParentClassConstructors parentClassConstructors;
    const ClassSpecifierAST *m_classAST = nullptr;
    bool m_test = false;
};

class GenerateGetterSetterOp : public CppQuickFixOperation
{
public:
    enum GenerateFlag {
        GenerateGetter = 1 << 0,
        GenerateSetter = 1 << 1,
        GenerateSignal = 1 << 2,
        GenerateMemberVariable = 1 << 3,
        GenerateReset = 1 << 4,
        GenerateProperty = 1 << 5,
        GenerateConstantProperty = 1 << 6,
        HaveExistingQProperty = 1 << 7,
        Invalid = -1,
    };

    GenerateGetterSetterOp(const CppQuickFixInterface &interface,
                           ExistingGetterSetterData data,
                           int generateFlags,
                           int priority,
                           const QString &description)
        : CppQuickFixOperation(interface)
        , m_generateFlags(generateFlags)
        , m_data(data)
    {
        setDescription(description);
        setPriority(priority);
    }

    static void generateQuickFixes(QuickFixOperations &results,
                                   const CppQuickFixInterface &interface,
                                   const ExistingGetterSetterData &data,
                                   const int possibleFlags)
    {
        // flags can have the value HaveExistingQProperty or a combination of all other values
        // of the enum 'GenerateFlag'
        int p = 0;
        if (possibleFlags & HaveExistingQProperty) {
            const QString desc = Tr::tr("Generate Missing Q_PROPERTY Members");
            results << new GenerateGetterSetterOp(interface, data, possibleFlags, ++p, desc);
        } else {
            if (possibleFlags & GenerateSetter) {
                const QString desc = Tr::tr("Generate Setter");
                results << new GenerateGetterSetterOp(interface, data, GenerateSetter, ++p, desc);
            }
            if (possibleFlags & GenerateGetter) {
                const QString desc = Tr::tr("Generate Getter");
                results << new GenerateGetterSetterOp(interface, data, GenerateGetter, ++p, desc);
            }
            if (possibleFlags & GenerateGetter && possibleFlags & GenerateSetter) {
                const QString desc = Tr::tr("Generate Getter and Setter");
                const int flags = GenerateGetter | GenerateSetter;
                results << new GenerateGetterSetterOp(interface, data, flags, ++p, desc);
            }

            if (possibleFlags & GenerateConstantProperty) {
                const QString desc = Tr::tr("Generate Constant Q_PROPERTY and Missing Members");
                const int flags = possibleFlags & ~(GenerateSetter | GenerateSignal | GenerateReset);
                results << new GenerateGetterSetterOp(interface, data, flags, ++p, desc);
            }
            if (possibleFlags & GenerateProperty) {
                if (possibleFlags & GenerateReset) {
                    const QString desc = Tr::tr(
                        "Generate Q_PROPERTY and Missing Members with Reset Function");
                    const int flags = possibleFlags & ~GenerateConstantProperty;
                    results << new GenerateGetterSetterOp(interface, data, flags, ++p, desc);
                }
                const QString desc = Tr::tr("Generate Q_PROPERTY and Missing Members");
                const int flags = possibleFlags & ~GenerateConstantProperty & ~GenerateReset;
                results << new GenerateGetterSetterOp(interface, data, flags, ++p, desc);
            }
        }
    }

    void perform() override
    {
        GetterSetterRefactoringHelper helper(this, m_data.clazz);
        helper.performGeneration(m_data, m_generateFlags);
        helper.applyChanges();
    }

private:
    int m_generateFlags;
    ExistingGetterSetterData m_data;
};

class CandidateTreeItem : public TreeItem
{
public:
    enum Column {
        NameColumn,
        GetterColumn,
        SetterColumn,
        SignalColumn,
        ResetColumn,
        QPropertyColumn,
        ConstantQPropertyColumn
    };
    using Flag = GenerateGetterSetterOp::GenerateFlag;
    constexpr static Flag ColumnFlag[] = {
        Flag::Invalid,
        Flag::GenerateGetter,
        Flag::GenerateSetter,
        Flag::GenerateSignal,
        Flag::GenerateReset,
        Flag::GenerateProperty,
        Flag::GenerateConstantProperty,
    };

    CandidateTreeItem(MemberInfo *memberInfo)
        : m_memberInfo(memberInfo)
    {}

private:
    QVariant data(int column, int role) const override
    {
        if (role == Qt::DisplayRole && column == NameColumn)
            return m_memberInfo->data.memberVariableName;
        if (role == Qt::CheckStateRole && column > 0
            && column <= static_cast<int>(std::size(ColumnFlag))) {
            return m_memberInfo->requestedFlags & ColumnFlag[column] ? Qt::Checked : Qt::Unchecked;
        }
        return {};
    }

    bool setData(int column, const QVariant &data, int role) override
    {
        if (column < 1 || column > static_cast<int>(std::size(ColumnFlag)))
            return false;
        if (role != Qt::CheckStateRole)
            return false;
        if (!(m_memberInfo->possibleFlags & ColumnFlag[column]))
            return false;
        const bool nowChecked = data.toInt() == Qt::Checked;
        if (nowChecked)
            m_memberInfo->requestedFlags |= ColumnFlag[column];
        else
            m_memberInfo->requestedFlags &= ~ColumnFlag[column];

        if (nowChecked) {
            if (column == QPropertyColumn) {
                m_memberInfo->requestedFlags |= Flag::GenerateGetter;
                m_memberInfo->requestedFlags |= Flag::GenerateSetter;
                m_memberInfo->requestedFlags |= Flag::GenerateSignal;
                m_memberInfo->requestedFlags &= ~Flag::GenerateConstantProperty;
            } else if (column == ConstantQPropertyColumn) {
                m_memberInfo->requestedFlags |= Flag::GenerateGetter;
                m_memberInfo->requestedFlags &= ~Flag::GenerateSetter;
                m_memberInfo->requestedFlags &= ~Flag::GenerateSignal;
                m_memberInfo->requestedFlags &= ~Flag::GenerateReset;
                m_memberInfo->requestedFlags &= ~Flag::GenerateProperty;
            } else if (column == SetterColumn || column == SignalColumn || column == ResetColumn) {
                m_memberInfo->requestedFlags &= ~Flag::GenerateConstantProperty;
            }
        } else {
            if (column == SignalColumn)
                m_memberInfo->requestedFlags &= ~Flag::GenerateProperty;
        }
        for (int i = 0; i < 16; ++i) {
            const bool allowed = m_memberInfo->possibleFlags & (1 << i);
            if (!allowed)
                m_memberInfo->requestedFlags &= ~(1 << i); // clear bit
        }
        update();
        return true;
    }

    Qt::ItemFlags flags(int column) const override
    {
        if (column == NameColumn)
            return Qt::ItemIsEnabled;
        if (column < 1 || column > static_cast<int>(std::size(ColumnFlag)))
            return {};
        if (m_memberInfo->possibleFlags & ColumnFlag[column])
            return Qt::ItemIsEnabled | Qt::ItemIsUserCheckable;
        return {};
    }

    MemberInfo *const m_memberInfo;
};

class GenerateGettersSettersDialog : public QDialog
{
    static constexpr CandidateTreeItem::Column CheckBoxColumn[4]
        = {CandidateTreeItem::Column::GetterColumn,
           CandidateTreeItem::Column::SetterColumn,
           CandidateTreeItem::Column::SignalColumn,
           CandidateTreeItem::Column::QPropertyColumn};

public:
    GenerateGettersSettersDialog(const GetterSetterCandidates &candidates)
        : QDialog()
        , m_candidates(candidates)
    {
        using Flags = GenerateGetterSetterOp::GenerateFlag;
        setWindowTitle(Tr::tr("Getters and Setters"));
        const auto model = new TreeModel<TreeItem, CandidateTreeItem>(this);
        model->setHeader(QStringList({
            Tr::tr("Member"),
            Tr::tr("Getter"),
            Tr::tr("Setter"),
            Tr::tr("Signal"),
            Tr::tr("Reset"),
            Tr::tr("QProperty"),
            Tr::tr("Constant QProperty"),
        }));
        for (MemberInfo &candidate : m_candidates)
            model->rootItem()->appendChild(new CandidateTreeItem(&candidate));
        const auto view = new BaseTreeView(this);
        view->setModel(model);
        int optimalWidth = 0;
        for (int i = 0; i < model->columnCount(QModelIndex{}); ++i) {
            view->resizeColumnToContents(i);
            optimalWidth += view->columnWidth(i);
        }

        const auto buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
        connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept);
        connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);

        const auto setCheckStateForAll = [model](int column, int checkState) {
            for (int i = 0; i < model->rowCount(); ++i)
                model->setData(model->index(i, column), checkState, Qt::CheckStateRole);
        };
        const auto preventPartiallyChecked = [](QCheckBox *checkbox) {
            if (checkbox->checkState() == Qt::PartiallyChecked)
                checkbox->setCheckState(Qt::Checked);
        };
        using Column = CandidateTreeItem::Column;
        const auto createConnections = [this, setCheckStateForAll, preventPartiallyChecked](
                                           QCheckBox *checkbox, Column column) {
            connect(checkbox, &QCheckBox::stateChanged, this, [setCheckStateForAll, column](int state) {
                if (state != Qt::PartiallyChecked)
                    setCheckStateForAll(column, state);
            });
            connect(checkbox, &QCheckBox::clicked, this, [checkbox, preventPartiallyChecked] {
                preventPartiallyChecked(checkbox);
            });
        };
        std::array<QCheckBox *, 4> checkBoxes = {};

        static_assert(std::size(CheckBoxColumn) == checkBoxes.size(),
                      "Must contain the same number of elements");
        for (std::size_t i = 0; i < checkBoxes.size(); ++i) {
            if (Utils::anyOf(candidates, [i](const MemberInfo &mi) {
                    return mi.possibleFlags & CandidateTreeItem::ColumnFlag[CheckBoxColumn[i]];
                })) {
                const Column column = CheckBoxColumn[i];
                if (column == Column::GetterColumn)
                    checkBoxes[i] = new QCheckBox(Tr::tr("Create getters for all members"));
                else if (column == Column::SetterColumn)
                    checkBoxes[i] = new QCheckBox(Tr::tr("Create setters for all members"));
                else if (column == Column::SignalColumn)
                    checkBoxes[i] = new QCheckBox(Tr::tr("Create signals for all members"));
                else if (column == Column::QPropertyColumn)
                    checkBoxes[i] = new QCheckBox(Tr::tr("Create Q_PROPERTY for all members"));

                createConnections(checkBoxes[i], column);
            }
        }
        connect(model, &QAbstractItemModel::dataChanged, this, [this, checkBoxes] {
            const auto countExisting = [this](Flags flag) {
                return Utils::count(m_candidates, [flag](const MemberInfo &mi) {
                    return !(mi.possibleFlags & flag);
                });
            };
            const auto countRequested = [this](Flags flag) {
                return Utils::count(m_candidates, [flag](const MemberInfo &mi) {
                    return mi.requestedFlags & flag;
                });
            };
            const auto countToState = [this](int requestedCount, int alreadyExistsCount) {
                if (requestedCount == 0)
                    return Qt::Unchecked;
                if (int(m_candidates.size()) - requestedCount == alreadyExistsCount)
                    return Qt::Checked;
                return Qt::PartiallyChecked;
            };
            for (std::size_t i = 0; i < checkBoxes.size(); ++i) {
                if (checkBoxes[i]) {
                    const Flags flag = CandidateTreeItem::ColumnFlag[CheckBoxColumn[i]];
                    checkBoxes[i]->setCheckState(
                        countToState(countRequested(flag), countExisting(flag)));
                }
            }
        });

        const auto mainLayout = new QVBoxLayout(this);
        mainLayout->addWidget(new QLabel(Tr::tr("Select the getters and setters "
                                                "to be created.")));
        for (auto checkBox : checkBoxes) {
            if (checkBox)
                mainLayout->addWidget(checkBox);
        }
        mainLayout->addWidget(view);
        mainLayout->addWidget(buttonBox);
        int left, right;
        mainLayout->getContentsMargins(&left, nullptr, &right, nullptr);
        optimalWidth += left + right;
        resize(optimalWidth, mainLayout->sizeHint().height());
    }

    GetterSetterCandidates candidates() const { return m_candidates; }

private:
    GetterSetterCandidates m_candidates;
};

class GenerateGettersSettersOperation : public CppQuickFixOperation
{
public:
    GenerateGettersSettersOperation(const CppQuickFixInterface &interface)
        : CppQuickFixOperation(interface)
    {
        setDescription(Tr::tr("Create Getter and Setter Member Functions"));

        m_classAST = astForClassOperations(interface);
        if (!m_classAST)
            return;
        Class * const theClass = m_classAST->symbol;
        if (!theClass)
            return;

        // Go through all data members and try to find out whether they have getters and/or setters.
        QList<Symbol *> dataMembers;
        QList<Symbol *> memberFunctions;
        for (auto it = theClass->memberBegin(); it != theClass->memberEnd(); ++it) {
            Symbol *const s = *it;
            if (!s->identifier() || !s->type() || s->type().isTypedef())
                continue;
            if ((s->asDeclaration() && s->type()->asFunctionType()) || s->asFunction())
                memberFunctions << s;
            else if (s->asDeclaration() && (s->isPrivate() || s->isProtected()))
                dataMembers << s;
        }

        auto file = interface.currentFile();
        QStringList qPropertyNames; // name after MEMBER or name of the property
        for (auto it = m_classAST->member_specifier_list; it; it = it->next) {
            if (it->value->asQtPropertyDeclaration()) {
                auto propDecl = it->value->asQtPropertyDeclaration();
                // iterator over 'READ ...', ... and check if we have a MEMBER
                for (auto p = propDecl->property_declaration_item_list; p; p = p->next) {
                    const char *tokenString = file->tokenAt(p->value->item_name_token).spell();
                    if (!qstrcmp(tokenString, "MEMBER"))
                        qPropertyNames << file->textOf(p->value->expression);
                }
                // no MEMBER, but maybe the property name is the same
                qPropertyNames << file->textOf(propDecl->property_name);
            }
        }
        const QStringList memberFunctionsAsStrings = toStringList(memberFunctions);

        for (Symbol *const member : std::as_const(dataMembers)) {
            ExistingGetterSetterData existing;
            existing.memberVariableName = QString::fromUtf8(member->identifier()->chars(),
                                                            member->identifier()->size());
            existing.declarationSymbol = member->asDeclaration();
            existing.clazz = theClass;

            // check if a Q_PROPERTY exist
            const QString baseName = CppQuickFixSettings::memberBaseName(existing.memberVariableName);
            if (qPropertyNames.contains(baseName)
                || qPropertyNames.contains(existing.memberVariableName))
                continue;

            findExistingFunctions(existing, memberFunctionsAsStrings);
            existing.qPropertyName = baseName;

            int possibleFlags = existing.computePossibleFlags();
            if (possibleFlags == 0)
                continue;
            m_candidates.emplace_back(existing, possibleFlags);
        }
    }

    GetterSetterCandidates candidates() const { return m_candidates; }
    bool isApplicable() const { return !m_candidates.empty(); }

    void setGetterSetterData(const GetterSetterCandidates &data)
    {
        m_candidates = data;
        m_hasData = true;
    }

private:
    void perform() override
    {
        if (!m_hasData) {
            GenerateGettersSettersDialog dlg(m_candidates);
            if (dlg.exec() == QDialog::Rejected)
                return;
            m_candidates = dlg.candidates();
        }
        if (m_candidates.empty())
            return;
        GetterSetterRefactoringHelper helper(this, m_candidates.front().data.clazz);
        for (MemberInfo &mi : m_candidates) {
            if (mi.requestedFlags != 0) {
                helper.performGeneration(mi.data, mi.requestedFlags);
            }
        }
        helper.applyChanges();
    }

    GetterSetterCandidates m_candidates;
    const ClassSpecifierAST *m_classAST = nullptr;
    bool m_hasData = false;
};

int ExistingGetterSetterData::computePossibleFlags() const
{
    const bool isConst = declarationSymbol->type().isConst();
    const bool isStatic = declarationSymbol->type().isStatic();
    using Flag = GenerateGetterSetterOp::GenerateFlag;
    int generateFlags = 0;
    if (getterName.isEmpty())
        generateFlags |= Flag::GenerateGetter;
    if (!isConst) {
        if (resetName.isEmpty())
            generateFlags |= Flag::GenerateReset;
        if (!isStatic && signalName.isEmpty() && setterName.isEmpty())
            generateFlags |= Flag::GenerateSignal;
        if (setterName.isEmpty())
            generateFlags |= Flag::GenerateSetter;
    }
    if (!isStatic) {
        const bool hasSignal = !signalName.isEmpty() || generateFlags & Flag::GenerateSignal;
        if (!isConst && hasSignal)
            generateFlags |= Flag::GenerateProperty;
    }
    if (setterName.isEmpty() && signalName.isEmpty())
        generateFlags |= Flag::GenerateConstantProperty;
    return generateFlags;
}

void GetterSetterRefactoringHelper::performGeneration(ExistingGetterSetterData data, int generateFlags)
{
    using Flag = GenerateGetterSetterOp::GenerateFlag;

    if (generateFlags & Flag::GenerateGetter && data.getterName.isEmpty()) {
        data.getterName = m_settings->getGetterName(data.qPropertyName, data.memberVariableName);
        if (data.getterName == data.memberVariableName) {
            data.getterName = "get" + data.memberVariableName.left(1).toUpper()
                              + data.memberVariableName.mid(1);
        }
    }
    if (generateFlags & Flag::GenerateSetter && data.setterName.isEmpty())
        data.setterName = m_settings->getSetterName(data.qPropertyName, data.memberVariableName);
    if (generateFlags & Flag::GenerateSignal && data.signalName.isEmpty())
        data.signalName = m_settings->getSignalName(data.qPropertyName, data.memberVariableName);
    if (generateFlags & Flag::GenerateReset && data.resetName.isEmpty())
        data.resetName = m_settings->getResetName(data.qPropertyName, data.memberVariableName);

    FullySpecifiedType memberVariableType = data.declarationSymbol->type();
    memberVariableType.setConst(false);
    const bool isMemberVariableStatic =  data.declarationSymbol->isStatic();
    memberVariableType.setStatic(false);
    Overview overview = CppCodeStyleSettings::currentProjectCodeStyleOverview();
    overview.showTemplateParameters = false;
    // TODO does not work with using. e.g. 'using foo = std::unique_ptr<int>'
    // TODO must be fully qualified
    auto getSetTemplate = m_settings->findGetterSetterTemplate(overview.prettyType(memberVariableType));
    overview.showTemplateParameters = true;

    // Ok... - If a type is a Named type we have to search recusive for the real type
    const bool isValueType = this->isValueType(memberVariableType,
                                               data.declarationSymbol->enclosingScope());
    const FullySpecifiedType parameterType = isValueType ? memberVariableType
                                                         : makeConstRef(memberVariableType);

    QString baseName = CppQuickFixSettings::memberBaseName(data.memberVariableName);
    if (baseName.isEmpty())
        baseName = data.memberVariableName;

    const QString parameterName = m_settings->getSetterParameterName(baseName, data.memberVariableName);
    if (parameterName == data.memberVariableName)
        data.memberVariableName = "this->" + data.memberVariableName;

    getSetTemplate.replacePlaceholders(data.memberVariableName, parameterName);

    using Pattern = CppQuickFixSettings::GetterSetterTemplate;
    std::optional<FullySpecifiedType> returnTypeTemplateParameter;
    if (getSetTemplate.returnTypeTemplate.has_value()) {
        QString returnTypeTemplate = getSetTemplate.returnTypeTemplate.value();
        if (returnTypeTemplate.contains(Pattern::TEMPLATE_PARAMETER_PATTERN)) {
            returnTypeTemplateParameter = getFirstTemplateParameter(data.declarationSymbol->type());
            if (!returnTypeTemplateParameter.has_value())
                return; // Maybe report error to the user
        }
    }

    enum class HeaderContext { InsideClass, OutsideClass };
    const auto getReturnTypeHeader = [&](HeaderContext headerContext) {
        Control *control = m_operation->currentFile()->cppDocument()->control();
        if (!getSetTemplate.returnTypeTemplate.has_value()) {
            const FullySpecifiedType &t = m_settings->returnByConstRef ? parameterType
                                                                       : memberVariableType;
            if (headerContext == HeaderContext::InsideClass)
                return t;
            LookupContext context(m_operation->currentFile()->cppDocument(), m_changes.snapshot());
            SubstitutionEnvironment env;
            env.setContext(context);
            env.switchScope(m_class);
            ClassOrNamespace *targetCoN = context.lookupType(m_class->enclosingScope());
            if (!targetCoN)
                targetCoN = context.globalNamespace();
            UseMinimalNames q(targetCoN);
            env.enter(&q);
            return rewriteType(t, &env, control);
        }
        QString typeTemplate = getSetTemplate.returnTypeTemplate.value();
        if (returnTypeTemplateParameter.has_value())
            typeTemplate.replace(Pattern::TEMPLATE_PARAMETER_PATTERN,
                                 overview.prettyType(returnTypeTemplateParameter.value()));
        if (typeTemplate.contains(Pattern::TYPE_PATTERN))
            typeTemplate.replace(Pattern::TYPE_PATTERN,
                                 overview.prettyType(data.declarationSymbol->type()));
        std::string utf8TypeName = typeTemplate.toUtf8().toStdString();
        return FullySpecifiedType(control->namedType(control->identifier(utf8TypeName.c_str())));
    };
    const FullySpecifiedType returnTypeHeader = getReturnTypeHeader(HeaderContext::OutsideClass);
    const FullySpecifiedType returnTypeClass = getReturnTypeHeader(HeaderContext::InsideClass);

    // getter declaration
    if (generateFlags & Flag::GenerateGetter) {
        // maybe we added 'this->' to memberVariableName because of a collision with parameterName
        // but here the 'this->' is not needed
        const QString returnExpression = QString{getSetTemplate.returnExpression}.replace("this->",
                                                                                          "");
        QString getterInClassDeclaration = overview.prettyType(returnTypeClass, data.getterName)
                                           + QLatin1String("()");
        if (isMemberVariableStatic)
            getterInClassDeclaration.prepend(QLatin1String("static "));
        else
            getterInClassDeclaration += QLatin1String(" const");
        getterInClassDeclaration.prepend(m_settings->getterAttributes + QLatin1Char(' '));

        auto getterLocation = m_settings->determineGetterLocation(1);
        // if we have an anonymous class we must add code inside the class
        if (data.clazz->name()->asAnonymousNameId())
            getterLocation = CppQuickFixSettings::FunctionLocation::InsideClass;

        if (getterLocation == CppQuickFixSettings::FunctionLocation::InsideClass) {
            getterInClassDeclaration += QLatin1String("\n{\nreturn ") + returnExpression
                                        + QLatin1String(";\n}\n");
        } else {
            getterInClassDeclaration += QLatin1String(";\n");
        }
        addHeaderCode(InsertionPointLocator::Public, getterInClassDeclaration);
        if (getterLocation == CppQuickFixSettings::FunctionLocation::CppFile && !hasSourceFile())
            getterLocation = CppQuickFixSettings::FunctionLocation::OutsideClass;

        if (getterLocation != CppQuickFixSettings::FunctionLocation::InsideClass) {
            const auto getReturnTypeAt = [&](CppRefactoringFilePtr targetFile,
                                             InsertionLocation targetLoc) {
                if (getSetTemplate.returnTypeTemplate.has_value()) {
                    QString returnType = getSetTemplate.returnTypeTemplate.value();
                    if (returnTypeTemplateParameter.has_value()) {
                        const QString templateTypeName = overview.prettyType(typeAt(
                            returnTypeTemplateParameter.value(), data.clazz, targetFile, targetLoc));
                        returnType.replace(Pattern::TEMPLATE_PARAMETER_PATTERN, templateTypeName);
                    }
                    if (returnType.contains(Pattern::TYPE_PATTERN)) {
                        const QString declarationType = overview.prettyType(
                            typeAt(memberVariableType, data.clazz, targetFile, targetLoc));
                        returnType.replace(Pattern::TYPE_PATTERN, declarationType);
                    }
                    Control *control = m_operation->currentFile()->cppDocument()->control();
                    std::string utf8String = returnType.toUtf8().toStdString();
                    return FullySpecifiedType(
                        control->namedType(control->identifier(utf8String.c_str())));
                } else {
                    FullySpecifiedType returnType = typeAt(memberVariableType,
                                                           data.clazz,
                                                           targetFile,
                                                           targetLoc);
                    if (m_settings->returnByConstRef && !isValueType)
                        return makeConstRef(returnType);
                    return returnType;
                }
            };
            const QString constSpec = isMemberVariableStatic ? QLatin1String("")
                                                             : QLatin1String(" const");
            if (getterLocation == CppQuickFixSettings::FunctionLocation::CppFile) {
                InsertionLocation loc = sourceLocationFor(data.declarationSymbol);
                FullySpecifiedType returnType;
                QString clazz;
                if (m_settings->rewriteTypesinCppFile()) {
                    returnType = getReturnTypeAt(m_sourceFile, loc);
                    clazz = symbolAt(data.clazz, m_sourceFile, loc);
                } else {
                    returnType = returnTypeHeader;
                    const Identifier *identifier = data.clazz->name()->identifier();
                    clazz = QString::fromUtf8(identifier->chars(), identifier->size());
                }
                const QString code = overview.prettyType(returnType, clazz + "::" + data.getterName)
                                     + "()" + constSpec + "\n{\nreturn " + returnExpression + ";\n}";
                addSourceFileCode(code);
            } else if (getterLocation == CppQuickFixSettings::FunctionLocation::OutsideClass) {
                InsertionLocation loc
                    = insertLocationForMethodDefinition(data.declarationSymbol,
                                                        false,
                                                        NamespaceHandling::Ignore,
                                                        m_changes,
                                                        m_headerFile->filePath());
                const FullySpecifiedType returnType = getReturnTypeAt(m_headerFile, loc);
                const QString clazz = symbolAt(data.clazz, m_headerFile, loc);
                QString code = overview.prettyType(returnType, clazz + "::" + data.getterName)
                               + "()" + constSpec + "\n{\nreturn " + returnExpression + ";\n}";
                if (m_isHeaderHeaderFile)
                    code.prepend("inline ");
                insertAndIndent(m_headerFile, loc, code);
            }
        }
    }

    // setter declaration
    InsertionPointLocator::AccessSpec setterAccessSpec = InsertionPointLocator::Public;
    if (m_settings->setterAsSlot) {
        const QByteArray connectName = "connect";
        const Identifier connectId(connectName.data(), connectName.size());
        const QList<LookupItem> items = m_operation->context().lookup(&connectId, data.clazz);
        for (const LookupItem &item : items) {
            if (item.declaration() && item.declaration()->enclosingClass()
                && overview.prettyName(item.declaration()->enclosingClass()->name())
                       == "QObject") {
                setterAccessSpec = InsertionPointLocator::PublicSlot;
                break;
            }
        }
    }
    const auto createSetterBodyWithSignal = [this, &getSetTemplate, &data] {
        QString body;
        QTextStream setter(&body);
        setter << "if (" << getSetTemplate.equalComparison << ")\nreturn;\n";

        setter << getSetTemplate.assignment << ";\n";
        if (m_settings->signalWithNewValue)
            setter << "emit " << data.signalName << "(" << getSetTemplate.returnExpression << ");\n";
        else
            setter << "emit " << data.signalName << "();\n";

        return body;
    };
    if (generateFlags & Flag::GenerateSetter) {
        QString headerDeclaration = "void " + data.setterName + '('
                                    + overview.prettyType(addConstToReference(parameterType),
                                                          parameterName)
                                    + ")";
        if (isMemberVariableStatic)
            headerDeclaration.prepend("static ");
        QString body = "\n{\n";
        if (data.signalName.isEmpty())
            body += getSetTemplate.assignment + ";\n";
        else
            body += createSetterBodyWithSignal();

        body += "}";

        auto setterLocation = m_settings->determineSetterLocation(body.count('\n') - 2);
        // if we have an anonymous class we must add code inside the class
        if (data.clazz->name()->asAnonymousNameId())
            setterLocation = CppQuickFixSettings::FunctionLocation::InsideClass;

        if (setterLocation == CppQuickFixSettings::FunctionLocation::CppFile && !hasSourceFile())
            setterLocation = CppQuickFixSettings::FunctionLocation::OutsideClass;

        if (setterLocation == CppQuickFixSettings::FunctionLocation::InsideClass) {
            headerDeclaration += body;
        } else {
            headerDeclaration += ";\n";
            if (setterLocation == CppQuickFixSettings::FunctionLocation::CppFile) {
                InsertionLocation loc = sourceLocationFor(data.declarationSymbol);
                QString clazz;
                FullySpecifiedType newParameterType = parameterType;
                if (m_settings->rewriteTypesinCppFile()) {
                    newParameterType = typeAt(memberVariableType, data.clazz, m_sourceFile, loc);
                    if (!isValueType)
                        newParameterType = makeConstRef(newParameterType);
                    clazz = symbolAt(data.clazz, m_sourceFile, loc);
                } else {
                    const Identifier *identifier = data.clazz->name()->identifier();
                    clazz = QString::fromUtf8(identifier->chars(), identifier->size());
                }
                newParameterType = addConstToReference(newParameterType);
                const QString code = "void " + clazz + "::" + data.setterName + '('
                                     + overview.prettyType(newParameterType, parameterName) + ')'
                                     + body;
                addSourceFileCode(code);
            } else if (setterLocation == CppQuickFixSettings::FunctionLocation::OutsideClass) {
                InsertionLocation loc
                    = insertLocationForMethodDefinition(data.declarationSymbol,
                                                        false,
                                                        NamespaceHandling::Ignore,
                                                        m_changes,
                                                        m_headerFile->filePath());

                FullySpecifiedType newParameterType = typeAt(data.declarationSymbol->type(),
                                                             data.clazz,
                                                             m_headerFile,
                                                             loc);
                if (!isValueType)
                    newParameterType = makeConstRef(newParameterType);
                newParameterType = addConstToReference(newParameterType);
                QString clazz = symbolAt(data.clazz, m_headerFile, loc);

                QString code = "void " + clazz + "::" + data.setterName + '('
                               + overview.prettyType(newParameterType, parameterName) + ')' + body;
                if (m_isHeaderHeaderFile)
                    code.prepend("inline ");
                insertAndIndent(m_headerFile, loc, code);
            }
        }
        addHeaderCode(setterAccessSpec, headerDeclaration);
    }

    // reset declaration
    if (generateFlags & Flag::GenerateReset) {
        QString headerDeclaration = "void " + data.resetName + "()";
        if (isMemberVariableStatic)
            headerDeclaration.prepend("static ");
        QString body = "\n{\n";
        if (!data.setterName.isEmpty()) {
            body += data.setterName + "({}); // TODO: Adapt to use your actual default value\n";
        } else {
            body += "static $TYPE defaultValue{}; "
                    "// TODO: Adapt to use your actual default value\n";
            if (data.signalName.isEmpty())
                body += getSetTemplate.assignment + ";\n";
            else
                body += createSetterBodyWithSignal();
        }
        body += "}";

        // the template use <parameterName> as new value name, but we want to use 'defaultValue'
        body.replace(QRegularExpression("\\b" + parameterName + "\\b"), "defaultValue");
        // body.count('\n') - 2 : do not count the 2 at start
        auto resetLocation = m_settings->determineSetterLocation(body.count('\n') - 2);
        // if we have an anonymous class we must add code inside the class
        if (data.clazz->name()->asAnonymousNameId())
            resetLocation = CppQuickFixSettings::FunctionLocation::InsideClass;

        if (resetLocation == CppQuickFixSettings::FunctionLocation::CppFile && !hasSourceFile())
            resetLocation = CppQuickFixSettings::FunctionLocation::OutsideClass;

        if (resetLocation == CppQuickFixSettings::FunctionLocation::InsideClass) {
            headerDeclaration += body.replace("$TYPE", overview.prettyType(memberVariableType));
        } else {
            headerDeclaration += ";\n";
            if (resetLocation == CppQuickFixSettings::FunctionLocation::CppFile) {
                const InsertionLocation loc = sourceLocationFor(data.declarationSymbol);
                QString clazz;
                FullySpecifiedType type = memberVariableType;
                if (m_settings->rewriteTypesinCppFile()) {
                    type = typeAt(memberVariableType, data.clazz, m_sourceFile, loc);
                    clazz = symbolAt(data.clazz, m_sourceFile, loc);
                } else {
                    const Identifier *identifier = data.clazz->name()->identifier();
                    clazz = QString::fromUtf8(identifier->chars(), identifier->size());
                }
                const QString code = "void " + clazz + "::" + data.resetName + "()"
                                     + body.replace("$TYPE", overview.prettyType(type));
                addSourceFileCode(code);
            } else if (resetLocation == CppQuickFixSettings::FunctionLocation::OutsideClass) {
                const InsertionLocation loc = insertLocationForMethodDefinition(
                    data.declarationSymbol,
                    false,
                    NamespaceHandling::Ignore,
                    m_changes,
                    m_headerFile->filePath());
                const FullySpecifiedType type = typeAt(data.declarationSymbol->type(),
                                                       data.clazz,
                                                       m_headerFile,
                                                       loc);
                const QString clazz = symbolAt(data.clazz, m_headerFile, loc);
                QString code = "void " + clazz + "::" + data.resetName + "()"
                               + body.replace("$TYPE", overview.prettyType(type));
                if (m_isHeaderHeaderFile)
                    code.prepend("inline ");
                insertAndIndent(m_headerFile, loc, code);
            }
        }
        addHeaderCode(setterAccessSpec, headerDeclaration);
    }

    // signal declaration
    if (generateFlags & Flag::GenerateSignal) {
        const auto &parameter = overview.prettyType(returnTypeClass, data.qPropertyName);
        const QString newValue = m_settings->signalWithNewValue ? parameter : QString();
        const QString declaration = QString("void %1(%2);\n").arg(data.signalName, newValue);
        addHeaderCode(InsertionPointLocator::Signals, declaration);
    }

    // member variable
    if (generateFlags & Flag::GenerateMemberVariable) {
        QString storageDeclaration = overview.prettyType(memberVariableType, data.memberVariableName);
        if (memberVariableType->asPointerType()
            && m_operation->semanticInfo().doc->translationUnit()->languageFeatures().cxx11Enabled) {
            storageDeclaration.append(" = nullptr");
        }
        storageDeclaration.append(";\n");
        addHeaderCode(InsertionPointLocator::Private, storageDeclaration);
    }

    // Q_PROPERTY
    if (generateFlags & Flag::GenerateProperty || generateFlags & Flag::GenerateConstantProperty) {
        // Use the returnTypeHeader as base because of custom types in getSetTemplates.
        // Remove const reference from type.
        FullySpecifiedType type = returnTypeClass;
        if (ReferenceType *ref = type.type()->asReferenceType())
            type = ref->elementType();
        type.setConst(false);

        QString propertyDeclaration
                = QLatin1String("Q_PROPERTY(")
                + overview
                .prettyType(type, CppQuickFixSettings::memberBaseName(data.memberVariableName));
        bool needMember = false;
        if (data.getterName.isEmpty())
            needMember = true;
        else
            propertyDeclaration += QLatin1String(" READ ") + data.getterName;
        if (generateFlags & Flag::GenerateConstantProperty) {
            if (needMember)
                propertyDeclaration += QLatin1String(" MEMBER ") + data.memberVariableName;
            propertyDeclaration.append(QLatin1String(" CONSTANT"));
        } else {
            if (data.setterName.isEmpty()) {
                needMember = true;
            } else if (!getSetTemplate.returnTypeTemplate.has_value()) {
                // if the return type of the getter and then Q_PROPERTY is different than
                // the setter type, we should not add WRITE to the Q_PROPERTY
                propertyDeclaration.append(QLatin1String(" WRITE ")).append(data.setterName);
            }
            if (needMember)
                propertyDeclaration += QLatin1String(" MEMBER ") + data.memberVariableName;
            if (!data.resetName.isEmpty())
                propertyDeclaration += QLatin1String(" RESET ") + data.resetName;
            propertyDeclaration.append(QLatin1String(" NOTIFY ")).append(data.signalName);
        }

        propertyDeclaration.append(QLatin1String(" FINAL)\n"));
        addHeaderCode(InsertionPointLocator::Private, propertyDeclaration);
    }
}

//! Generate constructor
class GenerateConstructor : public CppQuickFixFactory
{
public:
#ifdef WITH_TESTS
    static QObject* createTest();
#endif

protected:
    void setTest() { m_test = true; }

private:
    void doMatch(const CppQuickFixInterface &interface, QuickFixOperations &result) override
    {
        const auto op = QSharedPointer<GenerateConstructorOperation>::create(interface);
        if (!op->isApplicable())
            return;
        op->setTest(m_test);
        result << op;
    }

    bool m_test = false;
};

//! Adds getter and setter functions for a member variable
class GenerateGetterSetter : public CppQuickFixFactory
{
public:
#ifdef WITH_TESTS
    static QObject* createTest();
#endif

private:
    void doMatch(const CppQuickFixInterface &interface, QuickFixOperations &result) override
    {
        ExistingGetterSetterData existing;

        const QList<AST *> &path = interface.path();
        // We expect something like
        // [0] TranslationUnitAST
        // [1] NamespaceAST
        // [2] LinkageBodyAST
        // [3] SimpleDeclarationAST
        // [4] ClassSpecifierAST
        // [5] SimpleDeclarationAST
        // [6] DeclaratorAST
        // [7] DeclaratorIdAST
        // [8] SimpleNameAST

        const int n = path.size();
        if (n < 6)
            return;

        int i = 1;
        const auto variableNameAST = path.at(n - i++)->asSimpleName();
        const auto declaratorId = path.at(n - i++)->asDeclaratorId();
        // DeclaratorAST might be preceded by PointerAST, e.g. for the case
        // "class C { char *@s; };", where '@' denotes the text cursor position.
        auto declarator = path.at(n - i++)->asDeclarator();
        if (!declarator) {
            --i;
            if (path.at(n - i++)->asPointer()) {
                if (n < 7)
                    return;
                declarator = path.at(n - i++)->asDeclarator();
            }
            if (!declarator)
                return;
        }
        const auto variableDecl = path.at(n - i++)->asSimpleDeclaration();
        const auto classSpecifier = path.at(n - i++)->asClassSpecifier();
        const auto classDecl = path.at(n - i++)->asSimpleDeclaration();

        if (!(variableNameAST && declaratorId && variableDecl && classSpecifier && classDecl))
            return;

        // Do not get triggered on member functconstions and arrays
        if (declarator->postfix_declarator_list) {
            return;
        }

        // Construct getter and setter names
        const Name *variableName = variableNameAST->name;
        if (!variableName) {
            return;
        }
        const Identifier *variableId = variableName->identifier();
        if (!variableId) {
            return;
        }
        existing.memberVariableName = QString::fromUtf8(variableId->chars(), variableId->size());

        // Find the right symbol (for typeName) in the simple declaration
        Symbol *symbol = nullptr;
        const List<Symbol *> *symbols = variableDecl->symbols;
        QTC_ASSERT(symbols, return );
        for (; symbols; symbols = symbols->next) {
            Symbol *s = symbols->value;
            if (const Name *name = s->name()) {
                if (const Identifier *id = name->identifier()) {
                    const QString symbolName = QString::fromUtf8(id->chars(), id->size());
                    if (symbolName == existing.memberVariableName) {
                        symbol = s;
                        break;
                    }
                }
            }
        }
        if (!symbol) {
            // no type can be determined
            return;
        }
        if (!symbol->asDeclaration()) {
            return;
        }
        existing.declarationSymbol = symbol->asDeclaration();

        existing.clazz = classSpecifier->symbol;
        if (!existing.clazz)
            return;

        auto file = interface.currentFile();
        // check if a Q_PROPERTY exist
        const QString baseName = CppQuickFixSettings::memberBaseName(existing.memberVariableName);
        // eg: we have 'int m_test' and now 'Q_PROPERTY(int foo WRITE setTest MEMBER m_test NOTIFY tChanged)'
        for (auto it = classSpecifier->member_specifier_list; it; it = it->next) {
            if (it->value->asQtPropertyDeclaration()) {
                auto propDecl = it->value->asQtPropertyDeclaration();
                // iterator over 'READ ...', ...
                auto p = propDecl->property_declaration_item_list;
                // first check, if we have a MEMBER and the member is equal to the baseName
                for (; p; p = p->next) {
                    const char *tokenString = file->tokenAt(p->value->item_name_token).spell();
                    if (!qstrcmp(tokenString, "MEMBER")) {
                        if (baseName == file->textOf(p->value->expression))
                            return;
                    }
                }
                // no MEMBER, but maybe the property name is the same
                const QString propertyName = file->textOf(propDecl->property_name);
                // we compare the baseName. e.g. 'test' instead of 'm_test'
                if (propertyName == baseName)
                    return; // TODO Maybe offer quick fix "Add missing Q_PROPERTY Members"
            }
        }

        findExistingFunctions(existing, toStringList(getMemberFunctions(existing.clazz)));
        existing.qPropertyName = CppQuickFixSettings::memberBaseName(existing.memberVariableName);

        const int possibleFlags = existing.computePossibleFlags();
        GenerateGetterSetterOp::generateQuickFixes(result, interface, existing, possibleFlags);
    }
};

//! Adds getter and setter functions for several member variables
class GenerateGettersSettersForClass : public CppQuickFixFactory
{
public:
#ifdef WITH_TESTS
    static QObject* createTest();
#endif

protected:
    void setTest() { m_test = true; }

private:
    void doMatch(const CppQuickFixInterface &interface, QuickFixOperations &result) override
    {
        const auto op = QSharedPointer<GenerateGettersSettersOperation>::create(interface);
        if (!op->isApplicable())
            return;
        if (m_test) {
            GetterSetterCandidates candidates = op->candidates();
            for (MemberInfo &mi : candidates) {
                mi.requestedFlags = mi.possibleFlags;
                using Flag = GenerateGetterSetterOp::GenerateFlag;
                mi.requestedFlags &= ~Flag::GenerateConstantProperty;
            }
            op->setGetterSetterData(candidates);
        }
        result << op;
    }

    bool m_test = false;
};

//! Adds missing members for a Q_PROPERTY
class InsertQtPropertyMembers : public CppQuickFixFactory
{
public:
#ifdef WITH_TESTS
    static QObject* createTest();
#endif

private:
    void doMatch(const CppQuickFixInterface &interface, QuickFixOperations &result) override
    {
        using Flag = GenerateGetterSetterOp::GenerateFlag;
        ExistingGetterSetterData existing;
        // check for Q_PROPERTY

        const QList<AST *> &path = interface.path();
        if (path.isEmpty())
            return;

        AST *const ast = path.last();
        QtPropertyDeclarationAST *qtPropertyDeclaration = ast->asQtPropertyDeclaration();
        if (!qtPropertyDeclaration || !qtPropertyDeclaration->type_id)
            return;

        ClassSpecifierAST *klass = nullptr;
        for (int i = path.size() - 2; i >= 0; --i) {
            klass = path.at(i)->asClassSpecifier();
            if (klass)
                break;
        }
        if (!klass)
            return;
        existing.clazz = klass->symbol;

        CppRefactoringFilePtr file = interface.currentFile();
        const QString propertyName = file->textOf(qtPropertyDeclaration->property_name);
        existing.qPropertyName = propertyName;
        extractNames(file, qtPropertyDeclaration, existing);

        Control *control = interface.currentFile()->cppDocument()->control();

        existing.declarationSymbol = control->newDeclaration(ast->firstToken(),
                                                             qtPropertyDeclaration->property_name->name);
        existing.declarationSymbol->setVisibility(Symbol::Private);
        existing.declarationSymbol->setEnclosingScope(existing.clazz);

        {
            // create a 'right' Type Object
            // if we have Q_PROPERTY(int test ...) then we only get a NamedType for 'int', but we want
            // a IntegerType. So create a new dummy file with a dummy declaration to get the right
            // object
            QByteArray type = file->textOf(qtPropertyDeclaration->type_id).toUtf8();
            QByteArray newSource = file->document()
                                       ->toPlainText()
                                       .insert(file->startOf(qtPropertyDeclaration),
                                               QString::fromUtf8(type + " __dummy;\n"))
                                       .toUtf8();

            Document::Ptr doc = interface.snapshot().preprocessedDocument(newSource, "___quickfix.h");
            if (!doc->parse(Document::ParseTranslationUnit))
                return;
            doc->check();
            class TypeFinder : public ASTVisitor
            {
            public:
                FullySpecifiedType type;
                TypeFinder(TranslationUnit *u)
                    : ASTVisitor(u)
                {}
                bool visit(SimpleDeclarationAST *ast) override
                {
                    if (ast->symbols && !ast->symbols->next) {
                        const Name *name = ast->symbols->value->name();
                        if (name && name->asNameId() && name->asNameId()->identifier()) {
                            const Identifier *id = name->asNameId()->identifier();
                            if (QString::fromUtf8(id->chars(), id->size()) == "__dummy")
                                type = ast->symbols->value->type();
                        }
                    }
                    return true;
                }
            };
            TypeFinder finder(doc->translationUnit());
            finder.accept(doc->translationUnit()->ast());
            if (finder.type.type()->isUndefinedType())
                return;
            existing.declarationSymbol->setType(finder.type);
            existing.doc = doc; // to hold type
        }
        // check which methods are already there
        const bool haveFixMemberVariableName = !existing.memberVariableName.isEmpty();
        int generateFlags = Flag::GenerateMemberVariable;
        if (!existing.resetName.isEmpty())
            generateFlags |= Flag::GenerateReset;
        if (!existing.setterName.isEmpty())
            generateFlags |= Flag::GenerateSetter;
        if (!existing.getterName.isEmpty())
            generateFlags |= Flag::GenerateGetter;
        if (!existing.signalName.isEmpty())
            generateFlags |= Flag::GenerateSignal;
        Overview overview;
        for (int i = 0; i < existing.clazz->memberCount(); ++i) {
            Symbol *member = existing.clazz->memberAt(i);
            FullySpecifiedType type = member->type();
            if (member->asFunction() || (type.isValid() && type->asFunctionType())) {
                const QString name = overview.prettyName(member->name());
                if (name == existing.getterName)
                    generateFlags &= ~Flag::GenerateGetter;
                else if (name == existing.setterName)
                    generateFlags &= ~Flag::GenerateSetter;
                else if (name == existing.resetName)
                    generateFlags &= ~Flag::GenerateReset;
                else if (name == existing.signalName)
                    generateFlags &= ~Flag::GenerateSignal;
            } else if (member->asDeclaration()) {
                const QString name = overview.prettyName(member->name());
                if (haveFixMemberVariableName) {
                    if (name == existing.memberVariableName) {
                        generateFlags &= ~Flag::GenerateMemberVariable;
                    }
                } else {
                    const QString baseName = CppQuickFixSettings::memberBaseName(name);
                    if (existing.qPropertyName == baseName) {
                        existing.memberVariableName = name;
                        generateFlags &= ~Flag::GenerateMemberVariable;
                    }
                }
            }
        }
        if (generateFlags & Flag::GenerateMemberVariable) {
            CppQuickFixSettings *settings = CppQuickFixProjectsSettings::getQuickFixSettings(
                ProjectExplorer::ProjectTree::currentProject());
            existing.memberVariableName = settings->getMemberVariableName(existing.qPropertyName);
        }
        if (generateFlags == 0) {
            // everything is already there
            return;
        }
        generateFlags |= Flag::HaveExistingQProperty;
        GenerateGetterSetterOp::generateQuickFixes(result, interface, existing, generateFlags);
    }
};


#ifdef WITH_TESTS
using namespace Tests;

class GenerateGetterSetterTest : public QObject
{
    Q_OBJECT

private slots:
    void testNamespaceHandlingCreate_data()
    {
        QTest::addColumn<QByteArrayList>("headers");
        QTest::addColumn<QByteArrayList>("sources");

        QByteArray originalSource;
        QByteArray expectedSource;

        const QByteArray originalHeader =
                "namespace N1 {\n"
                "namespace N2 {\n"
                "class Something\n"
                "{\n"
                "    int @it;\n"
                "};\n"
                "}\n"
                "}\n";
        const QByteArray expectedHeader =
                "namespace N1 {\n"
                "namespace N2 {\n"
                "class Something\n"
                "{\n"
                "    int it;\n"
                "\n"
                "public:\n"
                "    int getIt() const;\n"
                "    void setIt(int value);\n"
                "};\n"
                "}\n"
                "}\n";

        originalSource = "#include \"file.h\"\n";
        expectedSource =
                "#include \"file.h\"\n\n\n"
                "namespace N1 {\n"
                "namespace N2 {\n"
                "int Something::getIt() const\n"
                "{\n"
                "    return it;\n"
                "}\n"
                "\n"
                "void Something::setIt(int value)\n"
                "{\n"
                "    it = value;\n"
                "}\n\n"
                "}\n"
                "}\n";
        QTest::addRow("insert new namespaces")
                << QByteArrayList{originalHeader, expectedHeader}
                << QByteArrayList{originalSource, expectedSource};

        originalSource =
                "#include \"file.h\"\n"
                "namespace N2 {} // decoy\n";
        expectedSource =
                "#include \"file.h\"\n"
                "namespace N2 {} // decoy\n\n\n"
                "namespace N1 {\n"
                "namespace N2 {\n"
                "int Something::getIt() const\n"
                "{\n"
                "    return it;\n"
                "}\n"
                "\n"
                "void Something::setIt(int value)\n"
                "{\n"
                "    it = value;\n"
                "}\n\n"
                "}\n"
                "}\n";
        QTest::addRow("insert new namespaces (with decoy)")
                << QByteArrayList{originalHeader, expectedHeader}
                << QByteArrayList{originalSource, expectedSource};

        originalSource = "#include \"file.h\"\n"
                         "namespace N2 {} // decoy\n"
                         "namespace {\n"
                         "namespace N1 {\n"
                         "namespace {\n"
                         "}\n"
                         "}\n"
                         "}\n";
        expectedSource = "#include \"file.h\"\n"
                         "namespace N2 {} // decoy\n"
                         "namespace {\n"
                         "namespace N1 {\n"
                         "namespace {\n"
                         "}\n"
                         "}\n"
                         "}\n"
                         "\n"
                         "\n"
                         "namespace N1 {\n"
                         "namespace N2 {\n"
                         "int Something::getIt() const\n"
                         "{\n"
                         "    return it;\n"
                         "}\n"
                         "\n"
                         "void Something::setIt(int value)\n"
                         "{\n"
                         "    it = value;\n"
                         "}\n"
                         "\n"
                         "}\n"
                         "}\n";
        QTest::addRow("insert inner namespace (with decoy and unnamed)")
            << QByteArrayList{originalHeader, expectedHeader}
            << QByteArrayList{originalSource, expectedSource};

        const QByteArray unnamedOriginalHeader = "namespace {\n" + originalHeader + "}\n";
        const QByteArray unnamedExpectedHeader = "namespace {\n" + expectedHeader + "}\n";

        originalSource = "#include \"file.h\"\n"
                         "namespace N2 {} // decoy\n"
                         "namespace {\n"
                         "namespace N1 {\n"
                         "namespace {\n"
                         "}\n"
                         "}\n"
                         "}\n";
        expectedSource = "#include \"file.h\"\n"
                         "namespace N2 {} // decoy\n"
                         "namespace {\n"
                         "namespace N1 {\n"
                         "\n"
                         "namespace N2 {\n"
                         "int Something::getIt() const\n"
                         "{\n"
                         "    return it;\n"
                         "}\n"
                         "\n"
                         "void Something::setIt(int value)\n"
                         "{\n"
                         "    it = value;\n"
                         "}\n"
                         "\n"
                         "}\n"
                         "\n"
                         "namespace {\n"
                         "}\n"
                         "}\n"
                         "}\n";
        QTest::addRow("insert inner namespace in unnamed (with decoy)")
            << QByteArrayList{unnamedOriginalHeader, unnamedExpectedHeader}
            << QByteArrayList{originalSource, expectedSource};

        originalSource =
                "#include \"file.h\"\n"
                "namespace N1 {\n"
                "namespace N2 {\n"
                "namespace N3 {\n"
                "}\n"
                "}\n"
                "}\n";
        expectedSource =
                "#include \"file.h\"\n"
                "namespace N1 {\n"
                "namespace N2 {\n"
                "namespace N3 {\n"
                "}\n\n"
                "int Something::getIt() const\n"
                "{\n"
                "    return it;\n"
                "}\n"
                "\n"
                "void Something::setIt(int value)\n"
                "{\n"
                "    it = value;\n"
                "}\n\n"
                "}\n"
                "}\n";
        QTest::addRow("all namespaces already present")
                << QByteArrayList{originalHeader, expectedHeader}
                << QByteArrayList{originalSource, expectedSource};

        originalSource = "#include \"file.h\"\n"
                         "namespace N1 {\n"
                         "using namespace N2::N3;\n"
                         "using namespace N2;\n"
                         "using namespace N2;\n"
                         "using namespace N3;\n"
                         "}\n";
        expectedSource = "#include \"file.h\"\n"
                         "namespace N1 {\n"
                         "using namespace N2::N3;\n"
                         "using namespace N2;\n"
                         "using namespace N2;\n"
                         "using namespace N3;\n"
                         "\n"
                         "int Something::getIt() const\n"
                         "{\n"
                         "    return it;\n"
                         "}\n"
                         "\n"
                         "void Something::setIt(int value)\n"
                         "{\n"
                         "    it = value;\n"
                         "}\n\n"
                         "}\n";
        QTest::addRow("namespaces present and using namespace")
            << QByteArrayList{originalHeader, expectedHeader}
            << QByteArrayList{originalSource, expectedSource};

        originalSource = "#include \"file.h\"\n"
                         "using namespace N1::N2::N3;\n"
                         "using namespace N1::N2;\n"
                         "namespace N1 {\n"
                         "using namespace N3;\n"
                         "}\n";
        expectedSource = "#include \"file.h\"\n"
                         "using namespace N1::N2::N3;\n"
                         "using namespace N1::N2;\n"
                         "namespace N1 {\n"
                         "using namespace N3;\n"
                         "\n"
                         "int Something::getIt() const\n"
                         "{\n"
                         "    return it;\n"
                         "}\n"
                         "\n"
                         "void Something::setIt(int value)\n"
                         "{\n"
                         "    it = value;\n"
                         "}\n"
                         "\n"
                         "}\n";
        QTest::addRow("namespaces present and outer using namespace")
            << QByteArrayList{originalHeader, expectedHeader}
            << QByteArrayList{originalSource, expectedSource};

        originalSource = "#include \"file.h\"\n"
                         "using namespace N1;\n"
                         "using namespace N2;\n"
                         "namespace N3 {\n"
                         "}\n";
        expectedSource = "#include \"file.h\"\n"
                         "using namespace N1;\n"
                         "using namespace N2;\n"
                         "namespace N3 {\n"
                         "}\n"
                         "\n"
                         "int Something::getIt() const\n"
                         "{\n"
                         "    return it;\n"
                         "}\n"
                         "\n"
                         "void Something::setIt(int value)\n"
                         "{\n"
                         "    it = value;\n"
                         "}\n";
        QTest::addRow("namespaces present and outer using namespace")
            << QByteArrayList{originalHeader, expectedHeader}
            << QByteArrayList{originalSource, expectedSource};
    }

    void testNamespaceHandlingCreate()
    {
        QFETCH(QByteArrayList, headers);
        QFETCH(QByteArrayList, sources);

        QList<TestDocumentPtr> testDocuments(
            {CppTestDocument::create("file.h", headers.at(0), headers.at(1)),
             CppTestDocument::create("file.cpp", sources.at(0), sources.at(1))});

        QuickFixSettings s;
        s->cppFileNamespaceHandling = CppQuickFixSettings::MissingNamespaceHandling::CreateMissing;
        s->setterParameterNameTemplate = "\"value\"";
        s->setterInCppFileFrom = 1;
        s->getterInCppFileFrom = 1;
        GenerateGetterSetter factory;
        QuickFixOperationTest(testDocuments, &factory, ProjectExplorer::HeaderPaths(), 2);
    }

    void testNamespaceHandlingAddUsing_data()
    {
        QTest::addColumn<QByteArrayList>("headers");
        QTest::addColumn<QByteArrayList>("sources");

        QByteArray originalSource;
        QByteArray expectedSource;

        const QByteArray originalHeader = "namespace N1 {\n"
                                          "namespace N2 {\n"
                                          "class Something\n"
                                          "{\n"
                                          "    int @it;\n"
                                          "};\n"
                                          "}\n"
                                          "}\n";
        const QByteArray expectedHeader = "namespace N1 {\n"
                                          "namespace N2 {\n"
                                          "class Something\n"
                                          "{\n"
                                          "    int it;\n"
                                          "\n"
                                          "public:\n"
                                          "    void setIt(int value);\n"
                                          "};\n"
                                          "}\n"
                                          "}\n";

        originalSource = "#include \"file.h\"\n";
        expectedSource = "#include \"file.h\"\n\n"
                         "using namespace N1::N2;\n"
                         "void Something::setIt(int value)\n"
                         "{\n"
                         "    it = value;\n"
                         "}\n";
        QTest::addRow("add using namespaces") << QByteArrayList{originalHeader, expectedHeader}
                                              << QByteArrayList{originalSource, expectedSource};

        const QByteArray unnamedOriginalHeader = "namespace {\n" + originalHeader + "}\n";
        const QByteArray unnamedExpectedHeader = "namespace {\n" + expectedHeader + "}\n";

        originalSource = "#include \"file.h\"\n"
                         "namespace N2 {} // decoy\n"
                         "namespace {\n"
                         "namespace N1 {\n"
                         "namespace {\n"
                         "}\n"
                         "}\n"
                         "}\n";
        expectedSource = "#include \"file.h\"\n"
                         "namespace N2 {} // decoy\n"
                         "namespace {\n"
                         "namespace N1 {\n"
                         "using namespace N2;\n"
                         "void Something::setIt(int value)\n"
                         "{\n"
                         "    it = value;\n"
                         "}\n"
                         "namespace {\n"
                         "}\n"
                         "}\n"
                         "}\n";
        QTest::addRow("insert using namespace into unnamed nested (with decoy)")
            << QByteArrayList{unnamedOriginalHeader, unnamedExpectedHeader}
            << QByteArrayList{originalSource, expectedSource};

        originalSource = "#include \"file.h\"\n";
        expectedSource = "#include \"file.h\"\n\n"
                         "using namespace N1::N2;\n"
                         "void Something::setIt(int value)\n"
                         "{\n"
                         "    it = value;\n"
                         "}\n";
        QTest::addRow("insert using namespace into unnamed")
            << QByteArrayList{unnamedOriginalHeader, unnamedExpectedHeader}
            << QByteArrayList{originalSource, expectedSource};

        originalSource = "#include \"file.h\"\n"
                         "namespace N2 {} // decoy\n"
                         "namespace {\n"
                         "namespace N1 {\n"
                         "namespace {\n"
                         "}\n"
                         "}\n"
                         "}\n";
        expectedSource = "#include \"file.h\"\n"
                         "namespace N2 {} // decoy\n"
                         "namespace {\n"
                         "namespace N1 {\n"
                         "namespace {\n"
                         "}\n"
                         "}\n"
                         "}\n"
                         "\n"
                         "using namespace N1::N2;\n"
                         "void Something::setIt(int value)\n"
                         "{\n"
                         "    it = value;\n"
                         "}\n";
        QTest::addRow("insert using namespace (with decoy)")
            << QByteArrayList{originalHeader, expectedHeader}
            << QByteArrayList{originalSource, expectedSource};
    }

    void testNamespaceHandlingAddUsing()
    {
        QFETCH(QByteArrayList, headers);
        QFETCH(QByteArrayList, sources);

        QList<TestDocumentPtr> testDocuments(
            {CppTestDocument::create("file.h", headers.at(0), headers.at(1)),
             CppTestDocument::create("file.cpp", sources.at(0), sources.at(1))});

        QuickFixSettings s;
        s->cppFileNamespaceHandling = CppQuickFixSettings::MissingNamespaceHandling::AddUsingDirective;
        s->setterParameterNameTemplate = "\"value\"";
        s->setterInCppFileFrom = 1;

        if (std::strstr(QTest::currentDataTag(), "unnamed nested") != nullptr)
            QSKIP("TODO"); // FIXME
        GenerateGetterSetter factory;
        QuickFixOperationTest(testDocuments, &factory);
    }

    void testNamespaceHandlingFullyQualify_data()
    {
        QTest::addColumn<QByteArrayList>("headers");
        QTest::addColumn<QByteArrayList>("sources");

        QByteArray originalSource;
        QByteArray expectedSource;

        const QByteArray originalHeader = "namespace N1 {\n"
                                          "namespace N2 {\n"
                                          "class Something\n"
                                          "{\n"
                                          "    int @it;\n"
                                          "};\n"
                                          "}\n"
                                          "}\n";
        const QByteArray expectedHeader = "namespace N1 {\n"
                                          "namespace N2 {\n"
                                          "class Something\n"
                                          "{\n"
                                          "    int it;\n"
                                          "\n"
                                          "public:\n"
                                          "    void setIt(int value);\n"
                                          "};\n"
                                          "}\n"
                                          "}\n";

        originalSource = "#include \"file.h\"\n";
        expectedSource = "#include \"file.h\"\n\n"
                         "void N1::N2::Something::setIt(int value)\n"
                         "{\n"
                         "    it = value;\n"
                         "}\n";
        QTest::addRow("fully qualify") << QByteArrayList{originalHeader, expectedHeader}
                                       << QByteArrayList{originalSource, expectedSource};

        originalSource = "#include \"file.h\"\n"
                         "namespace N2 {} // decoy\n";
        expectedSource = "#include \"file.h\"\n"
                         "namespace N2 {} // decoy\n"
                         "\n"
                         "void N1::N2::Something::setIt(int value)\n"
                         "{\n"
                         "    it = value;\n"
                         "}\n";
        QTest::addRow("fully qualify (with decoy)") << QByteArrayList{originalHeader, expectedHeader}
                                                    << QByteArrayList{originalSource, expectedSource};

        originalSource = "#include \"file.h\"\n"
                         "namespace N2 {} // decoy\n"
                         "namespace {\n"
                         "namespace N1 {\n"
                         "namespace {\n"
                         "}\n"
                         "}\n"
                         "}\n";
        expectedSource = "#include \"file.h\"\n"
                         "namespace N2 {} // decoy\n"
                         "namespace {\n"
                         "namespace N1 {\n"
                         "namespace {\n"
                         "}\n"
                         "}\n"
                         "}\n"
                         "\n"
                         "void N1::N2::Something::setIt(int value)\n"
                         "{\n"
                         "    it = value;\n"
                         "}\n";
        QTest::addRow("qualify in inner namespace (with decoy)")
            << QByteArrayList{originalHeader, expectedHeader}
            << QByteArrayList{originalSource, expectedSource};

        const QByteArray unnamedOriginalHeader = "namespace {\n" + originalHeader + "}\n";
        const QByteArray unnamedExpectedHeader = "namespace {\n" + expectedHeader + "}\n";

        originalSource = "#include \"file.h\"\n"
                         "namespace N2 {} // decoy\n"
                         "namespace {\n"
                         "namespace N1 {\n"
                         "namespace {\n"
                         "}\n"
                         "}\n"
                         "}\n";
        expectedSource = "#include \"file.h\"\n"
                         "namespace N2 {} // decoy\n"
                         "namespace {\n"
                         "namespace N1 {\n"
                         "void N2::Something::setIt(int value)\n"
                         "{\n"
                         "    it = value;\n"
                         "}\n"
                         "namespace {\n"
                         "}\n"
                         "}\n"
                         "}\n";
        QTest::addRow("qualify in inner namespace unnamed nested (with decoy)")
            << QByteArrayList{unnamedOriginalHeader, unnamedExpectedHeader}
            << QByteArrayList{originalSource, expectedSource};

        originalSource = "#include \"file.h\"\n";
        expectedSource = "#include \"file.h\"\n\n"
                         "void N1::N2::Something::setIt(int value)\n"
                         "{\n"
                         "    it = value;\n"
                         "}\n";
        QTest::addRow("qualify in unnamed namespace")
            << QByteArrayList{unnamedOriginalHeader, unnamedExpectedHeader}
            << QByteArrayList{originalSource, expectedSource};
    }

    void testNamespaceHandlingFullyQualify()
    {
        QFETCH(QByteArrayList, headers);
        QFETCH(QByteArrayList, sources);

        QList<TestDocumentPtr> testDocuments(
            {CppTestDocument::create("file.h", headers.at(0), headers.at(1)),
             CppTestDocument::create("file.cpp", sources.at(0), sources.at(1))});

        QuickFixSettings s;
        s->cppFileNamespaceHandling = CppQuickFixSettings::MissingNamespaceHandling::RewriteType;
        s->setterParameterNameTemplate = "\"value\"";
        s->setterInCppFileFrom = 1;

        if (std::strstr(QTest::currentDataTag(), "unnamed nested") != nullptr)
            QSKIP("TODO"); // FIXME
        GenerateGetterSetter factory;
        QuickFixOperationTest(testDocuments, &factory);
    }

    void testCustomNames_data()
    {
        QTest::addColumn<QByteArrayList>("headers");
        QTest::addColumn<int>("operation");

        QByteArray originalSource;
        QByteArray expectedSource;

        // Check if right names are created
        originalSource = R"-(
    class Test {
        int m_fooBar_test@;
    };
)-";
        expectedSource = R"-(
    class Test {
        int m_fooBar_test;

    public:
        int give_me_foo_bar_test() const
        {
            return m_fooBar_test;
        }
        void Seet_FooBar_test(int New_Foo_Bar_Test)
        {
            if (m_fooBar_test == New_Foo_Bar_Test)
                return;
            m_fooBar_test = New_Foo_Bar_Test;
            emit newFooBarTestValue();
        }
        void set_fooBarTest_toDefault()
        {
            Seet_FooBar_test({}); // TODO: Adapt to use your actual default value
        }

    signals:
        void newFooBarTestValue();

    private:
        Q_PROPERTY(int fooBar_test READ give_me_foo_bar_test WRITE Seet_FooBar_test RESET set_fooBarTest_toDefault NOTIFY newFooBarTestValue FINAL)
    };
)-";
        QTest::addRow("create right names") << QByteArrayList{originalSource, expectedSource} << 4;

        // Check if not triggered with custom names
        originalSource = R"-(
    class Test {
        int m_fooBar_test@;

    public:
        int give_me_foo_bar_test() const
        {
            return m_fooBar_test;
        }
        void Seet_FooBar_test(int New_Foo_Bar_Test)
        {
            if (m_fooBar_test == New_Foo_Bar_Test)
                return;
            m_fooBar_test = New_Foo_Bar_Test;
            emit newFooBarTestValue();
        }
        void set_fooBarTest_toDefault()
        {
            Seet_FooBar_test({}); // TODO: Adapt to use your actual default value
        }

    signals:
        void newFooBarTestValue();

    private:
        Q_PROPERTY(int fooBar_test READ give_me_foo_bar_test WRITE Seet_FooBar_test RESET set_fooBarTest_toDefault NOTIFY newFooBarTestValue FINAL)
    };
)-";
        expectedSource = "";
        QTest::addRow("everything already exists") << QByteArrayList{originalSource, expectedSource} << 4;

        // create from Q_PROPERTY with custom names
        originalSource = R"-(
    class Test {
        Q_PROPER@TY(int fooBar_test READ give_me_foo_bar_test WRITE Seet_FooBar_test RESET set_fooBarTest_toDefault NOTIFY newFooBarTestValue FINAL)

    public:
        int give_me_foo_bar_test() const
        {
            return mem_fooBar_test;
        }
        void Seet_FooBar_test(int New_Foo_Bar_Test)
        {
            if (mem_fooBar_test == New_Foo_Bar_Test)
                return;
            mem_fooBar_test = New_Foo_Bar_Test;
            emit newFooBarTestValue();
        }
        void set_fooBarTest_toDefault()
        {
            Seet_FooBar_test({}); // TODO: Adapt to use your actual default value
        }

    signals:
        void newFooBarTestValue();
    };
)-";
        expectedSource = R"-(
    class Test {
        Q_PROPERTY(int fooBar_test READ give_me_foo_bar_test WRITE Seet_FooBar_test RESET set_fooBarTest_toDefault NOTIFY newFooBarTestValue FINAL)

    public:
        int give_me_foo_bar_test() const
        {
            return mem_fooBar_test;
        }
        void Seet_FooBar_test(int New_Foo_Bar_Test)
        {
            if (mem_fooBar_test == New_Foo_Bar_Test)
                return;
            mem_fooBar_test = New_Foo_Bar_Test;
            emit newFooBarTestValue();
        }
        void set_fooBarTest_toDefault()
        {
            Seet_FooBar_test({}); // TODO: Adapt to use your actual default value
        }

    signals:
        void newFooBarTestValue();
    private:
        int mem_fooBar_test;
    };
)-";
        QTest::addRow("create only member variable")
            << QByteArrayList{originalSource, expectedSource} << 0;

        // create from Q_PROPERTY with custom names
        originalSource = R"-(
    class Test {
        Q_PROPE@RTY(int fooBar_test READ give_me_foo_bar_test WRITE Seet_FooBar_test RESET set_fooBarTest_toDefault NOTIFY newFooBarTestValue FINAL)
        int mem_fooBar_test;
    public:
    };
)-";
        expectedSource = R"-(
    class Test {
        Q_PROPERTY(int fooBar_test READ give_me_foo_bar_test WRITE Seet_FooBar_test RESET set_fooBarTest_toDefault NOTIFY newFooBarTestValue FINAL)
        int mem_fooBar_test;
    public:
        int give_me_foo_bar_test() const
        {
            return mem_fooBar_test;
        }
        void Seet_FooBar_test(int New_Foo_Bar_Test)
        {
            if (mem_fooBar_test == New_Foo_Bar_Test)
                return;
            mem_fooBar_test = New_Foo_Bar_Test;
            emit newFooBarTestValue();
        }
        void set_fooBarTest_toDefault()
        {
            Seet_FooBar_test({}); // TODO: Adapt to use your actual default value
        }
    signals:
        void newFooBarTestValue();
    };
)-";
        QTest::addRow("create methods with given member variable")
            << QByteArrayList{originalSource, expectedSource} << 0;
    }

    void testCustomNames()
    {
        QFETCH(QByteArrayList, headers);
        QFETCH(int, operation);

        QList<TestDocumentPtr> testDocuments(
            {CppTestDocument::create("file.h", headers.at(0), headers.at(1))});

        QuickFixSettings s;
        s->setterInCppFileFrom = 0;
        s->getterInCppFileFrom = 0;
        s->setterNameTemplate =  R"js("Seet_" + name[0].toUpperCase() + name.slice(1))js";
        s->getterNameTemplate = R"js("give_me_" + name.replace(/([A-Z])/g,
            function(v) { return "_" + v.toLowerCase(); }))js";
        s->signalNameTemplate = R"js("new" + name[0].toUpperCase()
            + name.slice(1).replace(/_([a-z])/g, function(v) { return v.slice(1).toUpperCase(); })
            + "Value")js";
        s->setterParameterNameTemplate = R"js("New_" + name[0].toUpperCase()
            + name.slice(1).replace(/([A-Z])/g,
                "_" + "$1").replace(/(_[a-z])/g, function(v) { return v.toUpperCase(); }))js";
        s->resetNameTemplate = R"js("set_" + name.replace(/_([a-z])/g,
            function(v) { return v.slice(1).toUpperCase(); }) + "_toDefault")js";
        s->memberVariableNameTemplate = R"js("mem_" + name)js";
        if (QByteArray(QTest::currentDataTag()) == "create methods with given member variable")
            s->nameFromMemberVariableTemplate = R"js(name.slice(4))js";
        if (operation == 0) {
            InsertQtPropertyMembers factory;
            QuickFixOperationTest(testDocuments, &factory, ProjectExplorer::HeaderPaths(), operation);
        } else {
            GenerateGetterSetter factory;
            QuickFixOperationTest(testDocuments, &factory, ProjectExplorer::HeaderPaths(), operation);
        }
    }

    void testValueTypes_data()
    {
        QTest::addColumn<QByteArrayList>("headers");
        QTest::addColumn<int>("operation");

        QByteArray originalSource;
        QByteArray expectedSource;

        // int should be a value type
        originalSource = R"-(
    class Test {
        int i@;
    };
)-";
        expectedSource = R"-(
    class Test {
        int i;

    public:
        int getI() const
        {
            return i;
        }
    };
)-";
        QTest::addRow("int") << QByteArrayList{originalSource, expectedSource} << 1;

        // return type should be only int without const
        originalSource = R"-(
    class Test {
        const int i@;
    };
)-";
        expectedSource = R"-(
    class Test {
        const int i;

    public:
        int getI() const
        {
            return i;
        }
    };
)-";
        QTest::addRow("const int") << QByteArrayList{originalSource, expectedSource} << 0;

        // float should be a value type
        originalSource = R"-(
    class Test {
        float f@;
    };
)-";
        expectedSource = R"-(
    class Test {
        float f;

    public:
        float getF() const
        {
            return f;
        }
    };
)-";
        QTest::addRow("float") << QByteArrayList{originalSource, expectedSource} << 1;

        // pointer should be a value type
        originalSource = R"-(
    class Test {
        void* v@;
    };
)-";
        expectedSource = R"-(
    class Test {
        void* v;

    public:
        void *getV() const
        {
            return v;
        }
    };
)-";
        QTest::addRow("pointer") << QByteArrayList{originalSource, expectedSource} << 1;

        // reference should be a value type (setter is const ref)
        originalSource = R"-(
    class Test {
        int& r@;
    };
)-";
        expectedSource = R"-(
    class Test {
        int& r;

    public:
        int &getR() const
        {
            return r;
        }
        void setR(const int &newR)
        {
            r = newR;
        }
    };
)-";
        QTest::addRow("reference to value type") << QByteArrayList{originalSource, expectedSource} << 2;

        // reference should be a value type
        originalSource = R"-(
    using bar = int;
    class Test {
        bar i@;
    };
)-";
        expectedSource = R"-(
    using bar = int;
    class Test {
        bar i;

    public:
        bar getI() const
        {
            return i;
        }
    };
)-";
        QTest::addRow("value type through using") << QByteArrayList{originalSource, expectedSource} << 1;

        // enum should be a value type
        originalSource = R"-(
    enum Foo{V1, V2};
    class Test {
        Foo e@;
    };
)-";
        expectedSource = R"-(
    enum Foo{V1, V2};
    class Test {
        Foo e;

    public:
        Foo getE() const
        {
            return e;
        }
    };
)-";
        QTest::addRow("enum") << QByteArrayList{originalSource, expectedSource} << 1;

        // class should not be a value type
        originalSource = R"-(
    class NoVal{};
    class Test {
        NoVal n@;
    };
)-";
        expectedSource = R"-(
    class NoVal{};
    class Test {
        NoVal n;

    public:
        const NoVal &getN() const
        {
            return n;
        }
    };
)-";
        QTest::addRow("class") << QByteArrayList{originalSource, expectedSource} << 1;

        // custom classes can be a value type
        originalSource = R"-(
    class Value{};
    class Test {
        Value v@;
    };
)-";
        expectedSource = R"-(
    class Value{};
    class Test {
        Value v;

    public:
        Value getV() const
        {
            return v;
        }
    };
)-";
        QTest::addRow("value class") << QByteArrayList{originalSource, expectedSource} << 1;

        // custom classes (in namespace) can be a value type
        originalSource = R"-(
    namespace N1{
    class Value{};
    }
    class Test {
        N1::Value v@;
    };
)-";
        expectedSource = R"-(
    namespace N1{
    class Value{};
    }
    class Test {
        N1::Value v;

    public:
        N1::Value getV() const
        {
            return v;
        }
    };
)-";
        QTest::addRow("value class in namespace") << QByteArrayList{originalSource, expectedSource} << 1;

        // custom template class can be a value type
        originalSource = R"-(
    template<typename T>
    class Value{};
    class Test {
        Value<int> v@;
    };
)-";
        expectedSource = R"-(
    template<typename T>
    class Value{};
    class Test {
        Value<int> v;

    public:
        Value<int> getV() const
        {
            return v;
        }
    };
)-";
        QTest::addRow("value template class") << QByteArrayList{originalSource, expectedSource} << 1;
    }

    void testValueTypes()
    {
        QFETCH(QByteArrayList, headers);
        QFETCH(int, operation);

        QList<TestDocumentPtr> testDocuments(
            {CppTestDocument::create("file.h", headers.at(0), headers.at(1))});

        QuickFixSettings s;
        s->setterInCppFileFrom = 0;
        s->getterInCppFileFrom = 0;
        s->valueTypes << "Value";
        s->returnByConstRef = true;

        GenerateGetterSetter factory;
        QuickFixOperationTest(testDocuments, &factory, ProjectExplorer::HeaderPaths(), operation);
    }

    /// Checks: Use template for a custom type
    void testCustomTemplate()
    {
        QList<TestDocumentPtr> testDocuments;
        QByteArray original;
        QByteArray expected;

        const QByteArray customTypeDecl = R"--(
namespace N1 {
namespace N2 {
struct test{};
}
template<typename T>
struct custom {
    void assign(const custom<T>&);
    bool equals(const custom<T>&);
    T* get();
};
)--";
        // Header File
        original = customTypeDecl + R"--(
class Foo
{
public:
    custom<N2::test> bar@;
};
})--";
        expected = customTypeDecl + R"--(
class Foo
{
public:
    custom<N2::test> bar@;
    N2::test *getBar() const;
    void setBar(const custom<N2::test> &newBar);
signals:
    void barChanged(N2::test *bar);
private:
    Q_PROPERTY(N2::test *bar READ getBar NOTIFY barChanged FINAL)
};
})--";
        testDocuments << CppTestDocument::create("file.h", original, expected);

        // Source File
        original = "";
        expected = R"-(
using namespace N1;
N2::test *Foo::getBar() const
{
    return bar.get();
}

void Foo::setBar(const custom<N2::test> &newBar)
{
    if (bar.equals(newBar))
        return;
    bar.assign(newBar);
    emit barChanged(bar.get());
}
)-";

        testDocuments << CppTestDocument::create("file.cpp", original, expected);

        QuickFixSettings s;
        s->cppFileNamespaceHandling = CppQuickFixSettings::MissingNamespaceHandling::AddUsingDirective;
        s->getterInCppFileFrom = 1;
        s->signalWithNewValue = true;
        CppQuickFixSettings::CustomTemplate t;
        t.types.append("custom");
        t.equalComparison = "<cur>.equals(<new>)";
        t.returnExpression = "<cur>.get()";
        t.returnType = "<T> *";
        t.assignment = "<cur>.assign(<new>)";
        s->customTemplates.push_back(t);

        GenerateGetterSetter factory;
        QuickFixOperationTest(testDocuments, &factory, ProjectExplorer::HeaderPaths(), 5);
    }

    /// Checks: if the setter parameter name is the same as the member variable name, this-> is needed
    void testNeedThis()
    {
        QList<TestDocumentPtr> testDocuments;

        // Header File
        const QByteArray original = R"-(
    class Foo {
        int bar@;
    public:
    };
)-";
        const QByteArray expected = R"-(
    class Foo {
        int bar@;
    public:
        void setBar(int bar)
        {
            this->bar = bar;
        }
    };
)-";
        testDocuments << CppTestDocument::create("file.h", original, expected);

        QuickFixSettings s;
        s->setterParameterNameTemplate = "name";
        s->setterInCppFileFrom = 0;

        GenerateGetterSetter factory;
        QuickFixOperationTest(testDocuments, &factory, ProjectExplorer::HeaderPaths(), 0);
    }

    void testOfferedFixes_data()
    {
        QTest::addColumn<QByteArray>("header");
        QTest::addColumn<QStringList>("offered");

        QByteArray header;
        QStringList offered;
        const QString setter = QStringLiteral("Generate Setter");
        const QString getter = QStringLiteral("Generate Getter");
        const QString getset = QStringLiteral("Generate Getter and Setter");
        const QString constQandMissing = QStringLiteral(
            "Generate Constant Q_PROPERTY and Missing Members");
        const QString qAndResetAndMissing = QStringLiteral(
            "Generate Q_PROPERTY and Missing Members with Reset Function");
        const QString qAndMissing = QStringLiteral("Generate Q_PROPERTY and Missing Members");
        const QStringList all{setter, getter, getset, constQandMissing, qAndResetAndMissing, qAndMissing};

        header = R"-(
    class Foo {
        static int bar@;
    };
)-";
        offered = QStringList{setter, getter, getset, constQandMissing};
        QTest::addRow("static") << header << offered;

        header = R"-(
    class Foo {
        static const int bar@;
    };
)-";
        offered = QStringList{getter, constQandMissing};
        QTest::addRow("const static") << header << offered;

        header = R"-(
    class Foo {
        const int bar@;
    };
)-";
        offered = QStringList{getter, constQandMissing};
        QTest::addRow("const") << header << offered;

        header = R"-(
    class Foo {
        const int bar@;
        int getBar() const;
    };
)-";
        offered = QStringList{constQandMissing};
        QTest::addRow("const + getter") << header << offered;

        header = R"-(
    class Foo {
        const int bar@;
        int getBar() const;
        void setBar(int value);
    };
)-";
        offered = QStringList{};
        QTest::addRow("const + getter + setter") << header << offered;

        header = R"-(
    class Foo {
        const int* bar@;
    };
)-";
        offered = all;
        QTest::addRow("pointer to const") << header << offered;

        header = R"-(
    class Foo {
        int bar@;
    public:
        int bar();
    };
)-";
        offered = QStringList{setter, constQandMissing, qAndResetAndMissing, qAndMissing};
        QTest::addRow("existing getter") << header << offered;

        header = R"-(
    class Foo {
        int bar@;
    public:
        set setBar(int);
    };
)-";
        offered = QStringList{getter};
        QTest::addRow("existing setter") << header << offered;

        header = R"-(
    class Foo {
        int bar@;
    signals:
        void barChanged(int);
    };
)-";
        offered = QStringList{setter, getter, getset, qAndResetAndMissing, qAndMissing};
        QTest::addRow("existing signal (no const Q_PROPERTY)") << header << offered;

        header = R"-(
    class Foo {
        int m_bar@;
        Q_PROPERTY(int bar)
    };
)-";
        offered = QStringList{}; // user should use "InsertQPropertyMembers", no duplicated code
        QTest::addRow("existing Q_PROPERTY") << header << offered;
    }

    void testOfferedFixes()
    {
        QFETCH(QByteArray, header);
        QFETCH(QStringList, offered);

        QList<TestDocumentPtr> testDocuments(
            {CppTestDocument::create("file.h", header, header)});

        GenerateGetterSetter factory;
        QuickFixOfferedOperationsTest(testDocuments, &factory, ProjectExplorer::HeaderPaths(), offered);
    }

    void testGeneral_data()
    {
        QTest::addColumn<int>("operation");
        QTest::addColumn<QByteArray>("original");
        QTest::addColumn<QByteArray>("expected");

        QTest::newRow("GenerateGetterSetter_referenceToNonConst")
            << 2
            << QByteArray("\n"
                 "class Something\n"
                 "{\n"
                 "    int &it@;\n"
                 "};\n")
            << QByteArray("\n"
                 "class Something\n"
                 "{\n"
                 "    int &it;\n"
                 "\n"
                 "public:\n"
                 "    int &getIt() const;\n"
                 "    void setIt(const int &it);\n"
                 "};\n"
                 "\n"
                 "int &Something::getIt() const\n"
                 "{\n"
                 "    return it;\n"
                 "}\n"
                 "\n"
                 "void Something::setIt(const int &it)\n"
                 "{\n"
                 "    this->it = it;\n"
                 "}\n");

        // Checks: No special treatment for reference to const.
        QTest::newRow("GenerateGetterSetter_referenceToConst")
            << 2
            << QByteArray("\n"
                 "class Something\n"
                 "{\n"
                 "    const int &it@;\n"
                 "};\n")
            << QByteArray("\n"
                 "class Something\n"
                 "{\n"
                 "    const int &it;\n"
                 "\n"
                 "public:\n"
                 "    const int &getIt() const;\n"
                 "    void setIt(const int &it);\n"
                 "};\n"
                 "\n"
                 "const int &Something::getIt() const\n"
                 "{\n"
                 "    return it;\n"
                 "}\n"
                 "\n"
                 "void Something::setIt(const int &it)\n"
                 "{\n"
                 "    this->it = it;\n"
                 "}\n");

        // Checks:
        // 1. Setter: Setter is a static function.
        // 2. Getter: Getter is a static, non const function.
        QTest::newRow("GenerateGetterSetter_staticMember")
            << 2
            << QByteArray("\n"
                 "class Something\n"
                 "{\n"
                 "    static int @m_member;\n"
                 "};\n")
            << QByteArray("\n"
                 "class Something\n"
                 "{\n"
                 "    static int m_member;\n"
                 "\n"
                 "public:\n"
                 "    static int member();\n"
                 "    static void setMember(int member);\n"
                 "};\n"
                 "\n"
                 "int Something::member()\n"
                 "{\n"
                 "    return m_member;\n"
                 "}\n"
                 "\n"
                 "void Something::setMember(int member)\n"
                 "{\n"
                 "    m_member = member;\n"
                 "}\n");

        // Check: Check if it works on the second declarator
        // clang-format off
        QTest::newRow("GenerateGetterSetter_secondDeclarator") << 2
            << QByteArray("\n"
                "class Something\n"
                "{\n"
                "    int *foo, @it;\n"
                "};\n")
            << QByteArray("\n"
                "class Something\n"
                "{\n"
                "    int *foo, it;\n"
                "\n"
                "public:\n"
                "    int getIt() const;\n"
                "    void setIt(int it);\n"
                "};\n"
                "\n"
                "int Something::getIt() const\n"
                "{\n"
                "    return it;\n"
                "}\n"
                "\n"
                "void Something::setIt(int it)\n"
                "{\n"
                "    this->it = it;\n"
                "}\n");
        // clang-format on

        // Check: Quick fix is offered for "int *@it;" ('@' denotes the text cursor position)
        QTest::newRow("GenerateGetterSetter_triggeringRightAfterPointerSign")
            << 2
            << QByteArray("\n"
                 "class Something\n"
                 "{\n"
                 "    int *@it;\n"
                 "};\n")
            << QByteArray("\n"
                 "class Something\n"
                 "{\n"
                 "    int *it;\n"
                 "\n"
                 "public:\n"
                 "    int *getIt() const;\n"
                 "    void setIt(int *it);\n"
                 "};\n"
                 "\n"
                 "int *Something::getIt() const\n"
                 "{\n"
                 "    return it;\n"
                 "}\n"
                 "\n"
                 "void Something::setIt(int *it)\n"
                 "{\n"
                 "    this->it = it;\n"
                 "}\n");

        // Checks if "m_" is recognized as "m" with the postfix "_" and not simply as "m_" prefix.
        QTest::newRow("GenerateGetterSetter_recognizeMasVariableName")
            << 2
            << QByteArray("\n"
                 "class Something\n"
                 "{\n"
                 "    int @m_;\n"
                 "};\n")
            << QByteArray("\n"
                 "class Something\n"
                 "{\n"
                 "    int m_;\n"
                 "\n"
                 "public:\n"
                 "    int m() const;\n"
                 "    void setM(int m);\n"
                 "};\n"
                 "\n"
                 "int Something::m() const\n"
                 "{\n"
                 "    return m_;\n"
                 "}\n"
                 "\n"
                 "void Something::setM(int m)\n"
                 "{\n"
                 "    m_ = m;\n"
                 "}\n");

        // Checks if "m" followed by an upper character is recognized as a prefix
        QTest::newRow("GenerateGetterSetter_recognizeMFollowedByCapital")
            << 2
            << QByteArray("\n"
                 "class Something\n"
                 "{\n"
                 "    int @mFoo;\n"
                 "};\n")
            << QByteArray("\n"
                 "class Something\n"
                 "{\n"
                 "    int mFoo;\n"
                 "\n"
                 "public:\n"
                 "    int foo() const;\n"
                 "    void setFoo(int foo);\n"
                 "};\n"
                 "\n"
                 "int Something::foo() const\n"
                 "{\n"
                 "    return mFoo;\n"
                 "}\n"
                 "\n"
                 "void Something::setFoo(int foo)\n"
                 "{\n"
                 "    mFoo = foo;\n"
                 "}\n");
    }

    void testGeneral()
    {
        QFETCH(int, operation);
        QFETCH(QByteArray, original);
        QFETCH(QByteArray, expected);

        QuickFixSettings s;
        s->getterNameTemplate = "name";
        s->setterParameterNameTemplate = "name";
        s->getterInCppFileFrom = 1;
        s->setterInCppFileFrom = 1;

        GenerateGetterSetter factory;
        QuickFixOperationTest(singleDocument(original, expected),
                              &factory,
                              ProjectExplorer::HeaderPaths(),
                              operation);
    }

    /// Checks: Only generate getter
    void testOnlyGetter()
    {
        QList<TestDocumentPtr> testDocuments;
        QByteArray original;
        QByteArray expected;

        // Header File
        original =
            "class Foo\n"
            "{\n"
            "public:\n"
            "    int bar@;\n"
            "};\n";
        expected =
            "class Foo\n"
            "{\n"
            "public:\n"
            "    int bar@;\n"
            "    int getBar() const;\n"
            "};\n";
        testDocuments << CppTestDocument::create("file.h", original, expected);

        // Source File
        original.resize(0);
        expected =
            "\n"
            "int Foo::getBar() const\n"
            "{\n"
            "    return bar;\n"
            "}\n";
        testDocuments << CppTestDocument::create("file.cpp", original, expected);

        QuickFixSettings s;
        s->getterInCppFileFrom = 1;
        GenerateGetterSetter factory;
        QuickFixOperationTest(testDocuments, &factory, ProjectExplorer::HeaderPaths(), 1);
    }

    /// Checks: Only generate setter
    void testOnlySetter()
    {
        QList<TestDocumentPtr> testDocuments;
        QByteArray original;
        QByteArray expected;
        QuickFixSettings s;
        s->setterAsSlot = true; // To be ignored, as we don't have QObjects here.

        // Header File
        original =
            "class Foo\n"
            "{\n"
            "public:\n"
            "    int bar@;\n"
            "};\n";
        expected =
            "class Foo\n"
            "{\n"
            "public:\n"
            "    int bar@;\n"
            "    void setBar(int value);\n"
            "};\n";
        testDocuments << CppTestDocument::create("file.h", original, expected);

        // Source File
        original.resize(0);
        expected =
            "\n"
            "void Foo::setBar(int value)\n"
            "{\n"
            "    bar = value;\n"
            "}\n";
        testDocuments << CppTestDocument::create("file.cpp", original, expected);

        s->setterInCppFileFrom = 1;
        s->setterParameterNameTemplate = "\"value\"";

        GenerateGetterSetter factory;
        QuickFixOperationTest(testDocuments, &factory, ProjectExplorer::HeaderPaths(), 0);
    }

    void testAnonymousClass()
    {
        QList<TestDocumentPtr> testDocuments;
        QByteArray original;
        QByteArray expected;
        QuickFixSettings s;
        s->setterInCppFileFrom = 1;
        s->getterNameTemplate = "name";
        s->setterParameterNameTemplate = "\"value\"";

        // Header File
        original = R"(
        class {
            int @m_foo;
        } bar;
)";
        expected = R"(
        class {
            int m_foo;

        public:
            int foo() const
            {
                return m_foo;
            }
            void setFoo(int value)
            {
                if (m_foo == value)
                    return;
                m_foo = value;
                emit fooChanged();
            }
            void resetFoo()
            {
                setFoo({}); // TODO: Adapt to use your actual default defaultValue
            }

        signals:
            void fooChanged();

        private:
            Q_PROPERTY(int foo READ foo WRITE setFoo RESET resetFoo NOTIFY fooChanged FINAL)
        } bar;
)";
        testDocuments << CppTestDocument::create("file.h", original, expected);

        // Source File
        testDocuments << CppTestDocument::create("file.cpp", {}, {});

        GenerateGetterSetter factory;
        QuickFixOperationTest(testDocuments, &factory, ProjectExplorer::HeaderPaths(), 4);
    }

    void testInlineInHeaderFile()
    {
        QList<TestDocumentPtr> testDocuments;
        const QByteArray original = R"-(
    class Foo {
    public:
        int bar@;
    };
)-";
        const QByteArray expected = R"-(
    class Foo {
    public:
        int bar;
        int getBar() const;
        void setBar(int value);
        void resetBar();
    signals:
        void barChanged();
    private:
        Q_PROPERTY(int bar READ getBar WRITE setBar RESET resetBar NOTIFY barChanged FINAL)
    };

    inline int Foo::getBar() const
    {
        return bar;
    }

    inline void Foo::setBar(int value)
    {
        if (bar == value)
            return;
        bar = value;
        emit barChanged();
    }

    inline void Foo::resetBar()
    {
        setBar({}); // TODO: Adapt to use your actual default defaultValue
    }
)-";
        testDocuments << CppTestDocument::create("file.h", original, expected);

        QuickFixSettings s;
        s->setterOutsideClassFrom = 1;
        s->getterOutsideClassFrom = 1;
        s->setterParameterNameTemplate = "\"value\"";

        GenerateGetterSetter factory;
        QuickFixOperationTest(testDocuments, &factory, ProjectExplorer::HeaderPaths(), 4);
    }

    void testOnlySetterHeaderFileWithIncludeGuard()
    {
        QList<TestDocumentPtr> testDocuments;
        const QByteArray     original =
                "#ifndef FILE__H__DECLARED\n"
                "#define FILE__H__DECLARED\n"
                "class Foo\n"
                "{\n"
                "public:\n"
                "    int bar@;\n"
                "};\n"
                "#endif\n";
        const QByteArray expected =
                "#ifndef FILE__H__DECLARED\n"
                "#define FILE__H__DECLARED\n"
                "class Foo\n"
                "{\n"
                "public:\n"
                "    int bar@;\n"
                "    void setBar(int value);\n"
                "};\n\n"
                "inline void Foo::setBar(int value)\n"
                "{\n"
                "    bar = value;\n"
                "}\n"
                "#endif\n";

        testDocuments << CppTestDocument::create("file.h", original, expected);

        QuickFixSettings s;
        s->setterOutsideClassFrom = 1;
        s->setterParameterNameTemplate = "\"value\"";

        GenerateGetterSetter factory;
        QuickFixOperationTest(testDocuments, &factory, ProjectExplorer::HeaderPaths(), 0);
    }

    void testFunctionAsTemplateArg()
    {
        QList<TestDocumentPtr> testDocuments;
        const QByteArray original = R"(
    template<typename T> class TS {};
    template<typename T, typename U> class TS<T(U)> {};

    class S2 {
        TS<int(int)> @member;
    };
)";
        const QByteArray expected = R"(
    template<typename T> class TS {};
    template<typename T, typename U> class TS<T(U)> {};

    class S2 {
        TS<int(int)> member;

    public:
        const TS<int (int)> &getMember() const
        {
            return member;
        }
    };
)";

        testDocuments << CppTestDocument::create("file.h", original, expected);

        QuickFixSettings s;
        s->getterOutsideClassFrom = 0;
        s->getterInCppFileFrom = 0;
        s->returnByConstRef = true;

        GenerateGetterSetter factory;
        QuickFixOperationTest(testDocuments, &factory, ProjectExplorer::HeaderPaths(), 1);
    }

    void testNotTriggeringOnMemberFunction()
    {
        const QByteArray input = "class Something { void @f(); };\n";
        GenerateGetterSetter factory;
        QuickFixOperationTest({CppTestDocument::create("file.h", input, {})}, &factory);
    }

    void testNotTriggeringOnMemberArray()
    {
        const QByteArray input = "class Something { void @a[10]; };\n";
        GenerateGetterSetter factory;
        QuickFixOperationTest({CppTestDocument::create("file.h", input, {})}, &factory);
    }

    void testGetterSetterReturnTypeClassScope()
    {
        const QByteArray headerInput = R"cpp(
class Foo
{
public:
    enum Bar { b1, b2 };

private:
    Bar @m_bar;
};
)cpp";
        const QByteArray headerOutput = R"cpp(
class Foo
{
public:
    enum Bar { b1, b2 };

    Bar bar() const;
    void setBar(Bar newBar);

private:
    Bar m_bar;
};
)cpp";
        const QByteArray srcInput = "#include \"foo.h\"\n";
        const QByteArray srcOutput = R"cpp(#include "foo.h"

Foo::Bar Foo::bar() const
{
    return m_bar;
}

void Foo::setBar(Bar newBar)
{
    m_bar = newBar;
}
)cpp";

        QList<TestDocumentPtr> testDocuments{
             CppTestDocument::create("foo.h", headerInput, headerOutput),
             CppTestDocument::create("foo.cpp", srcInput, srcOutput),
        };

        // QuickFixSettings s;
        // s->getterOutsideClassFrom = 0;
        // s->getterInCppFileFrom = 0;

        GenerateGetterSetter factory;
        QuickFixOperationTest(testDocuments, &factory, ProjectExplorer::HeaderPaths(), 2);
    }
};

class GenerateGettersSettersTest : public QObject
{
    Q_OBJECT

private slots:
    void test_data()
    {
        QTest::addColumn<QByteArray>("original");
        QTest::addColumn<QByteArray>("expected");

        const QByteArray onlyReset = R"(
    class Foo {
    public:
        int bar() const;
        void setBar(int bar);
    private:
        int m_bar;
    @};)";

        const QByteArray onlyResetAfter = R"(
    class @Foo {
    public:
        int bar() const;
        void setBar(int bar);
        void resetBar();

    private:
        int m_bar;
    };
    inline void Foo::resetBar()
    {
        setBar({}); // TODO: Adapt to use your actual default defaultValue
    }
)";
        QTest::addRow("only reset") << onlyReset << onlyResetAfter;

        const QByteArray withCandidates = R"(
    class @Foo {
    public:
        int bar() const;
        void setBar(int bar) { m_bar = bar; }

        int getBar2() const;

        int m_alreadyPublic;

    private:
        friend void distraction();
        class AnotherDistraction {};
        enum EvenMoreDistraction { val1, val2 };

        int m_bar;
        int bar2_;
        QString bar3;
    };)";
        const QByteArray after = R"(
    class Foo {
    public:
        int bar() const;
        void setBar(int bar) { m_bar = bar; }

        int getBar2() const;

        int m_alreadyPublic;

        void resetBar();
        void setBar2(int value);
        void resetBar2();
        const QString &getBar3() const;
        void setBar3(const QString &value);
        void resetBar3();

    signals:
        void bar2Changed();
        void bar3Changed();

    private:
        friend void distraction();
        class AnotherDistraction {};
        enum EvenMoreDistraction { val1, val2 };

        int m_bar;
        int bar2_;
        QString bar3;
        Q_PROPERTY(int bar2 READ getBar2 WRITE setBar2 RESET resetBar2 NOTIFY bar2Changed FINAL)
        Q_PROPERTY(QString bar3 READ getBar3 WRITE setBar3 RESET resetBar3 NOTIFY bar3Changed FINAL)
    };
    inline void Foo::resetBar()
    {
        setBar({}); // TODO: Adapt to use your actual default defaultValue
    }

    inline void Foo::setBar2(int value)
    {
        if (bar2_ == value)
            return;
        bar2_ = value;
        emit bar2Changed();
    }

    inline void Foo::resetBar2()
    {
        setBar2({}); // TODO: Adapt to use your actual default defaultValue
    }

    inline const QString &Foo::getBar3() const
    {
        return bar3;
    }

    inline void Foo::setBar3(const QString &value)
    {
        if (bar3 == value)
            return;
        bar3 = value;
        emit bar3Changed();
    }

    inline void Foo::resetBar3()
    {
        setBar3({}); // TODO: Adapt to use your actual default defaultValue
    }
)";
        QTest::addRow("with candidates") << withCandidates << after;
    }

    void test()
    {
        class TestFactory : public GenerateGettersSettersForClass
        {
        public:
            TestFactory() { setTest(); }
        };

        QFETCH(QByteArray, original);
        QFETCH(QByteArray, expected);

        QuickFixSettings s;
        s->setterParameterNameTemplate = "\"value\"";
        s->setterOutsideClassFrom = 1;
        s->getterOutsideClassFrom = 1;
        s->returnByConstRef = true;

        TestFactory factory;
        QuickFixOperationTest({CppTestDocument::create("file.h", original, expected)}, &factory);
    }
};

class InsertQtPropertyMembersTest : public QObject
{
    Q_OBJECT

private slots:
    void test_data()
    {
        QTest::addColumn<QByteArray>("original");
        QTest::addColumn<QByteArray>("expected");

        QTest::newRow("InsertQtPropertyMembers")
            << QByteArray("struct QObject { void connect(); }\n"
                 "struct XmarksTheSpot : public QObject {\n"
                 "    @Q_PROPERTY(int it READ getIt WRITE setIt RESET resetIt NOTIFY itChanged)\n"
                 "};\n")
            << QByteArray("struct QObject { void connect(); }\n"
                 "struct XmarksTheSpot : public QObject {\n"
                 "    Q_PROPERTY(int it READ getIt WRITE setIt RESET resetIt NOTIFY itChanged)\n"
                 "\n"
                 "public:\n"
                 "    int getIt() const;\n"
                 "\n"
                 "public slots:\n"
                 "    void setIt(int it)\n"
                 "    {\n"
                 "        if (m_it == it)\n"
                 "            return;\n"
                 "        m_it = it;\n"
                 "        emit itChanged(m_it);\n"
                 "    }\n"
                 "    void resetIt()\n"
                 "    {\n"
                 "        setIt({}); // TODO: Adapt to use your actual default value\n"
                 "    }\n"
                 "\n"
                 "signals:\n"
                 "    void itChanged(int it);\n"
                 "\n"
                 "private:\n"
                 "    int m_it;\n"
                 "};\n"
                 "\n"
                 "int XmarksTheSpot::getIt() const\n"
                 "{\n"
                 "    return m_it;\n"
                 "}\n");

        QTest::newRow("InsertQtPropertyMembersResetWithoutSet")
            << QByteArray("struct QObject { void connect(); }\n"
                 "struct XmarksTheSpot : public QObject {\n"
                 "    @Q_PROPERTY(int it READ getIt RESET resetIt NOTIFY itChanged)\n"
                 "};\n")
            << QByteArray("struct QObject { void connect(); }\n"
                 "struct XmarksTheSpot : public QObject {\n"
                 "    Q_PROPERTY(int it READ getIt RESET resetIt NOTIFY itChanged)\n"
                 "\n"
                 "public:\n"
                 "    int getIt() const;\n"
                 "\n"
                 "public slots:\n"
                 "    void resetIt()\n"
                 "    {\n"
                 "        static int defaultValue{}; // TODO: Adapt to use your actual default "
                 "value\n"
                 "        if (m_it == defaultValue)\n"
                 "            return;\n"
                 "        m_it = defaultValue;\n"
                 "        emit itChanged(m_it);\n"
                 "    }\n"
                 "\n"
                 "signals:\n"
                 "    void itChanged(int it);\n"
                 "\n"
                 "private:\n"
                 "    int m_it;\n"
                 "};\n"
                 "\n"
                 "int XmarksTheSpot::getIt() const\n"
                 "{\n"
                 "    return m_it;\n"
                 "}\n");

        QTest::newRow("InsertQtPropertyMembersResetWithoutSetAndNotify")
            << QByteArray("struct QObject { void connect(); }\n"
                 "struct XmarksTheSpot : public QObject {\n"
                 "    @Q_PROPERTY(int it READ getIt RESET resetIt)\n"
                 "};\n")
            << QByteArray("struct QObject { void connect(); }\n"
                 "struct XmarksTheSpot : public QObject {\n"
                 "    Q_PROPERTY(int it READ getIt RESET resetIt)\n"
                 "\n"
                 "public:\n"
                 "    int getIt() const;\n"
                 "\n"
                 "public slots:\n"
                 "    void resetIt()\n"
                 "    {\n"
                 "        static int defaultValue{}; // TODO: Adapt to use your actual default "
                 "value\n"
                 "        m_it = defaultValue;\n"
                 "    }\n"
                 "\n"
                 "private:\n"
                 "    int m_it;\n"
                 "};\n"
                 "\n"
                 "int XmarksTheSpot::getIt() const\n"
                 "{\n"
                 "    return m_it;\n"
                 "}\n");

        QTest::newRow("InsertQtPropertyMembersPrivateBeforePublic")
            << QByteArray("struct QObject { void connect(); }\n"
                 "class XmarksTheSpot : public QObject {\n"
                 "private:\n"
                 "    @Q_PROPERTY(int it READ getIt WRITE setIt NOTIFY itChanged)\n"
                 "public:\n"
                 "    void find();\n"
                 "};\n")
            << QByteArray("struct QObject { void connect(); }\n"
                 "class XmarksTheSpot : public QObject {\n"
                 "private:\n"
                 "    Q_PROPERTY(int it READ getIt WRITE setIt NOTIFY itChanged)\n"
                 "    int m_it;\n"
                 "\n"
                 "public:\n"
                 "    void find();\n"
                 "    int getIt() const;\n"
                 "public slots:\n"
                 "    void setIt(int it)\n"
                 "    {\n"
                 "        if (m_it == it)\n"
                 "            return;\n"
                 "        m_it = it;\n"
                 "        emit itChanged(m_it);\n"
                 "    }\n"
                 "signals:\n"
                 "    void itChanged(int it);\n"
                 "};\n"
                 "\n"
                 "int XmarksTheSpot::getIt() const\n"
                 "{\n"
                 "    return m_it;\n"
                 "}\n");
    }

    void test()
    {
        QFETCH(QByteArray, original);
        QFETCH(QByteArray, expected);

        QuickFixSettings s;
        s->setterAsSlot = true;
        s->setterInCppFileFrom = 0;
        s->setterParameterNameTemplate = "name";
        s->signalWithNewValue = true;

        InsertQtPropertyMembers factory;
        QuickFixOperationTest({CppTestDocument::create("file.cpp", original, expected)}, &factory);
    }

    void testNotTriggeringOnInvalidCode()
    {
        const QByteArray input = "class C { @Q_PROPERTY(typeid foo READ foo) };\n";
        InsertQtPropertyMembers factory;
        QuickFixOperationTest({CppTestDocument::create("file.h", input, {})}, &factory);
    }
};

class GenerateConstructorTest : public QObject
{
    Q_OBJECT

private slots:
    void test_data()
    {
        QTest::addColumn<QByteArray>("original_header");
        QTest::addColumn<QByteArray>("expected_header");
        QTest::addColumn<QByteArray>("original_source");
        QTest::addColumn<QByteArray>("expected_source");
        QTest::addColumn<int>("location");
        const int Inside = ConstructorLocation::Inside;
        const int Outside = ConstructorLocation::Outside;
        const int CppGenNamespace = ConstructorLocation::CppGenNamespace;
        const int CppGenUsingDirective = ConstructorLocation::CppGenUsingDirective;
        const int CppRewriteType = ConstructorLocation::CppRewriteType;

        QByteArray header = R"--(
class@ Foo{
    int test;
    static int s;
};
)--";
        QByteArray expected = R"--(
class Foo{
    int test;
    static int s;
public:
    Foo(int test) : test(test)
    {}
};
)--";
        QTest::newRow("ignore static") << header << expected << QByteArray() << QByteArray() << Inside;

        header = R"--(
class@ Foo{
    CustomType test;
};
)--";
        expected = R"--(
class Foo{
    CustomType test;
public:
    Foo(CustomType test) : test(std::move(test))
    {}
};
)--";
        QTest::newRow("Move custom value types")
            << header << expected << QByteArray() << QByteArray() << Inside;

        header = R"--(
class@ Foo{
    int test;
protected:
    Foo() = default;
};
)--";
        expected = R"--(
class Foo{
    int test;
public:
    Foo(int test) : test(test)
    {}

protected:
    Foo() = default;
};
)--";

        QTest::newRow("new section before existing")
            << header << expected << QByteArray() << QByteArray() << Inside;

        header = R"--(
class@ Foo{
    int test;
};
)--";
        expected = R"--(
class Foo{
    int test;
public:
    Foo(int test) : test(test)
    {}
};
)--";
        QTest::newRow("new section at end")
            << header << expected << QByteArray() << QByteArray() << Inside;

        header = R"--(
class@ Foo{
    int test;
public:
    /**
     * Random comment
     */
    Foo(int i, int i2);
};
)--";
        expected = R"--(
class Foo{
    int test;
public:
    Foo(int test) : test(test)
    {}
    /**
     * Random comment
     */
    Foo(int i, int i2);
};
)--";
        QTest::newRow("in section before")
            << header << expected << QByteArray() << QByteArray() << Inside;

        header = R"--(
class@ Foo{
    int test;
public:
    Foo() = default;
};
)--";
        expected = R"--(
class Foo{
    int test;
public:
    Foo(int test) : test(test)
    {}
    Foo() = default;
};
)--";
        QTest::newRow("in section after")
            << header << expected << QByteArray() << QByteArray() << Inside;

        header = R"--(
class@ Foo{
    int test1;
    int test2;
    int test3;
public:
};
)--";
        expected = R"--(
class Foo{
    int test1;
    int test2;
    int test3;
public:
    Foo(int test2, int test3, int test1) : test1(test1),
        test2(test2),
        test3(test3)
    {}
};
)--";
        // No worry, that is not the default behavior.
        // Move first member to the back when testing with 3 or more members
        QTest::newRow("changed parameter order")
            << header << expected << QByteArray() << QByteArray() << Inside;

        header = R"--(
class@ Foo{
    int test;
    int di_test;
public:
};
)--";
        expected = R"--(
class Foo{
    int test;
    int di_test;
public:
    Foo(int test, int di_test = 42) : test(test),
        di_test(di_test)
    {}
};
)--";
        QTest::newRow("default parameters")
            << header << expected << QByteArray() << QByteArray() << Inside;

        header = R"--(
struct Bar{
    Bar(int i);
};
class@ Foo : public Bar{
    int test;
public:
};
)--";
        expected = R"--(
struct Bar{
    Bar(int i);
};
class Foo : public Bar{
    int test;
public:
    Foo(int test, int i) : Bar(i),
        test(test)
    {}
};
)--";
        QTest::newRow("parent constructor")
            << header << expected << QByteArray() << QByteArray() << Inside;

        header = R"--(
struct Bar{
    Bar(int use_i = 6);
};
class@ Foo : public Bar{
    int test;
public:
};
)--";
        expected = R"--(
struct Bar{
    Bar(int use_i = 6);
};
class Foo : public Bar{
    int test;
public:
    Foo(int test, int use_i = 6) : Bar(use_i),
        test(test)
    {}
};
)--";
        QTest::newRow("parent constructor with default")
            << header << expected << QByteArray() << QByteArray() << Inside;

        header = R"--(
struct Bar{
    Bar(int use_i = L'A', int use_i2 = u8"B");
};
class@ Foo : public Bar{
public:
};
)--";
        expected = R"--(
struct Bar{
    Bar(int use_i = L'A', int use_i2 = u8"B");
};
class Foo : public Bar{
public:
    Foo(int use_i = L'A', int use_i2 = u8"B") : Bar(use_i, use_i2)
    {}
};
)--";
        QTest::newRow("parent constructor with char/string default value")
            << header << expected << QByteArray() << QByteArray() << Inside;

        const QByteArray common = R"--(
namespace N{
    template<typename T>
    struct vector{
    };
}
)--";
        header = common + R"--(
namespace M{
enum G{g};
class@ Foo{
    N::vector<G> g;
    enum E{e}e;
public:
};
}
)--";

        expected = common + R"--(
namespace M{
enum G{g};
class@ Foo{
    N::vector<G> g;
    enum E{e}e;
public:
    Foo(const N::vector<G> &g, E e);
};

Foo::Foo(const N::vector<G> &g, Foo::E e) : g(g),
    e(e)
{}

}
)--";
        QTest::newRow("source: right type outside class ")
            << QByteArray() << QByteArray() << header << expected << Outside;
        expected = common + R"--(
namespace M{
enum G{g};
class@ Foo{
    N::vector<G> g;
    enum E{e}e;
public:
    Foo(const N::vector<G> &g, E e);
};
}


inline M::Foo::Foo(const N::vector<M::G> &g, M::Foo::E e) : g(g),
    e(e)
{}

)--";
        QTest::newRow("header: right type outside class ")
            << header << expected << QByteArray() << QByteArray() << Outside;

        expected = common + R"--(
namespace M{
enum G{g};
class@ Foo{
    N::vector<G> g;
    enum E{e}e;
public:
    Foo(const N::vector<G> &g, E e);
};
}
)--";
        const QByteArray source = R"--(
#include "file.h"
)--";
        QByteArray expected_source = R"--(
#include "file.h"


namespace M {
Foo::Foo(const N::vector<G> &g, Foo::E e) : g(g),
    e(e)
{}

}
)--";
        QTest::newRow("source: right type inside namespace")
            << header << expected << source << expected_source << CppGenNamespace;

        expected_source = R"--(
#include "file.h"

using namespace M;
Foo::Foo(const N::vector<G> &g, Foo::E e) : g(g),
    e(e)
{}
)--";
        QTest::newRow("source: right type with using directive")
            << header << expected << source << expected_source << CppGenUsingDirective;

        expected_source = R"--(
#include "file.h"

M::Foo::Foo(const N::vector<M::G> &g, M::Foo::E e) : g(g),
    e(e)
{}
)--";
        QTest::newRow("source: right type while rewritung types")
            << header << expected << source << expected_source << CppRewriteType;

    }

    void test()
    {
        class TestFactory : public GenerateConstructor
        {
        public:
            TestFactory() { setTest(); }
        };

        QFETCH(QByteArray, original_header);
        QFETCH(QByteArray, expected_header);
        QFETCH(QByteArray, original_source);
        QFETCH(QByteArray, expected_source);
        QFETCH(int, location);

        QuickFixSettings s;
        s->valueTypes << "CustomType";
        using L = ConstructorLocation;
        if (location == L::Inside) {
            s->setterInCppFileFrom = -1;
            s->setterOutsideClassFrom = -1;
        } else if (location == L::Outside) {
            s->setterInCppFileFrom = -1;
            s->setterOutsideClassFrom = 1;
        } else if (location >= L::CppGenNamespace && location <= L::CppRewriteType) {
            s->setterInCppFileFrom = 1;
            s->setterOutsideClassFrom = -1;
            using Handling = CppQuickFixSettings::MissingNamespaceHandling;
            if (location == L::CppGenNamespace)
                s->cppFileNamespaceHandling = Handling::CreateMissing;
            else if (location == L::CppGenUsingDirective)
                s->cppFileNamespaceHandling = Handling::AddUsingDirective;
            else if (location == L::CppRewriteType)
                s->cppFileNamespaceHandling = Handling::RewriteType;
        } else {
            QFAIL("location is none of the values of the ConstructorLocation enum");
        }

        QList<TestDocumentPtr> testDocuments;
        testDocuments << CppTestDocument::create("file.h", original_header, expected_header);
        testDocuments << CppTestDocument::create("file.cpp", original_source, expected_source);
        TestFactory factory;
        QuickFixOperationTest(testDocuments, &factory);
    }

private:
    enum ConstructorLocation { Inside, Outside, CppGenNamespace, CppGenUsingDirective, CppRewriteType };
};

QObject *GenerateGetterSetter::createTest()
{
    return new GenerateGetterSetterTest;
}

QObject *GenerateGettersSettersForClass::createTest()
{
    return new GenerateGettersSettersTest;
}

QObject *InsertQtPropertyMembers::createTest()
{
    return new InsertQtPropertyMembersTest;
}

QObject *GenerateConstructor::createTest()
{
    return new GenerateConstructorTest;
}

#endif // WITH_TESTS

} // namespace

void registerCodeGenerationQuickfixes()
{
    CppQuickFixFactory::registerFactory<GenerateGetterSetter>();
    CppQuickFixFactory::registerFactory<GenerateGettersSettersForClass>();
    CppQuickFixFactory::registerFactory<GenerateConstructor>();
    CppQuickFixFactory::registerFactory<InsertQtPropertyMembers>();
}

} // namespace CppEditor::Internal

#include <cppcodegenerationquickfixes.moc>