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
|
#!/usr/bin/python
# -*- coding: utf-8; -*-
#
# Copyright (C) 2009, 2010 Google Inc. All rights reserved.
# Copyright (C) 2009 Torch Mobile Inc.
# Copyright (C) 2009 Apple Inc. All rights reserved.
# Copyright (C) 2010 Chris Jerdonek (cjerdonek@webkit.org)
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Unit test for cpp_style.py."""
# FIXME: Add a good test that tests UpdateIncludeState.
import codecs
import os
import random
import re
import unittest
import cpp as cpp_style
from cpp import CppChecker
from ..filter import FilterConfiguration
# This class works as an error collector and replaces cpp_style.Error
# function for the unit tests. We also verify each category we see
# is in STYLE_CATEGORIES, to help keep that list up to date.
class ErrorCollector:
_all_style_categories = CppChecker.categories
# This is a list including all categories seen in any unit test.
_seen_style_categories = {}
def __init__(self, assert_fn, filter=None):
"""assert_fn: a function to call when we notice a problem.
filter: filters the errors that we are concerned about."""
self._assert_fn = assert_fn
self._errors = []
if not filter:
filter = FilterConfiguration()
self._filter = filter
def __call__(self, unused_linenum, category, confidence, message):
self._assert_fn(category in self._all_style_categories,
'Message "%s" has category "%s",'
' which is not in STYLE_CATEGORIES' % (message, category))
if self._filter.should_check(category, ""):
self._seen_style_categories[category] = 1
self._errors.append('%s [%s] [%d]' % (message, category, confidence))
def results(self):
if len(self._errors) < 2:
return ''.join(self._errors) # Most tests expect to have a string.
else:
return self._errors # Let's give a list if there is more than one.
def result_list(self):
return self._errors
def verify_all_categories_are_seen(self):
"""Fails if there's a category in _all_style_categories - _seen_style_categories.
This should only be called after all tests are run, so
_seen_style_categories has had a chance to fully populate. Since
this isn't called from within the normal unittest framework, we
can't use the normal unittest assert macros. Instead we just exit
when we see an error. Good thing this test is always run last!
"""
for category in self._all_style_categories:
if category not in self._seen_style_categories:
import sys
sys.exit('FATAL ERROR: There are no tests for category "%s"' % category)
# This class is a lame mock of codecs. We do not verify filename, mode, or
# encoding, but for the current use case it is not needed.
class MockIo:
def __init__(self, mock_file):
self.mock_file = mock_file
def open(self, unused_filename, unused_mode, unused_encoding, _): # NOLINT
# (lint doesn't like open as a method name)
return self.mock_file
class CppFunctionsTest(unittest.TestCase):
"""Supports testing functions that do not need CppStyleTestBase."""
def test_convert_to_lower_with_underscores(self):
self.assertEquals(cpp_style._convert_to_lower_with_underscores('ABC'), 'abc')
self.assertEquals(cpp_style._convert_to_lower_with_underscores('aB'), 'a_b')
self.assertEquals(cpp_style._convert_to_lower_with_underscores('isAName'), 'is_a_name')
self.assertEquals(cpp_style._convert_to_lower_with_underscores('AnotherTest'), 'another_test')
self.assertEquals(cpp_style._convert_to_lower_with_underscores('PassRefPtr<MyClass>'), 'pass_ref_ptr<my_class>')
self.assertEquals(cpp_style._convert_to_lower_with_underscores('_ABC'), '_abc')
def test_create_acronym(self):
self.assertEquals(cpp_style._create_acronym('ABC'), 'ABC')
self.assertEquals(cpp_style._create_acronym('IsAName'), 'IAN')
self.assertEquals(cpp_style._create_acronym('PassRefPtr<MyClass>'), 'PRP<MC>')
def test_is_c_or_objective_c(self):
clean_lines = cpp_style.CleansedLines([''])
clean_objc_lines = cpp_style.CleansedLines(['#import "header.h"'])
self.assertTrue(cpp_style._FileState(clean_lines, 'c').is_c_or_objective_c())
self.assertTrue(cpp_style._FileState(clean_lines, 'm').is_c_or_objective_c())
self.assertFalse(cpp_style._FileState(clean_lines, 'cpp').is_c_or_objective_c())
self.assertFalse(cpp_style._FileState(clean_lines, 'cc').is_c_or_objective_c())
self.assertFalse(cpp_style._FileState(clean_lines, 'h').is_c_or_objective_c())
self.assertTrue(cpp_style._FileState(clean_objc_lines, 'h').is_c_or_objective_c())
def test_parameter(self):
# Test type.
parameter = cpp_style.Parameter('ExceptionCode', 13, 1)
self.assertEquals(parameter.type, 'ExceptionCode')
self.assertEquals(parameter.name, '')
self.assertEquals(parameter.row, 1)
# Test type and name.
parameter = cpp_style.Parameter('PassRefPtr<MyClass> parent', 19, 1)
self.assertEquals(parameter.type, 'PassRefPtr<MyClass>')
self.assertEquals(parameter.name, 'parent')
self.assertEquals(parameter.row, 1)
# Test type, no name, with default value.
parameter = cpp_style.Parameter('MyClass = 0', 7, 0)
self.assertEquals(parameter.type, 'MyClass')
self.assertEquals(parameter.name, '')
self.assertEquals(parameter.row, 0)
# Test type, name, and default value.
parameter = cpp_style.Parameter('MyClass a = 0', 7, 0)
self.assertEquals(parameter.type, 'MyClass')
self.assertEquals(parameter.name, 'a')
self.assertEquals(parameter.row, 0)
def test_single_line_view(self):
start_position = cpp_style.Position(row=1, column=1)
end_position = cpp_style.Position(row=3, column=1)
single_line_view = cpp_style.SingleLineView(['0', 'abcde', 'fgh', 'i'], start_position, end_position)
self.assertEquals(single_line_view.single_line, 'bcde fgh i')
self.assertEquals(single_line_view.convert_column_to_row(0), 1)
self.assertEquals(single_line_view.convert_column_to_row(4), 1)
self.assertEquals(single_line_view.convert_column_to_row(5), 2)
self.assertEquals(single_line_view.convert_column_to_row(8), 2)
self.assertEquals(single_line_view.convert_column_to_row(9), 3)
self.assertEquals(single_line_view.convert_column_to_row(100), 3)
start_position = cpp_style.Position(row=0, column=3)
end_position = cpp_style.Position(row=0, column=4)
single_line_view = cpp_style.SingleLineView(['abcdef'], start_position, end_position)
self.assertEquals(single_line_view.single_line, 'd')
def test_create_skeleton_parameters(self):
self.assertEquals(cpp_style.create_skeleton_parameters(''), '')
self.assertEquals(cpp_style.create_skeleton_parameters(' '), ' ')
self.assertEquals(cpp_style.create_skeleton_parameters('long'), 'long,')
self.assertEquals(cpp_style.create_skeleton_parameters('const unsigned long int'), ' int,')
self.assertEquals(cpp_style.create_skeleton_parameters('long int*'), ' int ,')
self.assertEquals(cpp_style.create_skeleton_parameters('PassRefPtr<Foo> a'), 'PassRefPtr a,')
self.assertEquals(cpp_style.create_skeleton_parameters(
'ComplexTemplate<NestedTemplate1<MyClass1, MyClass2>, NestedTemplate1<MyClass1, MyClass2> > param, int second'),
'ComplexTemplate param, int second,')
self.assertEquals(cpp_style.create_skeleton_parameters('int = 0, Namespace::Type& a'), 'int , Type a,')
# Create skeleton parameters is a bit too aggressive with function variables, but
# it allows for parsing other parameters and declarations like this are rare.
self.assertEquals(cpp_style.create_skeleton_parameters('void (*fn)(int a, int b), Namespace::Type& a'),
'void , Type a,')
# This doesn't look like functions declarations but the simplifications help to eliminate false positives.
self.assertEquals(cpp_style.create_skeleton_parameters('b{d}'), 'b ,')
def test_find_parameter_name_index(self):
self.assertEquals(cpp_style.find_parameter_name_index(' int a '), 5)
self.assertEquals(cpp_style.find_parameter_name_index(' PassRefPtr '), 16)
self.assertEquals(cpp_style.find_parameter_name_index('double'), 6)
def test_parameter_list(self):
elided_lines = ['int blah(PassRefPtr<MyClass> paramName,',
'const Other1Class& foo,',
'const ComplexTemplate<Class1, NestedTemplate<P1, P2> >* const * param = new ComplexTemplate<Class1, NestedTemplate<P1, P2> >(34, 42),',
'int* myCount = 0);']
start_position = cpp_style.Position(row=0, column=8)
end_position = cpp_style.Position(row=3, column=16)
expected_parameters = ({'type': 'PassRefPtr<MyClass>', 'name': 'paramName', 'row': 0},
{'type': 'const Other1Class&', 'name': 'foo', 'row': 1},
{'type': 'const ComplexTemplate<Class1, NestedTemplate<P1, P2> >* const *', 'name': 'param', 'row': 2},
{'type': 'int*', 'name': 'myCount', 'row': 3})
index = 0
for parameter in cpp_style.parameter_list(elided_lines, start_position, end_position):
expected_parameter = expected_parameters[index]
self.assertEquals(parameter.type, expected_parameter['type'])
self.assertEquals(parameter.name, expected_parameter['name'])
self.assertEquals(parameter.row, expected_parameter['row'])
index += 1
self.assertEquals(index, len(expected_parameters))
def test_check_parameter_against_text(self):
error_collector = ErrorCollector(self.assert_)
parameter = cpp_style.Parameter('FooF ooF', 4, 1)
self.assertFalse(cpp_style._check_parameter_name_against_text(parameter, 'FooF', error_collector))
self.assertEquals(error_collector.results(),
'The parameter name "ooF" adds no information, so it should be removed. [readability/parameter_name] [5]')
class CppStyleTestBase(unittest.TestCase):
"""Provides some useful helper functions for cpp_style tests.
Attributes:
min_confidence: An integer that is the current minimum confidence
level for the tests.
"""
# FIXME: Refactor the unit tests so the confidence level is passed
# explicitly, just like it is in the real code.
min_confidence = 1;
# Helper function to avoid needing to explicitly pass confidence
# in all the unit test calls to cpp_style.process_file_data().
def process_file_data(self, filename, file_extension, lines, error, unit_test_config={}):
"""Call cpp_style.process_file_data() with the min_confidence."""
return cpp_style.process_file_data(filename, file_extension, lines,
error, self.min_confidence, unit_test_config)
def perform_lint(self, code, filename, basic_error_rules, unit_test_config={}):
error_collector = ErrorCollector(self.assert_, FilterConfiguration(basic_error_rules))
lines = code.split('\n')
extension = filename.split('.')[1]
self.process_file_data(filename, extension, lines, error_collector, unit_test_config)
return error_collector.results()
# Perform lint on single line of input and return the error message.
def perform_single_line_lint(self, code, filename):
basic_error_rules = ('-build/header_guard',
'-legal/copyright',
'-readability/fn_size',
'-readability/parameter_name',
'-whitespace/ending_newline')
return self.perform_lint(code, filename, basic_error_rules)
# Perform lint over multiple lines and return the error message.
def perform_multi_line_lint(self, code, file_extension):
basic_error_rules = ('-build/header_guard',
'-legal/copyright',
'-readability/parameter_name',
'-whitespace/ending_newline')
return self.perform_lint(code, 'test.' + file_extension, basic_error_rules)
# Only keep some errors related to includes, namespaces and rtti.
def perform_language_rules_check(self, filename, code):
basic_error_rules = ('-',
'+build/include',
'+build/include_order',
'+build/namespaces',
'+runtime/rtti')
return self.perform_lint(code, filename, basic_error_rules)
# Only keep function length errors.
def perform_function_lengths_check(self, code):
basic_error_rules = ('-',
'+readability/fn_size')
return self.perform_lint(code, 'test.cpp', basic_error_rules)
# Only keep pass ptr errors.
def perform_pass_ptr_check(self, code):
basic_error_rules = ('-',
'+readability/pass_ptr')
return self.perform_lint(code, 'test.cpp', basic_error_rules)
# Only include what you use errors.
def perform_include_what_you_use(self, code, filename='foo.h', io=codecs):
basic_error_rules = ('-',
'+build/include_what_you_use')
unit_test_config = {cpp_style.INCLUDE_IO_INJECTION_KEY: io}
return self.perform_lint(code, filename, basic_error_rules, unit_test_config)
# Perform lint and compare the error message with "expected_message".
def assert_lint(self, code, expected_message, file_name='foo.cpp'):
self.assertEquals(expected_message, self.perform_single_line_lint(code, file_name))
def assert_lint_one_of_many_errors_re(self, code, expected_message_re, file_name='foo.cpp'):
messages = self.perform_single_line_lint(code, file_name)
for message in messages:
if re.search(expected_message_re, message):
return
self.assertEquals(expected_message_re, messages)
def assert_multi_line_lint(self, code, expected_message, file_name='foo.h'):
file_extension = file_name[file_name.rfind('.') + 1:]
self.assertEquals(expected_message, self.perform_multi_line_lint(code, file_extension))
def assert_multi_line_lint_re(self, code, expected_message_re, file_name='foo.h'):
file_extension = file_name[file_name.rfind('.') + 1:]
message = self.perform_multi_line_lint(code, file_extension)
if not re.search(expected_message_re, message):
self.fail('Message was:\n' + message + 'Expected match to "' + expected_message_re + '"')
def assert_language_rules_check(self, file_name, code, expected_message):
self.assertEquals(expected_message,
self.perform_language_rules_check(file_name, code))
def assert_include_what_you_use(self, code, expected_message):
self.assertEquals(expected_message,
self.perform_include_what_you_use(code))
def assert_blank_lines_check(self, lines, start_errors, end_errors):
error_collector = ErrorCollector(self.assert_)
self.process_file_data('foo.cpp', 'cpp', lines, error_collector)
self.assertEquals(
start_errors,
error_collector.results().count(
'Blank line at the start of a code block. Is this needed?'
' [whitespace/blank_line] [2]'))
self.assertEquals(
end_errors,
error_collector.results().count(
'Blank line at the end of a code block. Is this needed?'
' [whitespace/blank_line] [3]'))
class FunctionDetectionTest(CppStyleTestBase):
def perform_function_detection(self, lines, function_information):
clean_lines = cpp_style.CleansedLines(lines)
function_state = cpp_style._FunctionState(5)
error_collector = ErrorCollector(self.assert_)
cpp_style.detect_functions(clean_lines, 0, function_state, error_collector)
if not function_information:
self.assertEquals(function_state.in_a_function, False)
return
self.assertEquals(function_state.in_a_function, True)
self.assertEquals(function_state.current_function, function_information['name'] + '()')
self.assertEquals(function_state.body_start_line_number, function_information['body_start_line_number'])
self.assertEquals(function_state.ending_line_number, function_information['ending_line_number'])
self.assertEquals(function_state.is_declaration, function_information['is_declaration'])
expected_parameters = function_information.get('parameter_list')
if expected_parameters:
actual_parameters = function_state.parameter_list()
self.assertEquals(len(actual_parameters), len(expected_parameters))
for index in range(len(expected_parameters)):
actual_parameter = actual_parameters[index]
expected_parameter = expected_parameters[index]
self.assertEquals(actual_parameter.type, expected_parameter['type'])
self.assertEquals(actual_parameter.name, expected_parameter['name'])
self.assertEquals(actual_parameter.row, expected_parameter['row'])
def test_basic_function_detection(self):
self.perform_function_detection(
['void theTestFunctionName(int) {',
'}'],
{'name': 'theTestFunctionName',
'body_start_line_number': 0,
'ending_line_number': 1,
'is_declaration': False})
def test_function_declaration_detection(self):
self.perform_function_detection(
['void aFunctionName(int);'],
{'name': 'aFunctionName',
'body_start_line_number': 0,
'ending_line_number': 0,
'is_declaration': True})
self.perform_function_detection(
['CheckedInt<T> operator /(const CheckedInt<T> &lhs, const CheckedInt<T> &rhs);'],
{'name': 'operator /',
'body_start_line_number': 0,
'ending_line_number': 0,
'is_declaration': True})
self.perform_function_detection(
['CheckedInt<T> operator -(const CheckedInt<T> &lhs, const CheckedInt<T> &rhs);'],
{'name': 'operator -',
'body_start_line_number': 0,
'ending_line_number': 0,
'is_declaration': True})
self.perform_function_detection(
['CheckedInt<T> operator !=(const CheckedInt<T> &lhs, const CheckedInt<T> &rhs);'],
{'name': 'operator !=',
'body_start_line_number': 0,
'ending_line_number': 0,
'is_declaration': True})
self.perform_function_detection(
['CheckedInt<T> operator +(const CheckedInt<T> &lhs, const CheckedInt<T> &rhs);'],
{'name': 'operator +',
'body_start_line_number': 0,
'ending_line_number': 0,
'is_declaration': True})
def test_ignore_macros(self):
self.perform_function_detection(['void aFunctionName(int); \\'], None)
def test_non_functions(self):
# This case exposed an error because the open brace was in quotes.
self.perform_function_detection(
['asm(',
' "stmdb sp!, {r1-r3}" "\n"',
');'],
# This isn't a function but it looks like one to our simple
# algorithm and that is ok.
{'name': 'asm',
'body_start_line_number': 2,
'ending_line_number': 2,
'is_declaration': True})
# Simple test case with something that is not a function.
self.perform_function_detection(['class Stuff;'], None)
def test_parameter_list(self):
# A function with no arguments.
function_state = self.perform_function_detection(
['void functionName();'],
{'name': 'functionName',
'body_start_line_number': 0,
'ending_line_number': 0,
'is_declaration': True,
'parameter_list': ()})
# A function with one argument.
function_state = self.perform_function_detection(
['void functionName(int);'],
{'name': 'functionName',
'body_start_line_number': 0,
'ending_line_number': 0,
'is_declaration': True,
'parameter_list':
({'type': 'int', 'name': '', 'row': 0},)})
# A function with unsigned and short arguments
function_state = self.perform_function_detection(
['void functionName(unsigned a, short b, long c, long long short unsigned int);'],
{'name': 'functionName',
'body_start_line_number': 0,
'ending_line_number': 0,
'is_declaration': True,
'parameter_list':
({'type': 'unsigned', 'name': 'a', 'row': 0},
{'type': 'short', 'name': 'b', 'row': 0},
{'type': 'long', 'name': 'c', 'row': 0},
{'type': 'long long short unsigned int', 'name': '', 'row': 0})})
# Some parameter type with modifiers and no parameter names.
function_state = self.perform_function_detection(
['virtual void determineARIADropEffects(Vector<String>*&, const unsigned long int*&, const MediaPlayer::Preload, Other<Other2, Other3<P1, P2> >, int);'],
{'name': 'determineARIADropEffects',
'body_start_line_number': 0,
'ending_line_number': 0,
'is_declaration': True,
'parameter_list':
({'type': 'Vector<String>*&', 'name': '', 'row': 0},
{'type': 'const unsigned long int*&', 'name': '', 'row': 0},
{'type': 'const MediaPlayer::Preload', 'name': '', 'row': 0},
{'type': 'Other<Other2, Other3<P1, P2> >', 'name': '', 'row': 0},
{'type': 'int', 'name': '', 'row': 0})})
# Try parsing a function with a very complex definition.
function_state = self.perform_function_detection(
['AnotherTemplate<Class1, Class2> aFunctionName(PassRefPtr<MyClass> paramName,',
'const Other1Class& foo,',
'const ComplexTemplate<Class1, NestedTemplate<P1, P2> >* const * param = new ComplexTemplate<Class1, NestedTemplate<P1, P2> >(34, 42),',
'int* myCount = 0);'],
{'name': 'aFunctionName',
'body_start_line_number': 3,
'ending_line_number': 3,
'is_declaration': True,
'parameter_list':
({'type': 'PassRefPtr<MyClass>', 'name': 'paramName', 'row': 0},
{'type': 'const Other1Class&', 'name': 'foo', 'row': 1},
{'type': 'const ComplexTemplate<Class1, NestedTemplate<P1, P2> >* const *', 'name': 'param', 'row': 2},
{'type': 'int*', 'name': 'myCount', 'row': 3})})
class CppStyleTest(CppStyleTestBase):
# Test get line width.
def test_get_line_width(self):
self.assertEquals(0, cpp_style.get_line_width(''))
self.assertEquals(10, cpp_style.get_line_width(u'x' * 10))
self.assertEquals(16, cpp_style.get_line_width(u'都|道|府|県|支庁'))
def test_find_next_multi_line_comment_start(self):
self.assertEquals(1, cpp_style.find_next_multi_line_comment_start([''], 0))
lines = ['a', 'b', '/* c']
self.assertEquals(2, cpp_style.find_next_multi_line_comment_start(lines, 0))
lines = ['char a[] = "/*";'] # not recognized as comment.
self.assertEquals(1, cpp_style.find_next_multi_line_comment_start(lines, 0))
def test_find_next_multi_line_comment_end(self):
self.assertEquals(1, cpp_style.find_next_multi_line_comment_end([''], 0))
lines = ['a', 'b', ' c */']
self.assertEquals(2, cpp_style.find_next_multi_line_comment_end(lines, 0))
def test_remove_multi_line_comments_from_range(self):
lines = ['a', ' /* comment ', ' * still comment', ' comment */ ', 'b']
cpp_style.remove_multi_line_comments_from_range(lines, 1, 4)
self.assertEquals(['a', '// dummy', '// dummy', '// dummy', 'b'], lines)
def test_spaces_at_end_of_line(self):
self.assert_lint(
'// Hello there ',
'Line ends in whitespace. Consider deleting these extra spaces.'
' [whitespace/end_of_line] [4]')
# Test C-style cast cases.
def test_cstyle_cast(self):
self.assert_lint(
'int a = (int)1.0;',
'Using C-style cast. Use static_cast<int>(...) instead'
' [readability/casting] [4]')
self.assert_lint(
'int *a = (int *)DEFINED_VALUE;',
'Using C-style cast. Use reinterpret_cast<int *>(...) instead'
' [readability/casting] [4]', 'foo.c')
self.assert_lint(
'uint16 a = (uint16)1.0;',
'Using C-style cast. Use static_cast<uint16>(...) instead'
' [readability/casting] [4]')
self.assert_lint(
'int32 a = (int32)1.0;',
'Using C-style cast. Use static_cast<int32>(...) instead'
' [readability/casting] [4]')
self.assert_lint(
'uint64 a = (uint64)1.0;',
'Using C-style cast. Use static_cast<uint64>(...) instead'
' [readability/casting] [4]')
# Test taking address of casts (runtime/casting)
def test_runtime_casting(self):
self.assert_lint(
'int* x = &static_cast<int*>(foo);',
'Are you taking an address of a cast? '
'This is dangerous: could be a temp var. '
'Take the address before doing the cast, rather than after'
' [runtime/casting] [4]')
self.assert_lint(
'int* x = &dynamic_cast<int *>(foo);',
['Are you taking an address of a cast? '
'This is dangerous: could be a temp var. '
'Take the address before doing the cast, rather than after'
' [runtime/casting] [4]',
'Do not use dynamic_cast<>. If you need to cast within a class '
'hierarchy, use static_cast<> to upcast. Google doesn\'t support '
'RTTI. [runtime/rtti] [5]'])
self.assert_lint(
'int* x = &reinterpret_cast<int *>(foo);',
'Are you taking an address of a cast? '
'This is dangerous: could be a temp var. '
'Take the address before doing the cast, rather than after'
' [runtime/casting] [4]')
# It's OK to cast an address.
self.assert_lint(
'int* x = reinterpret_cast<int *>(&foo);',
'')
def test_runtime_selfinit(self):
self.assert_lint(
'Foo::Foo(Bar r, Bel l) : r_(r_), l_(l_) { }',
'You seem to be initializing a member variable with itself.'
' [runtime/init] [4]')
self.assert_lint(
'Foo::Foo(Bar r, Bel l) : r_(r), l_(l) { }',
'')
self.assert_lint(
'Foo::Foo(Bar r) : r_(r), l_(r_), ll_(l_) { }',
'')
def test_runtime_rtti(self):
statement = 'int* x = dynamic_cast<int*>(&foo);'
error_message = (
'Do not use dynamic_cast<>. If you need to cast within a class '
'hierarchy, use static_cast<> to upcast. Google doesn\'t support '
'RTTI. [runtime/rtti] [5]')
# dynamic_cast is disallowed in most files.
self.assert_language_rules_check('foo.cpp', statement, error_message)
self.assert_language_rules_check('foo.h', statement, error_message)
# We cannot test this functionality because of difference of
# function definitions. Anyway, we may never enable this.
#
# # Test for unnamed arguments in a method.
# def test_check_for_unnamed_params(self):
# message = ('All parameters should be named in a function'
# ' [readability/function] [3]')
# self.assert_lint('virtual void A(int*) const;', message)
# self.assert_lint('virtual void B(void (*fn)(int*));', message)
# self.assert_lint('virtual void C(int*);', message)
# self.assert_lint('void *(*f)(void *) = x;', message)
# self.assert_lint('void Method(char*) {', message)
# self.assert_lint('void Method(char*);', message)
# self.assert_lint('void Method(char* /*x*/);', message)
# self.assert_lint('typedef void (*Method)(int32);', message)
# self.assert_lint('static void operator delete[](void*) throw();', message)
#
# self.assert_lint('virtual void D(int* p);', '')
# self.assert_lint('void operator delete(void* x) throw();', '')
# self.assert_lint('void Method(char* x)\n{', '')
# self.assert_lint('void Method(char* /*x*/)\n{', '')
# self.assert_lint('void Method(char* x);', '')
# self.assert_lint('typedef void (*Method)(int32 x);', '')
# self.assert_lint('static void operator delete[](void* x) throw();', '')
# self.assert_lint('static void operator delete[](void* /*x*/) throw();', '')
#
# # This one should technically warn, but doesn't because the function
# # pointer is confusing.
# self.assert_lint('virtual void E(void (*fn)(int* p));', '')
# Test deprecated casts such as int(d)
def test_deprecated_cast(self):
self.assert_lint(
'int a = int(2.2);',
'Using deprecated casting style. '
'Use static_cast<int>(...) instead'
' [readability/casting] [4]')
# Checks for false positives...
self.assert_lint(
'int a = int(); // Constructor, o.k.',
'')
self.assert_lint(
'X::X() : a(int()) {} // default Constructor, o.k.',
'')
self.assert_lint(
'operator bool(); // Conversion operator, o.k.',
'')
# The second parameter to a gMock method definition is a function signature
# that often looks like a bad cast but should not picked up by lint.
def test_mock_method(self):
self.assert_lint(
'MOCK_METHOD0(method, int());',
'')
self.assert_lint(
'MOCK_CONST_METHOD1(method, float(string));',
'')
self.assert_lint(
'MOCK_CONST_METHOD2_T(method, double(float, float));',
'')
# Test sizeof(type) cases.
def test_sizeof_type(self):
self.assert_lint(
'sizeof(int);',
'Using sizeof(type). Use sizeof(varname) instead if possible'
' [runtime/sizeof] [1]')
self.assert_lint(
'sizeof(int *);',
'Using sizeof(type). Use sizeof(varname) instead if possible'
' [runtime/sizeof] [1]')
# Test typedef cases. There was a bug that cpp_style misidentified
# typedef for pointer to function as C-style cast and produced
# false-positive error messages.
def test_typedef_for_pointer_to_function(self):
self.assert_lint(
'typedef void (*Func)(int x);',
'')
self.assert_lint(
'typedef void (*Func)(int *x);',
'')
self.assert_lint(
'typedef void Func(int x);',
'')
self.assert_lint(
'typedef void Func(int *x);',
'')
def test_include_what_you_use_no_implementation_files(self):
code = 'std::vector<int> foo;'
self.assertEquals('Add #include <vector> for vector<>'
' [build/include_what_you_use] [4]',
self.perform_include_what_you_use(code, 'foo.h'))
self.assertEquals('',
self.perform_include_what_you_use(code, 'foo.cpp'))
def test_include_what_you_use(self):
self.assert_include_what_you_use(
'''#include <vector>
std::vector<int> foo;
''',
'')
self.assert_include_what_you_use(
'''#include <map>
std::pair<int,int> foo;
''',
'')
self.assert_include_what_you_use(
'''#include <multimap>
std::pair<int,int> foo;
''',
'')
self.assert_include_what_you_use(
'''#include <hash_map>
std::pair<int,int> foo;
''',
'')
self.assert_include_what_you_use(
'''#include <utility>
std::pair<int,int> foo;
''',
'')
self.assert_include_what_you_use(
'''#include <vector>
DECLARE_string(foobar);
''',
'')
self.assert_include_what_you_use(
'''#include <vector>
DEFINE_string(foobar, "", "");
''',
'')
self.assert_include_what_you_use(
'''#include <vector>
std::pair<int,int> foo;
''',
'Add #include <utility> for pair<>'
' [build/include_what_you_use] [4]')
self.assert_include_what_you_use(
'''#include "base/foobar.h"
std::vector<int> foo;
''',
'Add #include <vector> for vector<>'
' [build/include_what_you_use] [4]')
self.assert_include_what_you_use(
'''#include <vector>
std::set<int> foo;
''',
'Add #include <set> for set<>'
' [build/include_what_you_use] [4]')
self.assert_include_what_you_use(
'''#include "base/foobar.h"
hash_map<int, int> foobar;
''',
'Add #include <hash_map> for hash_map<>'
' [build/include_what_you_use] [4]')
self.assert_include_what_you_use(
'''#include "base/foobar.h"
bool foobar = std::less<int>(0,1);
''',
'Add #include <functional> for less<>'
' [build/include_what_you_use] [4]')
self.assert_include_what_you_use(
'''#include "base/foobar.h"
bool foobar = min<int>(0,1);
''',
'Add #include <algorithm> for min [build/include_what_you_use] [4]')
self.assert_include_what_you_use(
'void a(const string &foobar);',
'Add #include <string> for string [build/include_what_you_use] [4]')
self.assert_include_what_you_use(
'''#include "base/foobar.h"
bool foobar = swap(0,1);
''',
'Add #include <algorithm> for swap [build/include_what_you_use] [4]')
self.assert_include_what_you_use(
'''#include "base/foobar.h"
bool foobar = transform(a.begin(), a.end(), b.start(), Foo);
''',
'Add #include <algorithm> for transform '
'[build/include_what_you_use] [4]')
self.assert_include_what_you_use(
'''#include "base/foobar.h"
bool foobar = min_element(a.begin(), a.end());
''',
'Add #include <algorithm> for min_element '
'[build/include_what_you_use] [4]')
self.assert_include_what_you_use(
'''foo->swap(0,1);
foo.swap(0,1);
''',
'')
self.assert_include_what_you_use(
'''#include <string>
void a(const std::multimap<int,string> &foobar);
''',
'Add #include <map> for multimap<>'
' [build/include_what_you_use] [4]')
self.assert_include_what_you_use(
'''#include <queue>
void a(const std::priority_queue<int> &foobar);
''',
'')
self.assert_include_what_you_use(
'''#include "base/basictypes.h"
#include "base/port.h"
#include <assert.h>
#include <string>
#include <vector>
vector<string> hajoa;''', '')
self.assert_include_what_you_use(
'''#include <string>
int i = numeric_limits<int>::max()
''',
'Add #include <limits> for numeric_limits<>'
' [build/include_what_you_use] [4]')
self.assert_include_what_you_use(
'''#include <limits>
int i = numeric_limits<int>::max()
''',
'')
# Test the UpdateIncludeState code path.
mock_header_contents = ['#include "blah/foo.h"', '#include "blah/bar.h"']
message = self.perform_include_what_you_use(
'#include "config.h"\n'
'#include "blah/a.h"\n',
filename='blah/a.cpp',
io=MockIo(mock_header_contents))
self.assertEquals(message, '')
mock_header_contents = ['#include <set>']
message = self.perform_include_what_you_use(
'''#include "config.h"
#include "blah/a.h"
std::set<int> foo;''',
filename='blah/a.cpp',
io=MockIo(mock_header_contents))
self.assertEquals(message, '')
# If there's just a .cpp and the header can't be found then it's ok.
message = self.perform_include_what_you_use(
'''#include "config.h"
#include "blah/a.h"
std::set<int> foo;''',
filename='blah/a.cpp')
self.assertEquals(message, '')
# Make sure we find the headers with relative paths.
mock_header_contents = ['']
message = self.perform_include_what_you_use(
'''#include "config.h"
#include "%s/a.h"
std::set<int> foo;''' % os.path.basename(os.getcwd()),
filename='a.cpp',
io=MockIo(mock_header_contents))
self.assertEquals(message, 'Add #include <set> for set<> '
'[build/include_what_you_use] [4]')
def test_files_belong_to_same_module(self):
f = cpp_style.files_belong_to_same_module
self.assertEquals((True, ''), f('a.cpp', 'a.h'))
self.assertEquals((True, ''), f('base/google.cpp', 'base/google.h'))
self.assertEquals((True, ''), f('base/google_test.cpp', 'base/google.h'))
self.assertEquals((True, ''),
f('base/google_unittest.cpp', 'base/google.h'))
self.assertEquals((True, ''),
f('base/internal/google_unittest.cpp',
'base/public/google.h'))
self.assertEquals((True, 'xxx/yyy/'),
f('xxx/yyy/base/internal/google_unittest.cpp',
'base/public/google.h'))
self.assertEquals((True, 'xxx/yyy/'),
f('xxx/yyy/base/google_unittest.cpp',
'base/public/google.h'))
self.assertEquals((True, ''),
f('base/google_unittest.cpp', 'base/google-inl.h'))
self.assertEquals((True, '/home/build/google3/'),
f('/home/build/google3/base/google.cpp', 'base/google.h'))
self.assertEquals((False, ''),
f('/home/build/google3/base/google.cpp', 'basu/google.h'))
self.assertEquals((False, ''), f('a.cpp', 'b.h'))
def test_cleanse_line(self):
self.assertEquals('int foo = 0; ',
cpp_style.cleanse_comments('int foo = 0; // danger!'))
self.assertEquals('int o = 0;',
cpp_style.cleanse_comments('int /* foo */ o = 0;'))
self.assertEquals('foo(int a, int b);',
cpp_style.cleanse_comments('foo(int a /* abc */, int b);'))
self.assertEqual('f(a, b);',
cpp_style.cleanse_comments('f(a, /* name */ b);'))
self.assertEqual('f(a, b);',
cpp_style.cleanse_comments('f(a /* name */, b);'))
self.assertEqual('f(a, b);',
cpp_style.cleanse_comments('f(a, /* name */b);'))
def test_multi_line_comments(self):
# missing explicit is bad
self.assert_multi_line_lint(
r'''int a = 0;
/* multi-liner
class Foo {
Foo(int f); // should cause a lint warning in code
}
*/ ''',
'')
self.assert_multi_line_lint(
r'''/* int a = 0; multi-liner
static const int b = 0;''',
['Could not find end of multi-line comment'
' [readability/multiline_comment] [5]',
'Complex multi-line /*...*/-style comment found. '
'Lint may give bogus warnings. Consider replacing these with '
'//-style comments, with #if 0...#endif, or with more clearly '
'structured multi-line comments. [readability/multiline_comment] [5]'])
self.assert_multi_line_lint(r''' /* multi-line comment''',
['Could not find end of multi-line comment'
' [readability/multiline_comment] [5]',
'Complex multi-line /*...*/-style comment found. '
'Lint may give bogus warnings. Consider replacing these with '
'//-style comments, with #if 0...#endif, or with more clearly '
'structured multi-line comments. [readability/multiline_comment] [5]'])
self.assert_multi_line_lint(r''' // /* comment, but not multi-line''', '')
def test_multiline_strings(self):
multiline_string_error_message = (
'Multi-line string ("...") found. This lint script doesn\'t '
'do well with such strings, and may give bogus warnings. They\'re '
'ugly and unnecessary, and you should use concatenation instead".'
' [readability/multiline_string] [5]')
file_path = 'mydir/foo.cpp'
error_collector = ErrorCollector(self.assert_)
self.process_file_data(file_path, 'cpp',
['const char* str = "This is a\\',
' multiline string.";'],
error_collector)
self.assertEquals(
2, # One per line.
error_collector.result_list().count(multiline_string_error_message))
# Test non-explicit single-argument constructors
def test_explicit_single_argument_constructors(self):
# missing explicit is bad
self.assert_multi_line_lint(
'''class Foo {
Foo(int f);
};''',
'Single-argument constructors should be marked explicit.'
' [runtime/explicit] [5]')
# missing explicit is bad, even with whitespace
self.assert_multi_line_lint(
'''class Foo {
Foo (int f);
};''',
['Extra space before ( in function call [whitespace/parens] [4]',
'Single-argument constructors should be marked explicit.'
' [runtime/explicit] [5]'])
# missing explicit, with distracting comment, is still bad
self.assert_multi_line_lint(
'''class Foo {
Foo(int f); // simpler than Foo(blargh, blarg)
};''',
'Single-argument constructors should be marked explicit.'
' [runtime/explicit] [5]')
# missing explicit, with qualified classname
self.assert_multi_line_lint(
'''class Qualifier::AnotherOne::Foo {
Foo(int f);
};''',
'Single-argument constructors should be marked explicit.'
' [runtime/explicit] [5]')
# structs are caught as well.
self.assert_multi_line_lint(
'''struct Foo {
Foo(int f);
};''',
'Single-argument constructors should be marked explicit.'
' [runtime/explicit] [5]')
# Templatized classes are caught as well.
self.assert_multi_line_lint(
'''template<typename T> class Foo {
Foo(int f);
};''',
'Single-argument constructors should be marked explicit.'
' [runtime/explicit] [5]')
# proper style is okay
self.assert_multi_line_lint(
'''class Foo {
explicit Foo(int f);
};''',
'')
# two argument constructor is okay
self.assert_multi_line_lint(
'''class Foo {
Foo(int f, int b);
};''',
'')
# two argument constructor, across two lines, is okay
self.assert_multi_line_lint(
'''class Foo {
Foo(int f,
int b);
};''',
'')
# non-constructor (but similar name), is okay
self.assert_multi_line_lint(
'''class Foo {
aFoo(int f);
};''',
'')
# constructor with void argument is okay
self.assert_multi_line_lint(
'''class Foo {
Foo(void);
};''',
'')
# single argument method is okay
self.assert_multi_line_lint(
'''class Foo {
Bar(int b);
};''',
'')
# comments should be ignored
self.assert_multi_line_lint(
'''class Foo {
// Foo(int f);
};''',
'')
# single argument function following class definition is okay
# (okay, it's not actually valid, but we don't want a false positive)
self.assert_multi_line_lint(
'''class Foo {
Foo(int f, int b);
};
Foo(int f);''',
'')
# single argument function is okay
self.assert_multi_line_lint(
'''static Foo(int f);''',
'')
# single argument copy constructor is okay.
self.assert_multi_line_lint(
'''class Foo {
Foo(const Foo&);
};''',
'')
self.assert_multi_line_lint(
'''class Foo {
Foo(Foo&);
};''',
'')
def test_slash_star_comment_on_single_line(self):
self.assert_multi_line_lint(
'''/* static */ Foo(int f);''',
'')
self.assert_multi_line_lint(
'''/*/ static */ Foo(int f);''',
'')
self.assert_multi_line_lint(
'''/*/ static Foo(int f);''',
'Could not find end of multi-line comment'
' [readability/multiline_comment] [5]')
self.assert_multi_line_lint(
''' /*/ static Foo(int f);''',
'Could not find end of multi-line comment'
' [readability/multiline_comment] [5]')
self.assert_multi_line_lint(
''' /**/ static Foo(int f);''',
'')
# Test suspicious usage of "if" like this:
# if (a == b) {
# DoSomething();
# } if (a == c) { // Should be "else if".
# DoSomething(); // This gets called twice if a == b && a == c.
# }
def test_suspicious_usage_of_if(self):
self.assert_lint(
' if (a == b) {',
'')
self.assert_lint(
' } if (a == b) {',
'Did you mean "else if"? If not, start a new line for "if".'
' [readability/braces] [4]')
# Test suspicious usage of memset. Specifically, a 0
# as the final argument is almost certainly an error.
def test_suspicious_usage_of_memset(self):
# Normal use is okay.
self.assert_lint(
' memset(buf, 0, sizeof(buf))',
'')
# A 0 as the final argument is almost certainly an error.
self.assert_lint(
' memset(buf, sizeof(buf), 0)',
'Did you mean "memset(buf, 0, sizeof(buf))"?'
' [runtime/memset] [4]')
self.assert_lint(
' memset(buf, xsize * ysize, 0)',
'Did you mean "memset(buf, 0, xsize * ysize)"?'
' [runtime/memset] [4]')
# There is legitimate test code that uses this form.
# This is okay since the second argument is a literal.
self.assert_lint(
" memset(buf, 'y', 0)",
'')
self.assert_lint(
' memset(buf, 4, 0)',
'')
self.assert_lint(
' memset(buf, -1, 0)',
'')
self.assert_lint(
' memset(buf, 0xF1, 0)',
'')
self.assert_lint(
' memset(buf, 0xcd, 0)',
'')
def test_check_posix_threading(self):
self.assert_lint('sctime_r()', '')
self.assert_lint('strtok_r()', '')
self.assert_lint(' strtok_r(foo, ba, r)', '')
self.assert_lint('brand()', '')
self.assert_lint('_rand()', '')
self.assert_lint('.rand()', '')
self.assert_lint('>rand()', '')
self.assert_lint('rand()',
'Consider using rand_r(...) instead of rand(...)'
' for improved thread safety.'
' [runtime/threadsafe_fn] [2]')
self.assert_lint('strtok()',
'Consider using strtok_r(...) '
'instead of strtok(...)'
' for improved thread safety.'
' [runtime/threadsafe_fn] [2]')
# Test potential format string bugs like printf(foo).
def test_format_strings(self):
self.assert_lint('printf("foo")', '')
self.assert_lint('printf("foo: %s", foo)', '')
self.assert_lint('DocidForPrintf(docid)', '') # Should not trigger.
self.assert_lint(
'printf(foo)',
'Potential format string bug. Do printf("%s", foo) instead.'
' [runtime/printf] [4]')
self.assert_lint(
'printf(foo.c_str())',
'Potential format string bug. '
'Do printf("%s", foo.c_str()) instead.'
' [runtime/printf] [4]')
self.assert_lint(
'printf(foo->c_str())',
'Potential format string bug. '
'Do printf("%s", foo->c_str()) instead.'
' [runtime/printf] [4]')
self.assert_lint(
'StringPrintf(foo)',
'Potential format string bug. Do StringPrintf("%s", foo) instead.'
''
' [runtime/printf] [4]')
# Variable-length arrays are not permitted.
def test_variable_length_array_detection(self):
errmsg = ('Do not use variable-length arrays. Use an appropriately named '
"('k' followed by CamelCase) compile-time constant for the size."
' [runtime/arrays] [1]')
self.assert_lint('int a[any_old_variable];', errmsg)
self.assert_lint('int doublesize[some_var * 2];', errmsg)
self.assert_lint('int a[afunction()];', errmsg)
self.assert_lint('int a[function(kMaxFooBars)];', errmsg)
self.assert_lint('bool aList[items_->size()];', errmsg)
self.assert_lint('namespace::Type buffer[len+1];', errmsg)
self.assert_lint('int a[64];', '')
self.assert_lint('int a[0xFF];', '')
self.assert_lint('int first[256], second[256];', '')
self.assert_lint('int arrayName[kCompileTimeConstant];', '')
self.assert_lint('char buf[somenamespace::kBufSize];', '')
self.assert_lint('int arrayName[ALL_CAPS];', '')
self.assert_lint('AClass array1[foo::bar::ALL_CAPS];', '')
self.assert_lint('int a[kMaxStrLen + 1];', '')
self.assert_lint('int a[sizeof(foo)];', '')
self.assert_lint('int a[sizeof(*foo)];', '')
self.assert_lint('int a[sizeof foo];', '')
self.assert_lint('int a[sizeof(struct Foo)];', '')
self.assert_lint('int a[128 - sizeof(const bar)];', '')
self.assert_lint('int a[(sizeof(foo) * 4)];', '')
self.assert_lint('int a[(arraysize(fixed_size_array)/2) << 1];', 'Missing spaces around / [whitespace/operators] [3]')
self.assert_lint('delete a[some_var];', '')
self.assert_lint('return a[some_var];', '')
# Brace usage
def test_braces(self):
# Braces shouldn't be followed by a ; unless they're defining a struct
# or initializing an array
self.assert_lint('int a[3] = { 1, 2, 3 };', '')
self.assert_lint(
'''const int foo[] =
{1, 2, 3 };''',
'')
# For single line, unmatched '}' with a ';' is ignored (not enough context)
self.assert_multi_line_lint(
'''int a[3] = { 1,
2,
3 };''',
'')
self.assert_multi_line_lint(
'''int a[2][3] = { { 1, 2 },
{ 3, 4 } };''',
'')
self.assert_multi_line_lint(
'''int a[2][3] =
{ { 1, 2 },
{ 3, 4 } };''',
'')
# CHECK/EXPECT_TRUE/EXPECT_FALSE replacements
def test_check_check(self):
self.assert_lint('CHECK(x == 42)',
'Consider using CHECK_EQ instead of CHECK(a == b)'
' [readability/check] [2]')
self.assert_lint('CHECK(x != 42)',
'Consider using CHECK_NE instead of CHECK(a != b)'
' [readability/check] [2]')
self.assert_lint('CHECK(x >= 42)',
'Consider using CHECK_GE instead of CHECK(a >= b)'
' [readability/check] [2]')
self.assert_lint('CHECK(x > 42)',
'Consider using CHECK_GT instead of CHECK(a > b)'
' [readability/check] [2]')
self.assert_lint('CHECK(x <= 42)',
'Consider using CHECK_LE instead of CHECK(a <= b)'
' [readability/check] [2]')
self.assert_lint('CHECK(x < 42)',
'Consider using CHECK_LT instead of CHECK(a < b)'
' [readability/check] [2]')
self.assert_lint('DCHECK(x == 42)',
'Consider using DCHECK_EQ instead of DCHECK(a == b)'
' [readability/check] [2]')
self.assert_lint('DCHECK(x != 42)',
'Consider using DCHECK_NE instead of DCHECK(a != b)'
' [readability/check] [2]')
self.assert_lint('DCHECK(x >= 42)',
'Consider using DCHECK_GE instead of DCHECK(a >= b)'
' [readability/check] [2]')
self.assert_lint('DCHECK(x > 42)',
'Consider using DCHECK_GT instead of DCHECK(a > b)'
' [readability/check] [2]')
self.assert_lint('DCHECK(x <= 42)',
'Consider using DCHECK_LE instead of DCHECK(a <= b)'
' [readability/check] [2]')
self.assert_lint('DCHECK(x < 42)',
'Consider using DCHECK_LT instead of DCHECK(a < b)'
' [readability/check] [2]')
self.assert_lint(
'EXPECT_TRUE("42" == x)',
'Consider using EXPECT_EQ instead of EXPECT_TRUE(a == b)'
' [readability/check] [2]')
self.assert_lint(
'EXPECT_TRUE("42" != x)',
'Consider using EXPECT_NE instead of EXPECT_TRUE(a != b)'
' [readability/check] [2]')
self.assert_lint(
'EXPECT_TRUE(+42 >= x)',
'Consider using EXPECT_GE instead of EXPECT_TRUE(a >= b)'
' [readability/check] [2]')
self.assert_lint(
'EXPECT_TRUE_M(-42 > x)',
'Consider using EXPECT_GT_M instead of EXPECT_TRUE_M(a > b)'
' [readability/check] [2]')
self.assert_lint(
'EXPECT_TRUE_M(42U <= x)',
'Consider using EXPECT_LE_M instead of EXPECT_TRUE_M(a <= b)'
' [readability/check] [2]')
self.assert_lint(
'EXPECT_TRUE_M(42L < x)',
'Consider using EXPECT_LT_M instead of EXPECT_TRUE_M(a < b)'
' [readability/check] [2]')
self.assert_lint(
'EXPECT_FALSE(x == 42)',
'Consider using EXPECT_NE instead of EXPECT_FALSE(a == b)'
' [readability/check] [2]')
self.assert_lint(
'EXPECT_FALSE(x != 42)',
'Consider using EXPECT_EQ instead of EXPECT_FALSE(a != b)'
' [readability/check] [2]')
self.assert_lint(
'EXPECT_FALSE(x >= 42)',
'Consider using EXPECT_LT instead of EXPECT_FALSE(a >= b)'
' [readability/check] [2]')
self.assert_lint(
'ASSERT_FALSE(x > 42)',
'Consider using ASSERT_LE instead of ASSERT_FALSE(a > b)'
' [readability/check] [2]')
self.assert_lint(
'ASSERT_FALSE(x <= 42)',
'Consider using ASSERT_GT instead of ASSERT_FALSE(a <= b)'
' [readability/check] [2]')
self.assert_lint(
'ASSERT_FALSE_M(x < 42)',
'Consider using ASSERT_GE_M instead of ASSERT_FALSE_M(a < b)'
' [readability/check] [2]')
self.assert_lint('CHECK(some_iterator == obj.end())', '')
self.assert_lint('EXPECT_TRUE(some_iterator == obj.end())', '')
self.assert_lint('EXPECT_FALSE(some_iterator == obj.end())', '')
self.assert_lint('CHECK(CreateTestFile(dir, (1 << 20)));', '')
self.assert_lint('CHECK(CreateTestFile(dir, (1 >> 20)));', '')
self.assert_lint('CHECK(x<42)',
['Missing spaces around <'
' [whitespace/operators] [3]',
'Consider using CHECK_LT instead of CHECK(a < b)'
' [readability/check] [2]'])
self.assert_lint('CHECK(x>42)',
'Consider using CHECK_GT instead of CHECK(a > b)'
' [readability/check] [2]')
self.assert_lint(
' EXPECT_TRUE(42 < x) // Random comment.',
'Consider using EXPECT_LT instead of EXPECT_TRUE(a < b)'
' [readability/check] [2]')
self.assert_lint(
'EXPECT_TRUE( 42 < x )',
['Extra space after ( in function call'
' [whitespace/parens] [4]',
'Consider using EXPECT_LT instead of EXPECT_TRUE(a < b)'
' [readability/check] [2]'])
self.assert_lint(
'CHECK("foo" == "foo")',
'Consider using CHECK_EQ instead of CHECK(a == b)'
' [readability/check] [2]')
self.assert_lint('CHECK_EQ("foo", "foo")', '')
def test_brace_at_begin_of_line(self):
self.assert_lint('{',
'This { should be at the end of the previous line'
' [whitespace/braces] [4]')
self.assert_multi_line_lint(
'#endif\n'
'{\n'
'}\n',
'')
self.assert_multi_line_lint(
'if (condition) {',
'')
self.assert_multi_line_lint(
' MACRO1(macroArg) {',
'')
self.assert_multi_line_lint(
'ACCESSOR_GETTER(MessageEventPorts) {',
'Place brace on its own line for function definitions. [whitespace/braces] [4]')
self.assert_multi_line_lint(
'int foo() {',
'Place brace on its own line for function definitions. [whitespace/braces] [4]')
self.assert_multi_line_lint(
'int foo() const {',
'Place brace on its own line for function definitions. [whitespace/braces] [4]')
self.assert_multi_line_lint(
'int foo() const\n'
'{\n'
'}\n',
'')
self.assert_multi_line_lint(
'if (condition\n'
' && condition2\n'
' && condition3) {\n'
'}\n',
'')
def test_mismatching_spaces_in_parens(self):
self.assert_lint('if (foo ) {', 'Extra space before ) in if'
' [whitespace/parens] [5]')
self.assert_lint('switch ( foo) {', 'Extra space after ( in switch'
' [whitespace/parens] [5]')
self.assert_lint('for (foo; ba; bar ) {', 'Extra space before ) in for'
' [whitespace/parens] [5]')
self.assert_lint('for ((foo); (ba); (bar) ) {', 'Extra space before ) in for'
' [whitespace/parens] [5]')
self.assert_lint('for (; foo; bar) {', '')
self.assert_lint('for (; (foo); (bar)) {', '')
self.assert_lint('for ( ; foo; bar) {', '')
self.assert_lint('for ( ; (foo); (bar)) {', '')
self.assert_lint('for ( ; foo; bar ) {', 'Extra space before ) in for'
' [whitespace/parens] [5]')
self.assert_lint('for ( ; (foo); (bar) ) {', 'Extra space before ) in for'
' [whitespace/parens] [5]')
self.assert_lint('for (foo; bar; ) {', '')
self.assert_lint('for ((foo); (bar); ) {', '')
self.assert_lint('foreach (foo, foos ) {', 'Extra space before ) in foreach'
' [whitespace/parens] [5]')
self.assert_lint('foreach ( foo, foos) {', 'Extra space after ( in foreach'
' [whitespace/parens] [5]')
self.assert_lint('while ( foo) {', 'Extra space after ( in while'
' [whitespace/parens] [5]')
def test_spacing_for_fncall(self):
self.assert_lint('if (foo) {', '')
self.assert_lint('for (foo;bar;baz) {', '')
self.assert_lint('foreach (foo, foos) {', '')
self.assert_lint('while (foo) {', '')
self.assert_lint('switch (foo) {', '')
self.assert_lint('new (RenderArena()) RenderInline(document())', '')
self.assert_lint('foo( bar)', 'Extra space after ( in function call'
' [whitespace/parens] [4]')
self.assert_lint('foobar( \\', '')
self.assert_lint('foobar( \\', '')
self.assert_lint('( a + b)', 'Extra space after ('
' [whitespace/parens] [2]')
self.assert_lint('((a+b))', '')
self.assert_lint('foo (foo)', 'Extra space before ( in function call'
' [whitespace/parens] [4]')
self.assert_lint('#elif (foo(bar))', '')
self.assert_lint('#elif (foo(bar) && foo(baz))', '')
self.assert_lint('typedef foo (*foo)(foo)', '')
self.assert_lint('typedef foo (*foo12bar_)(foo)', '')
self.assert_lint('typedef foo (Foo::*bar)(foo)', '')
self.assert_lint('foo (Foo::*bar)(',
'Extra space before ( in function call'
' [whitespace/parens] [4]')
self.assert_lint('typedef foo (Foo::*bar)(', '')
self.assert_lint('(foo)(bar)', '')
self.assert_lint('Foo (*foo)(bar)', '')
self.assert_lint('Foo (*foo)(Bar bar,', '')
self.assert_lint('char (*p)[sizeof(foo)] = &foo', '')
self.assert_lint('char (&ref)[sizeof(foo)] = &foo', '')
self.assert_lint('const char32 (*table[])[6];', '')
def test_spacing_before_braces(self):
self.assert_lint('if (foo){', 'Missing space before {'
' [whitespace/braces] [5]')
self.assert_lint('for{', 'Missing space before {'
' [whitespace/braces] [5]')
self.assert_lint('for {', '')
self.assert_lint('EXPECT_DEBUG_DEATH({', '')
def test_spacing_around_else(self):
self.assert_lint('}else {', 'Missing space before else'
' [whitespace/braces] [5]')
self.assert_lint('} else{', 'Missing space before {'
' [whitespace/braces] [5]')
self.assert_lint('} else {', '')
self.assert_lint('} else if', '')
def test_spacing_for_binary_ops(self):
self.assert_lint('if (foo<=bar) {', 'Missing spaces around <='
' [whitespace/operators] [3]')
self.assert_lint('if (foo<bar) {', 'Missing spaces around <'
' [whitespace/operators] [3]')
self.assert_lint('if (foo<bar->baz) {', 'Missing spaces around <'
' [whitespace/operators] [3]')
self.assert_lint('if (foo<bar->bar) {', 'Missing spaces around <'
' [whitespace/operators] [3]')
self.assert_lint('typedef hash_map<Foo, Bar', 'Missing spaces around <'
' [whitespace/operators] [3]')
self.assert_lint('typedef hash_map<FoooooType, BaaaaarType,', '')
self.assert_lint('a<Foo> t+=b;', 'Missing spaces around +='
' [whitespace/operators] [3]')
self.assert_lint('a<Foo> t-=b;', 'Missing spaces around -='
' [whitespace/operators] [3]')
self.assert_lint('a<Foo*> t*=b;', 'Missing spaces around *='
' [whitespace/operators] [3]')
self.assert_lint('a<Foo*> t/=b;', 'Missing spaces around /='
' [whitespace/operators] [3]')
self.assert_lint('a<Foo*> t|=b;', 'Missing spaces around |='
' [whitespace/operators] [3]')
self.assert_lint('a<Foo*> t&=b;', 'Missing spaces around &='
' [whitespace/operators] [3]')
self.assert_lint('a<Foo*> t<<=b;', 'Missing spaces around <<='
' [whitespace/operators] [3]')
self.assert_lint('a<Foo*> t>>=b;', 'Missing spaces around >>='
' [whitespace/operators] [3]')
self.assert_lint('a<Foo*> t>>=&b|c;', 'Missing spaces around >>='
' [whitespace/operators] [3]')
self.assert_lint('a<Foo*> t<<=*b/c;', 'Missing spaces around <<='
' [whitespace/operators] [3]')
self.assert_lint('a<Foo> t -= b;', '')
self.assert_lint('a<Foo> t += b;', '')
self.assert_lint('a<Foo*> t *= b;', '')
self.assert_lint('a<Foo*> t /= b;', '')
self.assert_lint('a<Foo*> t |= b;', '')
self.assert_lint('a<Foo*> t &= b;', '')
self.assert_lint('a<Foo*> t <<= b;', '')
self.assert_lint('a<Foo*> t >>= b;', '')
self.assert_lint('a<Foo*> t >>= &b|c;', 'Missing spaces around |'
' [whitespace/operators] [3]')
self.assert_lint('a<Foo*> t <<= *b/c;', 'Missing spaces around /'
' [whitespace/operators] [3]')
self.assert_lint('a<Foo*> t <<= b/c; //Test', [
'Should have a space between // and comment '
'[whitespace/comments] [4]', 'Missing'
' spaces around / [whitespace/operators] [3]'])
self.assert_lint('a<Foo*> t <<= b||c; //Test', ['One space before end'
' of line comments [whitespace/comments] [5]',
'Should have a space between // and comment '
'[whitespace/comments] [4]',
'Missing spaces around || [whitespace/operators] [3]'])
self.assert_lint('a<Foo*> t <<= b&&c; // Test', 'Missing spaces around'
' && [whitespace/operators] [3]')
self.assert_lint('a<Foo*> t <<= b&&&c; // Test', 'Missing spaces around'
' && [whitespace/operators] [3]')
self.assert_lint('a<Foo*> t <<= b&&*c; // Test', 'Missing spaces around'
' && [whitespace/operators] [3]')
self.assert_lint('a<Foo*> t <<= b && *c; // Test', '')
self.assert_lint('a<Foo*> t <<= b && &c; // Test', '')
self.assert_lint('a<Foo*> t <<= b || &c; /*Test', 'Complex multi-line '
'/*...*/-style comment found. Lint may give bogus '
'warnings. Consider replacing these with //-style'
' comments, with #if 0...#endif, or with more clearly'
' structured multi-line comments. [readability/multiline_comment] [5]')
self.assert_lint('a<Foo&> t <<= &b | &c;', '')
self.assert_lint('a<Foo*> t <<= &b & &c; // Test', '')
self.assert_lint('a<Foo*> t <<= *b / &c; // Test', '')
self.assert_lint('if (a=b == 1)', 'Missing spaces around = [whitespace/operators] [4]')
self.assert_lint('a = 1<<20', 'Missing spaces around << [whitespace/operators] [3]')
self.assert_lint('if (a = b == 1)', '')
self.assert_lint('a = 1 << 20', '')
self.assert_multi_line_lint('#include <sys/io.h>\n', '')
self.assert_multi_line_lint('#import <foo/bar.h>\n', '')
def test_operator_methods(self):
self.assert_lint('String operator+(const String&, const String&);', '')
self.assert_lint('bool operator==(const String&, const String&);', '')
self.assert_lint('String& operator-=(const String&, const String&);', '')
self.assert_lint('String& operator+=(const String&, const String&);', '')
self.assert_lint('String& operator*=(const String&, const String&);', '')
self.assert_lint('String& operator%=(const String&, const String&);', '')
self.assert_lint('String& operator&=(const String&, const String&);', '')
self.assert_lint('String& operator<<=(const String&, const String&);', '')
self.assert_lint('String& operator>>=(const String&, const String&);', '')
self.assert_lint('String& operator|=(const String&, const String&);', '')
self.assert_lint('String& operator^=(const String&, const String&);', '')
def test_spacing_before_last_semicolon(self):
self.assert_lint('call_function() ;',
'Extra space before last semicolon. If this should be an '
'empty statement, use { } instead.'
' [whitespace/semicolon] [5]')
self.assert_lint('while (true) ;',
'Extra space before last semicolon. If this should be an '
'empty statement, use { } instead.'
' [whitespace/semicolon] [5]')
self.assert_lint('default:;',
'Semicolon defining empty statement. Use { } instead.'
' [whitespace/semicolon] [5]')
self.assert_lint(' ;',
'Line contains only semicolon. If this should be an empty '
'statement, use { } instead.'
' [whitespace/semicolon] [5]')
self.assert_lint('for (int i = 0; ;', '')
# Static or global STL strings.
def test_static_or_global_stlstrings(self):
self.assert_lint('string foo;',
'For a static/global string constant, use a C style '
'string instead: "char foo[]".'
' [runtime/string] [4]')
self.assert_lint('string kFoo = "hello"; // English',
'For a static/global string constant, use a C style '
'string instead: "char kFoo[]".'
' [runtime/string] [4]')
self.assert_lint('static string foo;',
'For a static/global string constant, use a C style '
'string instead: "static char foo[]".'
' [runtime/string] [4]')
self.assert_lint('static const string foo;',
'For a static/global string constant, use a C style '
'string instead: "static const char foo[]".'
' [runtime/string] [4]')
self.assert_lint('string Foo::bar;',
'For a static/global string constant, use a C style '
'string instead: "char Foo::bar[]".'
' [runtime/string] [4]')
# Rare case.
self.assert_lint('string foo("foobar");',
'For a static/global string constant, use a C style '
'string instead: "char foo[]".'
' [runtime/string] [4]')
# Should not catch local or member variables.
self.assert_lint(' string foo', '')
# Should not catch functions.
self.assert_lint('string EmptyString() { return ""; }', '')
self.assert_lint('string EmptyString () { return ""; }', '')
self.assert_lint('string VeryLongNameFunctionSometimesEndsWith(\n'
' VeryLongNameType veryLongNameVariable) {}', '')
self.assert_lint('template<>\n'
'string FunctionTemplateSpecialization<SomeType>(\n'
' int x) { return ""; }', '')
self.assert_lint('template<>\n'
'string FunctionTemplateSpecialization<vector<A::B>* >(\n'
' int x) { return ""; }', '')
# should not catch methods of template classes.
self.assert_lint('string Class<Type>::Method() const\n'
'{\n'
' return "";\n'
'}\n', '')
self.assert_lint('string Class<Type>::Method(\n'
' int arg) const\n'
'{\n'
' return "";\n'
'}\n', '')
def test_no_spaces_in_function_calls(self):
self.assert_lint('TellStory(1, 3);',
'')
self.assert_lint('TellStory(1, 3 );',
'Extra space before )'
' [whitespace/parens] [2]')
self.assert_lint('TellStory(1 /* wolf */, 3 /* pigs */);',
'')
self.assert_multi_line_lint('#endif\n );',
'')
def test_two_spaces_between_code_and_comments(self):
self.assert_lint('} // namespace foo',
'')
self.assert_lint('}// namespace foo',
'One space before end of line comments'
' [whitespace/comments] [5]')
self.assert_lint('printf("foo"); // Outside quotes.',
'')
self.assert_lint('int i = 0; // Having one space is fine.','')
self.assert_lint('int i = 0; // Having two spaces is bad.',
'One space before end of line comments'
' [whitespace/comments] [5]')
self.assert_lint('int i = 0; // Having three spaces is bad.',
'One space before end of line comments'
' [whitespace/comments] [5]')
self.assert_lint('// Top level comment', '')
self.assert_lint(' // Line starts with four spaces.', '')
self.assert_lint('foo();\n'
'{ // A scope is opening.', '')
self.assert_lint(' foo();\n'
' { // An indented scope is opening.', '')
self.assert_lint('if (foo) { // not a pure scope',
'')
self.assert_lint('printf("// In quotes.")', '')
self.assert_lint('printf("\\"%s // In quotes.")', '')
self.assert_lint('printf("%s", "// In quotes.")', '')
def test_space_after_comment_marker(self):
self.assert_lint('//', '')
self.assert_lint('//x', 'Should have a space between // and comment'
' [whitespace/comments] [4]')
self.assert_lint('// x', '')
self.assert_lint('//----', '')
self.assert_lint('//====', '')
self.assert_lint('//////', '')
self.assert_lint('////// x', '')
self.assert_lint('/// x', '')
self.assert_lint('////x', 'Should have a space between // and comment'
' [whitespace/comments] [4]')
def test_newline_at_eof(self):
def do_test(self, data, is_missing_eof):
error_collector = ErrorCollector(self.assert_)
self.process_file_data('foo.cpp', 'cpp', data.split('\n'),
error_collector)
# The warning appears only once.
self.assertEquals(
int(is_missing_eof),
error_collector.results().count(
'Could not find a newline character at the end of the file.'
' [whitespace/ending_newline] [5]'))
do_test(self, '// Newline\n// at EOF\n', False)
do_test(self, '// No newline\n// at EOF', True)
def test_invalid_utf8(self):
def do_test(self, raw_bytes, has_invalid_utf8):
error_collector = ErrorCollector(self.assert_)
self.process_file_data('foo.cpp', 'cpp',
unicode(raw_bytes, 'utf8', 'replace').split('\n'),
error_collector)
# The warning appears only once.
self.assertEquals(
int(has_invalid_utf8),
error_collector.results().count(
'Line contains invalid UTF-8'
' (or Unicode replacement character).'
' [readability/utf8] [5]'))
do_test(self, 'Hello world\n', False)
do_test(self, '\xe9\x8e\xbd\n', False)
do_test(self, '\xe9x\x8e\xbd\n', True)
# This is the encoding of the replacement character itself (which
# you can see by evaluating codecs.getencoder('utf8')(u'\ufffd')).
do_test(self, '\xef\xbf\xbd\n', True)
def test_is_blank_line(self):
self.assert_(cpp_style.is_blank_line(''))
self.assert_(cpp_style.is_blank_line(' '))
self.assert_(cpp_style.is_blank_line(' \t\r\n'))
self.assert_(not cpp_style.is_blank_line('int a;'))
self.assert_(not cpp_style.is_blank_line('{'))
def test_blank_lines_check(self):
self.assert_blank_lines_check(['{\n', '\n', '\n', '}\n'], 1, 1)
self.assert_blank_lines_check([' if (foo) {\n', '\n', ' }\n'], 1, 1)
self.assert_blank_lines_check(
['\n', '// {\n', '\n', '\n', '// Comment\n', '{\n', '}\n'], 0, 0)
self.assert_blank_lines_check(['\n', 'run("{");\n', '\n'], 0, 0)
self.assert_blank_lines_check(['\n', ' if (foo) { return 0; }\n', '\n'], 0, 0)
def test_allow_blank_line_before_closing_namespace(self):
error_collector = ErrorCollector(self.assert_)
self.process_file_data('foo.cpp', 'cpp',
['namespace {', '', '} // namespace'],
error_collector)
self.assertEquals(0, error_collector.results().count(
'Blank line at the end of a code block. Is this needed?'
' [whitespace/blank_line] [3]'))
def test_allow_blank_line_before_if_else_chain(self):
error_collector = ErrorCollector(self.assert_)
self.process_file_data('foo.cpp', 'cpp',
['if (hoge) {',
'', # No warning
'} else if (piyo) {',
'', # No warning
'} else if (piyopiyo) {',
' hoge = true;', # No warning
'} else {',
'', # Warning on this line
'}'],
error_collector)
self.assertEquals(1, error_collector.results().count(
'Blank line at the end of a code block. Is this needed?'
' [whitespace/blank_line] [3]'))
def test_else_on_same_line_as_closing_braces(self):
error_collector = ErrorCollector(self.assert_)
self.process_file_data('foo.cpp', 'cpp',
['if (hoge) {',
'',
'}',
' else {' # Warning on this line
'',
'}'],
error_collector)
self.assertEquals(1, error_collector.results().count(
'An else should appear on the same line as the preceding }'
' [whitespace/newline] [4]'))
def test_else_clause_not_on_same_line_as_else(self):
self.assert_lint(' else DoSomethingElse();',
'Else clause should never be on same line as else '
'(use 2 lines) [whitespace/newline] [4]')
self.assert_lint(' else ifDoSomethingElse();',
'Else clause should never be on same line as else '
'(use 2 lines) [whitespace/newline] [4]')
self.assert_lint(' else if (blah) {', '')
self.assert_lint(' variable_ends_in_else = true;', '')
def test_comma(self):
self.assert_lint('a = f(1,2);',
'Missing space after , [whitespace/comma] [3]')
self.assert_lint('int tmp=a,a=b,b=tmp;',
['Missing spaces around = [whitespace/operators] [4]',
'Missing space after , [whitespace/comma] [3]'])
self.assert_lint('f(a, /* name */ b);', '')
self.assert_lint('f(a, /* name */b);', '')
def test_declaration(self):
self.assert_lint('int a;', '')
self.assert_lint('int a;', 'Extra space between int and a [whitespace/declaration] [3]')
self.assert_lint('int* a;', 'Extra space between int* and a [whitespace/declaration] [3]')
self.assert_lint('else if { }', '')
self.assert_lint('else if { }', 'Extra space between else and if [whitespace/declaration] [3]')
def test_pointer_reference_marker_location(self):
self.assert_lint('int* b;', '', 'foo.cpp')
self.assert_lint('int *b;',
'Declaration has space between type name and * in int *b [whitespace/declaration] [3]',
'foo.cpp')
self.assert_lint('return *b;', '', 'foo.cpp')
self.assert_lint('delete *b;', '', 'foo.cpp')
self.assert_lint('int *b;', '', 'foo.c')
self.assert_lint('int* b;',
'Declaration has space between * and variable name in int* b [whitespace/declaration] [3]',
'foo.c')
self.assert_lint('int& b;', '', 'foo.cpp')
self.assert_lint('int &b;',
'Declaration has space between type name and & in int &b [whitespace/declaration] [3]',
'foo.cpp')
self.assert_lint('return &b;', '', 'foo.cpp')
def test_indent(self):
self.assert_lint('static int noindent;', '')
self.assert_lint(' int fourSpaceIndent;', '')
self.assert_lint(' int oneSpaceIndent;',
'Weird number of spaces at line-start. '
'Are you using a 4-space indent? [whitespace/indent] [3]')
self.assert_lint(' int threeSpaceIndent;',
'Weird number of spaces at line-start. '
'Are you using a 4-space indent? [whitespace/indent] [3]')
self.assert_lint(' char* oneSpaceIndent = "public:";',
'Weird number of spaces at line-start. '
'Are you using a 4-space indent? [whitespace/indent] [3]')
self.assert_lint(' public:', '')
self.assert_lint(' public:', '')
self.assert_lint(' public:', '')
def test_label(self):
self.assert_lint('public:',
'Labels should always be indented at least one space. '
'If this is a member-initializer list in a constructor, '
'the colon should be on the line after the definition '
'header. [whitespace/labels] [4]')
self.assert_lint(' public:', '')
self.assert_lint(' public:', '')
self.assert_lint(' public:', '')
self.assert_lint(' public:', '')
self.assert_lint(' public:', '')
def test_not_alabel(self):
self.assert_lint('MyVeryLongNamespace::MyVeryLongClassName::', '')
def test_tab(self):
self.assert_lint('\tint a;',
'Tab found; better to use spaces [whitespace/tab] [1]')
self.assert_lint('int a = 5;\t// set a to 5',
'Tab found; better to use spaces [whitespace/tab] [1]')
def test_unnamed_namespaces_in_headers(self):
self.assert_language_rules_check(
'foo.h', 'namespace {',
'Do not use unnamed namespaces in header files. See'
' http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces'
' for more information. [build/namespaces] [4]')
# namespace registration macros are OK.
self.assert_language_rules_check('foo.h', 'namespace { \\', '')
# named namespaces are OK.
self.assert_language_rules_check('foo.h', 'namespace foo {', '')
self.assert_language_rules_check('foo.h', 'namespace foonamespace {', '')
self.assert_language_rules_check('foo.cpp', 'namespace {', '')
self.assert_language_rules_check('foo.cpp', 'namespace foo {', '')
def test_build_class(self):
# Test that the linter can parse to the end of class definitions,
# and that it will report when it can't.
# Use multi-line linter because it performs the ClassState check.
self.assert_multi_line_lint(
'class Foo {',
'Failed to find complete declaration of class Foo'
' [build/class] [5]')
# Don't warn on forward declarations of various types.
self.assert_multi_line_lint(
'class Foo;',
'')
self.assert_multi_line_lint(
'''struct Foo*
foo = NewFoo();''',
'')
# Here is an example where the linter gets confused, even though
# the code doesn't violate the style guide.
self.assert_multi_line_lint(
'''class Foo
#ifdef DERIVE_FROM_GOO
: public Goo {
#else
: public Hoo {
#endif
};''',
'Failed to find complete declaration of class Foo'
' [build/class] [5]')
def test_build_end_comment(self):
# The crosstool compiler we currently use will fail to compile the
# code in this test, so we might consider removing the lint check.
self.assert_lint('#endif Not a comment',
'Uncommented text after #endif is non-standard.'
' Use a comment.'
' [build/endif_comment] [5]')
def test_build_forward_decl(self):
# The crosstool compiler we currently use will fail to compile the
# code in this test, so we might consider removing the lint check.
self.assert_lint('class Foo::Goo;',
'Inner-style forward declarations are invalid.'
' Remove this line.'
' [build/forward_decl] [5]')
def test_build_header_guard(self):
file_path = 'mydir/Foo.h'
# We can't rely on our internal stuff to get a sane path on the open source
# side of things, so just parse out the suggested header guard. This
# doesn't allow us to test the suggested header guard, but it does let us
# test all the other header tests.
error_collector = ErrorCollector(self.assert_)
self.process_file_data(file_path, 'h', [], error_collector)
expected_guard = ''
matcher = re.compile(
'No \#ifndef header guard found\, suggested CPP variable is\: ([A-Za-z_0-9]+) ')
for error in error_collector.result_list():
matches = matcher.match(error)
if matches:
expected_guard = matches.group(1)
break
# Make sure we extracted something for our header guard.
self.assertNotEqual(expected_guard, '')
# Wrong guard
error_collector = ErrorCollector(self.assert_)
self.process_file_data(file_path, 'h',
['#ifndef FOO_H', '#define FOO_H'], error_collector)
self.assertEquals(
1,
error_collector.result_list().count(
'#ifndef header guard has wrong style, please use: %s'
' [build/header_guard] [5]' % expected_guard),
error_collector.result_list())
# No define
error_collector = ErrorCollector(self.assert_)
self.process_file_data(file_path, 'h',
['#ifndef %s' % expected_guard], error_collector)
self.assertEquals(
1,
error_collector.result_list().count(
'No #ifndef header guard found, suggested CPP variable is: %s'
' [build/header_guard] [5]' % expected_guard),
error_collector.result_list())
# Mismatched define
error_collector = ErrorCollector(self.assert_)
self.process_file_data(file_path, 'h',
['#ifndef %s' % expected_guard,
'#define FOO_H'],
error_collector)
self.assertEquals(
1,
error_collector.result_list().count(
'No #ifndef header guard found, suggested CPP variable is: %s'
' [build/header_guard] [5]' % expected_guard),
error_collector.result_list())
# No header guard errors
error_collector = ErrorCollector(self.assert_)
self.process_file_data(file_path, 'h',
['#ifndef %s' % expected_guard,
'#define %s' % expected_guard,
'#endif // %s' % expected_guard],
error_collector)
for line in error_collector.result_list():
if line.find('build/header_guard') != -1:
self.fail('Unexpected error: %s' % line)
# Completely incorrect header guard
error_collector = ErrorCollector(self.assert_)
self.process_file_data(file_path, 'h',
['#ifndef FOO',
'#define FOO',
'#endif // FOO'],
error_collector)
self.assertEquals(
1,
error_collector.result_list().count(
'#ifndef header guard has wrong style, please use: %s'
' [build/header_guard] [5]' % expected_guard),
error_collector.result_list())
# Special case for flymake
error_collector = ErrorCollector(self.assert_)
self.process_file_data('mydir/Foo_flymake.h', 'h',
['#ifndef %s' % expected_guard,
'#define %s' % expected_guard,
'#endif // %s' % expected_guard],
error_collector)
for line in error_collector.result_list():
if line.find('build/header_guard') != -1:
self.fail('Unexpected error: %s' % line)
error_collector = ErrorCollector(self.assert_)
self.process_file_data('mydir/Foo_flymake.h', 'h', [], error_collector)
self.assertEquals(
1,
error_collector.result_list().count(
'No #ifndef header guard found, suggested CPP variable is: %s'
' [build/header_guard] [5]' % expected_guard),
error_collector.result_list())
# Allow the WTF_ prefix for files in that directory.
header_guard_filter = FilterConfiguration(('-', '+build/header_guard'))
error_collector = ErrorCollector(self.assert_, header_guard_filter)
self.process_file_data('Source/JavaScriptCore/wtf/TestName.h', 'h',
['#ifndef WTF_TestName_h', '#define WTF_TestName_h'],
error_collector)
self.assertEquals(0, len(error_collector.result_list()),
error_collector.result_list())
# Also allow the non WTF_ prefix for files in that directory.
error_collector = ErrorCollector(self.assert_, header_guard_filter)
self.process_file_data('Source/JavaScriptCore/wtf/TestName.h', 'h',
['#ifndef TestName_h', '#define TestName_h'],
error_collector)
self.assertEquals(0, len(error_collector.result_list()),
error_collector.result_list())
# Verify that we suggest the WTF prefix version.
error_collector = ErrorCollector(self.assert_, header_guard_filter)
self.process_file_data('Source/JavaScriptCore/wtf/TestName.h', 'h',
['#ifndef BAD_TestName_h', '#define BAD_TestName_h'],
error_collector)
self.assertEquals(
1,
error_collector.result_list().count(
'#ifndef header guard has wrong style, please use: WTF_TestName_h'
' [build/header_guard] [5]'),
error_collector.result_list())
def test_build_printf_format(self):
self.assert_lint(
r'printf("\%%d", value);',
'%, [, (, and { are undefined character escapes. Unescape them.'
' [build/printf_format] [3]')
self.assert_lint(
r'snprintf(buffer, sizeof(buffer), "\[%d", value);',
'%, [, (, and { are undefined character escapes. Unescape them.'
' [build/printf_format] [3]')
self.assert_lint(
r'fprintf(file, "\(%d", value);',
'%, [, (, and { are undefined character escapes. Unescape them.'
' [build/printf_format] [3]')
self.assert_lint(
r'vsnprintf(buffer, sizeof(buffer), "\\\{%d", ap);',
'%, [, (, and { are undefined character escapes. Unescape them.'
' [build/printf_format] [3]')
# Don't warn if double-slash precedes the symbol
self.assert_lint(r'printf("\\%%%d", value);',
'')
def test_runtime_printf_format(self):
self.assert_lint(
r'fprintf(file, "%q", value);',
'%q in format strings is deprecated. Use %ll instead.'
' [runtime/printf_format] [3]')
self.assert_lint(
r'aprintf(file, "The number is %12q", value);',
'%q in format strings is deprecated. Use %ll instead.'
' [runtime/printf_format] [3]')
self.assert_lint(
r'printf(file, "The number is" "%-12q", value);',
'%q in format strings is deprecated. Use %ll instead.'
' [runtime/printf_format] [3]')
self.assert_lint(
r'printf(file, "The number is" "%+12q", value);',
'%q in format strings is deprecated. Use %ll instead.'
' [runtime/printf_format] [3]')
self.assert_lint(
r'printf(file, "The number is" "% 12q", value);',
'%q in format strings is deprecated. Use %ll instead.'
' [runtime/printf_format] [3]')
self.assert_lint(
r'snprintf(file, "Never mix %d and %1$d parmaeters!", value);',
'%N$ formats are unconventional. Try rewriting to avoid them.'
' [runtime/printf_format] [2]')
def assert_lintLogCodeOnError(self, code, expected_message):
# Special assert_lint which logs the input code on error.
result = self.perform_single_line_lint(code, 'foo.cpp')
if result != expected_message:
self.fail('For code: "%s"\nGot: "%s"\nExpected: "%s"'
% (code, result, expected_message))
def test_build_storage_class(self):
qualifiers = [None, 'const', 'volatile']
signs = [None, 'signed', 'unsigned']
types = ['void', 'char', 'int', 'float', 'double',
'schar', 'int8', 'uint8', 'int16', 'uint16',
'int32', 'uint32', 'int64', 'uint64']
storage_classes = ['auto', 'extern', 'register', 'static', 'typedef']
build_storage_class_error_message = (
'Storage class (static, extern, typedef, etc) should be first.'
' [build/storage_class] [5]')
# Some explicit cases. Legal in C++, deprecated in C99.
self.assert_lint('const int static foo = 5;',
build_storage_class_error_message)
self.assert_lint('char static foo;',
build_storage_class_error_message)
self.assert_lint('double const static foo = 2.0;',
build_storage_class_error_message)
self.assert_lint('uint64 typedef unsignedLongLong;',
build_storage_class_error_message)
self.assert_lint('int register foo = 0;',
build_storage_class_error_message)
# Since there are a very large number of possibilities, randomly
# construct declarations.
# Make sure that the declaration is logged if there's an error.
# Seed generator with an integer for absolute reproducibility.
random.seed(25)
for unused_i in range(10):
# Build up random list of non-storage-class declaration specs.
other_decl_specs = [random.choice(qualifiers), random.choice(signs),
random.choice(types)]
# remove None
other_decl_specs = filter(lambda x: x is not None, other_decl_specs)
# shuffle
random.shuffle(other_decl_specs)
# insert storage class after the first
storage_class = random.choice(storage_classes)
insertion_point = random.randint(1, len(other_decl_specs))
decl_specs = (other_decl_specs[0:insertion_point]
+ [storage_class]
+ other_decl_specs[insertion_point:])
self.assert_lintLogCodeOnError(
' '.join(decl_specs) + ';',
build_storage_class_error_message)
# but no error if storage class is first
self.assert_lintLogCodeOnError(
storage_class + ' ' + ' '.join(other_decl_specs),
'')
def test_legal_copyright(self):
legal_copyright_message = (
'No copyright message found. '
'You should have a line: "Copyright [year] <Copyright Owner>"'
' [legal/copyright] [5]')
copyright_line = '// Copyright 2008 Google Inc. All Rights Reserved.'
file_path = 'mydir/googleclient/foo.cpp'
# There should be a copyright message in the first 10 lines
error_collector = ErrorCollector(self.assert_)
self.process_file_data(file_path, 'cpp', [], error_collector)
self.assertEquals(
1,
error_collector.result_list().count(legal_copyright_message))
error_collector = ErrorCollector(self.assert_)
self.process_file_data(
file_path, 'cpp',
['' for unused_i in range(10)] + [copyright_line],
error_collector)
self.assertEquals(
1,
error_collector.result_list().count(legal_copyright_message))
# Test that warning isn't issued if Copyright line appears early enough.
error_collector = ErrorCollector(self.assert_)
self.process_file_data(file_path, 'cpp', [copyright_line], error_collector)
for message in error_collector.result_list():
if message.find('legal/copyright') != -1:
self.fail('Unexpected error: %s' % message)
error_collector = ErrorCollector(self.assert_)
self.process_file_data(
file_path, 'cpp',
['' for unused_i in range(9)] + [copyright_line],
error_collector)
for message in error_collector.result_list():
if message.find('legal/copyright') != -1:
self.fail('Unexpected error: %s' % message)
def test_invalid_increment(self):
self.assert_lint('*count++;',
'Changing pointer instead of value (or unused value of '
'operator*). [runtime/invalid_increment] [5]')
class CleansedLinesTest(unittest.TestCase):
def test_init(self):
lines = ['Line 1',
'Line 2',
'Line 3 // Comment test',
'Line 4 "foo"']
clean_lines = cpp_style.CleansedLines(lines)
self.assertEquals(lines, clean_lines.raw_lines)
self.assertEquals(4, clean_lines.num_lines())
self.assertEquals(['Line 1',
'Line 2',
'Line 3 ',
'Line 4 "foo"'],
clean_lines.lines)
self.assertEquals(['Line 1',
'Line 2',
'Line 3 ',
'Line 4 ""'],
clean_lines.elided)
def test_init_empty(self):
clean_lines = cpp_style.CleansedLines([])
self.assertEquals([], clean_lines.raw_lines)
self.assertEquals(0, clean_lines.num_lines())
def test_collapse_strings(self):
collapse = cpp_style.CleansedLines.collapse_strings
self.assertEquals('""', collapse('""')) # "" (empty)
self.assertEquals('"""', collapse('"""')) # """ (bad)
self.assertEquals('""', collapse('"xyz"')) # "xyz" (string)
self.assertEquals('""', collapse('"\\\""')) # "\"" (string)
self.assertEquals('""', collapse('"\'"')) # "'" (string)
self.assertEquals('"\"', collapse('"\"')) # "\" (bad)
self.assertEquals('""', collapse('"\\\\"')) # "\\" (string)
self.assertEquals('"', collapse('"\\\\\\"')) # "\\\" (bad)
self.assertEquals('""', collapse('"\\\\\\\\"')) # "\\\\" (string)
self.assertEquals('\'\'', collapse('\'\'')) # '' (empty)
self.assertEquals('\'\'', collapse('\'a\'')) # 'a' (char)
self.assertEquals('\'\'', collapse('\'\\\'\'')) # '\'' (char)
self.assertEquals('\'', collapse('\'\\\'')) # '\' (bad)
self.assertEquals('', collapse('\\012')) # '\012' (char)
self.assertEquals('', collapse('\\xfF0')) # '\xfF0' (char)
self.assertEquals('', collapse('\\n')) # '\n' (char)
self.assertEquals('\#', collapse('\\#')) # '\#' (bad)
self.assertEquals('StringReplace(body, "", "");',
collapse('StringReplace(body, "\\\\", "\\\\\\\\");'))
self.assertEquals('\'\' ""',
collapse('\'"\' "foo"'))
class OrderOfIncludesTest(CppStyleTestBase):
def setUp(self):
self.include_state = cpp_style._IncludeState()
# Cheat os.path.abspath called in FileInfo class.
self.os_path_abspath_orig = os.path.abspath
os.path.abspath = lambda value: value
def tearDown(self):
os.path.abspath = self.os_path_abspath_orig
def test_try_drop_common_suffixes(self):
self.assertEqual('foo/foo', cpp_style._drop_common_suffixes('foo/foo-inl.h'))
self.assertEqual('foo/bar/foo',
cpp_style._drop_common_suffixes('foo/bar/foo_inl.h'))
self.assertEqual('foo/foo', cpp_style._drop_common_suffixes('foo/foo.cpp'))
self.assertEqual('foo/foo_unusualinternal',
cpp_style._drop_common_suffixes('foo/foo_unusualinternal.h'))
self.assertEqual('',
cpp_style._drop_common_suffixes('_test.cpp'))
self.assertEqual('test',
cpp_style._drop_common_suffixes('test.cpp'))
class OrderOfIncludesTest(CppStyleTestBase):
def setUp(self):
self.include_state = cpp_style._IncludeState()
# Cheat os.path.abspath called in FileInfo class.
self.os_path_abspath_orig = os.path.abspath
os.path.abspath = lambda value: value
def tearDown(self):
os.path.abspath = self.os_path_abspath_orig
def test_check_next_include_order__no_config(self):
self.assertEqual('Header file should not contain WebCore config.h.',
self.include_state.check_next_include_order(cpp_style._CONFIG_HEADER, True))
def test_check_next_include_order__no_self(self):
self.assertEqual('Header file should not contain itself.',
self.include_state.check_next_include_order(cpp_style._PRIMARY_HEADER, True))
# Test actual code to make sure that header types are correctly assigned.
self.assert_language_rules_check('Foo.h',
'#include "Foo.h"\n',
'Header file should not contain itself. Should be: alphabetically sorted.'
' [build/include_order] [4]')
self.assert_language_rules_check('FooBar.h',
'#include "Foo.h"\n',
'')
def test_check_next_include_order__likely_then_config(self):
self.assertEqual('Found header this file implements before WebCore config.h.',
self.include_state.check_next_include_order(cpp_style._PRIMARY_HEADER, False))
self.assertEqual('Found WebCore config.h after a header this file implements.',
self.include_state.check_next_include_order(cpp_style._CONFIG_HEADER, False))
def test_check_next_include_order__other_then_config(self):
self.assertEqual('Found other header before WebCore config.h.',
self.include_state.check_next_include_order(cpp_style._OTHER_HEADER, False))
self.assertEqual('Found WebCore config.h after other header.',
self.include_state.check_next_include_order(cpp_style._CONFIG_HEADER, False))
def test_check_next_include_order__config_then_other_then_likely(self):
self.assertEqual('', self.include_state.check_next_include_order(cpp_style._CONFIG_HEADER, False))
self.assertEqual('Found other header before a header this file implements.',
self.include_state.check_next_include_order(cpp_style._OTHER_HEADER, False))
self.assertEqual('Found header this file implements after other header.',
self.include_state.check_next_include_order(cpp_style._PRIMARY_HEADER, False))
def test_check_alphabetical_include_order(self):
self.assert_language_rules_check('foo.h',
'#include "a.h"\n'
'#include "c.h"\n'
'#include "b.h"\n',
'Alphabetical sorting problem. [build/include_order] [4]')
self.assert_language_rules_check('foo.h',
'#include "a.h"\n'
'#include "b.h"\n'
'#include "c.h"\n',
'')
self.assert_language_rules_check('foo.h',
'#include <assert.h>\n'
'#include "bar.h"\n',
'Alphabetical sorting problem. [build/include_order] [4]')
self.assert_language_rules_check('foo.h',
'#include "bar.h"\n'
'#include <assert.h>\n',
'')
def test_check_line_break_after_own_header(self):
self.assert_language_rules_check('foo.cpp',
'#include "config.h"\n'
'#include "foo.h"\n'
'#include "bar.h"\n',
'You should add a blank line after implementation file\'s own header. [build/include_order] [4]')
self.assert_language_rules_check('foo.cpp',
'#include "config.h"\n'
'#include "foo.h"\n'
'\n'
'#include "bar.h"\n',
'')
def test_check_preprocessor_in_include_section(self):
self.assert_language_rules_check('foo.cpp',
'#include "config.h"\n'
'#include "foo.h"\n'
'\n'
'#ifdef BAZ\n'
'#include "baz.h"\n'
'#else\n'
'#include "foobar.h"\n'
'#endif"\n'
'#include "bar.h"\n', # No flag because previous is in preprocessor section
'')
self.assert_language_rules_check('foo.cpp',
'#include "config.h"\n'
'#include "foo.h"\n'
'\n'
'#ifdef BAZ\n'
'#include "baz.h"\n'
'#endif"\n'
'#include "bar.h"\n'
'#include "a.h"\n', # Should still flag this.
'Alphabetical sorting problem. [build/include_order] [4]')
self.assert_language_rules_check('foo.cpp',
'#include "config.h"\n'
'#include "foo.h"\n'
'\n'
'#ifdef BAZ\n'
'#include "baz.h"\n'
'#include "bar.h"\n' #Should still flag this
'#endif"\n',
'Alphabetical sorting problem. [build/include_order] [4]')
self.assert_language_rules_check('foo.cpp',
'#include "config.h"\n'
'#include "foo.h"\n'
'\n'
'#ifdef BAZ\n'
'#include "baz.h"\n'
'#endif"\n'
'#ifdef FOOBAR\n'
'#include "foobar.h"\n'
'#endif"\n'
'#include "bar.h"\n'
'#include "a.h"\n', # Should still flag this.
'Alphabetical sorting problem. [build/include_order] [4]')
# Check that after an already included error, the sorting rules still work.
self.assert_language_rules_check('foo.cpp',
'#include "config.h"\n'
'#include "foo.h"\n'
'\n'
'#include "foo.h"\n'
'#include "g.h"\n',
'"foo.h" already included at foo.cpp:2 [build/include] [4]')
def test_check_wtf_includes(self):
self.assert_language_rules_check('foo.cpp',
'#include "config.h"\n'
'#include "foo.h"\n'
'\n'
'#include <wtf/Assertions.h>\n',
'')
self.assert_language_rules_check('foo.cpp',
'#include "config.h"\n'
'#include "foo.h"\n'
'\n'
'#include "wtf/Assertions.h"\n',
'wtf includes should be <wtf/file.h> instead of "wtf/file.h".'
' [build/include] [4]')
def test_classify_include(self):
classify_include = cpp_style._classify_include
include_state = cpp_style._IncludeState()
self.assertEqual(cpp_style._CONFIG_HEADER,
classify_include('foo/foo.cpp',
'config.h',
False, include_state))
self.assertEqual(cpp_style._PRIMARY_HEADER,
classify_include('foo/internal/foo.cpp',
'foo/public/foo.h',
False, include_state))
self.assertEqual(cpp_style._PRIMARY_HEADER,
classify_include('foo/internal/foo.cpp',
'foo/other/public/foo.h',
False, include_state))
self.assertEqual(cpp_style._OTHER_HEADER,
classify_include('foo/internal/foo.cpp',
'foo/other/public/foop.h',
False, include_state))
self.assertEqual(cpp_style._OTHER_HEADER,
classify_include('foo/foo.cpp',
'string',
True, include_state))
self.assertEqual(cpp_style._PRIMARY_HEADER,
classify_include('fooCustom.cpp',
'foo.h',
False, include_state))
self.assertEqual(cpp_style._PRIMARY_HEADER,
classify_include('PrefixFooCustom.cpp',
'Foo.h',
False, include_state))
self.assertEqual(cpp_style._MOC_HEADER,
classify_include('foo.cpp',
'foo.moc',
False, include_state))
self.assertEqual(cpp_style._MOC_HEADER,
classify_include('foo.cpp',
'moc_foo.cpp',
False, include_state))
# Tricky example where both includes might be classified as primary.
self.assert_language_rules_check('ScrollbarThemeWince.cpp',
'#include "config.h"\n'
'#include "ScrollbarThemeWince.h"\n'
'\n'
'#include "Scrollbar.h"\n',
'')
self.assert_language_rules_check('ScrollbarThemeWince.cpp',
'#include "config.h"\n'
'#include "Scrollbar.h"\n'
'\n'
'#include "ScrollbarThemeWince.h"\n',
'Found header this file implements after a header this file implements.'
' Should be: config.h, primary header, blank line, and then alphabetically sorted.'
' [build/include_order] [4]')
self.assert_language_rules_check('ResourceHandleWin.cpp',
'#include "config.h"\n'
'#include "ResourceHandle.h"\n'
'\n'
'#include "ResourceHandleWin.h"\n',
'')
def test_try_drop_common_suffixes(self):
self.assertEqual('foo/foo', cpp_style._drop_common_suffixes('foo/foo-inl.h'))
self.assertEqual('foo/bar/foo',
cpp_style._drop_common_suffixes('foo/bar/foo_inl.h'))
self.assertEqual('foo/foo', cpp_style._drop_common_suffixes('foo/foo.cpp'))
self.assertEqual('foo/foo_unusualinternal',
cpp_style._drop_common_suffixes('foo/foo_unusualinternal.h'))
self.assertEqual('',
cpp_style._drop_common_suffixes('_test.cpp'))
self.assertEqual('test',
cpp_style._drop_common_suffixes('test.cpp'))
self.assertEqual('test',
cpp_style._drop_common_suffixes('test.cpp'))
class CheckForFunctionLengthsTest(CppStyleTestBase):
def setUp(self):
# Reducing these thresholds for the tests speeds up tests significantly.
self.old_normal_trigger = cpp_style._FunctionState._NORMAL_TRIGGER
self.old_test_trigger = cpp_style._FunctionState._TEST_TRIGGER
cpp_style._FunctionState._NORMAL_TRIGGER = 10
cpp_style._FunctionState._TEST_TRIGGER = 25
def tearDown(self):
cpp_style._FunctionState._NORMAL_TRIGGER = self.old_normal_trigger
cpp_style._FunctionState._TEST_TRIGGER = self.old_test_trigger
# FIXME: Eliminate the need for this function.
def set_min_confidence(self, min_confidence):
"""Set new test confidence and return old test confidence."""
old_min_confidence = self.min_confidence
self.min_confidence = min_confidence
return old_min_confidence
def assert_function_lengths_check(self, code, expected_message):
"""Check warnings for long function bodies are as expected.
Args:
code: C++ source code expected to generate a warning message.
expected_message: Message expected to be generated by the C++ code.
"""
self.assertEquals(expected_message,
self.perform_function_lengths_check(code))
def trigger_lines(self, error_level):
"""Return number of lines needed to trigger a function length warning.
Args:
error_level: --v setting for cpp_style.
Returns:
Number of lines needed to trigger a function length warning.
"""
return cpp_style._FunctionState._NORMAL_TRIGGER * 2 ** error_level
def trigger_test_lines(self, error_level):
"""Return number of lines needed to trigger a test function length warning.
Args:
error_level: --v setting for cpp_style.
Returns:
Number of lines needed to trigger a test function length warning.
"""
return cpp_style._FunctionState._TEST_TRIGGER * 2 ** error_level
def assert_function_length_check_definition(self, lines, error_level):
"""Generate long function definition and check warnings are as expected.
Args:
lines: Number of lines to generate.
error_level: --v setting for cpp_style.
"""
trigger_level = self.trigger_lines(self.min_confidence)
self.assert_function_lengths_check(
'void test(int x)' + self.function_body(lines),
('Small and focused functions are preferred: '
'test() has %d non-comment lines '
'(error triggered by exceeding %d lines).'
' [readability/fn_size] [%d]'
% (lines, trigger_level, error_level)))
def assert_function_length_check_definition_ok(self, lines):
"""Generate shorter function definition and check no warning is produced.
Args:
lines: Number of lines to generate.
"""
self.assert_function_lengths_check(
'void test(int x)' + self.function_body(lines),
'')
def assert_function_length_check_at_error_level(self, error_level):
"""Generate and check function at the trigger level for --v setting.
Args:
error_level: --v setting for cpp_style.
"""
self.assert_function_length_check_definition(self.trigger_lines(error_level),
error_level)
def assert_function_length_check_below_error_level(self, error_level):
"""Generate and check function just below the trigger level for --v setting.
Args:
error_level: --v setting for cpp_style.
"""
self.assert_function_length_check_definition(self.trigger_lines(error_level) - 1,
error_level - 1)
def assert_function_length_check_above_error_level(self, error_level):
"""Generate and check function just above the trigger level for --v setting.
Args:
error_level: --v setting for cpp_style.
"""
self.assert_function_length_check_definition(self.trigger_lines(error_level) + 1,
error_level)
def function_body(self, number_of_lines):
return ' {\n' + ' this_is_just_a_test();\n' * number_of_lines + '}'
def function_body_with_blank_lines(self, number_of_lines):
return ' {\n' + ' this_is_just_a_test();\n\n' * number_of_lines + '}'
def function_body_with_no_lints(self, number_of_lines):
return ' {\n' + ' this_is_just_a_test(); // NOLINT\n' * number_of_lines + '}'
# Test line length checks.
def test_function_length_check_declaration(self):
self.assert_function_lengths_check(
'void test();', # Not a function definition
'')
def test_function_length_check_declaration_with_block_following(self):
self.assert_function_lengths_check(
('void test();\n'
+ self.function_body(66)), # Not a function definition
'')
def test_function_length_check_class_definition(self):
self.assert_function_lengths_check( # Not a function definition
'class Test' + self.function_body(66) + ';',
'')
def test_function_length_check_trivial(self):
self.assert_function_lengths_check(
'void test() {}', # Not counted
'')
def test_function_length_check_empty(self):
self.assert_function_lengths_check(
'void test() {\n}',
'')
def test_function_length_check_definition_below_severity0(self):
old_min_confidence = self.set_min_confidence(0)
self.assert_function_length_check_definition_ok(self.trigger_lines(0) - 1)
self.set_min_confidence(old_min_confidence)
def test_function_length_check_definition_at_severity0(self):
old_min_confidence = self.set_min_confidence(0)
self.assert_function_length_check_definition_ok(self.trigger_lines(0))
self.set_min_confidence(old_min_confidence)
def test_function_length_check_definition_above_severity0(self):
old_min_confidence = self.set_min_confidence(0)
self.assert_function_length_check_above_error_level(0)
self.set_min_confidence(old_min_confidence)
def test_function_length_check_definition_below_severity1v0(self):
old_min_confidence = self.set_min_confidence(0)
self.assert_function_length_check_below_error_level(1)
self.set_min_confidence(old_min_confidence)
def test_function_length_check_definition_at_severity1v0(self):
old_min_confidence = self.set_min_confidence(0)
self.assert_function_length_check_at_error_level(1)
self.set_min_confidence(old_min_confidence)
def test_function_length_check_definition_below_severity1(self):
self.assert_function_length_check_definition_ok(self.trigger_lines(1) - 1)
def test_function_length_check_definition_at_severity1(self):
self.assert_function_length_check_definition_ok(self.trigger_lines(1))
def test_function_length_check_definition_above_severity1(self):
self.assert_function_length_check_above_error_level(1)
def test_function_length_check_definition_severity1_plus_indented(self):
error_level = 1
error_lines = self.trigger_lines(error_level) + 1
trigger_level = self.trigger_lines(self.min_confidence)
indent_spaces = ' '
self.assert_function_lengths_check(
re.sub(r'(?m)^(.)', indent_spaces + r'\1',
'void test_indent(int x)\n' + self.function_body(error_lines)),
('Small and focused functions are preferred: '
'test_indent() has %d non-comment lines '
'(error triggered by exceeding %d lines).'
' [readability/fn_size] [%d]')
% (error_lines, trigger_level, error_level))
def test_function_length_check_definition_severity1_plus_blanks(self):
error_level = 1
error_lines = self.trigger_lines(error_level) + 1
trigger_level = self.trigger_lines(self.min_confidence)
self.assert_function_lengths_check(
'void test_blanks(int x)' + self.function_body(error_lines),
('Small and focused functions are preferred: '
'test_blanks() has %d non-comment lines '
'(error triggered by exceeding %d lines).'
' [readability/fn_size] [%d]')
% (error_lines, trigger_level, error_level))
def test_function_length_check_complex_definition_severity1(self):
error_level = 1
error_lines = self.trigger_lines(error_level) + 1
trigger_level = self.trigger_lines(self.min_confidence)
self.assert_function_lengths_check(
('my_namespace::my_other_namespace::MyVeryLongTypeName<Type1, bool func(const Element*)>*\n'
'my_namespace::my_other_namespace<Type3, Type4>::~MyFunction<Type5<Type6, Type7> >(int arg1, char* arg2)'
+ self.function_body(error_lines)),
('Small and focused functions are preferred: '
'my_namespace::my_other_namespace<Type3, Type4>::~MyFunction<Type5<Type6, Type7> >()'
' has %d non-comment lines '
'(error triggered by exceeding %d lines).'
' [readability/fn_size] [%d]')
% (error_lines, trigger_level, error_level))
def test_function_length_check_definition_severity1_for_test(self):
error_level = 1
error_lines = self.trigger_test_lines(error_level) + 1
trigger_level = self.trigger_test_lines(self.min_confidence)
self.assert_function_lengths_check(
'TEST_F(Test, Mutator)' + self.function_body(error_lines),
('Small and focused functions are preferred: '
'TEST_F(Test, Mutator) has %d non-comment lines '
'(error triggered by exceeding %d lines).'
' [readability/fn_size] [%d]')
% (error_lines, trigger_level, error_level))
def test_function_length_check_definition_severity1_for_split_line_test(self):
error_level = 1
error_lines = self.trigger_test_lines(error_level) + 1
trigger_level = self.trigger_test_lines(self.min_confidence)
self.assert_function_lengths_check(
('TEST_F(GoogleUpdateRecoveryRegistryProtectedTest,\n'
' FixGoogleUpdate_AllValues_MachineApp)' # note: 4 spaces
+ self.function_body(error_lines)),
('Small and focused functions are preferred: '
'TEST_F(GoogleUpdateRecoveryRegistryProtectedTest, ' # 1 space
'FixGoogleUpdate_AllValues_MachineApp) has %d non-comment lines '
'(error triggered by exceeding %d lines).'
' [readability/fn_size] [%d]')
% (error_lines, trigger_level, error_level))
def test_function_length_check_definition_severity1_for_bad_test_doesnt_break(self):
error_level = 1
error_lines = self.trigger_test_lines(error_level) + 1
trigger_level = self.trigger_test_lines(self.min_confidence)
# Since the function name isn't valid, the function detection algorithm
# will skip it, so no error is produced.
self.assert_function_lengths_check(
('TEST_F('
+ self.function_body(error_lines)),
'')
def test_function_length_check_definition_severity1_with_embedded_no_lints(self):
error_level = 1
error_lines = self.trigger_lines(error_level) + 1
trigger_level = self.trigger_lines(self.min_confidence)
self.assert_function_lengths_check(
'void test(int x)' + self.function_body_with_no_lints(error_lines),
('Small and focused functions are preferred: '
'test() has %d non-comment lines '
'(error triggered by exceeding %d lines).'
' [readability/fn_size] [%d]')
% (error_lines, trigger_level, error_level))
def test_function_length_check_definition_severity1_with_no_lint(self):
self.assert_function_lengths_check(
('void test(int x)' + self.function_body(self.trigger_lines(1))
+ ' // NOLINT -- long function'),
'')
def test_function_length_check_definition_below_severity2(self):
self.assert_function_length_check_below_error_level(2)
def test_function_length_check_definition_severity2(self):
self.assert_function_length_check_at_error_level(2)
def test_function_length_check_definition_above_severity2(self):
self.assert_function_length_check_above_error_level(2)
def test_function_length_check_definition_below_severity3(self):
self.assert_function_length_check_below_error_level(3)
def test_function_length_check_definition_severity3(self):
self.assert_function_length_check_at_error_level(3)
def test_function_length_check_definition_above_severity3(self):
self.assert_function_length_check_above_error_level(3)
def test_function_length_check_definition_below_severity4(self):
self.assert_function_length_check_below_error_level(4)
def test_function_length_check_definition_severity4(self):
self.assert_function_length_check_at_error_level(4)
def test_function_length_check_definition_above_severity4(self):
self.assert_function_length_check_above_error_level(4)
def test_function_length_check_definition_below_severity5(self):
self.assert_function_length_check_below_error_level(5)
def test_function_length_check_definition_at_severity5(self):
self.assert_function_length_check_at_error_level(5)
def test_function_length_check_definition_above_severity5(self):
self.assert_function_length_check_above_error_level(5)
def test_function_length_check_definition_huge_lines(self):
# 5 is the limit
self.assert_function_length_check_definition(self.trigger_lines(10), 5)
def test_function_length_not_determinable(self):
# Macro invocation without terminating semicolon.
self.assert_function_lengths_check(
'MACRO(arg)',
'')
# Macro with underscores
self.assert_function_lengths_check(
'MACRO_WITH_UNDERSCORES(arg1, arg2, arg3)',
'')
self.assert_function_lengths_check(
'NonMacro(arg)',
'Lint failed to find start of function body.'
' [readability/fn_size] [5]')
class NoNonVirtualDestructorsTest(CppStyleTestBase):
def test_no_error(self):
self.assert_multi_line_lint(
'''class Foo {
virtual ~Foo();
virtual void foo();
};''',
'')
self.assert_multi_line_lint(
'''class Foo {
virtual inline ~Foo();
virtual void foo();
};''',
'')
self.assert_multi_line_lint(
'''class Foo {
inline virtual ~Foo();
virtual void foo();
};''',
'')
self.assert_multi_line_lint(
'''class Foo::Goo {
virtual ~Goo();
virtual void goo();
};''',
'')
self.assert_multi_line_lint(
'class Foo { void foo(); };',
'More than one command on the same line [whitespace/newline] [4]')
self.assert_multi_line_lint(
'class MyClass {\n'
' int getIntValue() { ASSERT(m_ptr); return *m_ptr; }\n'
'};\n',
'')
self.assert_multi_line_lint(
'class MyClass {\n'
' int getIntValue()\n'
' {\n'
' ASSERT(m_ptr); return *m_ptr;\n'
' }\n'
'};\n',
'More than one command on the same line [whitespace/newline] [4]')
self.assert_multi_line_lint(
'''class Qualified::Goo : public Foo {
virtual void goo();
};''',
'')
self.assert_multi_line_lint(
# Line-ending :
'''class Goo :
public Foo {
virtual void goo();
};''',
'Labels should always be indented at least one space. If this is a '
'member-initializer list in a constructor, the colon should be on the '
'line after the definition header. [whitespace/labels] [4]')
def test_no_destructor_when_virtual_needed(self):
self.assert_multi_line_lint_re(
'''class Foo {
virtual void foo();
};''',
'The class Foo probably needs a virtual destructor')
def test_destructor_non_virtual_when_virtual_needed(self):
self.assert_multi_line_lint_re(
'''class Foo {
~Foo();
virtual void foo();
};''',
'The class Foo probably needs a virtual destructor')
def test_no_warn_when_derived(self):
self.assert_multi_line_lint(
'''class Foo : public Goo {
virtual void foo();
};''',
'')
def test_internal_braces(self):
self.assert_multi_line_lint_re(
'''class Foo {
enum Goo {
GOO
};
virtual void foo();
};''',
'The class Foo probably needs a virtual destructor')
def test_inner_class_needs_virtual_destructor(self):
self.assert_multi_line_lint_re(
'''class Foo {
class Goo {
virtual void goo();
};
};''',
'The class Goo probably needs a virtual destructor')
def test_outer_class_needs_virtual_destructor(self):
self.assert_multi_line_lint_re(
'''class Foo {
class Goo {
};
virtual void foo();
};''',
'The class Foo probably needs a virtual destructor')
def test_qualified_class_needs_virtual_destructor(self):
self.assert_multi_line_lint_re(
'''class Qualified::Foo {
virtual void foo();
};''',
'The class Qualified::Foo probably needs a virtual destructor')
def test_multi_line_declaration_no_error(self):
self.assert_multi_line_lint_re(
'''class Foo
: public Goo {
virtual void foo();
};''',
'')
def test_multi_line_declaration_with_error(self):
self.assert_multi_line_lint(
'''class Foo
{
virtual void foo();
};''',
['This { should be at the end of the previous line '
'[whitespace/braces] [4]',
'The class Foo probably needs a virtual destructor due to having '
'virtual method(s), one declared at line 3. [runtime/virtual] [4]'])
class PassPtrTest(CppStyleTestBase):
# For http://webkit.org/coding/RefPtr.html
def assert_pass_ptr_check(self, code, expected_message):
"""Check warnings for Pass*Ptr are as expected.
Args:
code: C++ source code expected to generate a warning message.
expected_message: Message expected to be generated by the C++ code.
"""
self.assertEquals(expected_message,
self.perform_pass_ptr_check(code))
def test_pass_ref_ptr_in_function(self):
# Local variables should never be PassRefPtr.
self.assert_pass_ptr_check(
'int myFunction()\n'
'{\n'
' PassRefPtr<Type1> variable = variable2;\n'
'}',
'Local variables should never be PassRefPtr (see '
'http://webkit.org/coding/RefPtr.html). [readability/pass_ptr] [5]')
def test_pass_own_ptr_in_function(self):
# Local variables should never be PassRefPtr.
self.assert_pass_ptr_check(
'int myFunction()\n'
'{\n'
' PassOwnPtr<Type1> variable = variable2;\n'
'}',
'Local variables should never be PassOwnPtr (see '
'http://webkit.org/coding/RefPtr.html). [readability/pass_ptr] [5]')
def test_pass_other_type_ptr_in_function(self):
# Local variables should never be PassRefPtr.
self.assert_pass_ptr_check(
'int myFunction()\n'
'{\n'
' PassOtherTypePtr<Type1> variable;\n'
'}',
'Local variables should never be PassOtherTypePtr (see '
'http://webkit.org/coding/RefPtr.html). [readability/pass_ptr] [5]')
def test_pass_ref_ptr_return_value(self):
self.assert_pass_ptr_check(
'PassRefPtr<Type1>\n'
'myFunction(int)\n'
'{\n'
'}',
'')
self.assert_pass_ptr_check(
'PassRefPtr<Type1> myFunction(int)\n'
'{\n'
'}',
'')
self.assert_pass_ptr_check(
'PassRefPtr<Type1> myFunction();\n',
'')
def test_pass_ref_ptr_parameter_value(self):
self.assert_pass_ptr_check(
'int myFunction(PassRefPtr<Type1>)\n'
'{\n'
'}',
'')
def test_ref_ptr_member_variable(self):
self.assert_pass_ptr_check(
'class Foo {'
' RefPtr<Type1> m_other;\n'
'};\n',
'')
class WebKitStyleTest(CppStyleTestBase):
# for http://webkit.org/coding/coding-style.html
def test_indentation(self):
# 1. Use spaces, not tabs. Tabs should only appear in files that
# require them for semantic meaning, like Makefiles.
self.assert_multi_line_lint(
'class Foo {\n'
' int goo;\n'
'};',
'')
self.assert_multi_line_lint(
'class Foo {\n'
'\tint goo;\n'
'};',
'Tab found; better to use spaces [whitespace/tab] [1]')
# 2. The indent size is 4 spaces.
self.assert_multi_line_lint(
'class Foo {\n'
' int goo;\n'
'};',
'')
self.assert_multi_line_lint(
'class Foo {\n'
' int goo;\n'
'};',
'Weird number of spaces at line-start. Are you using a 4-space indent? [whitespace/indent] [3]')
# FIXME: No tests for 8-spaces.
# 3. In a header, code inside a namespace should not be indented.
self.assert_multi_line_lint(
'namespace WebCore {\n\n'
'class Document {\n'
' int myVariable;\n'
'};\n'
'}',
'',
'foo.h')
self.assert_multi_line_lint(
'namespace OuterNamespace {\n'
' namespace InnerNamespace {\n'
' class Document {\n'
'};\n'
'};\n'
'}',
'Code inside a namespace should not be indented. [whitespace/indent] [4]',
'foo.h')
self.assert_multi_line_lint(
'namespace OuterNamespace {\n'
' class Document {\n'
' namespace InnerNamespace {\n'
'};\n'
'};\n'
'}',
'Code inside a namespace should not be indented. [whitespace/indent] [4]',
'foo.h')
self.assert_multi_line_lint(
'namespace WebCore {\n'
'#if 0\n'
' class Document {\n'
'};\n'
'#endif\n'
'}',
'Code inside a namespace should not be indented. [whitespace/indent] [4]',
'foo.h')
self.assert_multi_line_lint(
'namespace WebCore {\n'
'class Document {\n'
'};\n'
'}',
'',
'foo.h')
# 4. In an implementation file (files with the extension .cpp, .c
# or .mm), code inside a namespace should not be indented.
self.assert_multi_line_lint(
'namespace WebCore {\n\n'
'Document::Foo()\n'
' : foo(bar)\n'
' , boo(far)\n'
'{\n'
' stuff();\n'
'}',
'',
'foo.cpp')
self.assert_multi_line_lint(
'namespace OuterNamespace {\n'
'namespace InnerNamespace {\n'
'Document::Foo() { }\n'
' void* p;\n'
'}\n'
'}\n',
'Code inside a namespace should not be indented. [whitespace/indent] [4]',
'foo.cpp')
self.assert_multi_line_lint(
'namespace OuterNamespace {\n'
'namespace InnerNamespace {\n'
'Document::Foo() { }\n'
'}\n'
' void* p;\n'
'}\n',
'Code inside a namespace should not be indented. [whitespace/indent] [4]',
'foo.cpp')
self.assert_multi_line_lint(
'namespace WebCore {\n\n'
' const char* foo = "start:;"\n'
' "dfsfsfs";\n'
'}\n',
'Code inside a namespace should not be indented. [whitespace/indent] [4]',
'foo.cpp')
self.assert_multi_line_lint(
'namespace WebCore {\n\n'
'const char* foo(void* a = ";", // ;\n'
' void* b);\n'
' void* p;\n'
'}\n',
'Code inside a namespace should not be indented. [whitespace/indent] [4]',
'foo.cpp')
self.assert_multi_line_lint(
'namespace WebCore {\n\n'
'const char* foo[] = {\n'
' "void* b);", // ;\n'
' "asfdf",\n'
' }\n'
' void* p;\n'
'}\n',
'Code inside a namespace should not be indented. [whitespace/indent] [4]',
'foo.cpp')
self.assert_multi_line_lint(
'namespace WebCore {\n\n'
'const char* foo[] = {\n'
' "void* b);", // }\n'
' "asfdf",\n'
' }\n'
'}\n',
'',
'foo.cpp')
self.assert_multi_line_lint(
' namespace WebCore {\n\n'
' void Document::Foo()\n'
' {\n'
'start: // infinite loops are fun!\n'
' goto start;\n'
' }',
'namespace should never be indented. [whitespace/indent] [4]',
'foo.cpp')
self.assert_multi_line_lint(
'namespace WebCore {\n'
' Document::Foo() { }\n'
'}',
'Code inside a namespace should not be indented.'
' [whitespace/indent] [4]',
'foo.cpp')
self.assert_multi_line_lint(
'namespace WebCore {\n'
'#define abc(x) x; \\\n'
' x\n'
'}',
'',
'foo.cpp')
self.assert_multi_line_lint(
'namespace WebCore {\n'
'#define abc(x) x; \\\n'
' x\n'
' void* x;'
'}',
'Code inside a namespace should not be indented. [whitespace/indent] [4]',
'foo.cpp')
# 5. A case label should line up with its switch statement. The
# case statement is indented.
self.assert_multi_line_lint(
' switch (condition) {\n'
' case fooCondition:\n'
' case barCondition:\n'
' i++;\n'
' break;\n'
' default:\n'
' i--;\n'
' }\n',
'')
self.assert_multi_line_lint(
' switch (condition) {\n'
' case fooCondition:\n'
' switch (otherCondition) {\n'
' default:\n'
' return;\n'
' }\n'
' default:\n'
' i--;\n'
' }\n',
'')
self.assert_multi_line_lint(
' switch (condition) {\n'
' case fooCondition: break;\n'
' default: return;\n'
' }\n',
'')
self.assert_multi_line_lint(
' switch (condition) {\n'
' case fooCondition:\n'
' case barCondition:\n'
' i++;\n'
' break;\n'
' default:\n'
' i--;\n'
' }\n',
'A case label should not be indented, but line up with its switch statement.'
' [whitespace/indent] [4]')
self.assert_multi_line_lint(
' switch (condition) {\n'
' case fooCondition:\n'
' break;\n'
' default:\n'
' i--;\n'
' }\n',
'A case label should not be indented, but line up with its switch statement.'
' [whitespace/indent] [4]')
self.assert_multi_line_lint(
' switch (condition) {\n'
' case fooCondition:\n'
' case barCondition:\n'
' switch (otherCondition) {\n'
' default:\n'
' return;\n'
' }\n'
' default:\n'
' i--;\n'
' }\n',
'A case label should not be indented, but line up with its switch statement.'
' [whitespace/indent] [4]')
self.assert_multi_line_lint(
' switch (condition) {\n'
' case fooCondition:\n'
' case barCondition:\n'
' i++;\n'
' break;\n\n'
' default:\n'
' i--;\n'
' }\n',
'Non-label code inside switch statements should be indented.'
' [whitespace/indent] [4]')
self.assert_multi_line_lint(
' switch (condition) {\n'
' case fooCondition:\n'
' case barCondition:\n'
' switch (otherCondition) {\n'
' default:\n'
' return;\n'
' }\n'
' default:\n'
' i--;\n'
' }\n',
'Non-label code inside switch statements should be indented.'
' [whitespace/indent] [4]')
# 6. Boolean expressions at the same nesting level that span
# multiple lines should have their operators on the left side of
# the line instead of the right side.
self.assert_multi_line_lint(
' return attr->name() == srcAttr\n'
' || attr->name() == lowsrcAttr;\n',
'')
self.assert_multi_line_lint(
' return attr->name() == srcAttr ||\n'
' attr->name() == lowsrcAttr;\n',
'Boolean expressions that span multiple lines should have their '
'operators on the left side of the line instead of the right side.'
' [whitespace/operators] [4]')
def test_spacing(self):
# 1. Do not place spaces around unary operators.
self.assert_multi_line_lint(
'i++;',
'')
self.assert_multi_line_lint(
'i ++;',
'Extra space for operator ++; [whitespace/operators] [4]')
# 2. Do place spaces around binary and ternary operators.
self.assert_multi_line_lint(
'y = m * x + b;',
'')
self.assert_multi_line_lint(
'f(a, b);',
'')
self.assert_multi_line_lint(
'c = a | b;',
'')
self.assert_multi_line_lint(
'return condition ? 1 : 0;',
'')
self.assert_multi_line_lint(
'y=m*x+b;',
'Missing spaces around = [whitespace/operators] [4]')
self.assert_multi_line_lint(
'f(a,b);',
'Missing space after , [whitespace/comma] [3]')
self.assert_multi_line_lint(
'c = a|b;',
'Missing spaces around | [whitespace/operators] [3]')
# FIXME: We cannot catch this lint error.
# self.assert_multi_line_lint(
# 'return condition ? 1:0;',
# '')
# 3. Place spaces between control statements and their parentheses.
self.assert_multi_line_lint(
' if (condition)\n'
' doIt();\n',
'')
self.assert_multi_line_lint(
' if(condition)\n'
' doIt();\n',
'Missing space before ( in if( [whitespace/parens] [5]')
# 4. Do not place spaces between a function and its parentheses,
# or between a parenthesis and its content.
self.assert_multi_line_lint(
'f(a, b);',
'')
self.assert_multi_line_lint(
'f (a, b);',
'Extra space before ( in function call [whitespace/parens] [4]')
self.assert_multi_line_lint(
'f( a, b );',
['Extra space after ( in function call [whitespace/parens] [4]',
'Extra space before ) [whitespace/parens] [2]'])
def test_line_breaking(self):
# 1. Each statement should get its own line.
self.assert_multi_line_lint(
' x++;\n'
' y++;\n'
' if (condition);\n'
' doIt();\n',
'')
self.assert_multi_line_lint(
' if (condition) \\\n'
' doIt();\n',
'')
self.assert_multi_line_lint(
' x++; y++;',
'More than one command on the same line [whitespace/newline] [4]')
self.assert_multi_line_lint(
' if (condition) doIt();\n',
'More than one command on the same line in if [whitespace/parens] [4]')
# Ensure that having a # in the line doesn't hide the error.
self.assert_multi_line_lint(
' x++; char a[] = "#";',
'More than one command on the same line [whitespace/newline] [4]')
# Ignore preprocessor if's.
self.assert_multi_line_lint(
' #if (condition) || (condition2)\n',
'')
# 2. An else statement should go on the same line as a preceding
# close brace if one is present, else it should line up with the
# if statement.
self.assert_multi_line_lint(
'if (condition) {\n'
' doSomething();\n'
' doSomethingAgain();\n'
'} else {\n'
' doSomethingElse();\n'
' doSomethingElseAgain();\n'
'}\n',
'')
self.assert_multi_line_lint(
'if (condition)\n'
' doSomething();\n'
'else\n'
' doSomethingElse();\n',
'')
self.assert_multi_line_lint(
'if (condition)\n'
' doSomething();\n'
'else {\n'
' doSomethingElse();\n'
' doSomethingElseAgain();\n'
'}\n',
'')
self.assert_multi_line_lint(
'#define TEST_ASSERT(expression) do { if (!(expression)) { TestsController::shared().testFailed(__FILE__, __LINE__, #expression); return; } } while (0)\n',
'')
self.assert_multi_line_lint(
'#define TEST_ASSERT(expression) do { if ( !(expression)) { TestsController::shared().testFailed(__FILE__, __LINE__, #expression); return; } } while (0)\n',
'Extra space after ( in if [whitespace/parens] [5]')
# FIXME: currently we only check first conditional, so we cannot detect errors in next ones.
# self.assert_multi_line_lint(
# '#define TEST_ASSERT(expression) do { if (!(expression)) { TestsController::shared().testFailed(__FILE__, __LINE__, #expression); return; } } while (0 )\n',
# 'Mismatching spaces inside () in if [whitespace/parens] [5]')
self.assert_multi_line_lint(
'if (condition) {\n'
' doSomething();\n'
' doSomethingAgain();\n'
'}\n'
'else {\n'
' doSomethingElse();\n'
' doSomethingElseAgain();\n'
'}\n',
'An else should appear on the same line as the preceding } [whitespace/newline] [4]')
self.assert_multi_line_lint(
'if (condition) doSomething(); else doSomethingElse();\n',
['More than one command on the same line [whitespace/newline] [4]',
'Else clause should never be on same line as else (use 2 lines) [whitespace/newline] [4]',
'More than one command on the same line in if [whitespace/parens] [4]'])
self.assert_multi_line_lint(
'if (condition) doSomething(); else {\n'
' doSomethingElse();\n'
'}\n',
['More than one command on the same line in if [whitespace/parens] [4]',
'One line control clauses should not use braces. [whitespace/braces] [4]'])
self.assert_multi_line_lint(
'void func()\n'
'{\n'
' while (condition) { }\n'
' return 0;\n'
'}\n',
'')
self.assert_multi_line_lint(
'void func()\n'
'{\n'
' for (i = 0; i < 42; i++) { foobar(); }\n'
' return 0;\n'
'}\n',
'More than one command on the same line in for [whitespace/parens] [4]')
# 3. An else if statement should be written as an if statement
# when the prior if concludes with a return statement.
self.assert_multi_line_lint(
'if (motivated) {\n'
' if (liquid)\n'
' return money;\n'
'} else if (tired)\n'
' break;\n',
'')
self.assert_multi_line_lint(
'if (condition)\n'
' doSomething();\n'
'else if (otherCondition)\n'
' doSomethingElse();\n',
'')
self.assert_multi_line_lint(
'if (condition)\n'
' doSomething();\n'
'else\n'
' doSomethingElse();\n',
'')
self.assert_multi_line_lint(
'if (condition)\n'
' returnValue = foo;\n'
'else if (otherCondition)\n'
' returnValue = bar;\n',
'')
self.assert_multi_line_lint(
'if (condition)\n'
' returnValue = foo;\n'
'else\n'
' returnValue = bar;\n',
'')
self.assert_multi_line_lint(
'if (condition)\n'
' doSomething();\n'
'else if (liquid)\n'
' return money;\n'
'else if (broke)\n'
' return favor;\n'
'else\n'
' sleep(28800);\n',
'')
self.assert_multi_line_lint(
'if (liquid) {\n'
' prepare();\n'
' return money;\n'
'} else if (greedy) {\n'
' keep();\n'
' return nothing;\n'
'}\n',
'An else if statement should be written as an if statement when the '
'prior "if" concludes with a return, break, continue or goto statement.'
' [readability/control_flow] [4]')
self.assert_multi_line_lint(
' if (stupid) {\n'
'infiniteLoop:\n'
' goto infiniteLoop;\n'
' } else if (evil)\n'
' goto hell;\n',
'An else if statement should be written as an if statement when the '
'prior "if" concludes with a return, break, continue or goto statement.'
' [readability/control_flow] [4]')
self.assert_multi_line_lint(
'if (liquid)\n'
'{\n'
' prepare();\n'
' return money;\n'
'}\n'
'else if (greedy)\n'
' keep();\n',
['This { should be at the end of the previous line [whitespace/braces] [4]',
'An else should appear on the same line as the preceding } [whitespace/newline] [4]',
'An else if statement should be written as an if statement when the '
'prior "if" concludes with a return, break, continue or goto statement.'
' [readability/control_flow] [4]'])
self.assert_multi_line_lint(
'if (gone)\n'
' return;\n'
'else if (here)\n'
' go();\n',
'An else if statement should be written as an if statement when the '
'prior "if" concludes with a return, break, continue or goto statement.'
' [readability/control_flow] [4]')
self.assert_multi_line_lint(
'if (gone)\n'
' return;\n'
'else\n'
' go();\n',
'An else statement can be removed when the prior "if" concludes '
'with a return, break, continue or goto statement.'
' [readability/control_flow] [4]')
self.assert_multi_line_lint(
'if (motivated) {\n'
' prepare();\n'
' continue;\n'
'} else {\n'
' cleanUp();\n'
' break;\n'
'}\n',
'An else statement can be removed when the prior "if" concludes '
'with a return, break, continue or goto statement.'
' [readability/control_flow] [4]')
self.assert_multi_line_lint(
'if (tired)\n'
' break;\n'
'else {\n'
' prepare();\n'
' continue;\n'
'}\n',
'An else statement can be removed when the prior "if" concludes '
'with a return, break, continue or goto statement.'
' [readability/control_flow] [4]')
def test_braces(self):
# 1. Function definitions: place each brace on its own line.
self.assert_multi_line_lint(
'int main()\n'
'{\n'
' doSomething();\n'
'}\n',
'')
self.assert_multi_line_lint(
'int main() {\n'
' doSomething();\n'
'}\n',
'Place brace on its own line for function definitions. [whitespace/braces] [4]')
# 2. Other braces: place the open brace on the line preceding the
# code block; place the close brace on its own line.
self.assert_multi_line_lint(
'class MyClass {\n'
' int foo;\n'
'};\n',
'')
self.assert_multi_line_lint(
'namespace WebCore {\n'
'int foo;\n'
'};\n',
'')
self.assert_multi_line_lint(
'for (int i = 0; i < 10; i++) {\n'
' DoSomething();\n'
'};\n',
'')
self.assert_multi_line_lint(
'class MyClass\n'
'{\n'
' int foo;\n'
'};\n',
'This { should be at the end of the previous line [whitespace/braces] [4]')
self.assert_multi_line_lint(
'if (condition)\n'
'{\n'
' int foo;\n'
'}\n',
'This { should be at the end of the previous line [whitespace/braces] [4]')
self.assert_multi_line_lint(
'for (int i = 0; i < 10; i++)\n'
'{\n'
' int foo;\n'
'}\n',
'This { should be at the end of the previous line [whitespace/braces] [4]')
self.assert_multi_line_lint(
'while (true)\n'
'{\n'
' int foo;\n'
'}\n',
'This { should be at the end of the previous line [whitespace/braces] [4]')
self.assert_multi_line_lint(
'foreach (Foo* foo, foos)\n'
'{\n'
' int bar;\n'
'}\n',
'This { should be at the end of the previous line [whitespace/braces] [4]')
self.assert_multi_line_lint(
'switch (type)\n'
'{\n'
'case foo: return;\n'
'}\n',
'This { should be at the end of the previous line [whitespace/braces] [4]')
self.assert_multi_line_lint(
'if (condition)\n'
'{\n'
' int foo;\n'
'}\n',
'This { should be at the end of the previous line [whitespace/braces] [4]')
self.assert_multi_line_lint(
'for (int i = 0; i < 10; i++)\n'
'{\n'
' int foo;\n'
'}\n',
'This { should be at the end of the previous line [whitespace/braces] [4]')
self.assert_multi_line_lint(
'while (true)\n'
'{\n'
' int foo;\n'
'}\n',
'This { should be at the end of the previous line [whitespace/braces] [4]')
self.assert_multi_line_lint(
'switch (type)\n'
'{\n'
'case foo: return;\n'
'}\n',
'This { should be at the end of the previous line [whitespace/braces] [4]')
self.assert_multi_line_lint(
'else if (type)\n'
'{\n'
'case foo: return;\n'
'}\n',
'This { should be at the end of the previous line [whitespace/braces] [4]')
# 3. One-line control clauses should not use braces unless
# comments are included or a single statement spans multiple
# lines.
self.assert_multi_line_lint(
'if (true) {\n'
' int foo;\n'
'}\n',
'One line control clauses should not use braces. [whitespace/braces] [4]')
self.assert_multi_line_lint(
'for (; foo; bar) {\n'
' int foo;\n'
'}\n',
'One line control clauses should not use braces. [whitespace/braces] [4]')
self.assert_multi_line_lint(
'foreach (foo, foos) {\n'
' int bar;\n'
'}\n',
'One line control clauses should not use braces. [whitespace/braces] [4]')
self.assert_multi_line_lint(
'while (true) {\n'
' int foo;\n'
'}\n',
'One line control clauses should not use braces. [whitespace/braces] [4]')
self.assert_multi_line_lint(
'if (true)\n'
' int foo;\n'
'else {\n'
' int foo;\n'
'}\n',
'One line control clauses should not use braces. [whitespace/braces] [4]')
self.assert_multi_line_lint(
'if (true) {\n'
' int foo;\n'
'} else\n'
' int foo;\n',
'One line control clauses should not use braces. [whitespace/braces] [4]')
self.assert_multi_line_lint(
'if (true) {\n'
' // Some comment\n'
' int foo;\n'
'}\n',
'')
self.assert_multi_line_lint(
'if (true) {\n'
' myFunction(reallyLongParam1, reallyLongParam2,\n'
' reallyLongParam3);\n'
'}\n',
'')
# 4. Control clauses without a body should use empty braces.
self.assert_multi_line_lint(
'for ( ; current; current = current->next) { }\n',
'')
self.assert_multi_line_lint(
'for ( ; current;\n'
' current = current->next) {}\n',
'')
self.assert_multi_line_lint(
'for ( ; current; current = current->next);\n',
'Semicolon defining empty statement for this loop. Use { } instead. [whitespace/semicolon] [5]')
self.assert_multi_line_lint(
'while (true);\n',
'Semicolon defining empty statement for this loop. Use { } instead. [whitespace/semicolon] [5]')
self.assert_multi_line_lint(
'} while (true);\n',
'')
def test_null_false_zero(self):
# 1. In C++, the null pointer value should be written as 0. In C,
# it should be written as NULL. In Objective-C and Objective-C++,
# follow the guideline for C or C++, respectively, but use nil to
# represent a null Objective-C object.
self.assert_lint(
'functionCall(NULL)',
'Use 0 instead of NULL.'
' [readability/null] [5]',
'foo.cpp')
self.assert_lint(
"// Don't use NULL in comments since it isn't in code.",
'Use 0 instead of NULL.'
' [readability/null] [4]',
'foo.cpp')
self.assert_lint(
'"A string with NULL" // and a comment with NULL is tricky to flag correctly in cpp_style.',
'Use 0 instead of NULL.'
' [readability/null] [4]',
'foo.cpp')
self.assert_lint(
'"A string containing NULL is ok"',
'',
'foo.cpp')
self.assert_lint(
'if (aboutNULL)',
'',
'foo.cpp')
self.assert_lint(
'myVariable = NULLify',
'',
'foo.cpp')
# Make sure that the NULL check does not apply to C and Objective-C files.
self.assert_lint(
'functionCall(NULL)',
'',
'foo.c')
self.assert_lint(
'functionCall(NULL)',
'',
'foo.m')
# Make sure that the NULL check does not apply to g_object_{set,get} and
# g_str{join,concat}
self.assert_lint(
'g_object_get(foo, "prop", &bar, NULL);',
'')
self.assert_lint(
'g_object_set(foo, "prop", bar, NULL);',
'')
self.assert_lint(
'g_build_filename(foo, bar, NULL);',
'')
self.assert_lint(
'gst_bin_add_many(foo, bar, boo, NULL);',
'')
self.assert_lint(
'gst_bin_remove_many(foo, bar, boo, NULL);',
'')
self.assert_lint(
'gst_element_link_many(foo, bar, boo, NULL);',
'')
self.assert_lint(
'gst_element_unlink_many(foo, bar, boo, NULL);',
'')
self.assert_lint(
'gchar* result = g_strconcat("part1", "part2", "part3", NULL);',
'')
self.assert_lint(
'gchar* result = g_strconcat("part1", NULL);',
'')
self.assert_lint(
'gchar* result = g_strjoin(",", "part1", "part2", "part3", NULL);',
'')
self.assert_lint(
'gchar* result = g_strjoin(",", "part1", NULL);',
'')
self.assert_lint(
'gchar* result = gdk_pixbuf_save_to_callback(pixbuf, function, data, type, error, NULL);',
'')
self.assert_lint(
'gchar* result = gdk_pixbuf_save_to_buffer(pixbuf, function, data, type, error, NULL);',
'')
self.assert_lint(
'gchar* result = gdk_pixbuf_save_to_stream(pixbuf, function, data, type, error, NULL);',
'')
self.assert_lint(
'gtk_widget_style_get(style, "propertyName", &value, "otherName", &otherValue, NULL);',
'')
self.assert_lint(
'gtk_widget_style_get_property(style, NULL, NULL);',
'Use 0 instead of NULL. [readability/null] [5]',
'foo.cpp')
self.assert_lint(
'gtk_widget_style_get_valist(style, NULL, NULL);',
'Use 0 instead of NULL. [readability/null] [5]',
'foo.cpp')
# 2. C++ and C bool values should be written as true and
# false. Objective-C BOOL values should be written as YES and NO.
# FIXME: Implement this.
# 3. Tests for true/false, null/non-null, and zero/non-zero should
# all be done without equality comparisons.
self.assert_lint(
'if (count == 0)',
'Tests for true/false, null/non-null, and zero/non-zero should all be done without equality comparisons.'
' [readability/comparison_to_zero] [5]')
self.assert_lint_one_of_many_errors_re(
'if (string != NULL)',
r'Tests for true/false, null/non-null, and zero/non-zero should all be done without equality comparisons\.')
self.assert_lint(
'if (condition == true)',
'Tests for true/false, null/non-null, and zero/non-zero should all be done without equality comparisons.'
' [readability/comparison_to_zero] [5]')
self.assert_lint(
'if (myVariable != /* Why would anyone put a comment here? */ false)',
'Tests for true/false, null/non-null, and zero/non-zero should all be done without equality comparisons.'
' [readability/comparison_to_zero] [5]')
self.assert_lint(
'if (0 /* This comment also looks odd to me. */ != aLongerVariableName)',
'Tests for true/false, null/non-null, and zero/non-zero should all be done without equality comparisons.'
' [readability/comparison_to_zero] [5]')
self.assert_lint_one_of_many_errors_re(
'if (NULL == thisMayBeNull)',
r'Tests for true/false, null/non-null, and zero/non-zero should all be done without equality comparisons\.')
self.assert_lint(
'if (true != anotherCondition)',
'Tests for true/false, null/non-null, and zero/non-zero should all be done without equality comparisons.'
' [readability/comparison_to_zero] [5]')
self.assert_lint(
'if (false == myBoolValue)',
'Tests for true/false, null/non-null, and zero/non-zero should all be done without equality comparisons.'
' [readability/comparison_to_zero] [5]')
self.assert_lint(
'if (fontType == trueType)',
'')
self.assert_lint(
'if (othertrue == fontType)',
'')
def test_using_std(self):
self.assert_lint(
'using std::min;',
"Use 'using namespace std;' instead of 'using std::min;'."
" [build/using_std] [4]",
'foo.cpp')
def test_max_macro(self):
self.assert_lint(
'int i = MAX(0, 1);',
'',
'foo.c')
self.assert_lint(
'int i = MAX(0, 1);',
'Use std::max() or std::max<type>() instead of the MAX() macro.'
' [runtime/max_min_macros] [4]',
'foo.cpp')
self.assert_lint(
'inline int foo() { return MAX(0, 1); }',
'Use std::max() or std::max<type>() instead of the MAX() macro.'
' [runtime/max_min_macros] [4]',
'foo.h')
def test_min_macro(self):
self.assert_lint(
'int i = MIN(0, 1);',
'',
'foo.c')
self.assert_lint(
'int i = MIN(0, 1);',
'Use std::min() or std::min<type>() instead of the MIN() macro.'
' [runtime/max_min_macros] [4]',
'foo.cpp')
self.assert_lint(
'inline int foo() { return MIN(0, 1); }',
'Use std::min() or std::min<type>() instead of the MIN() macro.'
' [runtime/max_min_macros] [4]',
'foo.h')
def test_names(self):
name_underscore_error_message = " is incorrectly named. Don't use underscores in your identifier names. [readability/naming] [4]"
name_tooshort_error_message = " is incorrectly named. Don't use the single letter 'l' as an identifier name. [readability/naming] [4]"
# Basic cases from WebKit style guide.
self.assert_lint('struct Data;', '')
self.assert_lint('size_t bufferSize;', '')
self.assert_lint('class HTMLDocument;', '')
self.assert_lint('String mimeType();', '')
self.assert_lint('size_t buffer_size;',
'buffer_size' + name_underscore_error_message)
self.assert_lint('short m_length;', '')
self.assert_lint('short _length;',
'_length' + name_underscore_error_message)
self.assert_lint('short length_;',
'length_' + name_underscore_error_message)
self.assert_lint('unsigned _length;',
'_length' + name_underscore_error_message)
self.assert_lint('unsigned int _length;',
'_length' + name_underscore_error_message)
self.assert_lint('unsigned long long _length;',
'_length' + name_underscore_error_message)
# Allow underscores in Objective C files.
self.assert_lint('unsigned long long _length;',
'',
'foo.m')
self.assert_lint('unsigned long long _length;',
'',
'foo.mm')
self.assert_lint('#import "header_file.h"\n'
'unsigned long long _length;',
'',
'foo.h')
self.assert_lint('unsigned long long _length;\n'
'@interface WebFullscreenWindow;',
'',
'foo.h')
self.assert_lint('unsigned long long _length;\n'
'@implementation WebFullscreenWindow;',
'',
'foo.h')
self.assert_lint('unsigned long long _length;\n'
'@class WebWindowFadeAnimation;',
'',
'foo.h')
# Variable name 'l' is easy to confuse with '1'
self.assert_lint('int l;', 'l' + name_tooshort_error_message)
self.assert_lint('size_t l;', 'l' + name_tooshort_error_message)
self.assert_lint('long long l;', 'l' + name_tooshort_error_message)
# Pointers, references, functions, templates, and adjectives.
self.assert_lint('char* under_score;',
'under_score' + name_underscore_error_message)
self.assert_lint('const int UNDER_SCORE;',
'UNDER_SCORE' + name_underscore_error_message)
self.assert_lint('static inline const char const& const under_score;',
'under_score' + name_underscore_error_message)
self.assert_lint('WebCore::RenderObject* under_score;',
'under_score' + name_underscore_error_message)
self.assert_lint('int func_name();',
'func_name' + name_underscore_error_message)
self.assert_lint('RefPtr<RenderObject*> under_score;',
'under_score' + name_underscore_error_message)
self.assert_lint('WTF::Vector<WTF::RefPtr<const RenderObject* const> > under_score;',
'under_score' + name_underscore_error_message)
self.assert_lint('int under_score[];',
'under_score' + name_underscore_error_message)
self.assert_lint('struct dirent* under_score;',
'under_score' + name_underscore_error_message)
self.assert_lint('long under_score;',
'under_score' + name_underscore_error_message)
self.assert_lint('long long under_score;',
'under_score' + name_underscore_error_message)
self.assert_lint('long double under_score;',
'under_score' + name_underscore_error_message)
self.assert_lint('long long int under_score;',
'under_score' + name_underscore_error_message)
# Declarations in control statement.
self.assert_lint('if (int under_score = 42) {',
'under_score' + name_underscore_error_message)
self.assert_lint('else if (int under_score = 42) {',
'under_score' + name_underscore_error_message)
self.assert_lint('for (int under_score = 42; cond; i++) {',
'under_score' + name_underscore_error_message)
self.assert_lint('while (foo & under_score = bar) {',
'under_score' + name_underscore_error_message)
self.assert_lint('for (foo * under_score = p; cond; i++) {',
'under_score' + name_underscore_error_message)
self.assert_lint('for (foo * under_score; cond; i++) {',
'under_score' + name_underscore_error_message)
self.assert_lint('while (foo & value_in_thirdparty_library) {', '')
self.assert_lint('while (foo * value_in_thirdparty_library) {', '')
self.assert_lint('if (mli && S_OK == mli->foo()) {', '')
# More member variables and functions.
self.assert_lint('int SomeClass::s_validName', '')
self.assert_lint('int m_under_score;',
'm_under_score' + name_underscore_error_message)
self.assert_lint('int SomeClass::s_under_score = 0;',
'SomeClass::s_under_score' + name_underscore_error_message)
self.assert_lint('int SomeClass::under_score = 0;',
'SomeClass::under_score' + name_underscore_error_message)
# Other statements.
self.assert_lint('return INT_MAX;', '')
self.assert_lint('return_t under_score;',
'under_score' + name_underscore_error_message)
self.assert_lint('goto under_score;',
'under_score' + name_underscore_error_message)
self.assert_lint('delete static_cast<Foo*>(p);', '')
# Multiple variables in one line.
self.assert_lint('void myFunction(int variable1, int another_variable);',
'another_variable' + name_underscore_error_message)
self.assert_lint('int variable1, another_variable;',
'another_variable' + name_underscore_error_message)
self.assert_lint('int first_variable, secondVariable;',
'first_variable' + name_underscore_error_message)
self.assert_lint('void my_function(int variable_1, int variable_2);',
['my_function' + name_underscore_error_message,
'variable_1' + name_underscore_error_message,
'variable_2' + name_underscore_error_message])
self.assert_lint('for (int variable_1, variable_2;;) {',
['variable_1' + name_underscore_error_message,
'variable_2' + name_underscore_error_message])
# There is an exception for op code functions but only in the JavaScriptCore directory.
self.assert_lint('void this_op_code(int var1, int var2)', '', 'Source/JavaScriptCore/foo.cpp')
self.assert_lint('void op_code(int var1, int var2)', '', 'Source/JavaScriptCore/foo.cpp')
self.assert_lint('void this_op_code(int var1, int var2)', 'this_op_code' + name_underscore_error_message)
# GObject requires certain magical names in class declarations.
self.assert_lint('void webkit_dom_object_init();', '')
self.assert_lint('void webkit_dom_object_class_init();', '')
# There is an exception for some unit tests that begin with "tst_".
self.assert_lint('void tst_QWebFrame::arrayObjectEnumerable(int var1, int var2)', '')
# The Qt API uses names that begin with "qt_".
self.assert_lint('void QTFrame::qt_drt_is_awesome(int var1, int var2)', '')
self.assert_lint('void qt_drt_is_awesome(int var1, int var2);', '')
# Cairo forward-declarations should not be a failure.
self.assert_lint('typedef struct _cairo cairo_t;', '')
self.assert_lint('typedef struct _cairo_surface cairo_surface_t;', '')
self.assert_lint('typedef struct _cairo_scaled_font cairo_scaled_font_t;', '')
# NPAPI functions that start with NPN_, NPP_ or NP_ are allowed.
self.assert_lint('void NPN_Status(NPP, const char*)', '')
self.assert_lint('NPError NPP_SetWindow(NPP instance, NPWindow *window)', '')
self.assert_lint('NPObject* NP_Allocate(NPP, NPClass*)', '')
# const_iterator is allowed as well.
self.assert_lint('typedef VectorType::const_iterator const_iterator;', '')
# vm_throw is allowed as well.
self.assert_lint('int vm_throw;', '')
# Bitfields.
self.assert_lint('unsigned _fillRule : 1;',
'_fillRule' + name_underscore_error_message)
# new operators in initialization.
self.assert_lint('OwnPtr<uint32_t> variable(new uint32_t);', '')
self.assert_lint('OwnPtr<uint32_t> variable(new (expr) uint32_t);', '')
self.assert_lint('OwnPtr<uint32_t> under_score(new uint32_t);',
'under_score' + name_underscore_error_message)
def test_parameter_names(self):
# Leave meaningless variable names out of function declarations.
meaningless_variable_name_error_message = 'The parameter name "%s" adds no information, so it should be removed. [readability/parameter_name] [5]'
parameter_error_rules = ('-',
'+readability/parameter_name')
# No variable name, so no error.
self.assertEquals('',
self.perform_lint('void func(int);', 'test.cpp', parameter_error_rules))
# Verify that copying the name of the set function causes the error (with some odd casing).
self.assertEquals(meaningless_variable_name_error_message % 'itemCount',
self.perform_lint('void setItemCount(size_t itemCount);', 'test.cpp', parameter_error_rules))
self.assertEquals(meaningless_variable_name_error_message % 'abcCount',
self.perform_lint('void setABCCount(size_t abcCount);', 'test.cpp', parameter_error_rules))
# Verify that copying a type name will trigger the warning (even if the type is a template parameter).
self.assertEquals(meaningless_variable_name_error_message % 'context',
self.perform_lint('void funct(PassRefPtr<ScriptExecutionContext> context);', 'test.cpp', parameter_error_rules))
# Verify that acronyms as variable names trigger the error (for both set functions and type names).
self.assertEquals(meaningless_variable_name_error_message % 'ec',
self.perform_lint('void setExceptionCode(int ec);', 'test.cpp', parameter_error_rules))
self.assertEquals(meaningless_variable_name_error_message % 'ec',
self.perform_lint('void funct(ExceptionCode ec);', 'test.cpp', parameter_error_rules))
# 'object' alone, appended, or as part of an acronym is meaningless.
self.assertEquals(meaningless_variable_name_error_message % 'object',
self.perform_lint('void funct(RenderView object);', 'test.cpp', parameter_error_rules))
self.assertEquals(meaningless_variable_name_error_message % 'viewObject',
self.perform_lint('void funct(RenderView viewObject);', 'test.cpp', parameter_error_rules))
self.assertEquals(meaningless_variable_name_error_message % 'rvo',
self.perform_lint('void funct(RenderView rvo);', 'test.cpp', parameter_error_rules))
# Check that r, g, b, and a are allowed.
self.assertEquals('',
self.perform_lint('void setRGBAValues(int r, int g, int b, int a);', 'test.cpp', parameter_error_rules))
# Verify that a simple substring match isn't done which would cause false positives.
self.assertEquals('',
self.perform_lint('void setNateLateCount(size_t elate);', 'test.cpp', parameter_error_rules))
self.assertEquals('',
self.perform_lint('void funct(NateLate elate);', 'test.cpp', parameter_error_rules))
# Don't have generate warnings for functions (only declarations).
self.assertEquals('',
self.perform_lint('void funct(PassRefPtr<ScriptExecutionContext> context)\n'
'{\n'
'}\n', 'test.cpp', parameter_error_rules))
def test_comments(self):
# A comment at the beginning of a line is ok.
self.assert_lint('// comment', '')
self.assert_lint(' // comment', '')
self.assert_lint('} // namespace WebCore',
'One space before end of line comments'
' [whitespace/comments] [5]')
def test_other(self):
# FIXME: Implement this.
pass
class CppCheckerTest(unittest.TestCase):
"""Tests CppChecker class."""
def mock_handle_style_error(self):
pass
def _checker(self):
return CppChecker("foo", "h", self.mock_handle_style_error, 3)
def test_init(self):
"""Test __init__ constructor."""
checker = self._checker()
self.assertEquals(checker.file_extension, "h")
self.assertEquals(checker.file_path, "foo")
self.assertEquals(checker.handle_style_error, self.mock_handle_style_error)
self.assertEquals(checker.min_confidence, 3)
def test_eq(self):
"""Test __eq__ equality function."""
checker1 = self._checker()
checker2 = self._checker()
# == calls __eq__.
self.assertTrue(checker1 == checker2)
def mock_handle_style_error2(self):
pass
# Verify that a difference in any argument cause equality to fail.
checker = CppChecker("foo", "h", self.mock_handle_style_error, 3)
self.assertFalse(checker == CppChecker("bar", "h", self.mock_handle_style_error, 3))
self.assertFalse(checker == CppChecker("foo", "c", self.mock_handle_style_error, 3))
self.assertFalse(checker == CppChecker("foo", "h", mock_handle_style_error2, 3))
self.assertFalse(checker == CppChecker("foo", "h", self.mock_handle_style_error, 4))
def test_ne(self):
"""Test __ne__ inequality function."""
checker1 = self._checker()
checker2 = self._checker()
# != calls __ne__.
# By default, __ne__ always returns true on different objects.
# Thus, just check the distinguishing case to verify that the
# code defines __ne__.
self.assertFalse(checker1 != checker2)
def tearDown():
"""A global check to make sure all error-categories have been tested.
The main tearDown() routine is the only code we can guarantee will be
run after all other tests have been executed.
"""
try:
if _run_verifyallcategoriesseen:
ErrorCollector(None).verify_all_categories_are_seen()
except NameError:
# If nobody set the global _run_verifyallcategoriesseen, then
# we assume we shouldn't run the test
pass
if __name__ == '__main__':
import sys
# We don't want to run the verify_all_categories_are_seen() test unless
# we're running the full test suite: if we only run one test,
# obviously we're not going to see all the error categories. So we
# only run verify_all_categories_are_seen() when no commandline flags
# are passed in.
global _run_verifyallcategoriesseen
_run_verifyallcategoriesseen = (len(sys.argv) == 1)
unittest.main()
|