File: checkinternal.cpp

package info (click to toggle)
cppcheck 2.17.1-2
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 25,384 kB
  • sloc: cpp: 263,341; python: 19,737; ansic: 7,953; sh: 1,018; makefile: 996; xml: 994; cs: 291
file content (423 lines) | stat: -rw-r--r-- 16,901 bytes parent folder | download
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
/*
 * Cppcheck - A tool for static C/C++ code analysis
 * Copyright (C) 2007-2025 Cppcheck team.
 *
 * 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/>.
 */

#ifdef CHECK_INTERNAL

#include "checkinternal.h"

#include "astutils.h"
#include "errortypes.h"
#include "settings.h"
#include "symboldatabase.h"
#include "token.h"
#include "tokenize.h"

#include <cstring>
#include <set>
#include <vector>

// Register this check class (by creating a static instance of it).
// Disabled in release builds
namespace {
    CheckInternal instance;
}

void CheckInternal::checkTokenMatchPatterns()
{
    const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
    for (const Scope *scope : symbolDatabase->functionScopes) {
        for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
            if (!Token::simpleMatch(tok, "Token :: Match (") && !Token::simpleMatch(tok, "Token :: findmatch ("))
                continue;

            const std::string& funcname = tok->strAt(2);

            // Get pattern string
            const Token *patternTok = tok->tokAt(4)->nextArgument();
            if (!patternTok || patternTok->tokType() != Token::eString)
                continue;

            const std::string pattern = patternTok->strValue();
            if (pattern.empty()) {
                simplePatternError(tok, pattern, funcname);
                continue;
            }

            if (pattern.find("||") != std::string::npos || pattern.find(" | ") != std::string::npos || pattern[0] == '|' || (pattern[pattern.length() - 1] == '|' && pattern[pattern.length() - 2] == ' '))
                orInComplexPattern(tok, pattern, funcname);

            // Check for signs of complex patterns
            if (pattern.find_first_of("[|") != std::string::npos)
                continue;
            if (pattern.find("!!") != std::string::npos)
                continue;

            bool complex = false;
            size_t index = pattern.find('%');
            while (index != std::string::npos) {
                if (pattern.length() <= index + 2) {
                    complex = true;
                    break;
                }
                if (pattern[index + 1] == 'o' && pattern[index + 2] == 'r') // %or% or %oror%
                    index = pattern.find('%', index + 1);
                else {
                    complex = true;
                    break;
                }
                index = pattern.find('%', index + 1);
            }
            if (!complex)
                simplePatternError(tok, pattern, funcname);
        }
    }
}

void CheckInternal::checkRedundantTokCheck()
{
    for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
        if (Token::Match(tok, "&& Token :: simpleMatch|Match|findsimplematch|findmatch (")) {
            // in code like
            // if (tok->previous() && Token::match(tok->previous(), "bla")) {}
            // the first tok->previous() check is redundant
            const Token *astOp1 = tok->astOperand1();
            const Token *astOp2 = getArguments(tok->tokAt(3))[0];
            if (Token::simpleMatch(astOp1, "&&")) {
                astOp1 = astOp1->astOperand2();
            }
            if (astOp1->expressionString() == astOp2->expressionString()) {
                checkRedundantTokCheckError(astOp2);
            }
            // if (!tok || !Token::match(tok, "foo"))
        } else if (Token::Match(tok, "%oror% ! Token :: simpleMatch|Match|findsimplematch|findmatch (")) {
            const Token *negTok = tok->next()->astParent()->astOperand1();
            if (Token::simpleMatch(negTok, "||")) {
                negTok = negTok->astOperand2();
            }
            // the first tok condition is negated
            if (Token::simpleMatch(negTok, "!")) {
                const Token *astOp1 = negTok->astOperand1();
                const Token *astOp2 = getArguments(tok->tokAt(4))[0];

                if (astOp1->expressionString() == astOp2->expressionString()) {
                    checkRedundantTokCheckError(astOp2);
                }
            }
        }
    }
}


void CheckInternal::checkRedundantTokCheckError(const Token* tok)
{
    reportError(tok, Severity::style, "redundantTokCheck",
                "Unnecessary check of \"" + (tok? tok->expressionString(): "") + "\", match-function already checks if it is null.");
}

void CheckInternal::checkTokenSimpleMatchPatterns()
{
    const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
    for (const Scope* scope : symbolDatabase->functionScopes) {
        for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
            if (!Token::simpleMatch(tok, "Token :: simpleMatch (") && !Token::simpleMatch(tok, "Token :: findsimplematch ("))
                continue;

            const std::string& funcname = tok->strAt(2);

            // Get pattern string
            const Token *patternTok = tok->tokAt(4)->nextArgument();
            if (!patternTok || patternTok->tokType() != Token::eString)
                continue;

            const std::string pattern = patternTok->strValue();
            if (pattern.empty()) {
                complexPatternError(tok, pattern, funcname);
                continue;
            }

            // Check for [xyz] usage - but exclude standalone square brackets
            unsigned int char_count = 0;
            for (const char c : pattern) {
                if (c == ' ') {
                    char_count = 0;
                } else if (c == ']') {
                    if (char_count > 0) {
                        complexPatternError(tok, pattern, funcname);
                        continue;
                    }
                } else {
                    ++char_count;
                }
            }

            // Check | usage: Count characters before the symbol
            char_count = 0;
            for (const char c : pattern) {
                if (c == ' ') {
                    char_count = 0;
                } else if (c == '|') {
                    if (char_count > 0) {
                        complexPatternError(tok, pattern, funcname);
                        continue;
                    }
                } else {
                    ++char_count;
                }
            }

            // Check for real errors
            if (pattern.length() > 1) {
                for (size_t j = 0; j < pattern.length() - 1; j++) {
                    if (pattern[j] == '%' && pattern[j + 1] != ' ')
                        complexPatternError(tok, pattern, funcname);
                    else if (pattern[j] == '!' && pattern[j + 1] == '!')
                        complexPatternError(tok, pattern, funcname);
                }
            }
        }
    }
}

namespace {
    const std::set<std::string> knownPatterns = {
        "%any%"
        , "%assign%"
        , "%bool%"
        , "%char%"
        , "%comp%"
        , "%num%"
        , "%op%"
        , "%cop%"
        , "%or%"
        , "%oror%"
        , "%str%"
        , "%type%"
        , "%name%"
        , "%var%"
        , "%varid%"
    };
}

void CheckInternal::checkMissingPercentCharacter()
{
    const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
    for (const Scope* scope : symbolDatabase->functionScopes) {
        for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
            if (!Token::simpleMatch(tok, "Token :: Match (") && !Token::simpleMatch(tok, "Token :: findmatch ("))
                continue;

            const std::string& funcname = tok->strAt(2);

            // Get pattern string
            const Token *patternTok = tok->tokAt(4)->nextArgument();
            if (!patternTok || patternTok->tokType() != Token::eString)
                continue;

            const std::string pattern = patternTok->strValue();

            for (auto knownPattern = knownPatterns.cbegin(); knownPattern != knownPatterns.cend(); ++knownPattern) {
                const std::string brokenPattern = knownPattern->substr(0, knownPattern->size() - 1);

                std::string::size_type pos = 0;
                while ((pos = pattern.find(brokenPattern, pos)) != std::string::npos) {
                    // Check if it's the full pattern
                    if (pattern.find(*knownPattern, pos) != pos) {
                        // Known whitelist of substrings
                        if ((brokenPattern == "%var" && pattern.find("%varid%", pos) == pos) ||
                            (brokenPattern == "%or" && pattern.find("%oror%", pos) == pos)) {
                            ++pos;
                            continue;
                        }

                        missingPercentCharacterError(tok, pattern, funcname);
                    }

                    ++pos;
                }
            }
        }
    }
}

void CheckInternal::checkUnknownPattern()
{
    const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
    for (const Scope* scope : symbolDatabase->functionScopes) {
        for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
            if (!Token::simpleMatch(tok, "Token :: Match (") && !Token::simpleMatch(tok, "Token :: findmatch ("))
                continue;

            // Get pattern string
            const Token *patternTok = tok->tokAt(4)->nextArgument();
            if (!patternTok || patternTok->tokType() != Token::eString)
                continue;

            const std::string pattern = patternTok->strValue();
            bool inBrackets = false;

            for (std::string::size_type j = 0; j < pattern.length() - 1; j++) {
                if (pattern[j] == '[' && (j == 0 || pattern[j - 1] == ' '))
                    inBrackets = true;
                else if (pattern[j] == ']')
                    inBrackets = false;
                else if (pattern[j] == '%' && pattern[j + 1] != ' ' && pattern[j + 1] != '|' && !inBrackets) {
                    const std::string::size_type end = pattern.find('%', j + 1);
                    if (end != std::string::npos) {
                        const std::string s = pattern.substr(j, end - j + 1);
                        if (knownPatterns.find(s) == knownPatterns.end())
                            unknownPatternError(tok, s);
                    }
                }
            }
        }
    }
}

void CheckInternal::checkRedundantNextPrevious()
{
    const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
    for (const Scope* scope : symbolDatabase->functionScopes) {
        for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
            if (tok->str() != ".")
                continue;
            tok = tok->next();

            if (Token::Match(tok, "previous ( ) . previous|next|tokAt|str|strAt|link|linkAt (") || Token::Match(tok, "next ( ) . previous|next|tokAt|str|strAt|link|linkAt (") ||
                (Token::simpleMatch(tok, "tokAt (") && Token::Match(tok->linkAt(1), ") . previous|next|tokAt|strAt|linkAt|str|link ("))) {
                const std::string& func1 = tok->str();
                const std::string& func2 = tok->linkAt(1)->strAt(2);

                if ((func2 == "previous" || func2 == "next" || func2 == "str" || func2 == "link") && tok->linkAt(1)->strAt(4) != ")")
                    continue;

                redundantNextPreviousError(tok, func1, func2);
            }
        }
    }
}

void CheckInternal::checkExtraWhitespace()
{
    const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
    for (const Scope* scope : symbolDatabase->functionScopes) {
        for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
            if (!Token::Match(tok, "Token :: simpleMatch|findsimplematch|Match|findmatch ("))
                continue;

            const std::string& funcname = tok->strAt(2);

            // Get pattern string
            const Token *patternTok = tok->tokAt(4)->nextArgument();
            if (!patternTok || patternTok->tokType() != Token::eString)
                continue;

            const std::string pattern = patternTok->strValue();
            if (!pattern.empty() && (pattern[0] == ' ' || *pattern.crbegin() == ' '))
                extraWhitespaceError(tok, pattern, funcname);

            // two whitespaces or more
            if (pattern.find("  ") != std::string::npos)
                extraWhitespaceError(tok, pattern, funcname);
        }
    }
}

void CheckInternal::multiComparePatternError(const Token* tok, const std::string& pattern, const std::string &funcname)
{
    reportError(tok, Severity::error, "multiComparePatternError",
                "Bad multicompare pattern (a %cmd% must be first unless it is %or%,%op%,%cop%,%name%,%oror%) inside Token::" + funcname + "() call: \"" + pattern + "\""
                );
}

void CheckInternal::simplePatternError(const Token* tok, const std::string& pattern, const std::string &funcname)
{
    reportError(tok, Severity::warning, "simplePatternError",
                "Found simple pattern inside Token::" + funcname + "() call: \"" + pattern + "\""
                );
}

void CheckInternal::complexPatternError(const Token* tok, const std::string& pattern, const std::string &funcname)
{
    reportError(tok, Severity::error, "complexPatternError",
                "Found complex pattern inside Token::" + funcname + "() call: \"" + pattern + "\""
                );
}

void CheckInternal::missingPercentCharacterError(const Token* tok, const std::string& pattern, const std::string& funcname)
{
    reportError(tok, Severity::error, "missingPercentCharacter",
                "Missing percent end character in Token::" + funcname + "() pattern: \"" + pattern + "\""
                );
}

void CheckInternal::unknownPatternError(const Token* tok, const std::string& pattern)
{
    reportError(tok, Severity::error, "unknownPattern",
                "Unknown pattern used: \"" + pattern + "\"");
}

void CheckInternal::redundantNextPreviousError(const Token* tok, const std::string& func1, const std::string& func2)
{
    reportError(tok, Severity::style, "redundantNextPrevious",
                "Call to 'Token::" + func1 + "()' followed by 'Token::" + func2 + "()' can be simplified.");
}

void CheckInternal::orInComplexPattern(const Token* tok, const std::string& pattern, const std::string &funcname)
{
    reportError(tok, Severity::error, "orInComplexPattern",
                "Token::" + funcname + "() pattern \"" + pattern + "\" contains \"||\" or \"|\". Replace it by \"%oror%\" or \"%or%\".");
}

void CheckInternal::extraWhitespaceError(const Token* tok, const std::string& pattern, const std::string &funcname)
{
    reportError(tok, Severity::warning, "extraWhitespaceError",
                "Found extra whitespace inside Token::" + funcname + "() call: \"" + pattern + "\""
                );
}

void CheckInternal::runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger)
{
    if (!tokenizer.getSettings().checks.isEnabled(Checks::internalCheck))
        return;

    CheckInternal checkInternal(&tokenizer, &tokenizer.getSettings(), errorLogger);

    checkInternal.checkTokenMatchPatterns();
    checkInternal.checkTokenSimpleMatchPatterns();
    checkInternal.checkMissingPercentCharacter();
    checkInternal.checkUnknownPattern();
    checkInternal.checkRedundantNextPrevious();
    checkInternal.checkExtraWhitespace();
    checkInternal.checkRedundantTokCheck();
}

void CheckInternal::getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const
{
    CheckInternal c(nullptr, settings, errorLogger);
    c.multiComparePatternError(nullptr, ";|%type%", "Match");
    c.simplePatternError(nullptr, "class {", "Match");
    c.complexPatternError(nullptr, "%type% ( )", "Match");
    c.missingPercentCharacterError(nullptr, "%num", "Match");
    c.unknownPatternError(nullptr, "%typ");
    c.redundantNextPreviousError(nullptr, "previous", "next");
    c.orInComplexPattern(nullptr, "||", "Match");
    c.extraWhitespaceError(nullptr, "%str% ", "Match");
    c.checkRedundantTokCheckError(nullptr);
}

#endif // #ifdef CHECK_INTERNAL