/
checkclass.cpp
733 lines (611 loc) · 24.2 KB
/
checkclass.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
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2009 Daniel Marjamäki, Reijo Tomperi, Nicolas Le Cam,
* Leandro Penz, Kimmo Varis, Vesa Pikki
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/
*/
//---------------------------------------------------------------------------
#include "checkclass.h"
#include "tokenize.h"
#include "token.h"
#include "errorlogger.h"
#include <locale>
#include <cstring>
#include <string>
#include <sstream>
#include <algorithm>
//---------------------------------------------------------------------------
// Register CheckClass..
namespace
{
CheckClass instance;
}
//---------------------------------------------------------------------------
struct CheckClass::VAR *CheckClass::ClassChecking_GetVarList(const Token *tok1)
{
// Get variable list..
struct VAR *varlist = NULL;
unsigned int indentlevel = 0;
for (const Token *tok = tok1; tok; tok = tok->next())
{
if (!tok->next())
break;
if (tok->str() == "{")
++indentlevel;
else if (tok->str() == "}")
{
if (indentlevel <= 1)
break;
--indentlevel;
}
if (indentlevel != 1)
continue;
// "private:" "public:" "protected:" etc
bool b = bool((*tok->strAt(0) != ':') && strchr(tok->strAt(0), ':') != 0);
// Search for start of statement..
if (! Token::Match(tok, "[;{}]") && ! b)
continue;
// This is the start of a statement
const Token *next = tok->next();
const char *varname = 0;
// If next token contains a ":".. it is not part of a variable declaration
if (next->str().find(":") != std::string::npos)
{
}
// Is it a variable declaration?
else if (Token::Match(next, "%type% %var% ;"))
{
if (next->isStandardType())
varname = next->strAt(1);
else if (Token::findmatch(_tokenizer->tokens(), ("enum " + next->str()).c_str()))
varname = next->strAt(1);
}
// Pointer?
else if (Token::Match(next, "%type% * %var% ;"))
{
varname = next->strAt(2);
}
// Pointer?
else if (Token::Match(next, "%type% %type% * %var% ;"))
{
varname = next->strAt(3);
}
// If the varname was set in one of the two if-block above, create a entry for this variable..
if (varname)
{
struct VAR *var = new VAR(varname, false, varlist);
varlist = var;
}
}
return varlist;
}
//---------------------------------------------------------------------------
void CheckClass::InitVar(struct VAR *varlist, const char varname[])
{
for (struct VAR *var = varlist; var; var = var->next)
{
if (strcmp(var->name, varname) == 0)
{
var->init = true;
break;
}
}
}
//---------------------------------------------------------------------------
void CheckClass::ClassChecking_VarList_Initialize(const Token *tok1, const Token *ftok, struct VAR *varlist, const char classname[], std::list<std::string> &callstack)
{
bool Assign = false;
unsigned int indentlevel = 0;
for (; ftok; ftok = ftok->next())
{
if (!ftok->next())
break;
// Class constructor.. initializing variables like this
// clKalle::clKalle() : var(value) { }
if (indentlevel == 0)
{
if (Assign && Token::Match(ftok, "%var% ("))
{
InitVar(varlist, ftok->aaaa());
}
Assign |= (ftok->str() == ":");
}
if (ftok->str() == "{")
{
++indentlevel;
Assign = false;
}
if (ftok->str() == "}")
{
if (indentlevel <= 1)
break;
--indentlevel;
}
if (indentlevel < 1)
continue;
// Variable getting value from stream?
if (Token::Match(ftok, ">> %var%"))
{
InitVar(varlist, ftok->next()->aaaa());
}
// Before a new statement there is "[{};)=]" or "else"
if (! Token::Match(ftok, "[{};)=]") && ftok->str() != "else")
continue;
// Using the operator= function to initialize all variables..
if (Token::simpleMatch(ftok->next(), "* this = "))
{
for (struct VAR *var = varlist; var; var = var->next)
var->init = true;
break;
}
if (!Token::Match(ftok->next(), "%var%") && !Token::Match(ftok->next(), "this . %var%"))
continue;
// Goto the first token in this statement..
ftok = ftok->next();
// Skip "this->"
if (Token::simpleMatch(ftok, "this ."))
ftok = ftok->tokAt(2);
// Clearing all variables..
if (Token::simpleMatch(ftok, "memset ( this ,"))
{
for (struct VAR *var = varlist; var; var = var->next)
var->init = true;
break;
}
// Calling member function?
else if (Token::Match(ftok, "%var% ("))
{
// No recursive calls!
if (std::find(callstack.begin(), callstack.end(), ftok->str()) == callstack.end())
{
callstack.push_back(ftok->str());
int i = 0;
const Token *ftok2 = Tokenizer::FindClassFunction(tok1, classname, ftok->aaaa(), i);
ClassChecking_VarList_Initialize(tok1, ftok2, varlist, classname, callstack);
}
}
// Assignment of member variable?
else if (Token::Match(ftok, "%var% ="))
{
InitVar(varlist, ftok->aaaa());
}
// The functions 'clear' and 'Clear' are supposed to initialize variable.
if (Token::Match(ftok, "%var% . clear|Clear ("))
{
InitVar(varlist, ftok->aaaa());
}
}
}
//---------------------------------------------------------------------------
// ClassCheck: Check that all class constructors are ok.
//---------------------------------------------------------------------------
void CheckClass::constructors()
{
const char pattern_class[] = "class %var% {";
// Locate class
const Token *tok1 = Token::findmatch(_tokenizer->tokens(), pattern_class);
while (tok1)
{
const char *className[2];
className[0] = tok1->strAt(1);
className[1] = 0;
const Token *classNameToken = tok1->tokAt(1);
// TODO: handling of private constructors should be improved.
bool hasPrivateConstructor = false;
{
int indentlevel = 0;
bool isPrivate = true;
for (const Token *tok = tok1; tok; tok = tok->next())
{
// Indentation
if (tok->str() == "{")
++indentlevel;
else if (tok->str() == "}")
{
--indentlevel;
if (indentlevel <= 0)
break;
}
// Parse class contents (indentlevel == 1)..
if (indentlevel == 1)
{
// What section are we in.. private/non-private
if (tok->str() == "private:")
isPrivate = true;
else if (tok->str() == "protected:" || tok->str() == "public:")
isPrivate = false;
// Is there a private constructor?
else if (isPrivate && Token::simpleMatch(tok, (classNameToken->str() + " (").c_str()))
{
hasPrivateConstructor = true;
break;
}
}
}
}
if (hasPrivateConstructor)
{
// TODO: Handle private constructors.
// Right now to avoid false positives I just bail out
tok1 = Token::findmatch(tok1->next(), pattern_class);
continue;
}
// Are there a class constructor?
std::string tempPattern = "%any% " + classNameToken->str() + " (";
const Token *constructor_token = Token::findmatch(tok1, tempPattern.c_str());
while (Token::Match(constructor_token, "~"))
constructor_token = Token::findmatch(constructor_token->next(), tempPattern.c_str());
// There are no constructor.
if (! constructor_token)
{
// If "--style" has been given, give a warning
if (ErrorLogger::noConstructor(*_settings))
{
// If the class has member variables there should be an constructor
struct VAR *varlist = ClassChecking_GetVarList(tok1);
if (varlist)
{
noConstructorError(tok1, classNameToken->str());
}
// Delete the varlist..
while (varlist)
{
struct VAR *nextvar = varlist->next;
delete varlist;
varlist = nextvar;
}
}
tok1 = Token::findmatch(tok1->next(), pattern_class);
continue;
}
// Check that all member variables are initialized..
struct VAR *varlist = ClassChecking_GetVarList(tok1);
// Check constructors
CheckConstructors(tok1, varlist, className[0]);
// Check assignment operators
CheckConstructors(tok1, varlist, "operator =");
// Delete the varlist..
while (varlist)
{
struct VAR *nextvar = varlist->next;
delete varlist;
varlist = nextvar;
}
tok1 = Token::findmatch(tok1->next(), pattern_class);
}
}
void CheckClass::CheckConstructors(const Token *tok1, struct VAR *varlist, const char funcname[])
{
const char * const className = tok1->strAt(1);
int indentlevel = 0;
const Token *constructor_token = Tokenizer::FindClassFunction(tok1, className, funcname, indentlevel);
std::list<std::string> callstack;
ClassChecking_VarList_Initialize(tok1, constructor_token, varlist, className, callstack);
while (constructor_token)
{
// Check if any variables are uninitialized
for (struct VAR *var = varlist; var; var = var->next)
{
if (var->init)
continue;
// Is it a static member variable?
std::ostringstream pattern;
pattern << className << "::" << var->name << "=";
if (Token::findmatch(_tokenizer->tokens(), pattern.str().c_str()))
continue;
// It's non-static and it's not initialized => error
if (strcmp(funcname, "operator =") == 0)
operatorEqVarError(constructor_token, className, var->name);
else
uninitVarError(constructor_token, className, var->name);
}
for (struct VAR *var = varlist; var; var = var->next)
var->init = false;
constructor_token = Tokenizer::FindClassFunction(constructor_token->next(), className, funcname, indentlevel);
callstack.clear();
ClassChecking_VarList_Initialize(tok1, constructor_token, varlist, className, callstack);
}
}
//---------------------------------------------------------------------------
// ClassCheck: Unused private functions
//---------------------------------------------------------------------------
void CheckClass::privateFunctions()
{
// Locate some class
for (const Token *tok1 = Token::findmatch(_tokenizer->tokens(), "class %var% {"); tok1; tok1 = Token::findmatch(tok1->next(), "class %var% {"))
{
const std::string &classname = tok1->next()->str();
// The class implementation must be available..
const std::string classconstructor(classname + " :: " + classname);
if (tok1->fileIndex() > 0 && !Token::findmatch(_tokenizer->tokens(), classconstructor.c_str()))
continue;
// Get private functions..
std::list<const Token *> FuncList;
FuncList.clear();
bool priv = false;
unsigned int indent_level = 0;
for (const Token *tok = tok1; tok; tok = tok->next())
{
if (Token::Match(tok, "friend %var%"))
{
// Todo: Handle friend classes
FuncList.clear();
break;
}
if (tok->str() == "{")
++indent_level;
else if (tok->str() == "}")
{
if (indent_level <= 1)
break;
--indent_level;
}
else if (tok->str() == "private:")
priv = true;
else if (tok->str() == "public:")
priv = false;
else if (tok->str() == "protected:")
priv = false;
else if (priv && indent_level == 1)
{
if (Token::Match(tok, "typedef %type% ("))
tok = tok->tokAt(2);
if (Token::Match(tok, "%var% (") &&
!Token::Match(tok, classname.c_str()))
{
FuncList.push_back(tok);
}
}
}
// Check that all private functions are used..
bool HasFuncImpl = false;
bool inclass = false;
indent_level = 0;
const std::string pattern_function(classname + " ::");
for (const Token *ftok = _tokenizer->tokens(); ftok; ftok = ftok->next())
{
if (ftok->str() == "{")
++indent_level;
else if (ftok->str() == "}")
{
if (indent_level > 0)
--indent_level;
if (indent_level == 0)
inclass = false;
}
if (Token::Match(ftok, ("class " + classname + " :|{").c_str()))
{
indent_level = 0;
inclass = true;
}
// Check member class functions to see what functions are used..
if ((inclass && indent_level == 1 && Token::Match(ftok, ") const| {")) ||
(Token::Match(ftok, (classname + " :: ~| %var% (").c_str())))
{
while (ftok && ftok->str() != ")")
ftok = ftok->next();
if (!ftok)
break;
if (Token::Match(ftok, ") : %var% ("))
{
while (!Token::Match(ftok->next(), "[{};]"))
ftok = ftok->next();
}
if (!Token::Match(ftok, ") const| {"))
continue;
if (ftok->fileIndex() == 0)
HasFuncImpl = true;
// Parse function..
int indentlevel2 = 0;
for (const Token *tok2 = ftok; tok2; tok2 = tok2->next())
{
if (tok2->str() == "{")
++indentlevel2;
else if (tok2->str() == "}")
{
--indentlevel2;
if (indentlevel2 < 1)
break;
}
else if (Token::Match(tok2, "%var% ("))
{
// Remove function from FuncList
for (std::list<const Token *>::iterator it = FuncList.begin(); it != FuncList.end(); ++it)
{
if (tok2->str() == (*it)->str())
{
FuncList.remove(*it);
break;
}
}
}
}
}
}
while (HasFuncImpl && !FuncList.empty())
{
// Final check; check if the function pointer is used somewhere..
const std::string _pattern("return|(|)|,|= " + FuncList.front()->str());
if (!Token::findmatch(_tokenizer->tokens(), _pattern.c_str()))
{
unusedPrivateFunctionError(FuncList.front(), classname, FuncList.front()->str());
}
FuncList.pop_front();
}
}
}
//---------------------------------------------------------------------------
// ClassCheck: Check that memset is not used on classes
//---------------------------------------------------------------------------
void CheckClass::noMemset()
{
// Locate all 'memset' tokens..
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next())
{
if (!Token::Match(tok, "memset|memcpy|memmove"))
continue;
// Todo: Handle memcpy and memmove
const char *type = NULL;
if (Token::Match(tok, "memset ( %var% , %num% , sizeof ( %type% ) )"))
type = tok->strAt(8);
else if (Token::Match(tok, "memset ( & %var% , %num% , sizeof ( %type% ) )"))
type = tok->strAt(9);
else if (Token::Match(tok, "memset ( %var% , %num% , sizeof ( struct %type% ) )"))
type = tok->strAt(9);
else if (Token::Match(tok, "memset ( & %var% , %num% , sizeof ( struct %type% ) )"))
type = tok->strAt(10);
else if (Token::Match(tok, "%type% ( %var% , %var% , sizeof ( %type% ) )"))
type = tok->strAt(8);
// No type defined => The tokens didn't match
if (!(type && type[0]))
continue;
// Warn if type is a class..
const std::string pattern1(std::string("class ") + type);
if (Token::findmatch(_tokenizer->tokens(), pattern1.c_str()))
{
memsetClassError(tok, tok->str());
continue;
}
// Warn if type is a struct that contains any std::*
const std::string pattern2(std::string("struct ") + type);
for (const Token *tstruct = Token::findmatch(_tokenizer->tokens(), pattern2.c_str()); tstruct; tstruct = tstruct->next())
{
if (tstruct->str() == "}")
break;
if (Token::Match(tstruct, "std :: %type% %var% ;"))
{
memsetStructError(tok, tok->str(), tstruct->strAt(2));
break;
}
}
}
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// ClassCheck: "void operator=("
//---------------------------------------------------------------------------
void CheckClass::operatorEq()
{
const Token *tok = Token::findmatch(_tokenizer->tokens(), "void operator = (");
if (tok)
{
operatorEqReturnError(tok);
}
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// A destructor in a base class should be virtual
//---------------------------------------------------------------------------
void CheckClass::virtualDestructor()
{
const char pattern_classdecl[] = "class %var% : %var%";
const Token *derived = _tokenizer->tokens();
while ((derived = Token::findmatch(derived, pattern_classdecl)) != NULL)
{
// Check that the derived class has a non empty destructor..
{
std::ostringstream destructorPattern;
destructorPattern << "~ " << derived->strAt(1) << " ( ) {";
const Token *derived_destructor = Token::findmatch(_tokenizer->tokens(), destructorPattern.str().c_str());
// No destructor..
if (! derived_destructor)
{
derived = derived->next();
continue;
}
// Empty destructor..
if (Token::Match(derived_destructor, "~ %var% ( ) { }"))
{
derived = derived->next();
continue;
}
}
const Token *derivedClass = derived->tokAt(1);
// Iterate through each base class...
derived = derived->tokAt(3);
while (Token::Match(derived, "%var%"))
{
bool isPublic = Token::Match(derived, "public");
// What kind of inheritance is it.. public|protected|private
if (Token::Match(derived, "public|protected|private"))
derived = derived->next();
// Name of base class..
const char *baseName[2];
baseName[0] = derived->strAt(0);
baseName[1] = 0;
// Update derived so it's ready for the next loop.
derived = derived->next();
if (Token::Match(derived, ","))
derived = derived->next();
// If not public inheritance, skip checking of this base class..
if (! isPublic)
continue;
// Find the destructor declaration for the base class.
const Token *base = Token::findmatch(_tokenizer->tokens(), (std::string("%any% ~ ") + baseName[0] + " (").c_str());
while (Token::Match(base, "::"))
base = Token::findmatch(base->next(), (std::string("%any% ~ ") + baseName[0] + + " (").c_str());
while (Token::Match(base, "%var%") && !Token::Match(base, "virtual"))
base = base->previous();
// Check that there is a destructor..
if (! base)
{
// Is the class declaration available?
base = Token::findmatch(_tokenizer->tokens(), (std::string("class ") + baseName[0] + " :|{").c_str());
if (base)
{
virtualDestructorError(base, baseName[0], derivedClass->str());
}
}
// There is a destructor. Check that it's virtual..
else if (base->str() != "virtual")
{
virtualDestructorError(base, baseName[0], derivedClass->str());
}
}
}
}
//---------------------------------------------------------------------------
void CheckClass::noConstructorError(const Token *tok, const std::string &classname)
{
reportError(tok, "style", "noConstructor", "The class '" + classname + "' has no constructor");
}
void CheckClass::uninitVarError(const Token *tok, const std::string &classname, const std::string &varname)
{
reportError(tok, "style", "uninitVar", "Member variable not initialized in the constructor '" + classname + "::" + varname + "'");
}
void CheckClass::operatorEqVarError(const Token *tok, const std::string &classname, const std::string &varname)
{
reportError(tok, "all style", "operatorEqVarError", "Member variable '" + classname + "::" + varname + "' is not assigned a value in '" + classname + "::operator=" + "'");
}
void CheckClass::unusedPrivateFunctionError(const Token *tok, const std::string &classname, const std::string &funcname)
{
reportError(tok, "style", "unusedPrivateFunction", "Unused private function '" + classname + "::" + funcname + "'");
}
void CheckClass::memsetClassError(const Token *tok, const std::string &memfunc)
{
reportError(tok, "error", "memsetClass", "Using '" + memfunc + "' on class");
}
void CheckClass::memsetStructError(const Token *tok, const std::string &memfunc, const std::string &classname)
{
reportError(tok, "error", "memsetStruct", "Using '" + memfunc + "' on struct that contains a 'std::" + classname + "'");
}
void CheckClass::operatorEqReturnError(const Token *tok)
{
reportError(tok, "style", "operatorEq", "'operator=' should return something");
}
void CheckClass::virtualDestructorError(const Token *tok, const std::string &Base, const std::string &Derived)
{
reportError(tok, "error", "virtualDestructor", "Class " + Base + " which is inherited by class " + Derived + " does not have a virtual destructor");
}