This repository has been archived by the owner on Jan 13, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 70
/
Checks.d
3456 lines (3122 loc) · 103 KB
/
Checks.d
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
// Copyright (c) 2014- Facebook
// License: Boost License 1.0, http://boost.org/LICENSE_1_0.txt
// @author Andrei Alexandrescu (andrei.alexandrescu@facebook.com)
import std.algorithm, std.array, std.ascii, std.conv, std.exception, std.path,
std.range, std.stdio, std.string;
import Tokenizer, FileCategories;
bool c_mode;
enum explicitThrowSpec = "/* may throw */";
/*
* Errors vs. Warnings vs. Advice:
*
* Lint errors will be raised regardless of whether the line was
* edited in the change. Warnings will be ignored by Arcanist
* unless the change actually modifies the line the warning occurs
* on. Advice is even weaker than a warning.
*
* Please select errors vs. warnings intelligently. Too much spam
* on lines you don't touch reduces the value of lint output.
*
*/
void lintError(CppLexer.Token tok, const string error) {
stderr.writef("%.*s:%u: %s",
cast(uint) tok.file_.length, tok.file_,
cast(uint) tok.line_,
error);
}
immutable string warningPrefix = "Warning: ";
void lintWarning(CppLexer.Token tok, const string warning) {
// The FbcodeCppLinter just looks for the text "Warning" in the
// message.
lintError(tok, warningPrefix ~ warning);
}
void lintAdvice(CppLexer.Token tok, string advice) {
// The FbcodeCppLinter just looks for the text "Advice" in the
// message.
lintError(tok, "Advice: " ~ advice);
}
bool atSequence(Range)(Range r, const CppLexer.TokenType2[] list...) {
foreach (t; list) {
if (r.empty || t != r.front.type_) {
return false;
}
r.popFront;
}
return true;
}
string getSucceedingWhitespace(Token[] v) {
if (v.length < 2) return "";
return v[1].precedingWhitespace_;
}
bool isInMacro(Token[] v, const long idx) {
// Walk backwards through the tokens, continuing until a newline
// that is not preceded by a backslash is encountered (i.e. a
// true line break).
for (long i = idx; i >= 0; --i) {
if (v[i..$].atSequence(tk!"#", tk!"identifier") &&
v[i + 1].value == "define") return true;
if (i == 0) return false;
string pws = v[i].precedingWhitespace_;
auto pos = lastIndexOf(pws, '\n');
if (pos == -1) continue;
if (pos != 0) return false;
if (v[i - 1].type_ != tk!"\\") return false;
}
return false;
}
struct IncludedPath {
string path;
bool angleBrackets;
bool nolint;
bool precompiled;
}
bool getIncludedPath(R)(ref R r, out IncludedPath ipath) {
if (!r.atSequence(tk!"#", tk!"identifier") || r[1].value != "include") {
return false;
}
r.popFrontN(2);
bool found = false;
if (r.front.value_ == "PRECOMPILED") {
ipath.precompiled = true;
found = true;
}
if (r.front.type_ == tk!"string_literal") {
string val = r.front.value;
ipath.path = val[1 .. val.length - 1];
found = true;
} else if (r.front.type_ == tk!"<") {
r.popFront;
ipath.path = "";
for (; !r.empty; r.popFront) {
if (r.front.type_ == tk!">") {
break;
}
ipath.path ~= r.front.value;
}
ipath.angleBrackets = true;
found = true;
}
if (!found) {
return false;
}
ipath.nolint = getSucceedingWhitespace(r).canFind("nolint");
return true;
}
/*
* Skips a template parameter list or argument list, somewhat
* heuristically. Basically, scans forward tracking nesting of <>
* brackets and parenthesis to find the end of the list. This function
* takes as input an iterator as well as an optional parameter containsArray
* that is set to true if the outermost nest contains an array
*
* Known unsupported case: TK_RSHIFT can end a template instantiation
* in C++0x as if it were two TK_GREATERs.
* (E.g. vector<vector<int>>.)
*
* Returns: iterator pointing to the final TK_GREATER (or TK_EOF if it
* didn't finish).
*/
R skipTemplateSpec(R)(R r, bool* containsArray = null) {
assert(r.front.type_ == tk!"<");
uint angleNest = 1;
uint parenNest = 0;
if (containsArray) {
*containsArray = false;
}
r.popFront;
for (; r.front.type_ != tk!"\0"; r.popFront) {
if (r.front.type_ == tk!"(") {
++parenNest;
continue;
}
if (r.front.type_ == tk!")") {
--parenNest;
continue;
}
// Ignore angles inside of parens. This avoids confusion due to
// integral template parameters that use < and > as comparison
// operators.
if (parenNest > 0) {
continue;
}
if (r.front.type_ == tk!"[") {
if (angleNest == 1 && containsArray) {
*containsArray = true;
}
continue;
}
if (r.front.type_ == tk!"<") {
++angleNest;
continue;
}
if (r.front.type_ == tk!">") {
if (!--angleNest) {
break;
}
continue;
}
if (r.front.type_ == tk!">>") {
// it is possible to munch a template from within a template, so we
// only want to consume one of the '>>'
angleNest -= 2;
if (angleNest <= 0) break;
continue;
}
}
return r;
}
/*
* Returns whether `it' points to a token that is a reserved word for
* a built in type.
*/
bool atBuiltinType(R)(R it) {
return it.front.type_.among(tk!"double", tk!"float", tk!"int", tk!"short",
tk!"unsigned", tk!"long", tk!"signed", tk!"void", tk!"bool", tk!"wchar_t",
tk!"char") != 0;
}
/*
* heuristically read a potentially namespace-qualified identifier,
* advancing `it' in the process.
*
* Returns: a vector of all the identifier values involved, or an
* empty vector if no identifier was detected.
*/
string[] readQualifiedIdentifier(R)(ref R it) {
string[] result;
for (; it.front.type_.among(tk!"identifier", tk!"::"); it.popFront) {
if (it.front.type_ == tk!"identifier") {
result ~= it.front.value_;
}
}
return result;
}
/*
* starting from a left curly brace, skips until it finds the matching
* (balanced) right curly brace. Does not care about whether other characters
* within are balanced.
*
* Returns: iterator pointing to the final TK_RCURL (or TK_EOF if it
* didn't finish).
*/
R skipBlock(R)(R r) {
enforce(r.front.type_ == tk!"{");
uint openBraces = 1;
r.popFront;
for (; r.front.type_ != tk!"\0"; r.popFront) {
if (r.front.type_ == tk!"{") {
++openBraces;
continue;
}
if (r.front.type_ == tk!"}") {
if (!--openBraces) {
break;
}
continue;
}
}
return r;
}
/*
* Iterates through to find all class declarations and calls the callback
* with an iterator pointing to the first token in the class declaration.
* The iterator is guaranteed to have type TK_CLASS, TK_STRUCT, or TK_UNION.
*
* Note: The callback function is responsible for the scope of its search, as
* the vector of tokens passed may (likely will) extend past the end of the
* class block.
*
* Returns the sum of the results from calling the callback on
* each declaration.
*/
uint iterateClasses(alias callback)(Token[] v) {
uint result = 0;
for (auto it = v; !it.empty; it.popFront) {
if (it.atSequence(tk!"template", tk!"<")) {
it.popFront;
it = skipTemplateSpec(it);
continue;
}
if (it.front.type_.among(tk!"class", tk!"struct", tk!"union")) {
result += callback(it, v);
}
}
return result;
}
/*
* Starting from a function name or one of its arguments, skips the entire
* function prototype or function declaration (including function body).
*
* Implementation is simple: stop at the first semicolon, unless an opening
* curly brace is found, in which case we stop at the matching closing brace.
*
* Returns: iterator pointing to the final TK_RCURL or TK_SEMICOLON, or TK_EOF
* if it didn't finish.
*/
R skipFunctionDeclaration(R)(R r) {
r.popFront;
for (; r.front.type_ != tk!"\0"; r.popFront) {
if (r.front.type_ == tk!";") { // prototype
break;
} else if (r.front.type_ == tk!"{") { // full declaration
r = skipBlock(r);
break;
}
}
return r;
}
/**
* Represent an argument or the name of a function.
* first is an iterator that points to the start of the argument.
* last is an iterator that points to the token right after the end of the
* argument.
*/
struct Argument {
Token[] tox;
ref Token first() { return tox.front; }
ref Token last() { return tox.back; }
}
struct FunctionSpec {
Argument functionName;
Argument[] args;
bool isNoexcept;
bool explicitThrows;
bool isConst;
bool isDeleted;
bool isDefault;
};
string formatArg(Argument arg) {
string result;
foreach (i, a; arg.tox) {
if (i != 0 && !a.precedingWhitespace_.empty) {
result ~= ' ';
}
result ~= a.value;
}
return result;
}
string formatFunction(FunctionSpec spec) {
auto result = formatArg(spec.functionName) ~ "(";
foreach (i; 0 .. spec.args.length) {
if (i > 0) {
result ~= ", ";
}
result ~= formatArg(spec.args[i]);
}
result ~= ")";
return result;
}
/**
* Get the list of arguments of a function, assuming that the current
* iterator is at the open parenthesis of the function call. After the
* this method is called, the iterator will be moved to after the end
* of the function call.
* @param i: the current iterator, must be at the open parenthesis of the
* function call.
* @param args: the arguments of the function would be push to the back of args
* @return true if (we believe) that there was no problem during the run and
* false if we believe that something was wrong (most probably with skipping
* template specs.)
*/
bool getRealArguments(ref Token[] r, ref Argument[] args) {
assert(r.front.type_ == tk!"(", text(r));
// the first argument starts after the open parenthesis
auto argStart = r[1 .. $];
int parenCount = 1;
do {
if (r.front.type_ == tk!"\0") {
// if we meet EOF before the closing parenthesis, something must be wrong
// with the template spec skipping
return false;
}
r.popFront;
switch (r.front.type_.id) {
case tk!"(".id: parenCount++;
break;
case tk!")".id: parenCount--;
break;
case tk!"<".id: // This is a heuristic which would fail when < is used with
// the traditional meaning in an argument, e.g.
// memset(&foo, a < b ? c : d, sizeof(foo));
// but currently we have no way to distinguish that use of
// '<' and
// memset(&foo, something<A,B>(a), sizeof(foo));
// We include this heuristic in the hope that the second
// use of '<' is more common than the first.
r = skipTemplateSpec(r);
break;
case tk!",".id: if (parenCount == 1) {
// end an argument of the function we are looking at
args ~=
Argument(argStart[0 .. argStart.length - r.length]);
argStart = r[1 .. $];
}// otherwise we are in an inner function, so do nothing
break;
default: break;
}
} while (parenCount != 0);
if (argStart !is r) {
args ~= Argument(argStart[0 .. argStart.length - r.length]);
}
return true;
}
/**
* Get the argument list of a function, with the first argument being the
* function name plus the template spec.
* @param i: the current iterator, must be at the function name. At the end of
* the method, i will be pointing at the close parenthesis of the function call
* @param functionName: the function name will be stored here
* @param args: the arguments of the function would be push to the back of args
* @return true if (we believe) that there was no problem during the run and
* false if we believe that something was wrong (most probably with skipping
* template specs.)
*/
bool getFunctionSpec(ref Token[] r, ref FunctionSpec spec) {
auto r1 = r;
r.popFront;
if (r.front.type_ == tk!"<") {
r = skipTemplateSpec(r);
if (r.front.type_ == tk!"\0") {
return false;
}
r.popFront;
}
assert(r1.length >= r.length);
spec.functionName.tox = r1[0 .. r1.length - r.length];
if (!getRealArguments(r, spec.args)) {
return false;
}
auto r2 = r;
assert(r2.front.type_ == tk!")");
r2.popFront;
while (true) {
if (r2.front.precedingWhitespace_.canFind(explicitThrowSpec)) {
spec.explicitThrows = true;
}
if (r2.front.type_ == tk!"noexcept") {
spec.isNoexcept = true;
r2.popFront;
continue;
}
if (r2.front.type_ == tk!"const") {
spec.isConst = true;
r2.popFront;
continue;
}
if (r2.front.type_ == tk!"=") {
r2.popFront;
if (r2.front.type_ == tk!"delete") {
spec.isDeleted = true;
r2.popFront;
continue;
}
if (r2.front.type_ == tk!"default") {
spec.isDefault = true;
r2.popFront;
continue;
}
}
break;
}
return true;
}
uint checkInitializeFromItself(string fpath, Token[] tokens) {
auto firstInitializer = [
tk!":", tk!"identifier", tk!"(", tk!"identifier", tk!")"
];
auto nthInitialier = [
tk!",", tk!"identifier", tk!"(", tk!"identifier", tk!")"
];
uint result = 0;
for (auto it = tokens; !it.empty; it.popFront) {
if (it.atSequence(firstInitializer) || it.atSequence(nthInitialier)) {
it.popFront;
auto outerIdentifier = it.front;
it.popFrontN(2);
auto innerIdentifier = it.front;
bool isMember = outerIdentifier.value_.back == '_'
|| outerIdentifier.value_.startsWith("m_");
if (isMember && outerIdentifier.value_ == innerIdentifier.value_) {
lintError(outerIdentifier, text(
"Looks like you're initializing class member [",
outerIdentifier.value_, "] with itself.\n")
);
++result;
}
}
}
return result;
}
/**
* Lint check: check for blacklisted sequences of tokens.
*/
uint checkBlacklistedSequences(string fpath, CppLexer.Token[] v) {
struct BlacklistEntry {
CppLexer.TokenType2[] tokens;
string descr;
bool cpponly;
}
const static BlacklistEntry[] blacklist = [
BlacklistEntry([tk!"volatile"],
"'volatile' does not make your code thread-safe. If multiple threads are " ~
"sharing data, use std::atomic or locks. In addition, 'volatile' may " ~
"force the compiler to generate worse code than it could otherwise. " ~
"For more about why 'volatile' doesn't do what you think it does, see " ~
"http://www.kernel.org/doc/Documentation/" ~
"volatile-considered-harmful.txt.\n",
true), // C++ only.
];
const static CppLexer.TokenType2[][] exceptions = [
[CppLexer.tk!"asm", CppLexer.tk!"volatile"],
];
uint result = 0;
bool isException = false;
foreach (i; 0 .. v.length) {
foreach (e; exceptions) {
if (atSequence(v[i .. $], e)) { isException = true; break; }
}
foreach (ref entry; blacklist) {
if (!atSequence(v[i .. $], entry.tokens)) { continue; }
if (isException) { isException = false; continue; }
if (c_mode && entry.cpponly == true) { continue; }
if (v[i].precedingWhitespace_.canFind("nolint")) { continue; }
lintWarning(v[i], entry.descr);
++result;
}
}
return result;
}
uint checkBlacklistedIdentifiers(string fpath, CppLexer.Token[] v) {
uint result = 0;
string[string] banned = [
"strtok" :
"strtok() is not thread safe, and has safer alternatives. Consider " ~
"folly::split or strtok_r as appropriate.\n",
"strncpy" :
"strncpy is very often used in error; see " ~
"http://meyering.net/crusade-to-eliminate-strncpy/\n"
];
foreach (ref t; v) {
if (t.type_ != tk!"identifier") continue;
auto mapIt = t.value_ in banned;
if (!mapIt) continue;
lintError(t, *mapIt);
++result;
}
return result;
}
/**
* Lint check: no #defined names use an identifier reserved to the
* implementation.
*
* These are enforcing rules that actually apply to all identifiers,
* but we're only raising warnings for #define'd ones right now.
*/
uint checkDefinedNames(string fpath, Token[] v) {
// Define a set of exception to rules
static bool[string] okNames;
if (okNames.length == 0) {
static string[] okNamesInit = [
"__STDC_LIMIT_MACROS",
"__STDC_FORMAT_MACROS",
"_GNU_SOURCE",
"_XOPEN_SOURCE",
];
foreach (i; 0 .. okNamesInit.length) {
okNames[okNamesInit[i]] = true;
}
}
uint result = 0;
foreach (i, ref t; v) {
if (i == 0 || v[i - 1].type_ != tk!"#" || t.type_ != tk!"identifier"
|| t.value != "define") continue;
if (v[i - 1].precedingWhitespace_.canFind("nolint")) continue;
const t1 = v[i + 1];
auto const sym = t1.value_;
if (t1.type_ != tk!"identifier") {
// This actually happens because people #define private public
// for unittest reasons
lintWarning(t1, text("you're not supposed to #define ", sym, "\n"));
continue;
}
if (sym.length >= 2 && sym[0] == '_' && isUpper(sym[1])) {
if (sym in okNames) {
continue;
}
lintWarning(t, text("Symbol ", sym, " invalid." ~
" A symbol may not start with an underscore followed by a " ~
"capital letter.\n"));
++result;
} else if (sym.length >= 2 && sym[0] == '_' && sym[1] == '_') {
if (sym in okNames) {
continue;
}
lintWarning(t, text("Symbol ", sym, " invalid." ~
" A symbol may not begin with two adjacent underscores.\n"));
++result;
} else if (!c_mode /* C is less restrictive about this */ &&
sym.canFind("__")) {
if (sym in okNames) {
continue;
}
lintWarning(t, text("Symbol ", sym, " invalid." ~
" A symbol may not contain two adjacent underscores.\n"));
++result;
}
}
return result;
}
/**
* Lint check: only the following forms of catch are allowed:
*
* catch (Type &)
* catch (const Type &)
* catch (Type const &)
* catch (Type & e)
* catch (const Type & e)
* catch (Type const & e)
*
* Type cannot be built-in; this function enforces that it's
* user-defined.
*/
uint checkCatchByReference(string fpath, Token[] v) {
uint result = 0;
foreach (i, ref e; v) {
if (e.type_ != tk!"catch") continue;
if (getSucceedingWhitespace(v[i..$]).canFind("nolint")) continue;
size_t focal = 1;
enforce(v[i + focal].type_ == tk!"(", // a "(" comes always after catch
text(v[i + focal].file_, ":", v[i + focal].line_,
": Invalid C++ source code, please compile before lint."));
++focal;
if (v[i + focal].type_ == tk!"...") {
// catch (...
continue;
}
if (v[i + focal].type_ == tk!"const") {
// catch (const
++focal;
}
if (v[i + focal].type_ == tk!"typename") {
// catch ([const] typename
++focal;
}
if (v[i + focal].type_ == tk!"::") {
// catch ([const] [typename] ::
++focal;
}
// At this position we must have an identifier - the type caught,
// e.g. FBException, or the first identifier in an elaborate type
// specifier, such as facebook::FancyException<int, string>.
if (v[i + focal].type_ != tk!"identifier") {
const t = v[i + focal];
lintWarning(t, "Symbol " ~ t.value_ ~ " invalid in " ~
"catch clause. You may only catch user-defined types.\n");
++result;
continue;
}
++focal;
// We move the focus to the closing paren to detect the "&". We're
// balancing parens because there are weird corner cases like
// catch (Ex<(1 + 1)> & e).
for (size_t parens = 0; ; ++focal) {
enforce(focal < v.length,
text(v[i + focal].file_, ":", v[i + focal].line_,
": Invalid C++ source code, please compile before lint."));
if (v[i + focal].type_ == tk!")") {
if (parens == 0) break;
--parens;
} else if (v[i + focal].type_ == tk!"(") {
++parens;
}
}
// At this point we're straight on the closing ")". Backing off
// from there we should find either "& identifier" or "&" meaning
// anonymous identifier.
if (v[i + focal - 1].type_ == tk!"&") {
// check! catch (whatever &)
continue;
}
if (v[i + focal - 1].type_ == tk!"identifier" &&
v[i + focal - 2].type_ == tk!"&") {
// check! catch (whatever & ident)
continue;
}
// Oopsies times
const t = v[i + focal - 1];
// Get the type string
string theType;
foreach (j; 2 .. focal - 1) {
if (j > 2) theType ~= " ";
theType ~= v[i + j].value;
}
lintError(t, text("Symbol ", t.value_, " of type ", theType,
" caught by value. Use catch by (preferably const) reference " ~
"throughout.\n"));
++result;
}
return result;
}
/**
* Lint check: any usage of throw specifications is a lint error.
*
* We track whether we are at either namespace or class scope by
* looking for class/namespace tokens and tracking nesting level. Any
* time we go into a { } block that's not a class or namespace, we
* disable the lint checks (this is to avoid false positives for throw
* expressions).
*/
uint checkThrowSpecification(string, Token[] v) {
uint result = 0;
// Check for throw specifications inside classes
result += v.iterateClasses!(
function uint(Token[] it, Token[] v) {
uint result = 0;
it = it.find!(a => a.type_ == tk!"{");
if (it.empty) {
return result;
}
it.popFront;
const destructorSequence =
[tk!"~", tk!"identifier", tk!"(", tk!")",
tk!"throw", tk!"(", tk!")"];
for (; !it.empty && it.front.type_ != tk!"\0"; it.popFront) {
// Skip warnings for empty throw specifications on destructors,
// because sometimes it is necessary to put a throw() clause on
// classes deriving from std::exception.
if (it.atSequence(destructorSequence)) {
it.popFrontN(destructorSequence.length - 1);
continue;
}
// This avoids warning if the function is named "what", to allow
// inheriting from std::exception without upsetting lint.
if (it.front.type_ == tk!"identifier" && it.front.value_ == "what") {
it.popFront;
auto sequence = [tk!"(", tk!")", tk!"const",
tk!"throw", tk!"(", tk!")"];
if (it.atSequence(sequence)) {
it.popFrontN(sequence.length - 1);
}
continue;
}
if (it.front.type_ == tk!"{") {
it = skipBlock(it);
continue;
}
if (it.front.type_ == tk!"}") {
break;
}
if (it.front.type_ == tk!"throw" && it[1].type_ == tk!"(") {
lintWarning(it.front, "Throw specifications on functions are " ~
"deprecated.\n");
++result;
}
}
return result;
}
);
// Check for throw specifications in functional style code
for (auto it = v; !it.empty; it.popFront) {
// Don't accidentally identify a using statement as a namespace
if (it.front.type_ == tk!"using") {
if (it[1].type_ == tk!"namespace") {
it.popFront;
}
continue;
}
// Skip namespaces, classes, and blocks
if (it.front.type_.among(tk!"namespace", tk!"class", tk!"struct",
tk!"union", tk!"{")) {
auto term = it.find!(x => x.type_ == tk!"{");
if (term.empty) {
break;
}
it = skipBlock(term);
continue;
}
if (it.front.type_ == tk!"throw" && it[1].type_ == tk!"(") {
lintWarning(it.front, "Throw specifications on functions are " ~
"deprecated.\n");
++result;
}
}
return result;
}
/**
* Lint check: balance of #if(#ifdef, #ifndef)/#endif.
*/
uint checkIfEndifBalance(string fpath, Token[] v) {
int openIf = 0;
// Return after the first found error, because otherwise
// even one missed #if can be cause of a lot of errors.
foreach (i, ref e; v) {
if (v[i .. $].atSequence(tk!"#", tk!"if")
|| (v[i .. $].atSequence(tk!"#", tk!"identifier")
&& (v[i + 1].value_ == "ifndef" || v[i + 1].value_ == "ifdef"))) {
++openIf;
} else if (v[i .. $].atSequence(tk!"#", tk!"identifier")
&& v[i + 1].value_ == "endif") {
--openIf;
if (openIf < 0) {
lintError(e, "Unmatched #endif.\n");
return 1;
}
} else if (v[i .. $].atSequence(tk!"#", tk!"else")) {
if (openIf == 0) {
lintError(e, "Unmatched #else.\n");
return 1;
}
}
}
if (openIf != 0) {
lintError(v.back, "Unbalanced #if/#endif.\n");
return 1;
}
return 0;
}
/*
* Lint check: warn about common errors with constructors, such as:
* - single-argument constructors that aren't marked as explicit, to avoid them
* being used for implicit type conversion (C++ only)
* - Non-const copy constructors, or useless const move constructors.
* - Move constructors that aren't marked noexcept
*/
uint checkConstructors(string fpath, Token[] tokensV) {
if (getFileCategory(fpath) == FileCategory.source_c) {
return 0;
}
uint result = 0;
string[] nestedClasses;
const string explicitOverride = "/"~"* implicit *"~"/";
const CppLexer.TokenType2[] stdInitializerSequence =
[tk!"identifier", tk!"::", tk!"identifier", tk!"<"];
const CppLexer.TokenType2[] voidConstructorSequence =
[tk!"identifier", tk!"(", tk!"void", tk!")"];
for (auto tox = tokensV; tox.length; tox.popFront) {
// Avoid mis-identifying a class context due to use of the "class"
// keyword inside a template parameter list.
if (tox.atSequence(tk!"template", tk!"<")) {
tox = skipTemplateSpec(tox[1 .. $]);
continue;
}
// Parse within namespace blocks, but don't do top-level constructor checks.
// To do this, we treat namespaces like unnamed classes so any later
// function name checks will not match against an empty string.
if (tox.front.type_ == tk!"namespace") {
tox.popFront;
for (; tox.front.type_ != tk!"\0"; tox.popFront) {
if (tox.front.type_ == tk!";") {
break;
} else if (tox.front.type_ == tk!"{") {
nestedClasses ~= "";
break;
}
}
continue;
}
// Extract the class name if a class/struct definition is found
if (tox.front.type_ == tk!"class" || tox.front.type_ == tk!"struct") {
tox.popFront;
// If we hit any C-style structs, we'll handle them like we do namespaces:
// continue to parse within the block but don't show any lint errors.
if (tox.front.type_ == tk!"{") {
nestedClasses ~= "";
} else if (tox.front.type_ == tk!"identifier") {
auto classCandidate = tox.front.value_;
for (; tox.front.type_ != tk!"\0"; tox.popFront) {
if (tox.front.type_ == tk!";") {
break;
} else if (tox.front.type_ == tk!"{") {
nestedClasses ~= classCandidate;
break;
}
}
}
continue;
}
// Closing curly braces end the current scope, and should always be balanced
if (tox.front.type_ == tk!"}") {
if (nestedClasses.empty) { // parse fail
return result;
}
nestedClasses.popBack;
continue;
}
// Skip unrecognized blocks. We only want to parse top-level class blocks.
if (tox.front.type_ == tk!"{") {
tox = skipBlock(tox);
continue;
}
// Only check for constructors if we've previously entered a class block
if (nestedClasses.empty) {
continue;
}
// Handle an "explicit" keyword, with or without "constexpr"
bool checkImplicit = true;
if (tox.atSequence(tk!"explicit", tk!"constexpr") ||
tox.atSequence(tk!"constexpr", tk!"explicit")) {
checkImplicit = false;
tox.popFront;
tox.popFront;
}
if (tox.front.type_ == tk!"explicit") {
checkImplicit = false;
tox.popFront;
}
// Skip anything that doesn't look like a constructor
if (!tox.atSequence(tk!"identifier", tk!"(")) {
continue;
} else if (tox.front.value_ != nestedClasses.back) {
tox = skipFunctionDeclaration(tox);
continue;
}
// Suppress error and skip past functions clearly marked as implicit
if (tox.front.precedingWhitespace_.canFind(explicitOverride)) {
checkImplicit = false;
}
// Allow zero-argument void constructors
if (tox.atSequence(voidConstructorSequence)) {
tox = skipFunctionDeclaration(tox);
continue;
}
FunctionSpec spec;
spec.functionName = Argument(tox[0 .. 1]);
if (tox.front.precedingWhitespace_.canFind(explicitThrowSpec)) {
spec.explicitThrows = true;
}
if (!tox.getFunctionSpec(spec)) {
// Parse fail can be due to limitations in skipTemplateSpec, such as with:
// fn(std::vector<boost::shared_ptr<ProjectionOperator>> children);)
return result;
}
// Allow zero-argument constructors
if (spec.args.empty) {
tox = skipFunctionDeclaration(tox);
continue;
}
auto argIt = spec.args[0].tox;
bool foundConversionCtor = false;
bool isConstArgument = false;
if (argIt.front.type_ == tk!"const") {
isConstArgument = true;
argIt.popFront;
}