This repository has been archived by the owner on Aug 29, 2023. It is now read-only.
forked from facebookarchive/flint
-
Notifications
You must be signed in to change notification settings - Fork 21
/
Checks.cpp
2282 lines (1950 loc) · 65.1 KB
/
Checks.cpp
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
#include "Checks.hpp"
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
#include <array>
#include <numeric>
#include <cassert>
#include <stdexcept>
#include <stack>
#include "Options.hpp"
#include "Polyfill.hpp"
#include "ErrorReport.hpp"
#include "FileCategories.hpp"
namespace flint {
// Shorthand for comparing two strings (or fragments)
template <class S, class T>
inline bool cmpStr(const S &a, const T &b) { return equal(a.begin(), a.end(), b.begin()); }
inline bool cmpStr(const StringFragment &a, const StringFragment& b) { return (a == b); }
inline bool cmpStr(const StringFragment &a, const char* b) { return (a.size() == strlen(b)) && startsWith(a.begin(), b); }
inline bool cmpStr(const string &a, const string &b) { return a == b; }
inline bool cmpToks(const Token &a, const Token &b) { return cmpStr(a.value_, b.value_); };
#define cmpTok(a,b) cmpStr((a).value_, (b))
// Shorthand for comparing a Token and TokenType
inline bool isTok(const Token &token, TokenType type) { return token.type_ == type; }
using TokenIter = vector<Token>::const_iterator;
namespace { // Anonymous Namespace for Token stream traversal functions
const string emptyString;
/*
* 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(ErrorFile &errors, const Token &tok, const string &title, const string &desc = emptyString) {
errors.addError(ErrorObject(Lint::ERROR, tok.line_, title, desc));
};
void lintWarning(ErrorFile &errors, const Token &tok, const string &title, const string &desc = emptyString) {
errors.addError(ErrorObject(Lint::WARNING, tok.line_, title, desc));
};
void lintAdvice(ErrorFile &errors, const Token &tok, const string &title, const string &desc = emptyString) {
errors.addError(ErrorObject(Lint::ADVICE, tok.line_, title, desc));
};
void lint(ErrorFile &errors, const Token &tok, const Lint level, const string &title, const string &desc = emptyString) {
errors.addError(ErrorObject(level, tok.line_, title, desc));
};
/**
* Returns whether the current token is at the start of a given sequence
*
* @param tokens
* The token list for the file
* @param pos
* The current index position inside the token list
* @param list
* The token list for the desired sequence
* @return
* Returns true if we were at the start of a given sequence
*/
template <class Container>
bool atSequence(const vector<Token> &tokens, size_t pos, const Container &list) {
return equal(begin(list), end(list), begin(tokens) + pos, [](TokenType type, const Token &token)
{
return type == token.type_;
});
};
/**
* Moves pos to the next position of the target token
*
* @param tokens
* The token list for the file
* @param pos
* The current index position inside the token list
* @param target
* The token to match
* @return
* Returns true if we are at the given token
*/
bool skipToToken(const vector<Token> &tokens, size_t &pos, TokenType target) {
const size_t size = tokens.size();
for (; pos < size && !isTok(tokens[pos], target); ++pos) {}
return (pos < size && isTok(tokens[pos], target));
};
/**
* Strips the ""'s or <>'s from an #include path
*
* @param path
* The string to trim
* @return
* Returns the include path without it's wrapping quotes/brackets
*/
string getIncludedPath(const string &path) {
return path.substr(1, path.size() - 2);
};
/**
* Strips the ""'s or <>'s from an #include path
*
* @param path
* The string fragment to trim
* @return
* Returns the include path without it's wrapping quotes/brackets
*/
string getIncludedPath(const StringFragment &path) {
return string(path.begin() + 1, path.end() - 1);
};
/**
* Traverses the token list until the whole template sequence has been passed
*
* @param tokens
* The token list for the file
* @param pos
* The current index position inside the token list
* @param containsArray
* Optional parameter to return a bool of whether an array was found inside
* the template list
* @return
* Returns the position of the closing angle bracket
*/
size_t skipTemplateSpec(const vector<Token> &tokens, size_t pos, bool *containsArray = nullptr) {
assert(isTok(tokens[pos], TK_LESS));
uint angleNest = 1; // Because we began on the leading '<'
int parenNest = 0;
if (containsArray != nullptr) {
*containsArray = false;
}
++pos;
for (const size_t size = tokens.size(); pos < size && !isTok(tokens[pos], TK_EOF); ++pos) {
TokenType tok = tokens[pos].type_;
if (tok == TK_LPAREN) {
++parenNest;
continue;
}
if (tok == TK_RPAREN) {
--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 (tok == TK_LSQUARE) {
if (angleNest == 1 && containsArray != nullptr) {
*containsArray = true;
}
continue;
}
if (tok == TK_LESS) {
++angleNest;
continue;
}
if (tok == TK_GREATER) {
// Removed decrement/zero-check as one line
// It's not a race guys, readability > length of code
--angleNest;
if (angleNest == 0) {
return pos;
}
continue;
}
}
return pos;
};
/**
* Returns whether the current token is a built in type
*
* @param tokens
* The token list for the file
* @param pos
* The current index position inside the token list
* @return
* Returns true is the token as pos is a built in type
*/
inline bool atBuiltinType(const vector<Token> &tokens, size_t pos) {
static const array<TokenType, 11> builtIns = {{
TK_DOUBLE,
TK_FLOAT,
TK_INT,
TK_SHORT,
TK_UNSIGNED,
TK_LONG,
TK_SIGNED,
TK_VOID,
TK_BOOL,
TK_WCHAR_T,
TK_CHAR
}};
return find(begin(builtIns), end(builtIns), tokens[pos].type_) != end(builtIns);
};
/**
* Heuristically read a potentially namespace-qualified identifier,
* advancing 'pos' in the process.
*
* @param tokens
* The token list for the file
* @param pos
* The current index position inside the token list
* @return
* Returns a vector of all the identifier values involved, or an
* empty vector if no identifier was detected.
*/
vector<StringFragment> readQualifiedIdentifier(const vector<Token> &tokens, size_t &pos) {
vector<StringFragment> ret;
for (; isTok(tokens[pos], TK_IDENTIFIER) || isTok(tokens[pos], TK_DOUBLE_COLON); ++pos) {
if (isTok(tokens[pos], TK_IDENTIFIER)) {
ret.push_back(tokens[pos].value_);
}
}
return ret;
};
/**
* Traverses the token list until the whole code block has been passed
*
* @param tokens
* The token list for the file
* @param pos
* The current index position inside the token list
* @return
* Returns the position of the closing curly bracket
*/
size_t skipBlock(const vector<Token> &tokens, size_t pos) {
assert(isTok(tokens[pos], TK_LCURL));
uint openBraces = 1; // Because we began on the leading '{'
++pos;
for (const size_t size = tokens.size(); pos < size && !isTok(tokens[pos], TK_EOF); ++pos) {
const Token &tok = tokens[pos];
if (isTok(tok, TK_LCURL)) {
++openBraces;
continue;
}
if (isTok(tok, TK_RCURL)) {
// Removed decrement/zero-check as one line
// It's not a race guys, readability > length of code
--openBraces;
if (openBraces == 0) {
break;
}
continue;
}
}
return pos;
};
/**
* Traverses the token list until the whole parentheses chunk has passed
*
* @param tokens
* The token list for the file
* @param pos
* The current index position inside the token list
* @return
* Returns the position of the closing curly bracket
*/
size_t skipParens(const vector<Token> &tokens, size_t pos) {
assert(isTok(tokens[pos], TK_LPAREN));
uint openParens = 1; // Because we began on the leading '('
++pos;
for (const size_t size = tokens.size(); pos < size && !isTok(tokens[pos], TK_EOF); ++pos) {
const Token &tok = tokens[pos];
if (isTok(tok, TK_LPAREN)) {
++openParens;
continue;
}
if (isTok(tok, TK_RPAREN)) {
// Removed decrement/zero-check as one line
// It's not a race guys, readability > length of code
--openParens;
if (openParens == 0) {
break;
}
continue;
}
}
return pos;
};
/**
* Traverses the token list and runs a Callback function on each
* class/struct/union it finds
*
* @param errors
* Struct to track how many errors/warnings/advice occured
* @param tokens
* The token list for the file
* @param pos
* The current index position inside the token list
* @param callback
* The function to run on each code object
template<class Callback>
void iterateClasses(ErrorFile &errors, const vector<Token> &tokens, const Callback &callback) {
static const array<TokenType, 2> template_types = {
{ TK_TEMPLATE, TK_LESS }
};
for (size_t pos = 0; pos < tokens.size() - 1; ++pos) {
// Skip template sequence if we find ... template< ...
if (atSequence(tokens, pos, template_types)) {
pos = skipTemplateSpec(tokens, ++pos);
continue;
}
TokenType tok = tokens[pos].type_;
if (tok == TK_CLASS || tok == TK_STRUCT || tok == TK_UNION) {
callback(errors, tokens, pos);
}
}
};
*/
/**
* 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.
*
* @param tokens
* The token list for the file
* @param pos
* The current index position inside the token list
* @return
* Returns the position of the closing curly bracket or semicolon
*/
size_t skipFunctionDeclaration(const vector<Token> &tokens, size_t pos) {
for (const size_t size = tokens.size(); pos < size && !isTok(tokens[pos], TK_EOF); ++pos) {
TokenType tok = tokens[pos].type_;
if (tok == TK_SEMICOLON) { // Function Prototype
break;
}
else if (tok == TK_LCURL) { // Full Declaration
pos = skipBlock(tokens, pos);
break;
}
}
return pos;
};
/**
* 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 {
size_t first;
size_t last;
inline Argument(size_t a, size_t b) : first(a), last(b) {
// Just to check the port hasn't broken Token traversal somehow
assert(first <= last);
};
};
/**
* Take the bounds of an argument list and pretty print it to a string
*
* @param tokens
* The token list for the file
* @param arg
* A struct representing the bounds of the argument list tokens
* @return
* Returns a string representation of the argument token list
*/
string formatArg(const vector<Token> &tokens, const Argument &arg) {
string result;
for (size_t pos = arg.first; pos < arg.last; ++pos) {
if (pos != arg.first && !(tokens[pos].precedingWhitespace_.empty())) {
result += ' ';
}
const auto &val = tokens[pos].value_;
result.append(val.begin(), val.end());
}
return result;
};
/**
* Pretty print a function declaration/prototype to a string
*
* @param tokens
* The token list for the file
* @param func
* A reference to the name of the function
* @param args
* A list of arguments for the function
* @return
* Returns a string representation of the argument token list
*/
string formatFunction(const vector<Token> &tokens, const Argument &func, const vector<Argument> &args) {
static const string sep(", ");
string result = formatArg(tokens, func) + '(';
if (!args.empty()) {
result += formatArg(tokens, args[0]);
}
for (size_t i = 1, size = args.size(); i < size; ++i) {
result += sep;
result += formatArg(tokens, 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 call, the iterator will be moved to after the end of the function
* call.
*
* @param tokens
* The token list for the file
* @param pos
* The current index position inside the token list
* @param args
* A reference to the list to fill with arguments
* @return
* Returns true if we believe (sorta) that everything went okay,
* false if something bad happened (maybe)
*/
bool getRealArguments(const vector<Token> &tokens, size_t &pos, vector<Argument> &args) {
assert(isTok(tokens[pos], TK_LPAREN));
++pos;
size_t argStart = pos; // First arg starts after parenthesis
int parenCount = 1;
const size_t size = tokens.size();
for (; pos < size && !isTok(tokens[pos], TK_EOF); ++pos) {
TokenType tok = tokens[pos].type_;
if (tok == TK_LPAREN) {
++parenCount;
continue;
}
if (tok == TK_RPAREN) {
// Removed decrement/zero-check as one line
// It's not a race guys, readability > length of code
--parenCount;
if (parenCount == 0) {
break;
}
continue;
}
/*
if (tok == TK_LESS) {
// 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.
pos = skipTemplateSpec(tokens, pos);
continue;
}
*/
if (tok == TK_COMMA) {
if (parenCount == 1) {
// end an argument of the function we are looking at
args.push_back(Argument(argStart, pos));
argStart = pos + 1;
}
continue;
}
}
if (pos >= size || isTok(tokens[pos], TK_EOF)) {
return false;
}
if (argStart != pos) {
args.push_back(Argument(argStart, pos));
}
return true;
};
/**
* Get the argument list of a function, with the first argument being the
* function name plus the template spec.
*
* @param tokens
* The token list for the file
* @param pos
* The current index position inside the token list
* @param func
* A reference to the name of the function
* @param args
* A reference to the list to fill with arguments
* @return
* Returns true if we believe (sorta) that everything went okay,
* false if something bad happened (maybe)
*/
bool getFunctionNameAndArguments(const vector<Token> &tokens, size_t &pos
, Argument &func, vector<Argument> &args) {
func.first = pos;
++pos;
const size_t size = tokens.size();
if (pos < size && isTok(tokens[pos], TK_LESS)) {
pos = skipTemplateSpec(tokens, pos);
if (pos >= size || isTok(tokens[pos], TK_EOF)) {
return false;
}
++pos;
}
func.last = pos;
return getRealArguments(tokens, pos, args);
};
inline TokenIter getEndOfClass(TokenIter start, TokenIter maxPos) {
static const array<TokenType, 3> classMarkers = {
{ TK_EOF, TK_LCURL, TK_SEMICOLON }
};
return find_first_of(start, maxPos, begin(classMarkers), end(classMarkers), isTok);
};
bool matchAcrossTokens(const StringFragment &frag, TokenIter start, TokenIter end_iter) {
auto f_pos = frag.begin();
auto f_end = frag.end();
auto f_token_pos = start->value_.begin();
auto f_curr_end = start->value_.end();
while (f_pos != f_end && start != end_iter && *f_pos == *f_token_pos) {
f_pos++;
f_token_pos++;
if (f_token_pos == f_curr_end) {
start++;
}
}
return (f_pos == f_end);
};
}; // Anonymous Namespace
/**
* Check all member intializations to make sure they do not initialize on themselves
*
* @param path
* The path to the file currently being linted
* @param tokens
* The token list for the file
* @return
* Returns the number of errors this check found in the token stream
*/
void checkInitializeFromItself(ErrorFile &errors, const string &path, const vector<Token> &tokens) {
// Token Sequences for parameter initializers
static const array<TokenType, 5> firstInitializer = {
{ TK_COLON, TK_IDENTIFIER, TK_LPAREN, TK_IDENTIFIER, TK_RPAREN }
};
static const array<TokenType, 5> nthInitializer = {
{ TK_COMMA, TK_IDENTIFIER, TK_LPAREN, TK_IDENTIFIER, TK_RPAREN }
};
for (size_t pos = 0, size = tokens.size(); pos < size; ++pos) {
if (atSequence(tokens, pos, firstInitializer) || atSequence(tokens, pos, nthInitializer)) {
size_t outerPos = ++pos; // +1 for identifier
size_t innerPos = ++(++pos); // +2 again for the inner identifier
bool isMember = tokens[outerPos].value_.back() == '_' ||
startsWith(tokens[outerPos].value_.begin(), "m_");
if (isMember && cmpToks(tokens[outerPos], tokens[innerPos])) {
lintError(errors, tokens[outerPos],
"Initializing class member '" + to_string(tokens[outerPos].value_) + "' with itself.");
}
}
}
};
/**
* Check for blacklisted sequences of tokens
*
* @param path
* The path to the file currently being linted
* @param tokens
* The token list for the file
* @return
* Returns the number of errors this check found in the token stream
*/
void checkBlacklistedSequences(ErrorFile &errors, const string &path, const vector<Token> &tokens) {
struct BlacklistEntry {
vector<TokenType> tokens;
string title, descr;
bool cpponly;
BlacklistEntry(vector<TokenType> t, string h, string d, bool cpponly)
: tokens(move(t)), title(move(h)), descr(move(d)), cpponly(cpponly) {};
};
static const vector<BlacklistEntry> blacklist = {
{ { TK_VOLATILE },
"'volatile' is not 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.",
true, // C++ only.
}
};
static const array< vector<TokenType>, 1 > exceptions = {
{ { TK_ASM, TK_VOLATILE } }
};
bool isException = false;
for (size_t pos = 0, size = tokens.size(); pos < size; ++pos) {
// Make sure we aren't at an exception to the blacklist
for (const auto &e : exceptions) {
if (atSequence(tokens, pos, e)) {
isException = true;
break;
}
}
for (const BlacklistEntry &entry : blacklist) {
if (!atSequence(tokens, pos, entry.tokens)) {
continue;
}
if (isException) {
isException = false;
continue;
}
if (Options.CMODE && entry.cpponly) {
continue;
}
lintWarning(errors, tokens[pos], entry.title, entry.descr);
}
}
};
/**
* Check for blacklisted identifiers
*
* @param errors
* Struct to track how many errors/warnings/advice occured
* @param path
* The path to the file currently being linted
* @param tokens
* The token list for the file
*/
void checkBlacklistedIdentifiers(ErrorFile &errors, const string &path, const vector<Token> &tokens) {
static const unordered_map<string, pair<Lint,string>> blacklist = {
{ "strtok",
{ Lint::ERROR, "'strtok' is not thread safe. Consider 'strtok_r'." }
},
{ "NULL",
{ Lint::ADVICE, "Prefer `nullptr' to `NULL' in new C++ code." }
}
};
for (size_t pos = 0, size = tokens.size(); pos < size; ++pos) {
if (isTok(tokens[pos], TK_IDENTIFIER)) {
for (const auto &entry : blacklist) {
if (cmpTok(tokens[pos], entry.first.c_str())) {
auto& desc = entry.second;
lint(errors, tokens[pos], desc.first, desc.second);
continue;
}
}
}
}
};
/**
* Check for conflicting namespace usages
*
* @param errors
* Struct to track how many errors/warnings/advice occured
* @param path
* The path to the file currently being linted
* @param tokens
* The token list for the file
*/
void checkUsingNamespaceDirectives(ErrorFile &errors, const string &path, const vector<Token> &tokens) {
vector<StringFragment> namespaces;
stack<size_t> scopes;
static const array<TokenType, 2> usingNamespace = {
{TK_USING, TK_NAMESPACE}
};
static const vector<string> exclusive {
"std", "std::tr1", "boost", "::std", "::std::tr1", "::boost"
};
static const vector<StringFragment> exclusiveFragments = []()->vector<StringFragment> {
vector<StringFragment> out;
for_each(begin(exclusive), end(exclusive), [&](const string &str) { out.push_back(StringFragment{begin(str), end(str)}); });
return out;
}();
for (size_t pos = 0, size = tokens.size(); pos < size; ++pos) {
if (isTok(tokens[pos], TK_LCURL)) {
scopes.push(namespaces.size());
continue;
}
if (isTok(tokens[pos], TK_RCURL)) {
if (!scopes.empty()) {
auto del = scopes.top();
while (namespaces.size() > del) {
namespaces.pop_back();
}
scopes.pop();
}
continue;
}
if (atSequence(tokens, pos, usingNamespace)) {
pos += 2;
auto isExclusive = find_if(begin(exclusiveFragments), end(exclusiveFragments), [=](const StringFragment &frag) { return matchAcrossTokens(frag, begin(tokens) + pos, end(tokens)); });
if (isExclusive == end(exclusiveFragments)) {
continue;
}
auto conflict = find_if(begin(namespaces), end(namespaces), [&](const StringFragment &frag) { return !(frag == *isExclusive); });
if (conflict != end(namespaces)) {
lintWarning(errors, tokens[pos], "Conflicting namespaces: " + to_string(*isExclusive) + " and " + to_string(*conflict));
}
namespaces.push_back(*isExclusive);
continue;
}
}
};
/**
* Check for static variables and functions in global/namespace scopes
*
* @param errors
* Struct to track how many errors/warnings/advice occured
* @param path
* The path to the file currently being linted
* @param tokens
* The token list for the file
*/
void checkNamespaceScopedStatics(ErrorFile &errors, const string &path, const vector<Token> &tokens) {
if (!isHeader(path)) {
return;
}
static const array<TokenType, 3> regularNamespace = {
{TK_NAMESPACE, TK_IDENTIFIER, TK_LCURL}
};
static const array<TokenType, 2> unnamedNamespace = {
{TK_NAMESPACE, TK_LCURL}
};
static const array<TokenType, 2> usingNamespace = {
{TK_USING, TK_NAMESPACE}
};
for (size_t pos = 0, size = tokens.size(); pos < size; ++pos) {
if (atSequence(tokens, pos, regularNamespace)) {
pos += 2;
continue;
}
if (atSequence(tokens, pos, unnamedNamespace)) {
++pos;
continue;
}
const Token &token = tokens[pos];
if (isTok(token, TK_LCURL)) {
pos = skipBlock(tokens, pos);
continue;
}
if (isTok(tokens[pos], TK_STATIC)) {
lintWarning(errors, tokens[pos], "Don't use static at global or namespace scopes in headers.");
}
// Checking for 'using namespace' violations here as well
if (atSequence(tokens, pos, usingNamespace)) {
lintWarning(errors, tokens[pos], "Avoid the use of using namespace directives at global/namespace scope in headers");
}
}
};
/**
* Check for public non-virtual destructors in classes with virtual functions
*
* @param errors
* Struct to track how many errors/warnings/advice occured
* @param path
* The path to the file currently being linted
* @param tokens
* The token list for the file
*/
void checkVirtualDestructors(ErrorFile &errors, const string &path, const vector<Token> &tokens, const vector<size_t> &structures) {
static const array<TokenType, 3> accessSpecifiers = {
{ TK_PUBLIC, TK_PRIVATE, TK_PROTECTED }
};
static const string msg = "Classes with virtual functions should not have a public non-virtual destructor.";
auto size = structures.size();
auto penultimate = size - 1;
for (size_t i = 0; i < size; ++i) {
auto startIter = begin(tokens) + structures[i];
auto endIter = (i == penultimate) ? end(tokens) : begin(tokens) + structures[i + 1];
auto &tok = *startIter;
if (isTok(tok, TK_UNION)) {
continue;
}
// Start at end of class definition to avoid virtual bases
auto endOfClass = getEndOfClass(startIter + 1, endIter);
if (endOfClass == endIter || !isTok(*endOfClass, TK_LCURL)) {
continue;
}
// Find something virtual
auto virtualLocation = find_if(endOfClass + 1, endIter, [](const Token &token){ return isTok(token, TK_VIRTUAL); });
if (virtualLocation == endIter) {
continue; // No virtual functions or destructor
}
// Now that we have something virtual, we need a destructor
auto userDestructor = adjacent_find(startIter, endIter, [](const Token &first, const Token &second) {
return isTok(first, TK_TILDE) && isTok(second, TK_IDENTIFIER);
});
// compiler defined is not virtual
if (userDestructor == endIter) {
lintWarning(errors, *startIter, msg);
continue;
}
// We're good, we've got a virtual destructor
if (isTok(*(userDestructor - 1), TK_VIRTUAL)) {
continue;
}
// Now what kind of access do we have for our virtual destructor
using rev_iter = reverse_iterator<TokenIter>;
auto lastAccess = find_first_of(rev_iter(userDestructor), rev_iter(startIter), begin(accessSpecifiers), end(accessSpecifiers), isTok);
auto access = (lastAccess != rev_iter(startIter)) ? lastAccess->type_ : isTok(tok, TK_STRUCT) ? TK_PUBLIC : TK_PRIVATE;
if (access == TK_PUBLIC) {
lintWarning(errors, *startIter, msg);
}
}
};
/**
* Check for non-public std::exception inheritance
*
* @param errors
* Struct to track how many errors/warnings/advice occured
* @param path
* The path to the file currently being linted
* @param tokens
* The token list for the file
*/
void checkExceptionInheritance(ErrorFile &errors, const string &path, const vector<Token> &tokens, const vector<size_t> &structures) {
static const array<TokenType, 4> classMarkersWithColon = {
{ TK_EOF, TK_LCURL, TK_SEMICOLON, TK_COLON }
};
static const array<TokenType, 3> accessSpecifiers = {
{ TK_PUBLIC, TK_PRIVATE, TK_PROTECTED }
};
for (size_t i = 0, struct_size = structures.size(); i < struct_size; ++i) {
// Start pos at the index of each identified structure
auto pos = begin(tokens) + structures[i];
const auto &tok = *pos;
if (isTok(tok, TK_UNION)) {
continue;
}
auto colon = find_first_of(pos, end(tokens), begin(classMarkersWithColon), end(classMarkersWithColon), isTok);
if (colon == end(tokens)) {
return;
}
if (colon->type_ != TK_COLON) {
continue;
}
auto endOfClass = getEndOfClass(colon + 1, end(tokens));
auto exceptionPos = find_if(colon + 1, endOfClass, [](const Token &candidate) {
return isTok(candidate, TK_IDENTIFIER) && cmpTok(candidate, "exception");
});
if (exceptionPos == endOfClass)
continue;
auto usingStdException = !isTok(*(exceptionPos - 1), TK_DOUBLE_COLON) || (isTok(*(exceptionPos - 2), TK_IDENTIFIER) && cmpTok(*(exceptionPos - 2), "std"));
if (!usingStdException) {
continue;
}
// OK, we're going with the last access specifier before the exception token
auto lastAccess = accumulate(colon + 1, exceptionPos, TK_PROTECTED, [](const TokenType &curr, const Token &next) -> TokenType {
if (isTok(next, TK_COMMA)) {
return TK_PROTECTED;
}
auto access = find(begin(accessSpecifiers), end(accessSpecifiers), next.type_);
return access == end(accessSpecifiers) ? curr : *access;
});
if ((isTok(tok, TK_CLASS) && lastAccess != TK_PUBLIC) || (isTok(tok, TK_STRUCT) && lastAccess == TK_PRIVATE)) {
lintWarning(errors, *exceptionPos, "std::exception should be inherited publically (C++ std: 11.2)");
}
}
};
/**
* 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.
*
* @param errors
* Struct to track how many errors/warnings/advice occured
* @param path
* The path to the file currently being linted
* @param tokens
* The token list for the file
*/