ID
int64 1
1.09k
| Language
stringclasses 1
value | Repository Name
stringclasses 8
values | File Name
stringlengths 3
35
| File Path in Repository
stringlengths 9
82
| File Path for Unit Test
stringclasses 5
values | Code
stringlengths 17
1.91M
| Unit Test - (Ground Truth)
stringclasses 5
values |
---|---|---|---|---|---|---|---|
1,001 | cpp | cppcheck | testprogrammemory.cpp | test/testprogrammemory.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#include "config.h"
#include "fixture.h"
#include "helpers.h"
#include "token.h"
#include "programmemory.h"
#include "vfvalue.h"
class TestProgramMemory : public TestFixture {
public:
TestProgramMemory() : TestFixture("TestProgramMemory") {}
private:
void run() override {
TEST_CASE(copyOnWrite);
}
void copyOnWrite() const {
SimpleTokenList tokenlist("1+1;");
Token* tok = tokenlist.front();
const nonneg int id = 123;
tok->exprId(id);
ProgramMemory pm;
const ValueFlow::Value* v = pm.getValue(id);
ASSERT(!v);
pm.setValue(tok, ValueFlow::Value{41});
v = pm.getValue(id);
ASSERT(v);
ASSERT_EQUALS(41, v->intvalue);
// create a copy
ProgramMemory pm2 = pm;
// make sure the value was copied
v = pm2.getValue(id);
ASSERT(v);
ASSERT_EQUALS(41, v->intvalue);
// set a value in the copy to trigger copy-on-write
pm2.setValue(tok, ValueFlow::Value{42});
// make another copy and set another value
ProgramMemory pm3 = pm2;
// set a value in the copy to trigger copy-on-write
pm3.setValue(tok, ValueFlow::Value{43});
// make sure the value was set
v = pm2.getValue(id);
ASSERT(v);
ASSERT_EQUALS(42, v->intvalue);
// make sure the value was set
v = pm3.getValue(id);
ASSERT(v);
ASSERT_EQUALS(43, v->intvalue);
// make sure the original value remains unchanged
v = pm.getValue(id);
ASSERT(v);
ASSERT_EQUALS(41, v->intvalue);
}
};
REGISTER_TEST(TestProgramMemory)
| null |
1,002 | cpp | cppcheck | testsymboldatabase.cpp | test/testsymboldatabase.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#include "errortypes.h"
#include "fixture.h"
#include "helpers.h"
#include "platform.h"
#include "settings.h"
#include "sourcelocation.h"
#include "symboldatabase.h"
#include "token.h"
#include "tokenize.h"
#include "tokenlist.h"
#include <algorithm>
#include <cstdint>
#include <cstring>
#include <iterator>
#include <limits>
#include <list>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
class TestSymbolDatabase;
#define GET_SYMBOL_DB(code) \
SimpleTokenizer tokenizer(settings1, *this); \
const SymbolDatabase *db = getSymbolDB_inner(tokenizer, code, true); \
ASSERT(db); \
do {} while (false)
#define GET_SYMBOL_DB_C(code) \
SimpleTokenizer tokenizer(settings1, *this); \
const SymbolDatabase *db = getSymbolDB_inner(tokenizer, code, false); \
do {} while (false)
#define GET_SYMBOL_DB_DBG(code) \
SimpleTokenizer tokenizer(settingsDbg, *this); \
const SymbolDatabase *db = getSymbolDB_inner(tokenizer, code, true); \
ASSERT(db); \
do {} while (false)
class TestSymbolDatabase : public TestFixture {
public:
TestSymbolDatabase() : TestFixture("TestSymbolDatabase") {}
private:
const Token* vartok{nullptr};
const Token* typetok{nullptr};
const Settings settings1 = settingsBuilder().library("std.cfg").build();
const Settings settings2 = settingsBuilder().platform(Platform::Type::Unspecified).build();
const Settings settingsDbg = settingsBuilder().library("std.cfg").debugwarnings(true).build();
void reset() {
vartok = nullptr;
typetok = nullptr;
}
template<size_t size>
static const SymbolDatabase* getSymbolDB_inner(SimpleTokenizer& tokenizer, const char (&code)[size], bool cpp) {
return tokenizer.tokenize(code, cpp) ? tokenizer.getSymbolDatabase() : nullptr;
}
static const Token* findToken(Tokenizer& tokenizer, const std::string& expr, unsigned int exprline)
{
for (const Token* tok = tokenizer.tokens(); tok; tok = tok->next()) {
if (Token::simpleMatch(tok, expr.c_str(), expr.size()) && tok->linenr() == exprline) {
return tok;
}
}
return nullptr;
}
static std::string asExprIdString(const Token* tok)
{
return tok->expressionString() + "@" + std::to_string(tok->exprId());
}
template<size_t size>
std::string testExprIdEqual(const char (&code)[size],
const std::string& expr1,
unsigned int exprline1,
const std::string& expr2,
unsigned int exprline2,
SourceLocation loc = SourceLocation::current())
{
SimpleTokenizer tokenizer(settings1, *this);
ASSERT_LOC(tokenizer.tokenize(code), loc.file_name(), loc.line());
const Token* tok1 = findToken(tokenizer, expr1, exprline1);
const Token* tok2 = findToken(tokenizer, expr2, exprline2);
if (!tok1)
return "'" + expr1 + "'" + " not found";
if (!tok2)
return "'" + expr2 + "'" + " not found";
if (tok1->exprId() == 0)
return asExprIdString(tok1) + " has not exprId";
if (tok2->exprId() == 0)
return asExprIdString(tok2) + " has not exprId";
if (tok1->exprId() != tok2->exprId())
return asExprIdString(tok1) + " != " + asExprIdString(tok2);
return "";
}
template<size_t size>
bool testExprIdNotEqual(const char (&code)[size],
const std::string& expr1,
unsigned int exprline1,
const std::string& expr2,
unsigned int exprline2,
SourceLocation loc = SourceLocation::current())
{
std::string result = testExprIdEqual(code, expr1, exprline1, expr2, exprline2, loc);
return !result.empty();
}
static const Scope *findFunctionScopeByToken(const SymbolDatabase * db, const Token *tok) {
std::list<Scope>::const_iterator scope;
for (scope = db->scopeList.cbegin(); scope != db->scopeList.cend(); ++scope) {
if (scope->type == Scope::eFunction) {
if (scope->classDef == tok)
return &(*scope);
}
}
return nullptr;
}
static const Function *findFunctionByName(const char str[], const Scope* startScope) {
const Scope* currScope = startScope;
while (currScope && currScope->isExecutable()) {
if (currScope->functionOf)
currScope = currScope->functionOf;
else
currScope = currScope->nestedIn;
}
while (currScope) {
auto it = std::find_if(currScope->functionList.cbegin(), currScope->functionList.cend(), [&](const Function& f) {
return f.tokenDef->str() == str;
});
if (it != currScope->functionList.end())
return &*it;
currScope = currScope->nestedIn;
}
return nullptr;
}
void run() override {
TEST_CASE(array);
TEST_CASE(array_ptr);
TEST_CASE(stlarray1);
TEST_CASE(stlarray2);
TEST_CASE(stlarray3);
TEST_CASE(test_isVariableDeclarationCanHandleNull);
TEST_CASE(test_isVariableDeclarationIdentifiesSimpleDeclaration);
TEST_CASE(test_isVariableDeclarationIdentifiesInitialization);
TEST_CASE(test_isVariableDeclarationIdentifiesCpp11Initialization);
TEST_CASE(test_isVariableDeclarationIdentifiesScopedDeclaration);
TEST_CASE(test_isVariableDeclarationIdentifiesStdDeclaration);
TEST_CASE(test_isVariableDeclarationIdentifiesScopedStdDeclaration);
TEST_CASE(test_isVariableDeclarationIdentifiesManyScopes);
TEST_CASE(test_isVariableDeclarationIdentifiesPointers);
TEST_CASE(test_isVariableDeclarationIdentifiesPointers2);
TEST_CASE(test_isVariableDeclarationDoesNotIdentifyConstness);
TEST_CASE(test_isVariableDeclarationIdentifiesFirstOfManyVariables);
TEST_CASE(test_isVariableDeclarationIdentifiesScopedPointerDeclaration);
TEST_CASE(test_isVariableDeclarationIdentifiesDeclarationWithIndirection);
TEST_CASE(test_isVariableDeclarationIdentifiesDeclarationWithMultipleIndirection);
TEST_CASE(test_isVariableDeclarationIdentifiesArray);
TEST_CASE(test_isVariableDeclarationIdentifiesPointerArray);
TEST_CASE(test_isVariableDeclarationIdentifiesOfArrayPointers1);
TEST_CASE(test_isVariableDeclarationIdentifiesOfArrayPointers2);
TEST_CASE(test_isVariableDeclarationIdentifiesOfArrayPointers3);
TEST_CASE(test_isVariableDeclarationIdentifiesArrayOfFunctionPointers);
TEST_CASE(isVariableDeclarationIdentifiesTemplatedPointerVariable);
TEST_CASE(isVariableDeclarationIdentifiesTemplatedPointerToPointerVariable);
TEST_CASE(isVariableDeclarationIdentifiesTemplatedArrayVariable);
TEST_CASE(isVariableDeclarationIdentifiesTemplatedVariable);
TEST_CASE(isVariableDeclarationIdentifiesTemplatedVariableIterator);
TEST_CASE(isVariableDeclarationIdentifiesNestedTemplateVariable);
TEST_CASE(isVariableDeclarationIdentifiesReference);
TEST_CASE(isVariableDeclarationDoesNotIdentifyTemplateClass);
TEST_CASE(isVariableDeclarationDoesNotIdentifyCppCast);
TEST_CASE(isVariableDeclarationPointerConst);
TEST_CASE(isVariableDeclarationRValueRef);
TEST_CASE(isVariableDeclarationDoesNotIdentifyCase);
TEST_CASE(isVariableDeclarationIf);
TEST_CASE(isVariableStlType);
TEST_CASE(isVariablePointerToConstPointer);
TEST_CASE(isVariablePointerToVolatilePointer);
TEST_CASE(isVariablePointerToConstVolatilePointer);
TEST_CASE(isVariableMultiplePointersAndQualifiers);
TEST_CASE(variableVolatile);
TEST_CASE(variableConstexpr);
TEST_CASE(isVariableDecltype);
TEST_CASE(isVariableAlignas);
TEST_CASE(VariableValueType1);
TEST_CASE(VariableValueType2);
TEST_CASE(VariableValueType3);
TEST_CASE(VariableValueType4); // smart pointer type
TEST_CASE(VariableValueType5); // smart pointer type
TEST_CASE(VariableValueType6); // smart pointer type
TEST_CASE(VariableValueTypeReferences);
TEST_CASE(VariableValueTypeTemplate);
TEST_CASE(findVariableType1);
TEST_CASE(findVariableType2);
TEST_CASE(findVariableType3);
TEST_CASE(findVariableTypeExternC);
TEST_CASE(rangeBasedFor);
TEST_CASE(memberVar1);
TEST_CASE(arrayMemberVar1);
TEST_CASE(arrayMemberVar2);
TEST_CASE(arrayMemberVar3);
TEST_CASE(arrayMemberVar4);
TEST_CASE(staticMemberVar);
TEST_CASE(getVariableFromVarIdBoundsCheck);
TEST_CASE(hasRegularFunction);
TEST_CASE(hasRegularFunction_trailingReturnType);
TEST_CASE(hasInlineClassFunction);
TEST_CASE(hasInlineClassFunction_trailingReturnType);
TEST_CASE(hasMissingInlineClassFunction);
TEST_CASE(hasClassFunction);
TEST_CASE(hasClassFunction_trailingReturnType);
TEST_CASE(hasClassFunction_decltype_auto);
TEST_CASE(hasRegularFunctionReturningFunctionPointer);
TEST_CASE(hasInlineClassFunctionReturningFunctionPointer);
TEST_CASE(hasMissingInlineClassFunctionReturningFunctionPointer);
TEST_CASE(hasInlineClassOperatorTemplate);
TEST_CASE(hasClassFunctionReturningFunctionPointer);
TEST_CASE(methodWithRedundantScope);
TEST_CASE(complexFunctionArrayPtr);
TEST_CASE(pointerToMemberFunction);
TEST_CASE(hasSubClassConstructor);
TEST_CASE(testConstructors);
TEST_CASE(functionDeclarationTemplate);
TEST_CASE(functionDeclarations);
TEST_CASE(functionDeclarations2);
TEST_CASE(constexprFunction);
TEST_CASE(constructorInitialization);
TEST_CASE(memberFunctionOfUnknownClassMacro1);
TEST_CASE(memberFunctionOfUnknownClassMacro2);
TEST_CASE(memberFunctionOfUnknownClassMacro3);
TEST_CASE(functionLinkage);
TEST_CASE(externalFunctionsInsideAFunction); // #12420
TEST_CASE(namespacedFunctionInsideExternBlock); // #12420
TEST_CASE(classWithFriend);
TEST_CASE(parseFunctionCorrect);
TEST_CASE(parseFunctionDeclarationCorrect);
TEST_CASE(Cpp11InitInInitList);
TEST_CASE(hasGlobalVariables1);
TEST_CASE(hasGlobalVariables2);
TEST_CASE(hasGlobalVariables3);
TEST_CASE(checkTypeStartEndToken1);
TEST_CASE(checkTypeStartEndToken2); // handling for unknown macro: 'void f() MACRO {..'
TEST_CASE(checkTypeStartEndToken3); // no variable name: void f(const char){}
TEST_CASE(functionArgs1);
TEST_CASE(functionArgs2);
TEST_CASE(functionArgs4);
TEST_CASE(functionArgs5); // #7650
TEST_CASE(functionArgs6); // #7651
TEST_CASE(functionArgs7); // #7652
TEST_CASE(functionArgs8); // #7653
TEST_CASE(functionArgs9); // #7657
TEST_CASE(functionArgs10);
TEST_CASE(functionArgs11);
TEST_CASE(functionArgs12); // #7661
TEST_CASE(functionArgs13); // #7697
TEST_CASE(functionArgs14); // #9055
TEST_CASE(functionArgs15); // #7159
TEST_CASE(functionArgs16); // #9591
TEST_CASE(functionArgs17);
TEST_CASE(functionArgs18); // #10376
TEST_CASE(functionArgs19); // #10376
TEST_CASE(functionArgs20);
TEST_CASE(functionArgs21);
TEST_CASE(functionImplicitlyVirtual);
TEST_CASE(functionGetOverridden);
TEST_CASE(functionIsInlineKeyword);
TEST_CASE(functionStatic);
TEST_CASE(functionReturnsReference); // Function::returnsReference
TEST_CASE(namespaces1);
TEST_CASE(namespaces2);
TEST_CASE(namespaces3); // #3854 - unknown macro
TEST_CASE(namespaces4);
TEST_CASE(needInitialization);
TEST_CASE(tryCatch1);
TEST_CASE(symboldatabase1);
TEST_CASE(symboldatabase2);
TEST_CASE(symboldatabase3); // ticket #2000
TEST_CASE(symboldatabase4);
TEST_CASE(symboldatabase5); // ticket #2178
TEST_CASE(symboldatabase6); // ticket #2221
TEST_CASE(symboldatabase7); // ticket #2230
TEST_CASE(symboldatabase8); // ticket #2252
TEST_CASE(symboldatabase9); // ticket #2525
TEST_CASE(symboldatabase10); // ticket #2537
TEST_CASE(symboldatabase11); // ticket #2539
TEST_CASE(symboldatabase12); // ticket #2547
TEST_CASE(symboldatabase13); // ticket #2577
TEST_CASE(symboldatabase14); // ticket #2589
TEST_CASE(symboldatabase17); // ticket #2657
TEST_CASE(symboldatabase19); // ticket #2991 (segmentation fault)
TEST_CASE(symboldatabase20); // ticket #3013 (segmentation fault)
TEST_CASE(symboldatabase21);
TEST_CASE(symboldatabase22); // ticket #3437 (segmentation fault)
TEST_CASE(symboldatabase23); // ticket #3435
TEST_CASE(symboldatabase24); // ticket #3508 (constructor, destructor)
TEST_CASE(symboldatabase25); // ticket #3561 (throw C++)
TEST_CASE(symboldatabase26); // ticket #3561 (throw C)
TEST_CASE(symboldatabase27); // ticket #3543 (segmentation fault)
TEST_CASE(symboldatabase28);
TEST_CASE(symboldatabase29); // ticket #4442 (segmentation fault)
TEST_CASE(symboldatabase30);
TEST_CASE(symboldatabase31);
TEST_CASE(symboldatabase32);
TEST_CASE(symboldatabase33); // ticket #4682 (false negatives)
TEST_CASE(symboldatabase34); // ticket #4694 (segmentation fault)
TEST_CASE(symboldatabase35); // ticket #4806 (segmentation fault)
TEST_CASE(symboldatabase36); // ticket #4892 (segmentation fault)
TEST_CASE(symboldatabase37);
TEST_CASE(symboldatabase38); // ticket #5125 (infinite recursion)
TEST_CASE(symboldatabase40); // ticket #5153
TEST_CASE(symboldatabase41); // ticket #5197 (unknown macro)
TEST_CASE(symboldatabase42); // only put variables in variable list
TEST_CASE(symboldatabase43); // #4738
TEST_CASE(symboldatabase44);
TEST_CASE(symboldatabase45); // #6125
TEST_CASE(symboldatabase46); // #6171 (anonymous namespace)
TEST_CASE(symboldatabase47); // #6308
TEST_CASE(symboldatabase48); // #6417
TEST_CASE(symboldatabase49); // #6424
TEST_CASE(symboldatabase50); // #6432
TEST_CASE(symboldatabase51); // #6538
TEST_CASE(symboldatabase52); // #6581
TEST_CASE(symboldatabase53); // #7124 (library podtype)
TEST_CASE(symboldatabase54); // #7257
TEST_CASE(symboldatabase55); // #7767 (return unknown macro)
TEST_CASE(symboldatabase56); // #7909
TEST_CASE(symboldatabase57);
TEST_CASE(symboldatabase58); // #6985 (using namespace type lookup)
TEST_CASE(symboldatabase59);
TEST_CASE(symboldatabase60);
TEST_CASE(symboldatabase61);
TEST_CASE(symboldatabase62);
TEST_CASE(symboldatabase63);
TEST_CASE(symboldatabase64);
TEST_CASE(symboldatabase65);
TEST_CASE(symboldatabase66); // #8540
TEST_CASE(symboldatabase67); // #8538
TEST_CASE(symboldatabase68); // #8560
TEST_CASE(symboldatabase69);
TEST_CASE(symboldatabase70);
TEST_CASE(symboldatabase71);
TEST_CASE(symboldatabase72); // #8600
TEST_CASE(symboldatabase74); // #8838 - final
TEST_CASE(symboldatabase75);
TEST_CASE(symboldatabase76); // #9056
TEST_CASE(symboldatabase77); // #8663
TEST_CASE(symboldatabase78); // #9147
TEST_CASE(symboldatabase79); // #9392
TEST_CASE(symboldatabase80); // #9389
TEST_CASE(symboldatabase81); // #9411
TEST_CASE(symboldatabase82);
TEST_CASE(symboldatabase83); // #9431
TEST_CASE(symboldatabase84);
TEST_CASE(symboldatabase85);
TEST_CASE(symboldatabase86);
TEST_CASE(symboldatabase87); // #9922 'extern const char ( * x [ 256 ] ) ;'
TEST_CASE(symboldatabase88); // #10040 (using namespace)
TEST_CASE(symboldatabase89); // valuetype name
TEST_CASE(symboldatabase90);
TEST_CASE(symboldatabase91);
TEST_CASE(symboldatabase92); // daca crash
TEST_CASE(symboldatabase93); // alignas attribute
TEST_CASE(symboldatabase94); // structured bindings
TEST_CASE(symboldatabase95); // #10295
TEST_CASE(symboldatabase96); // #10126
TEST_CASE(symboldatabase97); // #10598 - final class
TEST_CASE(symboldatabase98); // #10451
TEST_CASE(symboldatabase99); // #10864
TEST_CASE(symboldatabase100); // #10174
TEST_CASE(symboldatabase101);
TEST_CASE(symboldatabase102);
TEST_CASE(symboldatabase103);
TEST_CASE(symboldatabase104);
TEST_CASE(symboldatabase105);
TEST_CASE(symboldatabase106);
TEST_CASE(symboldatabase107);
TEST_CASE(symboldatabase108);
TEST_CASE(createSymbolDatabaseFindAllScopes1);
TEST_CASE(createSymbolDatabaseFindAllScopes2);
TEST_CASE(createSymbolDatabaseFindAllScopes3);
TEST_CASE(createSymbolDatabaseFindAllScopes4);
TEST_CASE(createSymbolDatabaseFindAllScopes5);
TEST_CASE(createSymbolDatabaseFindAllScopes6);
TEST_CASE(createSymbolDatabaseFindAllScopes7);
TEST_CASE(createSymbolDatabaseFindAllScopes8); // #12761
TEST_CASE(createSymbolDatabaseFindAllScopes9);
TEST_CASE(createSymbolDatabaseIncompleteVars);
TEST_CASE(enum1);
TEST_CASE(enum2);
TEST_CASE(enum3);
TEST_CASE(enum4);
TEST_CASE(enum5);
TEST_CASE(enum6);
TEST_CASE(enum7);
TEST_CASE(enum8);
TEST_CASE(enum9);
TEST_CASE(enum10); // #11001
TEST_CASE(enum11);
TEST_CASE(enum12);
TEST_CASE(enum13);
TEST_CASE(enum14);
TEST_CASE(enum15);
TEST_CASE(enum16);
TEST_CASE(enum17);
TEST_CASE(enum18);
TEST_CASE(sizeOfType);
TEST_CASE(isImplicitlyVirtual);
TEST_CASE(isPure);
TEST_CASE(isFunction1); // UNKNOWN_MACRO(a,b) { .. }
TEST_CASE(isFunction2);
TEST_CASE(isFunction3);
TEST_CASE(findFunction1);
TEST_CASE(findFunction2); // mismatch: parameter passed by address => reference argument
TEST_CASE(findFunction3);
TEST_CASE(findFunction4);
TEST_CASE(findFunction5); // #6230
TEST_CASE(findFunction6);
TEST_CASE(findFunction7); // #6700
TEST_CASE(findFunction8);
TEST_CASE(findFunction9);
TEST_CASE(findFunction10); // #7673
TEST_CASE(findFunction12);
TEST_CASE(findFunction13);
TEST_CASE(findFunction14);
TEST_CASE(findFunction15);
TEST_CASE(findFunction16);
TEST_CASE(findFunction17);
TEST_CASE(findFunction18);
TEST_CASE(findFunction19);
TEST_CASE(findFunction20); // #8280
TEST_CASE(findFunction21);
TEST_CASE(findFunction22);
TEST_CASE(findFunction23);
TEST_CASE(findFunction24); // smart pointer
TEST_CASE(findFunction25); // std::vector<std::shared_ptr<Fred>>
TEST_CASE(findFunction26); // #8668 - pointer parameter in function call, const pointer function argument
TEST_CASE(findFunction27);
TEST_CASE(findFunction28);
TEST_CASE(findFunction29);
TEST_CASE(findFunction30);
TEST_CASE(findFunction31);
TEST_CASE(findFunction32); // C: relax type matching
TEST_CASE(findFunction33); // #9885 variadic function
TEST_CASE(findFunction34); // #10061
TEST_CASE(findFunction35);
TEST_CASE(findFunction36); // #10122
TEST_CASE(findFunction37); // #10124
TEST_CASE(findFunction38); // #10125
TEST_CASE(findFunction39); // #10127
TEST_CASE(findFunction40); // #10135
TEST_CASE(findFunction41); // #10202
TEST_CASE(findFunction42);
TEST_CASE(findFunction43); // #10087
TEST_CASE(findFunction44); // #11182
TEST_CASE(findFunction45);
TEST_CASE(findFunction46);
TEST_CASE(findFunction47);
TEST_CASE(findFunction48);
TEST_CASE(findFunction49); // #11888
TEST_CASE(findFunction50); // #11904 - method with same name and arguments in derived class
TEST_CASE(findFunction51); // #11975 - method with same name in derived class
TEST_CASE(findFunction52);
TEST_CASE(findFunction53);
TEST_CASE(findFunction54);
TEST_CASE(findFunction55); // #13004
TEST_CASE(findFunction56);
TEST_CASE(findFunction57);
TEST_CASE(findFunction58); // #13310
TEST_CASE(findFunctionRef1);
TEST_CASE(findFunctionRef2); // #13328
TEST_CASE(findFunctionContainer);
TEST_CASE(findFunctionExternC);
TEST_CASE(findFunctionGlobalScope); // ::foo
TEST_CASE(overloadedFunction1);
TEST_CASE(valueTypeMatchParameter); // ValueType::matchParameter
TEST_CASE(noexceptFunction1);
TEST_CASE(noexceptFunction2);
TEST_CASE(noexceptFunction3);
TEST_CASE(noexceptFunction4);
TEST_CASE(throwFunction1);
TEST_CASE(throwFunction2);
TEST_CASE(constAttributeFunction);
TEST_CASE(pureAttributeFunction);
TEST_CASE(nothrowAttributeFunction);
TEST_CASE(nothrowDeclspecFunction);
TEST_CASE(noreturnAttributeFunction);
TEST_CASE(nodiscardAttributeFunction);
TEST_CASE(varTypesIntegral); // known integral
TEST_CASE(varTypesFloating); // known floating
TEST_CASE(varTypesOther); // (un)known
TEST_CASE(functionPrototype); // #5867
TEST_CASE(lambda); // #5867
TEST_CASE(lambda2); // #7473
TEST_CASE(lambda3);
TEST_CASE(lambda4);
TEST_CASE(lambda5);
TEST_CASE(circularDependencies); // #6298
TEST_CASE(executableScopeWithUnknownFunction);
TEST_CASE(valueType1);
TEST_CASE(valueType2);
TEST_CASE(valueType3);
TEST_CASE(valueTypeThis);
TEST_CASE(variadic1); // #7453
TEST_CASE(variadic2); // #7649
TEST_CASE(variadic3); // #7387
TEST_CASE(noReturnType);
TEST_CASE(auto1);
TEST_CASE(auto2);
TEST_CASE(auto3);
TEST_CASE(auto4);
TEST_CASE(auto5);
TEST_CASE(auto6); // #7963 (segmentation fault)
TEST_CASE(auto7);
TEST_CASE(auto8);
TEST_CASE(auto9); // #8044 (segmentation fault)
TEST_CASE(auto10); // #8020
TEST_CASE(auto11); // #8964 - const auto startX = x;
TEST_CASE(auto12); // #8993 - const std::string &x; auto y = x; if (y.empty()) ..
TEST_CASE(auto13);
TEST_CASE(auto14);
TEST_CASE(auto15); // C++17 auto deduction from braced-init-list
TEST_CASE(auto16);
TEST_CASE(auto17); // #11163
TEST_CASE(auto18);
TEST_CASE(auto19);
TEST_CASE(auto20);
TEST_CASE(auto21);
TEST_CASE(auto22);
TEST_CASE(unionWithConstructor);
TEST_CASE(incomplete_type); // #9255 (infinite recursion)
TEST_CASE(exprIds);
TEST_CASE(testValuetypeOriginalName);
}
void array() {
GET_SYMBOL_DB_C("int a[10+2];");
ASSERT(db != nullptr);
ASSERT(db->variableList().size() == 2); // the first one is not used
const Variable * v = db->getVariableFromVarId(1);
ASSERT(v != nullptr);
ASSERT(v->isArray());
ASSERT_EQUALS(1U, v->dimensions().size());
ASSERT_EQUALS(12U, v->dimension(0));
}
void array_ptr() {
GET_SYMBOL_DB("const char* a[] = { \"abc\" };\n"
"const char* b[] = { \"def\", \"ghijkl\" };");
ASSERT(db != nullptr);
ASSERT(db->variableList().size() == 3); // the first one is not used
const Variable* v = db->getVariableFromVarId(1);
ASSERT(v != nullptr);
ASSERT(v->isArray());
ASSERT(v->isPointerArray());
ASSERT_EQUALS(1U, v->dimensions().size());
ASSERT_EQUALS(1U, v->dimension(0));
v = db->getVariableFromVarId(2);
ASSERT(v != nullptr);
ASSERT(v->isArray());
ASSERT(v->isPointerArray());
ASSERT_EQUALS(1U, v->dimensions().size());
ASSERT_EQUALS(2U, v->dimension(0));
}
void stlarray1() {
GET_SYMBOL_DB("std::array<int, 16 + 4> arr;");
ASSERT(db != nullptr);
ASSERT_EQUALS(2, db->variableList().size()); // the first one is not used
const Variable * v = db->getVariableFromVarId(1);
ASSERT(v != nullptr);
ASSERT(v->isArray());
ASSERT_EQUALS(1U, v->dimensions().size());
ASSERT_EQUALS(20U, v->dimension(0));
}
void stlarray2() {
GET_SYMBOL_DB("constexpr int sz = 16; std::array<int, sz + 4> arr;");
ASSERT(db != nullptr);
ASSERT_EQUALS(3, db->variableList().size()); // the first one is not used
const Variable * v = db->getVariableFromVarId(2);
ASSERT(v != nullptr);
ASSERT(v->isArray());
ASSERT_EQUALS(1U, v->dimensions().size());
ASSERT_EQUALS(20U, v->dimension(0));
}
void stlarray3() {
GET_SYMBOL_DB("std::array<int, 4> a;\n"
"std::array<int, 4> b[2];\n"
"const std::array<int, 4>& r = a;\n");
ASSERT(db != nullptr);
ASSERT_EQUALS(4, db->variableList().size()); // the first one is not used
auto it = db->variableList().begin() + 1;
ASSERT((*it)->isArray());
ASSERT(!(*it)->isPointer());
ASSERT(!(*it)->isReference());
ASSERT_EQUALS(1U, (*it)->dimensions().size());
ASSERT_EQUALS(4U, (*it)->dimension(0));
const ValueType* vt = (*it)->valueType();
ASSERT(vt);
ASSERT(vt->container);
ASSERT_EQUALS(vt->pointer, 0);
const Token* tok = (*it)->nameToken();
ASSERT(tok && (vt = tok->valueType()));
ASSERT_EQUALS(vt->pointer, 0);
++it;
ASSERT((*it)->isArray());
ASSERT(!(*it)->isPointer());
ASSERT(!(*it)->isReference());
ASSERT_EQUALS(1U, (*it)->dimensions().size());
ASSERT_EQUALS(4U, (*it)->dimension(0));
vt = (*it)->valueType();
ASSERT_EQUALS(vt->pointer, 0);
tok = (*it)->nameToken();
ASSERT(tok && (vt = tok->valueType()));
ASSERT_EQUALS(vt->pointer, 1);
++it;
ASSERT((*it)->isArray());
ASSERT(!(*it)->isPointer());
ASSERT((*it)->isReference());
ASSERT((*it)->isConst());
ASSERT_EQUALS(1U, (*it)->dimensions().size());
ASSERT_EQUALS(4U, (*it)->dimension(0));
vt = (*it)->valueType();
ASSERT_EQUALS(vt->pointer, 0);
ASSERT(vt->reference == Reference::LValue);
tok = (*it)->nameToken();
ASSERT(tok && (vt = tok->valueType()));
ASSERT_EQUALS(vt->pointer, 0);
ASSERT_EQUALS(vt->constness, 1);
ASSERT(vt->reference == Reference::LValue);
}
void test_isVariableDeclarationCanHandleNull() {
reset();
GET_SYMBOL_DB("void main(){}");
const bool result = db->scopeList.front().isVariableDeclaration(nullptr, vartok, typetok);
ASSERT_EQUALS(false, result);
ASSERT(nullptr == vartok);
ASSERT(nullptr == typetok);
Variable v(nullptr, nullptr, nullptr, 0, AccessControl::Public, nullptr, nullptr, settings1);
}
void test_isVariableDeclarationIdentifiesSimpleDeclaration() {
reset();
GET_SYMBOL_DB("int x;");
const bool result = db->scopeList.front().isVariableDeclaration(tokenizer.tokens(), vartok, typetok);
ASSERT_EQUALS(true, result);
ASSERT_EQUALS("x", vartok->str());
ASSERT_EQUALS("int", typetok->str());
Variable v(vartok, typetok, vartok->previous(), 0, AccessControl::Public, nullptr, nullptr, settings1);
ASSERT(false == v.isArray());
ASSERT(false == v.isPointer());
ASSERT(false == v.isReference());
}
void test_isVariableDeclarationIdentifiesInitialization() {
reset();
GET_SYMBOL_DB("int x (1);");
const bool result = db->scopeList.front().isVariableDeclaration(tokenizer.tokens(), vartok, typetok);
ASSERT_EQUALS(true, result);
ASSERT_EQUALS("x", vartok->str());
ASSERT_EQUALS("int", typetok->str());
Variable v(vartok, typetok, vartok->previous(), 0, AccessControl::Public, nullptr, nullptr, settings1);
ASSERT(false == v.isArray());
ASSERT(false == v.isPointer());
ASSERT(false == v.isReference());
}
void test_isVariableDeclarationIdentifiesCpp11Initialization() {
reset();
GET_SYMBOL_DB("int x {1};");
const bool result = db->scopeList.front().isVariableDeclaration(tokenizer.tokens(), vartok, typetok);
ASSERT_EQUALS(true, result);
ASSERT_EQUALS("x", vartok->str());
ASSERT_EQUALS("int", typetok->str());
Variable v(vartok, typetok, vartok->previous(), 0, AccessControl::Public, nullptr, nullptr, settings1);
ASSERT(false == v.isArray());
ASSERT(false == v.isPointer());
ASSERT(false == v.isReference());
}
void test_isVariableDeclarationIdentifiesScopedDeclaration() {
reset();
GET_SYMBOL_DB("::int x;");
const bool result = db->scopeList.front().isVariableDeclaration(tokenizer.tokens(), vartok, typetok);
ASSERT_EQUALS(true, result);
ASSERT_EQUALS("x", vartok->str());
ASSERT_EQUALS("int", typetok->str());
Variable v(vartok, typetok, vartok->previous(), 0, AccessControl::Public, nullptr, nullptr, settings1);
ASSERT(false == v.isArray());
ASSERT(false == v.isPointer());
ASSERT(false == v.isReference());
}
void test_isVariableDeclarationIdentifiesStdDeclaration() {
reset();
GET_SYMBOL_DB("std::string x;");
const bool result = db->scopeList.front().isVariableDeclaration(tokenizer.tokens(), vartok, typetok);
ASSERT_EQUALS(true, result);
ASSERT_EQUALS("x", vartok->str());
ASSERT_EQUALS("string", typetok->str());
Variable v(vartok, typetok, vartok->previous(), 0, AccessControl::Public, nullptr, nullptr, settings1);
ASSERT(false == v.isArray());
ASSERT(false == v.isPointer());
ASSERT(false == v.isReference());
}
void test_isVariableDeclarationIdentifiesScopedStdDeclaration() {
reset();
GET_SYMBOL_DB("::std::string x;");
const bool result = db->scopeList.front().isVariableDeclaration(tokenizer.tokens(), vartok, typetok);
ASSERT_EQUALS(true, result);
ASSERT_EQUALS("x", vartok->str());
ASSERT_EQUALS("string", typetok->str());
Variable v(vartok, typetok, vartok->previous(), 0, AccessControl::Public, nullptr, nullptr, settings1);
ASSERT(false == v.isArray());
ASSERT(false == v.isPointer());
ASSERT(false == v.isReference());
}
void test_isVariableDeclarationIdentifiesManyScopes() {
reset();
GET_SYMBOL_DB("AA::BB::CC::DD::EE x;");
const bool result = db->scopeList.front().isVariableDeclaration(tokenizer.tokens(), vartok, typetok);
ASSERT_EQUALS(true, result);
ASSERT_EQUALS("x", vartok->str());
ASSERT_EQUALS("EE", typetok->str());
Variable v(vartok, typetok, vartok->previous(), 0, AccessControl::Public, nullptr, nullptr, settings1);
ASSERT(false == v.isArray());
ASSERT(false == v.isPointer());
ASSERT(false == v.isReference());
}
void test_isVariableDeclarationIdentifiesPointers() {
{
reset();
GET_SYMBOL_DB("int* p;");
const bool result1 = db->scopeList.front().isVariableDeclaration(tokenizer.tokens(), vartok, typetok);
ASSERT_EQUALS(true, result1);
ASSERT_EQUALS("p", vartok->str());
ASSERT_EQUALS("int", typetok->str());
Variable v1(vartok, typetok, vartok->previous(), 0, AccessControl::Public, nullptr, nullptr, settings1);
ASSERT(false == v1.isArray());
ASSERT(true == v1.isPointer());
ASSERT(false == v1.isReference());
}
{
reset();
const SimpleTokenizer constpointer(*this, "const int* p;");
Variable v2(constpointer.tokens()->tokAt(3), constpointer.tokens()->next(), constpointer.tokens()->tokAt(2), 0, AccessControl::Public, nullptr, nullptr, settings1);
ASSERT(false == v2.isArray());
ASSERT(true == v2.isPointer());
ASSERT(false == v2.isConst());
ASSERT(false == v2.isReference());
}
{
reset();
GET_SYMBOL_DB("int* const p;");
const bool result2 = db->scopeList.front().isVariableDeclaration(tokenizer.tokens(), vartok, typetok);
ASSERT_EQUALS(true, result2);
ASSERT_EQUALS("p", vartok->str());
ASSERT_EQUALS("int", typetok->str());
Variable v3(vartok, typetok, vartok->previous(), 0, AccessControl::Public, nullptr, nullptr, settings1);
ASSERT(false == v3.isArray());
ASSERT(true == v3.isPointer());
ASSERT(true == v3.isConst());
ASSERT(false == v3.isReference());
}
}
void test_isVariableDeclarationIdentifiesPointers2() {
GET_SYMBOL_DB("void slurpInManifest() {\n"
" std::string tmpiostring(*tI);\n"
" if(tmpiostring==\"infoonly\"){}\n"
"}");
const Token *tok = Token::findsimplematch(tokenizer.tokens(), "tmpiostring ==");
ASSERT(tok->variable());
ASSERT(!tok->variable()->isPointer());
}
void test_isVariableDeclarationDoesNotIdentifyConstness() {
reset();
GET_SYMBOL_DB("const int* cp;");
const bool result = db->scopeList.front().isVariableDeclaration(tokenizer.tokens(), vartok, typetok);
ASSERT_EQUALS(false, result);
ASSERT(nullptr == vartok);
ASSERT(nullptr == typetok);
}
void test_isVariableDeclarationIdentifiesFirstOfManyVariables() {
reset();
GET_SYMBOL_DB("int first, second;");
const bool result = db->scopeList.front().isVariableDeclaration(tokenizer.tokens(), vartok, typetok);
ASSERT_EQUALS(true, result);
ASSERT_EQUALS("first", vartok->str());
ASSERT_EQUALS("int", typetok->str());
Variable v(vartok, typetok, vartok->previous(), 0, AccessControl::Public, nullptr, nullptr, settings1);
ASSERT(false == v.isArray());
ASSERT(false == v.isPointer());
ASSERT(false == v.isReference());
}
void test_isVariableDeclarationIdentifiesScopedPointerDeclaration() {
reset();
GET_SYMBOL_DB("AA::BB::CC::DD::EE* p;");
const bool result = db->scopeList.front().isVariableDeclaration(tokenizer.tokens(), vartok, typetok);
ASSERT_EQUALS(true, result);
ASSERT_EQUALS("p", vartok->str());
ASSERT_EQUALS("EE", typetok->str());
Variable v(vartok, typetok, vartok->previous(), 0, AccessControl::Public, nullptr, nullptr, settings1);
ASSERT(false == v.isArray());
ASSERT(true == v.isPointer());
ASSERT(false == v.isReference());
}
void test_isVariableDeclarationIdentifiesDeclarationWithIndirection() {
reset();
GET_SYMBOL_DB("int** pp;");
const bool result = db->scopeList.front().isVariableDeclaration(tokenizer.tokens(), vartok, typetok);
ASSERT_EQUALS(true, result);
ASSERT_EQUALS("pp", vartok->str());
ASSERT_EQUALS("int", typetok->str());
Variable v(vartok, typetok, vartok->previous(), 0, AccessControl::Public, nullptr, nullptr, settings1);
ASSERT(false == v.isArray());
ASSERT(true == v.isPointer());
ASSERT(false == v.isReference());
}
void test_isVariableDeclarationIdentifiesDeclarationWithMultipleIndirection() {
reset();
GET_SYMBOL_DB("int***** p;");
const bool result = db->scopeList.front().isVariableDeclaration(tokenizer.tokens(), vartok, typetok);
ASSERT_EQUALS(true, result);
ASSERT_EQUALS("p", vartok->str());
ASSERT_EQUALS("int", typetok->str());
Variable v(vartok, typetok, vartok->previous(), 0, AccessControl::Public, nullptr, nullptr, settings1);
ASSERT(false == v.isArray());
ASSERT(true == v.isPointer());
ASSERT(false == v.isReference());
}
void test_isVariableDeclarationIdentifiesArray() {
reset();
GET_SYMBOL_DB("::std::string v[3];");
const bool result = db->scopeList.front().isVariableDeclaration(tokenizer.tokens(), vartok, typetok);
ASSERT_EQUALS(true, result);
ASSERT_EQUALS("v", vartok->str());
ASSERT_EQUALS("string", typetok->str());
Variable v(vartok, typetok, vartok->previous(), 0, AccessControl::Public, nullptr, nullptr, settings1);
ASSERT(true == v.isArray());
ASSERT(false == v.isPointer());
ASSERT(false == v.isPointerArray());
ASSERT(false == v.isReference());
}
void test_isVariableDeclarationIdentifiesPointerArray() {
reset();
GET_SYMBOL_DB("A *a[5];");
const bool result = db->scopeList.front().isVariableDeclaration(tokenizer.tokens(), vartok, typetok);
ASSERT_EQUALS(true, result);
ASSERT_EQUALS("a", vartok->str());
ASSERT_EQUALS("A", typetok->str());
Variable v(vartok, typetok, vartok->previous(), 0, AccessControl::Public, nullptr, nullptr, settings1);
ASSERT(false == v.isPointer());
ASSERT(true == v.isArray());
ASSERT(false == v.isPointerToArray());
ASSERT(true == v.isPointerArray());
ASSERT(false == v.isReference());
}
void test_isVariableDeclarationIdentifiesOfArrayPointers1() {
reset();
GET_SYMBOL_DB("A (*a)[5];");
const bool result = db->scopeList.front().isVariableDeclaration(tokenizer.tokens(), vartok, typetok);
ASSERT_EQUALS(true, result);
ASSERT_EQUALS("a", vartok->str());
ASSERT_EQUALS("A", typetok->str());
Variable v(vartok, typetok, vartok->previous(), 0, AccessControl::Public, nullptr, nullptr, settings1);
ASSERT(true == v.isPointer());
ASSERT(false == v.isArray());
ASSERT(true == v.isPointerToArray());
ASSERT(false == v.isPointerArray());
ASSERT(false == v.isReference());
}
void test_isVariableDeclarationIdentifiesOfArrayPointers2() {
reset();
GET_SYMBOL_DB("A (*const a)[5];");
const bool result = db->scopeList.front().isVariableDeclaration(tokenizer.tokens(), vartok, typetok);
ASSERT_EQUALS(true, result);
ASSERT_EQUALS("a", vartok->str());
ASSERT_EQUALS("A", typetok->str());
Variable v(vartok, typetok, vartok->previous(), 0, AccessControl::Public, nullptr, nullptr, settings1);
ASSERT(true == v.isPointer());
ASSERT(false == v.isArray());
ASSERT(true == v.isPointerToArray());
ASSERT(false == v.isPointerArray());
ASSERT(false == v.isReference());
}
void test_isVariableDeclarationIdentifiesOfArrayPointers3() {
reset();
GET_SYMBOL_DB("A (** a)[5];");
const bool result = db->scopeList.front().isVariableDeclaration(tokenizer.tokens(), vartok, typetok);
ASSERT_EQUALS(true, result);
ASSERT_EQUALS("a", vartok->str());
ASSERT_EQUALS("A", typetok->str());
Variable v(vartok, typetok, vartok->previous(), 0, AccessControl::Public, nullptr, nullptr, settings1);
ASSERT(true == v.isPointer());
ASSERT(false == v.isArray());
ASSERT(true == v.isPointerToArray());
ASSERT(false == v.isPointerArray());
ASSERT(false == v.isReference());
}
void test_isVariableDeclarationIdentifiesArrayOfFunctionPointers() {
reset();
GET_SYMBOL_DB("int (*a[])(int) = { g };"); // #11596
const bool result = db->scopeList.front().isVariableDeclaration(tokenizer.tokens(), vartok, typetok);
ASSERT_EQUALS(true, result);
ASSERT_EQUALS("a", vartok->str());
ASSERT_EQUALS("int", typetok->str());
Variable v(vartok, typetok, vartok->previous(), 0, AccessControl::Public, nullptr, nullptr, settings1);
ASSERT(false == v.isPointer());
ASSERT(true == v.isArray());
ASSERT(false == v.isPointerToArray());
ASSERT(true == v.isPointerArray());
ASSERT(false == v.isReference());
ASSERT(true == v.isInit());
}
void isVariableDeclarationIdentifiesTemplatedPointerVariable() {
reset();
GET_SYMBOL_DB("std::set<char>* chars;");
const bool result = db->scopeList.front().isVariableDeclaration(tokenizer.tokens(), vartok, typetok);
ASSERT_EQUALS(true, result);
ASSERT_EQUALS("chars", vartok->str());
ASSERT_EQUALS("set", typetok->str());
Variable v(vartok, typetok, vartok->previous(), 0, AccessControl::Public, nullptr, nullptr, settings1);
ASSERT(false == v.isArray());
ASSERT(true == v.isPointer());
ASSERT(false == v.isReference());
}
void isVariableDeclarationIdentifiesTemplatedPointerToPointerVariable() {
reset();
GET_SYMBOL_DB("std::deque<int>*** ints;");
const bool result = db->scopeList.front().isVariableDeclaration(tokenizer.tokens(), vartok, typetok);
ASSERT_EQUALS(true, result);
ASSERT_EQUALS("ints", vartok->str());
ASSERT_EQUALS("deque", typetok->str());
Variable v(vartok, typetok, vartok->previous(), 0, AccessControl::Public, nullptr, nullptr, settings1);
ASSERT(false == v.isArray());
ASSERT(true == v.isPointer());
ASSERT(false == v.isReference());
}
void isVariableDeclarationIdentifiesTemplatedArrayVariable() {
reset();
GET_SYMBOL_DB("std::deque<int> ints[3];");
const bool result = db->scopeList.front().isVariableDeclaration(tokenizer.tokens(), vartok, typetok);
ASSERT_EQUALS(true, result);
ASSERT_EQUALS("ints", vartok->str());
ASSERT_EQUALS("deque", typetok->str());
Variable v(vartok, typetok, vartok->previous(), 0, AccessControl::Public, nullptr, nullptr, settings1);
ASSERT(true == v.isArray());
ASSERT(false == v.isPointer());
ASSERT(false == v.isReference());
}
void isVariableDeclarationIdentifiesTemplatedVariable() {
reset();
GET_SYMBOL_DB("std::vector<int> ints;");
const bool result = db->scopeList.front().isVariableDeclaration(tokenizer.tokens(), vartok, typetok);
ASSERT_EQUALS(true, result);
ASSERT_EQUALS("ints", vartok->str());
ASSERT_EQUALS("vector", typetok->str());
Variable v(vartok, typetok, vartok->previous(), 0, AccessControl::Public, nullptr, nullptr, settings1);
ASSERT(false == v.isArray());
ASSERT(false == v.isPointer());
ASSERT(false == v.isReference());
}
void isVariableDeclarationIdentifiesTemplatedVariableIterator() {
reset();
GET_SYMBOL_DB("std::list<int>::const_iterator floats;");
const bool result = db->scopeList.front().isVariableDeclaration(tokenizer.tokens(), vartok, typetok);
ASSERT_EQUALS(true, result);
ASSERT_EQUALS("floats", vartok->str());
ASSERT_EQUALS("const_iterator", typetok->str());
Variable v(vartok, typetok, vartok->previous(), 0, AccessControl::Public, nullptr, nullptr, settings1);
ASSERT(false == v.isArray());
ASSERT(false == v.isPointer());
ASSERT(false == v.isReference());
}
void isVariableDeclarationIdentifiesNestedTemplateVariable() {
reset();
GET_SYMBOL_DB("std::deque<std::set<int> > intsets;");
const bool result = db->scopeList.front().isVariableDeclaration(tokenizer.tokens(), vartok, typetok);
ASSERT_EQUALS(true, result);
ASSERT_EQUALS("intsets", vartok->str());
ASSERT_EQUALS("deque", typetok->str());
Variable v(vartok, typetok, vartok->previous(), 0, AccessControl::Public, nullptr, nullptr, settings1);
ASSERT(false == v.isArray());
ASSERT(false == v.isPointer());
ASSERT(false == v.isReference());
}
void isVariableDeclarationIdentifiesReference() {
{
reset();
GET_SYMBOL_DB("int& foo;");
const bool result1 = db->scopeList.front().isVariableDeclaration(tokenizer.tokens(), vartok, typetok);
ASSERT_EQUALS(true, result1);
Variable v1(vartok, typetok, vartok->previous(), 0, AccessControl::Public, nullptr, nullptr, settings1);
ASSERT(false == v1.isArray());
ASSERT(false == v1.isPointer());
ASSERT(true == v1.isReference());
}
{
reset();
GET_SYMBOL_DB("foo*& bar;");
const bool result2 = db->scopeList.front().isVariableDeclaration(tokenizer.tokens(), vartok, typetok);
ASSERT_EQUALS(true, result2);
Variable v2(vartok, typetok, vartok->previous(), 0, AccessControl::Public, nullptr, nullptr, settings1);
ASSERT(false == v2.isArray());
ASSERT(true == v2.isPointer());
ASSERT(true == v2.isReference());
}
{
reset();
GET_SYMBOL_DB("std::vector<int>& foo;");
const bool result3 = db->scopeList.front().isVariableDeclaration(tokenizer.tokens(), vartok, typetok);
ASSERT_EQUALS(true, result3);
Variable v3(vartok, typetok, vartok->previous(), 0, AccessControl::Public, nullptr, nullptr, settings1);
ASSERT(false == v3.isArray());
ASSERT(false == v3.isPointer());
ASSERT(true == v3.isReference());
}
}
void isVariableDeclarationDoesNotIdentifyTemplateClass() {
reset();
GET_SYMBOL_DB("template <class T> class SomeClass{};");
const bool result = db->scopeList.front().isVariableDeclaration(tokenizer.tokens(), vartok, typetok);
ASSERT_EQUALS(false, result);
}
void isVariableDeclarationDoesNotIdentifyCppCast() {
reset();
GET_SYMBOL_DB("reinterpret_cast <char *> (code)[0] = 0;");
const bool result = db->scopeList.front().isVariableDeclaration(tokenizer.tokens(), vartok, typetok);
ASSERT_EQUALS(false, result);
}
void isVariableDeclarationPointerConst() {
reset();
GET_SYMBOL_DB("std::string const* s;");
const bool result = db->scopeList.front().isVariableDeclaration(tokenizer.tokens()->next(), vartok, typetok);
ASSERT_EQUALS(true, result);
Variable v(vartok, typetok, vartok->previous(), 0, AccessControl::Public, nullptr, nullptr, settings1);
ASSERT(false == v.isArray());
ASSERT(true == v.isPointer());
ASSERT(false == v.isReference());
}
void isVariableDeclarationRValueRef() {
reset();
GET_SYMBOL_DB("int&& i;");
const bool result = db->scopeList.front().isVariableDeclaration(tokenizer.tokens(), vartok, typetok);
ASSERT_EQUALS(true, result);
Variable v(vartok, typetok, vartok->previous(), 0, AccessControl::Public, nullptr, nullptr, settings1);
ASSERT(false == v.isArray());
ASSERT(false == v.isPointer());
ASSERT(true == v.isReference());
ASSERT(true == v.isRValueReference());
ASSERT(tokenizer.tokens()->tokAt(2)->scope() != nullptr);
}
void isVariableDeclarationDoesNotIdentifyCase() {
GET_SYMBOL_DB_C("a b;\n"
"void f() {\n"
" switch (c) {\n"
" case b:;\n"
" }"
"}");
const Variable* b = db->getVariableFromVarId(1);
ASSERT_EQUALS("b", b->name());
ASSERT_EQUALS("a", b->typeStartToken()->str());
}
void isVariableDeclarationIf() {
GET_SYMBOL_DB("void foo() {\n"
" for (auto& elem : items) {\n"
" if (auto x = bar()) { int y = 3; }\n"
" }\n"
"}");
const Token *x = Token::findsimplematch(tokenizer.tokens(), "x");
ASSERT(x);
ASSERT(x->varId());
ASSERT(x->variable());
const Token *y = Token::findsimplematch(tokenizer.tokens(), "y");
ASSERT(y);
ASSERT(y->varId());
ASSERT(y->variable());
}
void VariableValueType1() {
GET_SYMBOL_DB("typedef uint8_t u8;\n"
"static u8 x;");
const Variable* x = db->getVariableFromVarId(1);
ASSERT_EQUALS("x", x->name());
ASSERT(x->valueType()->isIntegral());
}
void VariableValueType2() {
GET_SYMBOL_DB("using u8 = uint8_t;\n"
"static u8 x;");
const Variable* x = db->getVariableFromVarId(1);
ASSERT_EQUALS("x", x->name());
ASSERT(x->valueType()->isIntegral());
}
void VariableValueType3() {
// std::string::size_type
{
GET_SYMBOL_DB("void f(std::string::size_type x);");
const Variable* const x = db->getVariableFromVarId(1);
ASSERT_EQUALS("x", x->name());
// TODO: Configure std::string::size_type somehow.
TODO_ASSERT_EQUALS(ValueType::Type::LONGLONG, ValueType::Type::UNKNOWN_INT, x->valueType()->type);
ASSERT_EQUALS(ValueType::Sign::UNSIGNED, x->valueType()->sign);
}
// std::wstring::size_type
{
GET_SYMBOL_DB("void f(std::wstring::size_type x);");
const Variable* const x = db->getVariableFromVarId(1);
ASSERT_EQUALS("x", x->name());
// TODO: Configure std::wstring::size_type somehow.
TODO_ASSERT_EQUALS(ValueType::Type::LONGLONG, ValueType::Type::UNKNOWN_INT, x->valueType()->type);
ASSERT_EQUALS(ValueType::Sign::UNSIGNED, x->valueType()->sign);
}
// std::u16string::size_type
{
GET_SYMBOL_DB("void f(std::u16string::size_type x);");
const Variable* const x = db->getVariableFromVarId(1);
ASSERT_EQUALS("x", x->name());
// TODO: Configure std::u16string::size_type somehow.
TODO_ASSERT_EQUALS(ValueType::Type::LONGLONG, ValueType::Type::UNKNOWN_INT, x->valueType()->type);
ASSERT_EQUALS(ValueType::Sign::UNSIGNED, x->valueType()->sign);
}
// std::u32string::size_type
{
GET_SYMBOL_DB("void f(std::u32string::size_type x);");
const Variable* const x = db->getVariableFromVarId(1);
ASSERT_EQUALS("x", x->name());
// TODO: Configure std::u32string::size_type somehow.
TODO_ASSERT_EQUALS(ValueType::Type::LONGLONG, ValueType::Type::UNKNOWN_INT, x->valueType()->type);
ASSERT_EQUALS(ValueType::Sign::UNSIGNED, x->valueType()->sign);
}
}
void VariableValueType4() {
GET_SYMBOL_DB("class C {\n"
"public:\n"
" std::shared_ptr<C> x;\n"
"};");
const Variable* const x = db->getVariableFromVarId(1);
ASSERT(x->valueType());
ASSERT(x->valueType()->smartPointerType);
}
void VariableValueType5() {
GET_SYMBOL_DB("class C {};\n"
"void foo(std::shared_ptr<C>* p) {}");
const Variable* const p = db->getVariableFromVarId(1);
ASSERT(p->valueType());
ASSERT(p->valueType()->smartPointerTypeToken);
ASSERT(p->valueType()->pointer == 1);
}
void VariableValueType6() {
GET_SYMBOL_DB("struct Data{};\n"
"void foo() { std::unique_ptr<Data> data = std::unique_ptr<Data>(new Data); }");
const Token* check = Token::findsimplematch(tokenizer.tokens(), "( new");
ASSERT(check);
ASSERT(check->valueType());
ASSERT(check->valueType()->smartPointerTypeToken);
}
void VariableValueTypeReferences() {
{
GET_SYMBOL_DB("void foo(int x) {}\n");
const Variable* const p = db->getVariableFromVarId(1);
ASSERT(p->valueType());
ASSERT(p->valueType()->pointer == 0);
ASSERT(p->valueType()->constness == 0);
ASSERT(p->valueType()->volatileness == 0);
ASSERT(p->valueType()->reference == Reference::None);
}
{
GET_SYMBOL_DB("void foo(volatile int x) {}\n");
const Variable* const p = db->getVariableFromVarId(1);
ASSERT(p->valueType());
ASSERT(p->valueType()->pointer == 0);
ASSERT(p->valueType()->constness == 0);
ASSERT(p->valueType()->volatileness == 1);
ASSERT(p->valueType()->reference == Reference::None);
}
{
GET_SYMBOL_DB("void foo(int* x) {}\n");
const Variable* const p = db->getVariableFromVarId(1);
ASSERT(p->valueType());
ASSERT(p->valueType()->pointer == 1);
ASSERT(p->valueType()->constness == 0);
ASSERT(p->valueType()->volatileness == 0);
ASSERT(p->valueType()->reference == Reference::None);
}
{
GET_SYMBOL_DB("void foo(int& x) {}\n");
const Variable* const p = db->getVariableFromVarId(1);
ASSERT(p->valueType());
ASSERT(p->valueType()->pointer == 0);
ASSERT(p->valueType()->constness == 0);
ASSERT(p->valueType()->volatileness == 0);
ASSERT(p->valueType()->reference == Reference::LValue);
}
{
GET_SYMBOL_DB("void foo(int&& x) {}\n");
const Variable* const p = db->getVariableFromVarId(1);
ASSERT(p->valueType());
ASSERT(p->valueType()->pointer == 0);
ASSERT(p->valueType()->constness == 0);
ASSERT(p->valueType()->volatileness == 0);
ASSERT(p->valueType()->reference == Reference::RValue);
}
{
GET_SYMBOL_DB("void foo(int*& x) {}\n");
const Variable* const p = db->getVariableFromVarId(1);
ASSERT(p->valueType());
ASSERT(p->valueType()->pointer == 1);
ASSERT(p->valueType()->constness == 0);
ASSERT(p->valueType()->volatileness == 0);
ASSERT(p->valueType()->reference == Reference::LValue);
}
{
GET_SYMBOL_DB("void foo(int*&& x) {}\n");
const Variable* const p = db->getVariableFromVarId(1);
ASSERT(p->valueType());
ASSERT(p->valueType()->pointer == 1);
ASSERT(p->valueType()->constness == 0);
ASSERT(p->valueType()->volatileness == 0);
ASSERT(p->valueType()->reference == Reference::RValue);
}
{
GET_SYMBOL_DB("void foo(int**& x) {}\n");
const Variable* const p = db->getVariableFromVarId(1);
ASSERT(p->valueType());
ASSERT(p->valueType()->pointer == 2);
ASSERT(p->valueType()->constness == 0);
ASSERT(p->valueType()->volatileness == 0);
ASSERT(p->valueType()->reference == Reference::LValue);
}
{
GET_SYMBOL_DB("void foo(int**&& x) {}\n");
const Variable* const p = db->getVariableFromVarId(1);
ASSERT(p->valueType());
ASSERT(p->valueType()->pointer == 2);
ASSERT(p->valueType()->constness == 0);
ASSERT(p->valueType()->volatileness == 0);
ASSERT(p->valueType()->reference == Reference::RValue);
}
{
GET_SYMBOL_DB("void foo(const int& x) {}\n");
const Variable* const p = db->getVariableFromVarId(1);
ASSERT(p->valueType());
ASSERT(p->valueType()->pointer == 0);
ASSERT(p->valueType()->constness == 1);
ASSERT(p->valueType()->volatileness == 0);
ASSERT(p->valueType()->reference == Reference::LValue);
}
{
GET_SYMBOL_DB("void foo(const int&& x) {}\n");
const Variable* const p = db->getVariableFromVarId(1);
ASSERT(p->valueType());
ASSERT(p->valueType()->pointer == 0);
ASSERT(p->valueType()->constness == 1);
ASSERT(p->valueType()->volatileness == 0);
ASSERT(p->valueType()->reference == Reference::RValue);
}
{
GET_SYMBOL_DB("void foo(const int*& x) {}\n");
const Variable* const p = db->getVariableFromVarId(1);
ASSERT(p->valueType());
ASSERT(p->valueType()->pointer == 1);
ASSERT(p->valueType()->constness == 1);
ASSERT(p->valueType()->volatileness == 0);
ASSERT(p->valueType()->reference == Reference::LValue);
}
{
GET_SYMBOL_DB("void foo(const int*&& x) {}\n");
const Variable* const p = db->getVariableFromVarId(1);
ASSERT(p->valueType());
ASSERT(p->valueType()->pointer == 1);
ASSERT(p->valueType()->constness == 1);
ASSERT(p->valueType()->volatileness == 0);
ASSERT(p->valueType()->reference == Reference::RValue);
}
{
GET_SYMBOL_DB("void foo(int* const & x) {}\n");
const Variable* const p = db->getVariableFromVarId(1);
ASSERT(p->valueType());
ASSERT(p->valueType()->pointer == 1);
ASSERT(p->valueType()->constness == 2);
ASSERT(p->valueType()->volatileness == 0);
ASSERT(p->valueType()->reference == Reference::LValue);
}
{
GET_SYMBOL_DB("void foo(int* const && x) {}\n");
const Variable* const p = db->getVariableFromVarId(1);
ASSERT(p->valueType());
ASSERT(p->valueType()->pointer == 1);
ASSERT(p->valueType()->constness == 2);
ASSERT(p->valueType()->volatileness == 0);
ASSERT(p->valueType()->reference == Reference::RValue);
}
{
GET_SYMBOL_DB("extern const volatile int* test[];\n");
const Variable* const p = db->getVariableFromVarId(1);
ASSERT(p->valueType());
ASSERT(p->valueType()->pointer == 1);
ASSERT(p->valueType()->constness == 1);
ASSERT(p->valueType()->volatileness == 1);
ASSERT(p->valueType()->reference == Reference::None);
}
{
GET_SYMBOL_DB("extern const int* volatile test[];\n");
const Variable* const p = db->getVariableFromVarId(1);
ASSERT(p->valueType());
ASSERT(p->valueType()->pointer == 1);
ASSERT(p->valueType()->constness == 1);
ASSERT(p->valueType()->volatileness == 2);
ASSERT(p->valueType()->reference == Reference::None);
}
{
GET_SYMBOL_DB_C("typedef unsigned char uint8_t;\n uint8_t ubVar = 0;\n");
const Variable* const p = db->getVariableFromVarId(1);
ASSERT(p->valueType());
ASSERT(p->valueType()->pointer == 0);
ASSERT(p->valueType()->constness == 0);
ASSERT(p->valueType()->volatileness == 0);
ASSERT(p->valueType()->originalTypeName == "uint8_t");
ASSERT(p->valueType()->reference == Reference::None);
}
{
GET_SYMBOL_DB_C("typedef enum eEnumDef {CPPCHECK=0}eEnum_t;\n eEnum_t eVar = CPPCHECK;\n");
const Variable* const p = db->getVariableFromVarId(1);
ASSERT(p->valueType());
ASSERT(p->valueType()->pointer == 0);
ASSERT(p->valueType()->constness == 0);
ASSERT(p->valueType()->volatileness == 0);
ASSERT(p->valueType()->originalTypeName == "eEnum_t");
ASSERT(p->valueType()->reference == Reference::None);
}
{
GET_SYMBOL_DB_C("typedef unsigned char uint8_t;\n typedef struct stStructDef {uint8_t ubTest;}stStruct_t;\n stStruct_t stVar;\n");
const Variable* p = db->getVariableFromVarId(1);
ASSERT(p->valueType());
ASSERT(p->valueType()->pointer == 0);
ASSERT(p->valueType()->constness == 0);
ASSERT(p->valueType()->volatileness == 0);
ASSERT(p->valueType()->originalTypeName == "uint8_t");
ASSERT(p->valueType()->reference == Reference::None);
p = db->getVariableFromVarId(2);
ASSERT(p->valueType());
ASSERT(p->valueType()->pointer == 0);
ASSERT(p->valueType()->constness == 0);
ASSERT(p->valueType()->volatileness == 0);
ASSERT(p->valueType()->originalTypeName == "stStruct_t");
ASSERT(p->valueType()->reference == Reference::None);
}
{
GET_SYMBOL_DB_C("typedef int (*ubFunctionPointer_fp)(int);\n void test(ubFunctionPointer_fp functionPointer);\n");
const Variable* const p = db->getVariableFromVarId(1);
ASSERT(p->valueType());
ASSERT(p->valueType()->pointer == 1);
ASSERT(p->valueType()->constness == 0);
ASSERT(p->valueType()->volatileness == 0);
ASSERT(p->valueType()->originalTypeName == "ubFunctionPointer_fp");
ASSERT(p->valueType()->reference == Reference::None);
}
}
void VariableValueTypeTemplate() {
{
GET_SYMBOL_DB("template <class T>\n" // #12393
"struct S {\n"
" struct U {\n"
" S<T>* p;\n"
" };\n"
" U u;\n"
"};\n");
const Variable* const p = db->getVariableFromVarId(1);
ASSERT_EQUALS(p->name(), "p");
ASSERT(p->valueType());
ASSERT(p->valueType()->pointer == 1);
ASSERT(p->valueType()->constness == 0);
ASSERT(p->valueType()->reference == Reference::None);
ASSERT_EQUALS(p->scope()->className, "U");
ASSERT_EQUALS(p->typeScope()->className, "S");
}
}
void findVariableType1() {
GET_SYMBOL_DB("class A {\n"
"public:\n"
" struct B {};\n"
" void f();\n"
"};\n"
"\n"
"void f()\n"
"{\n"
" struct A::B b;\n"
" b.x = 1;\n"
"}");
ASSERT(db != nullptr);
const Variable* bvar = db->getVariableFromVarId(1);
ASSERT_EQUALS("b", bvar->name());
ASSERT(bvar->type() != nullptr);
}
void findVariableType2() {
GET_SYMBOL_DB("class A {\n"
"public:\n"
" class B {\n"
" public:\n"
" struct C {\n"
" int x;\n"
" int y;\n"
" };\n"
" };\n"
"\n"
" void f();\n"
"};\n"
"\n"
"void A::f()\n"
"{\n"
" struct B::C c;\n"
" c.x = 1;\n"
"}");
ASSERT(db != nullptr);
const Variable* cvar = db->getVariableFromVarId(3);
ASSERT_EQUALS("c", cvar->name());
ASSERT(cvar->type() != nullptr);
}
void findVariableType3() {
GET_SYMBOL_DB("namespace {\n"
" struct A {\n"
" int x;\n"
" int y;\n"
" };\n"
"}\n"
"\n"
"void f()\n"
"{\n"
" struct A a;\n"
" a.x = 1;\n"
"}");
(void)db;
const Variable* avar = Token::findsimplematch(tokenizer.tokens(), "a")->variable();
ASSERT(avar);
ASSERT(avar && avar->type() != nullptr);
}
void findVariableTypeExternC() {
GET_SYMBOL_DB("extern \"C\" { typedef int INT; }\n"
"void bar() {\n"
" INT x = 3;\n"
"}");
(void)db;
const Variable* avar = Token::findsimplematch(tokenizer.tokens(), "x")->variable();
ASSERT(avar);
ASSERT(avar->valueType() != nullptr);
ASSERT(avar->valueType()->str() == "signed int");
}
void rangeBasedFor() {
GET_SYMBOL_DB("void reset() {\n"
" for(auto& e : array)\n"
" foo(e);\n"
"}");
ASSERT(db != nullptr);
ASSERT(db->scopeList.back().type == Scope::eFor);
ASSERT_EQUALS(2, db->variableList().size());
const Variable* e = db->getVariableFromVarId(1);
ASSERT(e && e->isReference() && e->isLocal());
}
void isVariableStlType() {
{
reset();
GET_SYMBOL_DB("std::string s;");
const bool result = db->scopeList.front().isVariableDeclaration(tokenizer.tokens(), vartok, typetok);
ASSERT_EQUALS(true, result);
Variable v(vartok, tokenizer.tokens(), tokenizer.list.back(), 0, AccessControl::Public, nullptr, nullptr, settings1);
static const std::set<std::string> types = { "string", "wstring" };
static const std::set<std::string> no_types = { "set" };
ASSERT_EQUALS(true, v.isStlType());
ASSERT_EQUALS(true, v.isStlType(types));
ASSERT_EQUALS(false, v.isStlType(no_types));
ASSERT_EQUALS(true, v.isStlStringType());
}
{
reset();
GET_SYMBOL_DB("std::vector<int> v;");
const bool result = db->scopeList.front().isVariableDeclaration(tokenizer.tokens(), vartok, typetok);
ASSERT_EQUALS(true, result);
Variable v(vartok, tokenizer.tokens(), tokenizer.list.back(), 0, AccessControl::Public, nullptr, nullptr, settings1);
static const std::set<std::string> types = { "bitset", "set", "vector", "wstring" };
static const std::set<std::string> no_types = { "bitset", "map", "set" };
ASSERT_EQUALS(true, v.isStlType());
ASSERT_EQUALS(true, v.isStlType(types));
ASSERT_EQUALS(false, v.isStlType(no_types));
ASSERT_EQUALS(false, v.isStlStringType());
}
{
reset();
GET_SYMBOL_DB("SomeClass s;");
const bool result = db->scopeList.front().isVariableDeclaration(tokenizer.tokens(), vartok, typetok);
ASSERT_EQUALS(true, result);
Variable v(vartok, tokenizer.tokens(), tokenizer.list.back(), 0, AccessControl::Public, nullptr, nullptr, settings1);
static const std::set<std::string> types = { "bitset", "set", "vector" };
ASSERT_EQUALS(false, v.isStlType());
ASSERT_EQUALS(false, v.isStlType(types));
ASSERT_EQUALS(false, v.isStlStringType());
}
}
void isVariablePointerToConstPointer() {
reset();
GET_SYMBOL_DB("char* const * s;");
const bool result = db->scopeList.front().isVariableDeclaration(tokenizer.tokens(), vartok, typetok);
ASSERT_EQUALS(true, result);
Variable v(vartok, typetok, vartok->previous(), 0, AccessControl::Public, nullptr, nullptr, settings1);
ASSERT(false == v.isArray());
ASSERT(true == v.isPointer());
ASSERT(false == v.isReference());
}
void isVariablePointerToVolatilePointer() {
reset();
GET_SYMBOL_DB("char* volatile * s;");
const bool result = db->scopeList.front().isVariableDeclaration(tokenizer.tokens(), vartok, typetok);
ASSERT_EQUALS(true, result);
Variable v(vartok, typetok, vartok->previous(), 0, AccessControl::Public, nullptr, nullptr, settings1);
ASSERT(false == v.isArray());
ASSERT(true == v.isPointer());
ASSERT(false == v.isReference());
}
void isVariablePointerToConstVolatilePointer() {
reset();
GET_SYMBOL_DB("char* const volatile * s;");
const bool result = db->scopeList.front().isVariableDeclaration(tokenizer.tokens(), vartok, typetok);
ASSERT_EQUALS(true, result);
Variable v(vartok, typetok, vartok->previous(), 0, AccessControl::Public, nullptr, nullptr, settings1);
ASSERT(false == v.isArray());
ASSERT(true == v.isPointer());
ASSERT(false == v.isReference());
}
void isVariableMultiplePointersAndQualifiers() {
reset();
GET_SYMBOL_DB("const char* const volatile * const volatile * const volatile * const volatile s;");
const bool result = db->scopeList.front().isVariableDeclaration(tokenizer.tokens()->next(), vartok, typetok);
ASSERT_EQUALS(true, result);
Variable v(vartok, typetok, vartok->previous(), 0, AccessControl::Public, nullptr, nullptr, settings1);
ASSERT(false == v.isArray());
ASSERT(true == v.isPointer());
ASSERT(false == v.isReference());
}
void variableVolatile() {
GET_SYMBOL_DB("std::atomic<int> x;\n"
"volatile int y;");
const Token *x = Token::findsimplematch(tokenizer.tokens(), "x");
ASSERT(x);
ASSERT(x->variable());
ASSERT(x->variable()->isVolatile());
const Token *y = Token::findsimplematch(tokenizer.tokens(), "y");
ASSERT(y);
ASSERT(y->variable());
ASSERT(y->variable()->isVolatile());
}
void variableConstexpr() {
GET_SYMBOL_DB("constexpr int x = 16;");
const Token *x = Token::findsimplematch(tokenizer.tokens(), "x");
ASSERT(x);
ASSERT(x->variable());
ASSERT(x->variable()->isConst());
ASSERT(x->variable()->isStatic());
ASSERT(x->valueType());
ASSERT(x->valueType()->pointer == 0);
ASSERT(x->valueType()->constness == 1);
ASSERT(x->valueType()->reference == Reference::None);
}
void isVariableDecltype() {
GET_SYMBOL_DB("int x;\n"
"decltype(x) a;\n"
"const decltype(x) b;\n"
"decltype(x) *c;\n");
ASSERT(db);
ASSERT_EQUALS(4, db->scopeList.front().varlist.size());
const Variable *a = Token::findsimplematch(tokenizer.tokens(), "a")->variable();
ASSERT(a);
ASSERT_EQUALS("a", a->name());
ASSERT(a->valueType());
ASSERT_EQUALS("signed int", a->valueType()->str());
const Variable *b = Token::findsimplematch(tokenizer.tokens(), "b")->variable();
ASSERT(b);
ASSERT_EQUALS("b", b->name());
ASSERT(b->valueType());
ASSERT_EQUALS("const signed int", b->valueType()->str());
const Variable *c = Token::findsimplematch(tokenizer.tokens(), "c")->variable();
ASSERT(c);
ASSERT_EQUALS("c", c->name());
ASSERT(c->valueType());
ASSERT_EQUALS("signed int *", c->valueType()->str());
}
void isVariableAlignas() {
GET_SYMBOL_DB_C("extern alignas(16) int x;\n"
"alignas(16) int x;\n");
ASSERT(db);
ASSERT_EQUALS(2, db->scopeList.front().varlist.size());
const Variable *x1 = Token::findsimplematch(tokenizer.tokens(), "x")->variable();
ASSERT(x1 && Token::simpleMatch(x1->typeStartToken(), "int x ;"));
}
void memberVar1() {
GET_SYMBOL_DB("struct Foo {\n"
" int x;\n"
"};\n"
"struct Bar : public Foo {};\n"
"void f() {\n"
" struct Bar bar;\n"
" bar.x = 123;\n" // <- x should get a variable() pointer
"}");
ASSERT(db != nullptr);
const Token *tok = Token::findsimplematch(tokenizer.tokens(), "x =");
ASSERT(tok->variable());
ASSERT(Token::simpleMatch(tok->variable()->typeStartToken(), "int x ;"));
}
void arrayMemberVar1() {
GET_SYMBOL_DB("struct Foo {\n"
" int x;\n"
"};\n"
"void f() {\n"
" struct Foo foo[10];\n"
" foo[1].x = 123;\n" // <- x should get a variable() pointer
"}");
const Token *tok = Token::findsimplematch(tokenizer.tokens(), ". x");
tok = tok ? tok->next() : nullptr;
ASSERT(db != nullptr);
ASSERT(tok && tok->variable() && Token::simpleMatch(tok->variable()->typeStartToken(), "int x ;"));
ASSERT(tok && tok->varId() == 3U); // It's possible to set a varId
}
void arrayMemberVar2() {
GET_SYMBOL_DB("struct Foo {\n"
" int x;\n"
"};\n"
"void f() {\n"
" struct Foo foo[10][10];\n"
" foo[1][2].x = 123;\n" // <- x should get a variable() pointer
"}");
const Token *tok = Token::findsimplematch(tokenizer.tokens(), ". x");
tok = tok ? tok->next() : nullptr;
ASSERT(db != nullptr);
ASSERT(tok && tok->variable() && Token::simpleMatch(tok->variable()->typeStartToken(), "int x ;"));
ASSERT(tok && tok->varId() == 3U); // It's possible to set a varId
}
void arrayMemberVar3() {
GET_SYMBOL_DB("struct Foo {\n"
" int x;\n"
"};\n"
"void f() {\n"
" struct Foo foo[10];\n"
" (foo[1]).x = 123;\n" // <- x should get a variable() pointer
"}");
const Token *tok = Token::findsimplematch(tokenizer.tokens(), ". x");
tok = tok ? tok->next() : nullptr;
ASSERT(db != nullptr);
ASSERT(tok && tok->variable() && Token::simpleMatch(tok->variable()->typeStartToken(), "int x ;"));
ASSERT(tok && tok->varId() == 3U); // It's possible to set a varId
}
void arrayMemberVar4() {
GET_SYMBOL_DB("struct S { unsigned char* s; };\n"
"struct T { S s[38]; };\n"
"void f(T* t) {\n"
" t->s;\n"
"}\n");
const Token *tok = Token::findsimplematch(tokenizer.tokens(), ". s");
tok = tok ? tok->next() : nullptr;
ASSERT(db != nullptr);
ASSERT(tok && tok->variable() && Token::simpleMatch(tok->variable()->typeStartToken(), "S s [ 38 ] ;"));
ASSERT(tok && tok->varId() == 4U);
}
void staticMemberVar() {
GET_SYMBOL_DB("class Foo {\n"
" static const double d;\n"
"};\n"
"const double Foo::d = 5.0;");
const Variable* v = db->getVariableFromVarId(1);
ASSERT(v && db->variableList().size() == 2);
ASSERT(v && v->isStatic() && v->isConst() && v->isPrivate());
}
void getVariableFromVarIdBoundsCheck() {
GET_SYMBOL_DB("int x;\n"
"int y;");
const Variable* v = db->getVariableFromVarId(2);
// three elements: varId 0 also counts via a fake-entry
ASSERT(v && db->variableList().size() == 3);
// TODO: we should provide our own error message
#ifdef _MSC_VER
ASSERT_THROW_EQUALS_2(db->getVariableFromVarId(3), std::out_of_range, "invalid vector subscript");
#elif !defined(_LIBCPP_VERSION)
ASSERT_THROW_EQUALS_2(db->getVariableFromVarId(3), std::out_of_range, "vector::_M_range_check: __n (which is 3) >= this->size() (which is 3)");
#else
ASSERT_THROW_EQUALS_2(db->getVariableFromVarId(3), std::out_of_range, "vector");
#endif
}
void hasRegularFunction() {
GET_SYMBOL_DB("void func() { }");
// 2 scopes: Global and Function
ASSERT(db && db->scopeList.size() == 2);
const Scope *scope = findFunctionScopeByToken(db, tokenizer.tokens()->next());
ASSERT(scope && scope->className == "func");
ASSERT(scope->functionOf == nullptr);
const Function *function = findFunctionByName("func", &db->scopeList.front());
ASSERT(function && function->token->str() == "func");
ASSERT(function && function->token == tokenizer.tokens()->next());
ASSERT(function && function->hasBody());
ASSERT(function && function->functionScope == scope && scope->function == function && function->nestedIn != scope);
ASSERT(function && function->retDef == tokenizer.tokens());
}
void hasRegularFunction_trailingReturnType() {
GET_SYMBOL_DB("auto func() -> int { }");
// 2 scopes: Global and Function
ASSERT(db && db->scopeList.size() == 2);
const Scope *scope = findFunctionScopeByToken(db, tokenizer.tokens()->next());
ASSERT(scope && scope->className == "func");
ASSERT(scope->functionOf == nullptr);
const Function *function = findFunctionByName("func", &db->scopeList.front());
ASSERT(function && function->token->str() == "func");
ASSERT(function && function->token == tokenizer.tokens()->next());
ASSERT(function && function->hasBody());
ASSERT(function && function->functionScope == scope && scope->function == function && function->nestedIn != scope);
ASSERT(function && function->retDef == tokenizer.tokens()->tokAt(5));
}
void hasInlineClassFunction() {
GET_SYMBOL_DB("class Fred { void func() { } };");
// 3 scopes: Global, Class, and Function
ASSERT(db && db->scopeList.size() == 3);
const Token * const functionToken = Token::findsimplematch(tokenizer.tokens(), "func");
const Scope *scope = findFunctionScopeByToken(db, functionToken);
ASSERT(scope && scope->className == "func");
ASSERT(scope->functionOf && scope->functionOf == db->findScopeByName("Fred"));
const Function *function = findFunctionByName("func", &db->scopeList.back());
ASSERT(function && function->token->str() == "func");
ASSERT(function && function->token == functionToken);
ASSERT(function && function->hasBody() && function->isInline());
ASSERT(function && function->functionScope == scope && scope->function == function && function->nestedIn == db->findScopeByName("Fred"));
ASSERT(function && function->retDef == functionToken->previous());
ASSERT(db);
ASSERT(db->findScopeByName("Fred") && db->findScopeByName("Fred")->definedType->getFunction("func") == function);
}
void hasInlineClassFunction_trailingReturnType() {
GET_SYMBOL_DB("class Fred { auto func() -> int { } };");
// 3 scopes: Global, Class, and Function
ASSERT(db && db->scopeList.size() == 3);
const Token * const functionToken = Token::findsimplematch(tokenizer.tokens(), "func");
const Scope *scope = findFunctionScopeByToken(db, functionToken);
ASSERT(scope && scope->className == "func");
ASSERT(scope->functionOf && scope->functionOf == db->findScopeByName("Fred"));
const Function *function = findFunctionByName("func", &db->scopeList.back());
ASSERT(function && function->token->str() == "func");
ASSERT(function && function->token == functionToken);
ASSERT(function && function->hasBody() && function->isInline());
ASSERT(function && function->functionScope == scope && scope->function == function && function->nestedIn == db->findScopeByName("Fred"));
ASSERT(function && function->retDef == functionToken->tokAt(4));
ASSERT(db);
ASSERT(db->findScopeByName("Fred") && db->findScopeByName("Fred")->definedType->getFunction("func") == function);
}
void hasMissingInlineClassFunction() {
GET_SYMBOL_DB("class Fred { void func(); };");
// 2 scopes: Global and Class (no Function scope because there is no function implementation)
ASSERT(db && db->scopeList.size() == 2);
const Token * const functionToken = Token::findsimplematch(tokenizer.tokens(), "func");
const Scope *scope = findFunctionScopeByToken(db, functionToken);
ASSERT(scope == nullptr);
const Function *function = findFunctionByName("func", &db->scopeList.back());
ASSERT(function && function->token->str() == "func");
ASSERT(function && function->token == functionToken);
ASSERT(function && !function->hasBody());
}
void hasInlineClassOperatorTemplate() {
GET_SYMBOL_DB("struct Fred { template<typename T> Foo & operator=(const Foo &) { return *this; } };");
// 3 scopes: Global, Class, and Function
ASSERT(db && db->scopeList.size() == 3);
const Token * const functionToken = Token::findsimplematch(tokenizer.tokens(), "operator=");
const Scope *scope = findFunctionScopeByToken(db, functionToken);
ASSERT(scope && scope->className == "operator=");
ASSERT(scope->functionOf && scope->functionOf == db->findScopeByName("Fred"));
const Function *function = findFunctionByName("operator=", &db->scopeList.back());
ASSERT(function && function->token->str() == "operator=");
ASSERT(function && function->token == functionToken);
ASSERT(function && function->hasBody() && function->isInline());
ASSERT(function && function->functionScope == scope && scope->function == function && function->nestedIn == db->findScopeByName("Fred"));
ASSERT(function && function->retDef == functionToken->tokAt(-2));
ASSERT(db);
ASSERT(db->findScopeByName("Fred") && db->findScopeByName("Fred")->definedType->getFunction("operator=") == function);
}
void hasClassFunction() {
GET_SYMBOL_DB("class Fred { void func(); }; void Fred::func() { }");
// 3 scopes: Global, Class, and Function
ASSERT(db && db->scopeList.size() == 3);
const Token * const functionToken = Token::findsimplematch(tokenizer.tokens()->linkAt(2), "func");
const Scope *scope = findFunctionScopeByToken(db, functionToken);
ASSERT(scope && scope->className == "func");
ASSERT(scope->functionOf && scope->functionOf == db->findScopeByName("Fred"));
const Function *function = findFunctionByName("func", &db->scopeList.back());
ASSERT(function && function->token->str() == "func");
ASSERT(function && function->token == functionToken);
ASSERT(function && function->hasBody() && !function->isInline());
ASSERT(function && function->functionScope == scope && scope->function == function && function->nestedIn == db->findScopeByName("Fred"));
}
void hasClassFunction_trailingReturnType() {
GET_SYMBOL_DB("class Fred { auto func() -> int; }; auto Fred::func() -> int { }");
// 3 scopes: Global, Class, and Function
ASSERT(db && db->scopeList.size() == 3);
const Token * const functionToken = Token::findsimplematch(tokenizer.tokens()->linkAt(2), "func");
const Scope *scope = findFunctionScopeByToken(db, functionToken);
ASSERT(scope && scope->className == "func");
ASSERT(scope->functionOf && scope->functionOf == db->findScopeByName("Fred"));
const Function *function = findFunctionByName("func", &db->scopeList.back());
ASSERT(function && function->token->str() == "func");
ASSERT(function && function->token == functionToken);
ASSERT(function && function->hasBody() && !function->isInline());
ASSERT(function && function->functionScope == scope && scope->function == function && function->nestedIn == db->findScopeByName("Fred"));
}
void hasClassFunction_decltype_auto()
{
GET_SYMBOL_DB("struct d { decltype(auto) f() {} };");
// 3 scopes: Global, Class, and Function
ASSERT(db && db->scopeList.size() == 3);
const Token* const functionToken = Token::findsimplematch(tokenizer.tokens(), "f");
const Scope* scope = findFunctionScopeByToken(db, functionToken);
ASSERT(scope && scope->className == "f");
ASSERT(scope->functionOf && scope->functionOf == db->findScopeByName("d"));
const Function* function = findFunctionByName("f", &db->scopeList.back());
ASSERT(function && function->token->str() == "f");
ASSERT(function && function->token == functionToken);
ASSERT(function && function->hasBody());
}
void hasRegularFunctionReturningFunctionPointer() {
GET_SYMBOL_DB("void (*func(int f))(char) { }");
// 2 scopes: Global and Function
ASSERT(db && db->scopeList.size() == 2);
const Token * const functionToken = Token::findsimplematch(tokenizer.tokens(), "func");
const Scope *scope = findFunctionScopeByToken(db, functionToken);
ASSERT(scope && scope->className == "func");
const Function *function = findFunctionByName("func", &db->scopeList.front());
ASSERT(function && function->token->str() == "func");
ASSERT(function && function->token == functionToken);
ASSERT(function && function->hasBody());
}
void hasInlineClassFunctionReturningFunctionPointer() {
GET_SYMBOL_DB("class Fred { void (*func(int f))(char) { } };");
// 3 scopes: Global, Class, and Function
ASSERT(db && db->scopeList.size() == 3);
const Token * const functionToken = Token::findsimplematch(tokenizer.tokens(), "func");
const Scope *scope = findFunctionScopeByToken(db, functionToken);
ASSERT(scope && scope->className == "func");
const Function *function = findFunctionByName("func", &db->scopeList.back());
ASSERT(function && function->token->str() == "func");
ASSERT(function && function->token == functionToken);
ASSERT(function && function->hasBody() && function->isInline());
}
void hasMissingInlineClassFunctionReturningFunctionPointer() {
GET_SYMBOL_DB("class Fred { void (*func(int f))(char); };");
// 2 scopes: Global and Class (no Function scope because there is no function implementation)
ASSERT(db && db->scopeList.size() == 2);
const Token * const functionToken = Token::findsimplematch(tokenizer.tokens(), "func");
const Scope *scope = findFunctionScopeByToken(db, functionToken);
ASSERT(scope == nullptr);
const Function *function = findFunctionByName("func", &db->scopeList.back());
ASSERT(function && function->token->str() == "func");
ASSERT(function && function->token == functionToken);
ASSERT(function && !function->hasBody());
}
void hasClassFunctionReturningFunctionPointer() {
GET_SYMBOL_DB("class Fred { void (*func(int f))(char); }; void (*Fred::func(int f))(char) { }");
// 3 scopes: Global, Class, and Function
ASSERT(db && db->scopeList.size() == 3);
const Token * const functionToken = Token::findsimplematch(tokenizer.tokens()->linkAt(2), "func");
const Scope *scope = findFunctionScopeByToken(db, functionToken);
ASSERT(scope && scope->className == "func");
const Function *function = findFunctionByName("func", &db->scopeList.back());
ASSERT(function && function->token->str() == "func");
ASSERT(function && function->token == functionToken);
ASSERT(function && function->hasBody() && !function->isInline());
}
void methodWithRedundantScope() {
GET_SYMBOL_DB("class Fred { void Fred::func() {} };");
// 3 scopes: Global, Class, and Function
ASSERT(db && db->scopeList.size() == 3);
const Token * const functionToken = Token::findsimplematch(tokenizer.tokens(), "func");
const Scope *scope = findFunctionScopeByToken(db, functionToken);
ASSERT(scope && scope->className == "func");
const Function *function = findFunctionByName("func", &db->scopeList.back());
ASSERT(function && function->token->str() == "func");
ASSERT(function && function->token == functionToken);
ASSERT(function && function->hasBody() && function->isInline());
}
void complexFunctionArrayPtr() {
GET_SYMBOL_DB("int(*p1)[10]; \n" // pointer to array 10 of int
"void(*p2)(char); \n" // pointer to function (char) returning void
"int(*(*p3)(char))[10];\n" // pointer to function (char) returning pointer to array 10 of int
"float(*(*p4)(char))(long); \n" // pointer to function (char) returning pointer to function (long) returning float
"short(*(*(*p5) (char))(long))(double);\n" // pointer to function (char) returning pointer to function (long) returning pointer to function (double) returning short
"int(*a1[10])(void); \n" // array 10 of pointer to function (void) returning int
"float(*(*a2[10])(char))(long);\n" // array 10 of pointer to func (char) returning pointer to func (long) returning float
"short(*(*(*a3[10])(char))(long))(double);\n" // array 10 of pointer to function (char) returning pointer to function (long) returning pointer to function (double) returning short
"::boost::rational(&r_)[9];\n" // reference to array of ::boost::rational
"::boost::rational<T>(&r_)[9];"); // reference to array of ::boost::rational<T> (template!)
ASSERT(db != nullptr);
ASSERT_EQUALS(10, db->variableList().size() - 1);
ASSERT_EQUALS(true, db->getVariableFromVarId(1) && db->getVariableFromVarId(1)->dimensions().size() == 1);
ASSERT_EQUALS(true, db->getVariableFromVarId(2) != nullptr);
// NOLINTNEXTLINE(readability-container-size-empty)
ASSERT_EQUALS(true, db->getVariableFromVarId(3) && db->getVariableFromVarId(3)->dimensions().size() == 0);
ASSERT_EQUALS(true, db->getVariableFromVarId(4) != nullptr);
ASSERT_EQUALS(true, db->getVariableFromVarId(5) != nullptr);
ASSERT_EQUALS(true, db->getVariableFromVarId(6) && db->getVariableFromVarId(6)->dimensions().size() == 1);
ASSERT_EQUALS(true, db->getVariableFromVarId(7) && db->getVariableFromVarId(7)->dimensions().size() == 1);
ASSERT_EQUALS(true, db->getVariableFromVarId(8) && db->getVariableFromVarId(8)->dimensions().size() == 1);
ASSERT_EQUALS(true, db->getVariableFromVarId(9) && db->getVariableFromVarId(9)->dimensions().size() == 1);
ASSERT_EQUALS(true, db->getVariableFromVarId(10) && db->getVariableFromVarId(10)->dimensions().size() == 1);
ASSERT_EQUALS("", errout_str());
}
void pointerToMemberFunction() {
GET_SYMBOL_DB("bool (A::*pFun)();"); // Pointer to member function of A, returning bool and taking no parameters
ASSERT(db != nullptr);
ASSERT_EQUALS(1, db->variableList().size() - 1);
ASSERT_EQUALS(true, db->getVariableFromVarId(1) != nullptr);
ASSERT_EQUALS("pFun", db->getVariableFromVarId(1)->name());
ASSERT_EQUALS("", errout_str());
}
void hasSubClassConstructor() {
GET_SYMBOL_DB("class Foo { class Sub; }; class Foo::Sub { Sub() {} };");
ASSERT(db != nullptr);
bool seen_something = false;
for (const Scope & scope : db->scopeList) {
for (auto func = scope.functionList.cbegin(); func != scope.functionList.cend(); ++func) {
ASSERT_EQUALS("Sub", func->token->str());
ASSERT_EQUALS(true, func->hasBody());
ASSERT_EQUALS(Function::eConstructor, func->type);
seen_something = true;
}
}
ASSERT_EQUALS(true, seen_something);
}
void testConstructors() {
{
GET_SYMBOL_DB("class Foo { Foo(); };");
const Function* ctor = tokenizer.tokens()->tokAt(3)->function();
ASSERT(db && ctor && ctor->type == Function::eConstructor);
ASSERT(ctor && ctor->retDef == nullptr);
}
{
GET_SYMBOL_DB("class Foo { Foo(Foo f); };");
const Function* ctor = tokenizer.tokens()->tokAt(3)->function();
ASSERT(db && ctor && ctor->type == Function::eConstructor && !ctor->isExplicit());
ASSERT(ctor && ctor->retDef == nullptr);
}
{
GET_SYMBOL_DB("class Foo { explicit Foo(Foo f); };");
const Function* ctor = tokenizer.tokens()->tokAt(4)->function();
ASSERT(db && ctor && ctor->type == Function::eConstructor && ctor->isExplicit());
ASSERT(ctor && ctor->retDef == nullptr);
}
{
GET_SYMBOL_DB("class Foo { Foo(Bar& f); };");
const Function* ctor = tokenizer.tokens()->tokAt(3)->function();
ASSERT(db && ctor && ctor->type == Function::eConstructor);
ASSERT(ctor && ctor->retDef == nullptr);
}
{
GET_SYMBOL_DB("class Foo { Foo(Foo& f); };");
const Function* ctor = tokenizer.tokens()->tokAt(3)->function();
ASSERT(db && ctor && ctor->type == Function::eCopyConstructor);
ASSERT(ctor && ctor->retDef == nullptr);
}
{
GET_SYMBOL_DB("class Foo { Foo(const Foo &f); };");
const Function* ctor = tokenizer.tokens()->tokAt(3)->function();
ASSERT(db && ctor && ctor->type == Function::eCopyConstructor);
ASSERT(ctor && ctor->retDef == nullptr);
}
{
GET_SYMBOL_DB("template <T> class Foo { Foo(Foo<T>& f); };");
const Function* ctor = tokenizer.tokens()->tokAt(7)->function();
ASSERT(db && ctor && ctor->type == Function::eCopyConstructor);
ASSERT(ctor && ctor->retDef == nullptr);
}
{
GET_SYMBOL_DB("class Foo { Foo(Foo& f, int default = 0); };");
const Function* ctor = tokenizer.tokens()->tokAt(3)->function();
ASSERT(db && ctor && ctor->type == Function::eCopyConstructor);
ASSERT(ctor && ctor->retDef == nullptr);
}
{
GET_SYMBOL_DB("class Foo { Foo(Foo& f, char noDefault); };");
const Function* ctor = tokenizer.tokens()->tokAt(3)->function();
ASSERT(db && ctor && ctor->type == Function::eConstructor);
ASSERT(ctor && ctor->retDef == nullptr);
}
{
GET_SYMBOL_DB("class Foo { Foo(Foo&& f); };");
const Function* ctor = tokenizer.tokens()->tokAt(3)->function();
ASSERT(db && ctor && ctor->type == Function::eMoveConstructor);
ASSERT(ctor && ctor->retDef == nullptr);
}
{
GET_SYMBOL_DB("class Foo { Foo(Foo&& f, int default = 1, bool defaultToo = true); };");
const Function* ctor = tokenizer.tokens()->tokAt(3)->function();
ASSERT(db && ctor && ctor->type == Function::eMoveConstructor);
ASSERT(ctor && ctor->retDef == nullptr);
}
{
GET_SYMBOL_DB("void f() { extern void f(); }");
ASSERT(db && db->scopeList.size() == 2);
const Function* f = findFunctionByName("f", &db->scopeList.back());
ASSERT(f && f->type == Function::eFunction);
}
}
void functionDeclarationTemplate() {
GET_SYMBOL_DB("std::map<int, string> foo() {}");
// 2 scopes: Global and Function
ASSERT(db && db->scopeList.size() == 2 && findFunctionByName("foo", &db->scopeList.back()));
const Scope *scope = &db->scopeList.front();
ASSERT(scope && scope->functionList.size() == 1);
const Function *foo = &scope->functionList.front();
ASSERT(foo && foo->token->str() == "foo");
ASSERT(foo && foo->hasBody());
}
void functionDeclarations() {
GET_SYMBOL_DB("void foo();\nvoid foo();\nint foo(int i);\nvoid foo() {}");
// 2 scopes: Global and Function
ASSERT(db && db->scopeList.size() == 2 && findFunctionByName("foo", &db->scopeList.back()));
const Scope *scope = &db->scopeList.front();
ASSERT(scope && scope->functionList.size() == 2);
const Function *foo = &scope->functionList.front();
const Function *foo_int = &scope->functionList.back();
ASSERT(foo && foo->token->str() == "foo");
ASSERT(foo && foo->hasBody());
ASSERT(foo && foo->token->strAt(2) == ")");
ASSERT(foo_int && !foo_int->token);
ASSERT(foo_int && foo_int->tokenDef->str() == "foo");
ASSERT(foo_int && !foo_int->hasBody());
ASSERT(foo_int && foo_int->tokenDef->strAt(2) == "int");
ASSERT(&foo_int->argumentList.front() == db->getVariableFromVarId(1));
}
void functionDeclarations2() {
GET_SYMBOL_DB("std::array<int,2> foo(int x);");
// 1 scopes: Global
ASSERT(db && db->scopeList.size() == 1);
const Scope *scope = &db->scopeList.front();
ASSERT(scope && scope->functionList.size() == 1);
const Function *foo = &scope->functionList.front();
ASSERT(foo);
ASSERT(foo->tokenDef->str() == "foo");
ASSERT(!foo->hasBody());
const Token*parenthesis = foo->tokenDef->next();
ASSERT(parenthesis->str() == "(" && parenthesis->strAt(-1) == "foo");
ASSERT(parenthesis->valueType()->type == ValueType::Type::CONTAINER);
}
void constexprFunction() {
GET_SYMBOL_DB("constexpr int foo();");
// 1 scopes: Global
ASSERT(db && db->scopeList.size() == 1);
const Scope *scope = &db->scopeList.front();
ASSERT(scope && scope->functionList.size() == 1);
const Function *foo = &scope->functionList.front();
ASSERT(foo);
ASSERT(foo->tokenDef->str() == "foo");
ASSERT(!foo->hasBody());
ASSERT(foo->isConstexpr());
}
void constructorInitialization() {
GET_SYMBOL_DB("std::string logfile;\n"
"std::ofstream log(logfile.c_str(), std::ios::out);");
// 1 scope: Global
ASSERT(db && db->scopeList.size() == 1);
// No functions
ASSERT(db->scopeList.front().functionList.empty());
}
void memberFunctionOfUnknownClassMacro1() {
GET_SYMBOL_DB("class ScVbaFormatCondition { OUString getServiceImplName() SAL_OVERRIDE; };\n"
"void ScVbaValidation::getFormula1() {\n"
" sal_uInt16 nFlags = 0;\n"
" if (pDocSh && !getCellRangesForAddress(nFlags)) ;\n"
"}");
ASSERT(db && errout_str().empty());
const Scope *scope = db->findScopeByName("getFormula1");
ASSERT(scope != nullptr);
ASSERT(scope && scope->nestedIn == &db->scopeList.front());
}
void memberFunctionOfUnknownClassMacro2() {
GET_SYMBOL_DB("class ScVbaFormatCondition { OUString getServiceImplName() SAL_OVERRIDE {} };\n"
"void getFormula1() {\n"
" sal_uInt16 nFlags = 0;\n"
" if (pDocSh && !getCellRangesForAddress(nFlags)) ;\n"
"}");
ASSERT(db && errout_str().empty());
const Scope *scope = db->findScopeByName("getFormula1");
ASSERT(scope != nullptr);
ASSERT(scope && scope->nestedIn == &db->scopeList.front());
scope = db->findScopeByName("getServiceImplName");
ASSERT(scope != nullptr);
ASSERT(scope && scope->nestedIn && scope->nestedIn->className == "ScVbaFormatCondition");
}
void memberFunctionOfUnknownClassMacro3() {
GET_SYMBOL_DB("class ScVbaFormatCondition { OUString getServiceImplName() THROW(whatever); };\n"
"void ScVbaValidation::getFormula1() {\n"
" sal_uInt16 nFlags = 0;\n"
" if (pDocSh && !getCellRangesForAddress(nFlags)) ;\n"
"}");
ASSERT(db && errout_str().empty());
const Scope *scope = db->findScopeByName("getFormula1");
ASSERT(scope != nullptr);
ASSERT(scope && scope->nestedIn == &db->scopeList.front());
}
void functionLinkage() {
GET_SYMBOL_DB("static void f1() { }\n"
"void f2();\n"
"extern void f3();\n"
"void f4();\n"
"extern void f5() { };\n"
"void f6() { }");
ASSERT(db && errout_str().empty());
const Token *f = Token::findsimplematch(tokenizer.tokens(), "f1");
ASSERT(f && f->function() && f->function()->isStaticLocal() && f->function()->retDef->str() == "void");
f = Token::findsimplematch(tokenizer.tokens(), "f2");
ASSERT(f && f->function() && !f->function()->isStaticLocal() && f->function()->retDef->str() == "void");
f = Token::findsimplematch(tokenizer.tokens(), "f3");
ASSERT(f && f->function() && f->function()->isExtern() && f->function()->retDef->str() == "void");
f = Token::findsimplematch(tokenizer.tokens(), "f4");
ASSERT(f && f->function() && !f->function()->isExtern() && f->function()->retDef->str() == "void");
f = Token::findsimplematch(tokenizer.tokens(), "f5");
ASSERT(f && f->function() && f->function()->isExtern() && f->function()->retDef->str() == "void");
f = Token::findsimplematch(tokenizer.tokens(), "f6");
ASSERT(f && f->function() && !f->function()->isExtern() && f->function()->retDef->str() == "void");
}
void externalFunctionsInsideAFunction() {
GET_SYMBOL_DB("void foo( void )\n"
"{\n"
" extern void bar( void );\n"
" bar();\n"
"}\n");
ASSERT(db && errout_str().empty());
const Token *f = Token::findsimplematch(tokenizer.tokens(), "bar");
ASSERT(f && f->function() && f->function()->isExtern() && f == f->function()->tokenDef && f->function()->retDef->str() == "void");
const Token *call = Token::findsimplematch(f->next(), "bar");
ASSERT(call && call->function() == f->function());
}
void namespacedFunctionInsideExternBlock() {
// Should not crash
GET_SYMBOL_DB("namespace N {\n"
" void f();\n"
"}\n"
"extern \"C\" {\n"
" void f() {\n"
" N::f();\n"
" }\n"
"}\n");
ASSERT(db && errout_str().empty());
}
void classWithFriend() {
GET_SYMBOL_DB("class Foo {}; class Bar1 { friend class Foo; }; class Bar2 { friend Foo; };");
// 3 scopes: Global, 3 classes
ASSERT(db && db->scopeList.size() == 4);
const Scope* foo = db->findScopeByName("Foo");
ASSERT(foo != nullptr);
const Scope* bar1 = db->findScopeByName("Bar1");
ASSERT(bar1 != nullptr);
const Scope* bar2 = db->findScopeByName("Bar2");
ASSERT(bar2 != nullptr);
ASSERT(bar1->definedType->friendList.size() == 1 && bar1->definedType->friendList.front().nameEnd->str() == "Foo" && bar1->definedType->friendList.front().type == foo->definedType);
ASSERT(bar2->definedType->friendList.size() == 1 && bar2->definedType->friendList.front().nameEnd->str() == "Foo" && bar2->definedType->friendList.front().type == foo->definedType);
}
void parseFunctionCorrect() {
// ticket 3188 - "if" statement parsed as function
GET_SYMBOL_DB("void func(i) int i; { if (i == 1) return; }");
ASSERT(db != nullptr);
// 3 scopes: Global, function, if
ASSERT_EQUALS(3, db->scopeList.size());
ASSERT(findFunctionByName("func", &db->scopeList.back()) != nullptr);
ASSERT(findFunctionByName("if", &db->scopeList.back()) == nullptr);
}
void parseFunctionDeclarationCorrect() {
GET_SYMBOL_DB("void func();\n"
"int bar() {}\n"
"void func() {}");
ASSERT_EQUALS(3, db->findScopeByName("func")->bodyStart->linenr());
}
void Cpp11InitInInitList() {
GET_SYMBOL_DB("class Foo {\n"
" std::vector<std::string> bar;\n"
" Foo() : bar({\"a\", \"b\"})\n"
" {}\n"
"};");
ASSERT_EQUALS(4, db->scopeList.front().nestedList.front()->nestedList.front()->bodyStart->linenr());
}
void hasGlobalVariables1() {
GET_SYMBOL_DB("int i;");
ASSERT(db && db->scopeList.size() == 1);
const std::list<Scope>::const_iterator it = db->scopeList.cbegin();
ASSERT(it->varlist.size() == 1);
const std::list<Variable>::const_iterator var = it->varlist.cbegin();
ASSERT(var->name() == "i");
ASSERT(var->typeStartToken()->str() == "int");
}
void hasGlobalVariables2() {
GET_SYMBOL_DB("int array[2][2];");
ASSERT(db && db->scopeList.size() == 1);
const std::list<Scope>::const_iterator it = db->scopeList.cbegin();
ASSERT(it->varlist.size() == 1);
const std::list<Variable>::const_iterator var = it->varlist.cbegin();
ASSERT(var->name() == "array");
ASSERT(var->typeStartToken()->str() == "int");
}
void hasGlobalVariables3() {
GET_SYMBOL_DB("int array[2][2] = { { 0, 0 }, { 0, 0 } };");
ASSERT(db && db->scopeList.size() == 1);
const std::list<Scope>::const_iterator it = db->scopeList.cbegin();
ASSERT(it->varlist.size() == 1);
const std::list<Variable>::const_iterator var = it->varlist.cbegin();
ASSERT(var->name() == "array");
ASSERT(var->typeStartToken()->str() == "int");
}
void checkTypeStartEndToken1() {
GET_SYMBOL_DB("static std::string i;\n"
"static const std::string j;\n"
"const std::string* k;\n"
"const char m[];\n"
"void f(const char* const l) {}");
ASSERT(db && db->variableList().size() == 6 && db->getVariableFromVarId(1) && db->getVariableFromVarId(2) && db->getVariableFromVarId(3) && db->getVariableFromVarId(4) && db->getVariableFromVarId(5));
ASSERT_EQUALS("std", db->getVariableFromVarId(1)->typeStartToken()->str());
ASSERT_EQUALS("std", db->getVariableFromVarId(2)->typeStartToken()->str());
ASSERT_EQUALS("std", db->getVariableFromVarId(3)->typeStartToken()->str());
ASSERT_EQUALS("char", db->getVariableFromVarId(4)->typeStartToken()->str());
ASSERT_EQUALS("char", db->getVariableFromVarId(5)->typeStartToken()->str());
ASSERT_EQUALS("string", db->getVariableFromVarId(1)->typeEndToken()->str());
ASSERT_EQUALS("string", db->getVariableFromVarId(2)->typeEndToken()->str());
ASSERT_EQUALS("*", db->getVariableFromVarId(3)->typeEndToken()->str());
ASSERT_EQUALS("char", db->getVariableFromVarId(4)->typeEndToken()->str());
ASSERT_EQUALS("*", db->getVariableFromVarId(5)->typeEndToken()->str());
}
void checkTypeStartEndToken2() {
GET_SYMBOL_DB("class CodeGenerator {\n"
" DiagnosticsEngine Diags;\n"
"public:\n"
" void Initialize() {\n"
" Builder.reset(Diags);\n"
" }\n"
"\n"
" void HandleTagDeclRequiredDefinition() LLVM_OVERRIDE {\n"
" if (Diags.hasErrorOccurred())\n"
" return;\n"
" }\n"
"};");
ASSERT_EQUALS("DiagnosticsEngine", db->getVariableFromVarId(1)->typeStartToken()->str());
}
void checkTypeStartEndToken3() {
GET_SYMBOL_DB("void f(const char) {}");
ASSERT(db && db->functionScopes.size()==1U);
const Function * const f = db->functionScopes.front()->function;
ASSERT_EQUALS(1U, f->argCount());
ASSERT_EQUALS(0U, f->initializedArgCount());
ASSERT_EQUALS(1U, f->minArgCount());
const Variable * const arg1 = f->getArgumentVar(0);
ASSERT_EQUALS("char", arg1->typeStartToken()->str());
ASSERT_EQUALS("char", arg1->typeEndToken()->str());
}
#define check(...) check_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
void check_(const char* file, int line, const char (&code)[size], bool debug = true, bool cpp = true, const Settings* pSettings = nullptr) {
// Check..
const Settings settings = settingsBuilder(pSettings ? *pSettings : settings1).debugwarnings(debug).build();
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code, cpp), file, line);
// force symbol database creation
tokenizer.createSymbolDatabase();
}
void functionArgs1() {
{
GET_SYMBOL_DB("void f(std::vector<std::string>, const std::vector<int> & v) { }");
ASSERT_EQUALS(1+1, db->variableList().size());
const Variable* v = db->getVariableFromVarId(1);
ASSERT(v && v->isReference() && v->isConst() && v->isArgument());
const Scope* f = db->findScopeByName("f");
ASSERT(f && f->type == Scope::eFunction && f->function);
ASSERT(f->function->argumentList.size() == 2 && f->function->argumentList.front().index() == 0 && f->function->argumentList.front().name().empty() && f->function->argumentList.back().index() == 1);
ASSERT_EQUALS("", errout_str());
}
{
GET_SYMBOL_DB("void g(std::map<std::string, std::vector<int> > m) { }");
ASSERT_EQUALS(1+1, db->variableList().size());
const Variable* m = db->getVariableFromVarId(1);
ASSERT(m && !m->isReference() && !m->isConst() && m->isArgument() && m->isClass());
const Scope* g = db->findScopeByName("g");
ASSERT(g && g->type == Scope::eFunction && g->function && g->function->argumentList.size() == 1 && g->function->argumentList.front().index() == 0);
ASSERT_EQUALS("", errout_str());
}
{
GET_SYMBOL_DB("void g(std::map<int, int> m = std::map<int, int>()) { }");
const Scope* g = db->findScopeByName("g");
ASSERT(g && g->type == Scope::eFunction && g->function && g->function->argumentList.size() == 1 && g->function->argumentList.front().index() == 0 && g->function->initializedArgCount() == 1);
ASSERT_EQUALS("", errout_str());
}
{
GET_SYMBOL_DB("void g(int = 0) { }");
const Scope* g = db->findScopeByName("g");
ASSERT(g && g->type == Scope::eFunction && g->function && g->function->argumentList.size() == 1 && g->function->argumentList.front().hasDefault());
ASSERT_EQUALS("", errout_str());
}
{
GET_SYMBOL_DB("void g(int*) { }"); // unnamed pointer argument (#8052)
const Scope* g = db->findScopeByName("g");
ASSERT(g && g->type == Scope::eFunction && g->function && g->function->argumentList.size() == 1 && g->function->argumentList.front().nameToken() == nullptr && g->function->argumentList.front().isPointer());
ASSERT_EQUALS("", errout_str());
}
{
GET_SYMBOL_DB("void g(int* const) { }"); // 'const' is not the name of the variable - #5882
const Scope* g = db->findScopeByName("g");
ASSERT(g && g->type == Scope::eFunction && g->function && g->function->argumentList.size() == 1 && g->function->argumentList.front().nameToken() == nullptr);
ASSERT_EQUALS("", errout_str());
}
}
void functionArgs2() {
GET_SYMBOL_DB("void f(int a[][4]) { }");
const Variable *a = db->getVariableFromVarId(1);
ASSERT_EQUALS("a", a->nameToken()->str());
ASSERT_EQUALS(2UL, a->dimensions().size());
ASSERT_EQUALS(0UL, a->dimension(0));
ASSERT_EQUALS(false, a->dimensions()[0].known);
ASSERT_EQUALS(4UL, a->dimension(1));
ASSERT_EQUALS(true, a->dimensions()[1].known);
}
void functionArgs4() {
GET_SYMBOL_DB("void f1(char [10], struct foo [10]);");
ASSERT_EQUALS(true, db->scopeList.front().functionList.size() == 1UL);
const Function *func = &db->scopeList.front().functionList.front();
ASSERT_EQUALS(true, func && func->argumentList.size() == 2UL);
const Variable *first = &func->argumentList.front();
ASSERT_EQUALS(0UL, first->name().size());
ASSERT_EQUALS(1UL, first->dimensions().size());
ASSERT_EQUALS(10UL, first->dimension(0));
const Variable *second = &func->argumentList.back();
ASSERT_EQUALS(0UL, second->name().size());
ASSERT_EQUALS(1UL, second->dimensions().size());
ASSERT_EQUALS(10UL, second->dimension(0));
}
void functionArgs5() { // #7650
GET_SYMBOL_DB("class ABC {};\n"
"class Y {\n"
" enum ABC {A,B,C};\n"
" void f(enum ABC abc) {}\n"
"};");
ASSERT_EQUALS(true, db != nullptr);
const Token *f = Token::findsimplematch(tokenizer.tokens(), "f ( enum");
ASSERT_EQUALS(true, f && f->function());
const Function *func = f->function();
ASSERT_EQUALS(true, func->argumentList.size() == 1 && func->argumentList.front().type());
const Type * type = func->argumentList.front().type();
ASSERT_EQUALS(true, type->isEnumType());
}
void functionArgs6() { // #7651
GET_SYMBOL_DB("class ABC {};\n"
"class Y {\n"
" enum ABC {A,B,C};\n"
" void f(ABC abc) {}\n"
"};");
ASSERT_EQUALS(true, db != nullptr);
const Token *f = Token::findsimplematch(tokenizer.tokens(), "f ( ABC");
ASSERT_EQUALS(true, f && f->function());
const Function *func = f->function();
ASSERT_EQUALS(true, func->argumentList.size() == 1 && func->argumentList.front().type());
const Type * type = func->argumentList.front().type();
ASSERT_EQUALS(true, type->isEnumType());
}
void functionArgs7() { // #7652
{
GET_SYMBOL_DB("struct AB { int a; int b; };\n"
"int foo(struct AB *ab);\n"
"void bar() {\n"
" struct AB ab;\n"
" foo(&ab);\n"
"};");
ASSERT_EQUALS(true, db != nullptr);
const Token *f = Token::findsimplematch(tokenizer.tokens(), "foo ( & ab");
ASSERT_EQUALS(true, f && f->function());
const Function *func = f->function();
ASSERT_EQUALS(true, func->tokenDef->linenr() == 2 && func->argumentList.size() == 1 && func->argumentList.front().type());
const Type * type = func->argumentList.front().type();
ASSERT_EQUALS(true, type->classDef->linenr() == 1);
}
{
GET_SYMBOL_DB("struct AB { int a; int b; };\n"
"int foo(AB *ab);\n"
"void bar() {\n"
" struct AB ab;\n"
" foo(&ab);\n"
"};");
ASSERT_EQUALS(true, db != nullptr);
const Token *f = Token::findsimplematch(tokenizer.tokens(), "foo ( & ab");
ASSERT_EQUALS(true, f && f->function());
const Function *func = f->function();
ASSERT_EQUALS(true, func->tokenDef->linenr() == 2 && func->argumentList.size() == 1 && func->argumentList.front().type());
const Type * type = func->argumentList.front().type();
ASSERT_EQUALS(true, type->classDef->linenr() == 1);
}
{
GET_SYMBOL_DB("struct AB { int a; int b; };\n"
"int foo(struct AB *ab);\n"
"void bar() {\n"
" AB ab;\n"
" foo(&ab);\n"
"};");
ASSERT_EQUALS(true, db != nullptr);
const Token *f = Token::findsimplematch(tokenizer.tokens(), "foo ( & ab");
ASSERT_EQUALS(true, f && f->function());
const Function *func = f->function();
ASSERT_EQUALS(true, func->tokenDef->linenr() == 2 && func->argumentList.size() == 1 && func->argumentList.front().type());
const Type * type = func->argumentList.front().type();
ASSERT_EQUALS(true, type->classDef->linenr() == 1);
}
{
GET_SYMBOL_DB("struct AB { int a; int b; };\n"
"int foo(AB *ab);\n"
"void bar() {\n"
" AB ab;\n"
" foo(&ab);\n"
"};");
ASSERT_EQUALS(true, db != nullptr);
const Token *f = Token::findsimplematch(tokenizer.tokens(), "foo ( & ab");
ASSERT_EQUALS(true, f && f->function());
const Function *func = f->function();
ASSERT_EQUALS(true, func->tokenDef->linenr() == 2 && func->argumentList.size() == 1 && func->argumentList.front().type());
const Type * type = func->argumentList.front().type();
ASSERT_EQUALS(true, type->classDef->linenr() == 1);
}
}
void functionArgs8() { // #7653
GET_SYMBOL_DB("struct A { int i; };\n"
"struct B { double d; };\n"
"int foo(struct A a);\n"
"double foo(struct B b);\n"
"void bar() {\n"
" struct B b;\n"
" foo(b);\n"
"}");
ASSERT_EQUALS(true, db != nullptr);
const Token *f = Token::findsimplematch(tokenizer.tokens(), "foo ( b");
ASSERT_EQUALS(true, f && f->function());
const Function *func = f->function();
ASSERT_EQUALS(true, func->tokenDef->linenr() == 4 && func->argumentList.size() == 1 && func->argumentList.front().type());
const Type * type = func->argumentList.front().type();
ASSERT_EQUALS(true, type->isStructType());
}
void functionArgs9() { // #7657
GET_SYMBOL_DB("struct A {\n"
" struct B {\n"
" enum C { };\n"
" };\n"
"};\n"
"void foo(A::B::C c) { }");
ASSERT_EQUALS(true, db != nullptr);
const Token *f = Token::findsimplematch(tokenizer.tokens(), "foo (");
ASSERT_EQUALS(true, f && f->function());
const Function *func = f->function();
ASSERT_EQUALS(true, func->argumentList.size() == 1 && func->argumentList.front().type());
const Type * type = func->argumentList.front().type();
ASSERT_EQUALS(true, type->isEnumType());
}
void functionArgs10() {
GET_SYMBOL_DB("class Fred {\n"
"public:\n"
" Fred(Whitespace = PRESERVE_WHITESPACE);\n"
"};\n"
"Fred::Fred(Whitespace whitespace) { }");
ASSERT_EQUALS(true, db != nullptr);
ASSERT_EQUALS(3, db->scopeList.size());
auto scope = db->scopeList.cbegin();
++scope;
ASSERT_EQUALS((unsigned int)Scope::eClass, (unsigned int)scope->type);
ASSERT_EQUALS(1, scope->functionList.size());
ASSERT(scope->functionList.cbegin()->functionScope != nullptr);
const Scope * functionScope = scope->functionList.cbegin()->functionScope;
++scope;
ASSERT(functionScope == &*scope);
}
void functionArgs11() {
GET_SYMBOL_DB("class Fred {\n"
"public:\n"
" void foo(char a[16]);\n"
"};\n"
"void Fred::foo(char b[16]) { }");
ASSERT_EQUALS(true, db != nullptr);
ASSERT_EQUALS(3, db->scopeList.size());
auto scope = db->scopeList.cbegin();
++scope;
ASSERT_EQUALS((unsigned int)Scope::eClass, (unsigned int)scope->type);
ASSERT_EQUALS(1, scope->functionList.size());
ASSERT(scope->functionList.cbegin()->functionScope != nullptr);
const Scope * functionScope = scope->functionList.cbegin()->functionScope;
++scope;
ASSERT(functionScope == &*scope);
}
void functionArgs12() { // #7661
GET_SYMBOL_DB("struct A {\n"
" enum E { };\n"
" int a[10];\n"
"};\n"
"struct B : public A {\n"
" void foo(B::E e) { }\n"
"};");
ASSERT_EQUALS(true, db != nullptr);
const Token *f = Token::findsimplematch(tokenizer.tokens(), "foo (");
ASSERT_EQUALS(true, f && f->function());
const Function *func = f->function();
ASSERT_EQUALS(true, func->argumentList.size() == 1 && func->argumentList.front().type());
const Type * type = func->argumentList.front().type();
ASSERT_EQUALS(true, type->isEnumType());
}
void functionArgs13() { // #7697
GET_SYMBOL_DB("struct A {\n"
" enum E { };\n"
" struct S { };\n"
"};\n"
"struct B : public A {\n"
" B(E e);\n"
" B(S s);\n"
"};\n"
"B::B(A::E e) { }\n"
"B::B(A::S s) { }");
ASSERT_EQUALS(true, db != nullptr);
const Token *f = Token::findsimplematch(tokenizer.tokens(), "B ( A :: E");
ASSERT_EQUALS(true, f && f->function());
const Function *func = f->function();
ASSERT_EQUALS(true, func->argumentList.size() == 1 && func->argumentList.front().type());
const Type * type = func->argumentList.front().type();
ASSERT_EQUALS(true, type->isEnumType() && type->name() == "E");
f = Token::findsimplematch(tokenizer.tokens(), "B ( A :: S");
ASSERT_EQUALS(true, f && f->function());
const Function *func2 = f->function();
ASSERT_EQUALS(true, func2->argumentList.size() == 1 && func2->argumentList.front().type());
const Type * type2 = func2->argumentList.front().type();
ASSERT_EQUALS(true, type2->isStructType() && type2->name() == "S");
}
void functionArgs14() { // #7697
GET_SYMBOL_DB("void f(int (&a)[10], int (&b)[10]);");
(void)db;
const Function *func = tokenizer.tokens()->next()->function();
ASSERT_EQUALS(true, func != nullptr);
ASSERT_EQUALS(2, func ? func->argCount() : 0);
ASSERT_EQUALS(0, func ? func->initializedArgCount() : 1);
ASSERT_EQUALS(2, func ? func->minArgCount() : 0);
}
void functionArgs15() { // #7159
const char code[] =
"class Class {\n"
" void Method(\n"
" char c = []()->char {\n"
" int d = rand();\n"// the '=' on this line used to reproduce the defect
" return d;\n"
" }()\n"
" );\n"
"};\n";
GET_SYMBOL_DB(code);
ASSERT(db);
ASSERT_EQUALS(2, db->scopeList.size());
const Scope& classScope = db->scopeList.back();
ASSERT_EQUALS(Scope::eClass, classScope.type);
ASSERT_EQUALS("Class", classScope.className);
ASSERT_EQUALS(1, classScope.functionList.size());
const Function& method = classScope.functionList.front();
ASSERT_EQUALS("Method", method.name());
ASSERT_EQUALS(1, method.argCount());
ASSERT_EQUALS(1, method.initializedArgCount());
ASSERT_EQUALS(0, method.minArgCount());
}
void functionArgs16() { // #9591
const char code[] =
"struct A { int var; };\n"
"void foo(int x, decltype(A::var) *&p) {}";
GET_SYMBOL_DB(code);
ASSERT(db);
const Scope *scope = db->functionScopes.front();
const Function *func = scope->function;
ASSERT_EQUALS(2, func->argCount());
const Variable *arg2 = func->getArgumentVar(1);
ASSERT_EQUALS("p", arg2->name());
ASSERT(arg2->isPointer());
ASSERT(arg2->isReference());
}
void functionArgs17() {
const char code[] = "void f(int (*fp)(), int x, int y) {}";
GET_SYMBOL_DB(code);
ASSERT(db != nullptr);
const Scope *scope = db->functionScopes.front();
const Function *func = scope->function;
ASSERT_EQUALS(3, func->argCount());
}
void functionArgs18() {
const char code[] = "void f(int (*param1)[2], int param2) {}";
GET_SYMBOL_DB(code);
ASSERT(db != nullptr);
const Scope *scope = db->functionScopes.front();
const Function *func = scope->function;
ASSERT_EQUALS(2, func->argCount());
}
void functionArgs19() {
const char code[] = "void f(int (*fp)(int), int x, int y) {}";
GET_SYMBOL_DB(code);
ASSERT(db != nullptr);
const Scope *scope = db->functionScopes.front();
const Function *func = scope->function;
ASSERT_EQUALS(3, func->argCount());
}
void functionArgs20() {
{
const char code[] = "void f(void *(*g)(void *) = [](void *p) { return p; }) {}"; // #11769
GET_SYMBOL_DB(code);
ASSERT(db != nullptr);
const Scope *scope = db->functionScopes.front();
const Function *func = scope->function;
ASSERT_EQUALS(1, func->argCount());
const Variable* arg = func->getArgumentVar(0);
TODO_ASSERT(arg->hasDefault());
}
{
const char code[] = "void f() { auto g = [&](const std::function<int(int)>& h = [](int i) -> int { return i; }) {}; }"; // #12338
GET_SYMBOL_DB(code);
ASSERT(db != nullptr);
ASSERT_EQUALS(3, db->scopeList.size());
ASSERT_EQUALS(Scope::ScopeType::eLambda, db->scopeList.back().type);
}
{
const char code[] = "void f() {\n"
" auto g = [&](const std::function<const std::vector<int>&(const std::vector<int>&)>& h = [](const std::vector<int>& v) -> const std::vector<int>& { return v; }) {};\n"
"}\n";
GET_SYMBOL_DB(code);
ASSERT(db != nullptr);
ASSERT_EQUALS(3, db->scopeList.size());
ASSERT_EQUALS(Scope::ScopeType::eLambda, db->scopeList.back().type);
}
{
const char code[] = "void f() {\n"
" auto g = [&](const std::function<int(int)>& h = [](int i) -> decltype(0) { return i; }) {};\n"
"}\n";
GET_SYMBOL_DB(code);
ASSERT(db != nullptr);
ASSERT_EQUALS(3, db->scopeList.size());
ASSERT_EQUALS(Scope::ScopeType::eLambda, db->scopeList.back().type);
}
}
void functionArgs21() {
const char code[] = "void f(std::vector<int>::size_type) {}\n" // #11408
"template<typename T>\n"
"struct S { using t = int; };\n"
"template<typename T>\n"
"S<T> operator+(const S<T>&lhs, typename S<T>::t) { return lhs; }";
GET_SYMBOL_DB(code);
ASSERT(db != nullptr);
auto it = db->functionScopes.begin();
const Function *func = (*it)->function;
ASSERT_EQUALS("f", func->name());
ASSERT_EQUALS(1, func->argCount());
const Variable* arg = func->getArgumentVar(0);
ASSERT_EQUALS("", arg->name());
++it;
func = (*it)->function;
ASSERT_EQUALS("operator+", func->name());
ASSERT_EQUALS(2, func->argCount());
arg = func->getArgumentVar(1);
ASSERT_EQUALS("", arg->name());
}
void functionImplicitlyVirtual() {
GET_SYMBOL_DB("class base { virtual void f(); };\n"
"class derived : base { void f(); };\n"
"void derived::f() {}");
ASSERT(db != nullptr);
ASSERT_EQUALS(4, db->scopeList.size());
const Function *function = db->scopeList.back().function;
ASSERT_EQUALS(true, function && function->isImplicitlyVirtual(false));
}
void functionGetOverridden() {
GET_SYMBOL_DB("struct B { virtual void f(); };\n"
"struct D : B {\n"
"public:\n"
" void f() override;\n"
"};\n"
"struct D2 : D { void f() override {} };\n");
ASSERT(db != nullptr);
ASSERT_EQUALS(5, db->scopeList.size());
const Function *func = db->scopeList.back().function;
ASSERT(func && func->nestedIn);
ASSERT_EQUALS("D2", func->nestedIn->className);
bool foundAllBaseClasses{};
const Function* baseFunc = func->getOverriddenFunction(&foundAllBaseClasses);
ASSERT(baseFunc && baseFunc->nestedIn && foundAllBaseClasses);
ASSERT_EQUALS("D", baseFunc->nestedIn->className);
}
void functionIsInlineKeyword() {
GET_SYMBOL_DB("inline void fs() {}");
(void)db;
const Function *func = db->scopeList.back().function;
ASSERT(func);
ASSERT(func->isInlineKeyword());
}
void functionStatic() {
GET_SYMBOL_DB("static void fs() { }");
(void)db;
const Function *func = db->scopeList.back().function;
ASSERT(func);
ASSERT(func->isStatic());
}
void functionReturnsReference() {
GET_SYMBOL_DB("Fred::Reference foo();");
ASSERT_EQUALS(1, db->scopeList.back().functionList.size());
const Function &func = *db->scopeList.back().functionList.cbegin();
ASSERT(!Function::returnsReference(&func, false));
ASSERT(Function::returnsReference(&func, true));
}
void namespaces1() {
GET_SYMBOL_DB("namespace fred {\n"
" namespace barney {\n"
" class X { X(int); };\n"
" }\n"
"}\n"
"namespace barney { X::X(int) { } }");
// Locate the scope for the class..
auto it = std::find_if(db->scopeList.cbegin(), db->scopeList.cend(), [](const Scope& s) {
return s.isClassOrStruct();
});
const Scope *scope = (it == db->scopeList.end()) ? nullptr : &*it;
ASSERT(scope != nullptr);
if (!scope)
return;
ASSERT_EQUALS("X", scope->className);
// The class has a constructor but the implementation _is not_ seen
ASSERT_EQUALS(1U, scope->functionList.size());
const Function *function = &(scope->functionList.front());
ASSERT_EQUALS(false, function->hasBody());
}
// based on namespaces1 but here the namespaces match
void namespaces2() {
GET_SYMBOL_DB("namespace fred {\n"
" namespace barney {\n"
" class X { X(int); };\n"
" }\n"
"}\n"
"namespace fred {\n"
" namespace barney {\n"
" X::X(int) { }\n"
" }\n"
"}");
// Locate the scope for the class..
auto it = std::find_if(db->scopeList.cbegin(), db->scopeList.cend(), [](const Scope& s) {
return s.isClassOrStruct();
});
const Scope* scope = (it == db->scopeList.end()) ? nullptr : &*it;
ASSERT(scope != nullptr);
if (!scope)
return;
ASSERT_EQUALS("X", scope->className);
// The class has a constructor and the implementation _is_ seen
ASSERT_EQUALS(1U, scope->functionList.size());
const Function *function = &(scope->functionList.front());
ASSERT_EQUALS("X", function->tokenDef->str());
ASSERT_EQUALS(true, function->hasBody());
}
void namespaces3() { // #3854 - namespace with unknown macro
GET_SYMBOL_DB("namespace fred UNKNOWN_MACRO(default) {\n"
"}");
ASSERT_EQUALS(2U, db->scopeList.size());
ASSERT_EQUALS(Scope::eGlobal, db->scopeList.front().type);
ASSERT_EQUALS(Scope::eNamespace, db->scopeList.back().type);
}
void namespaces4() { // #4698 - type lookup
GET_SYMBOL_DB("struct A { int a; };\n"
"namespace fred { struct A {}; }\n"
"fred::A fredA;");
const Variable *fredA = db->getVariableFromVarId(2U);
ASSERT_EQUALS("fredA", fredA->name());
const Type *fredAType = fredA->type();
ASSERT_EQUALS(2U, fredAType->classDef->linenr());
}
void needInitialization() {
{
GET_SYMBOL_DB_DBG("template <typename T>\n" // #10259
"struct A {\n"
" using type = T;\n"
" type t_;\n"
"};\n");
ASSERT_EQUALS("", errout_str());
}
{
GET_SYMBOL_DB_DBG("class T;\n" // #12367
"struct S {\n"
" S(T& t);\n"
" T& _t;\n"
"};\n");
ASSERT_EQUALS("", errout_str());
}
{
GET_SYMBOL_DB_DBG("struct S {\n" // #12395
" static S s;\n"
"};\n");
ASSERT_EQUALS("", errout_str());
const Variable* const s = db->getVariableFromVarId(1);
ASSERT(s->scope()->definedType->needInitialization == Type::NeedInitialization::False);
}
}
void tryCatch1() {
const char str[] = "void foo() {\n"
" try { }\n"
" catch (const Error1 & x) { }\n"
" catch (const X::Error2 & x) { }\n"
" catch (Error3 x) { }\n"
" catch (X::Error4 x) { }\n"
"}";
GET_SYMBOL_DB(str);
ASSERT_EQUALS("", errout_str());
ASSERT(db && db->variableList().size() == 5); // index 0 + 4 variables
ASSERT(db && db->scopeList.size() == 7); // global + function + try + 4 catch
}
void symboldatabase1() {
check("namespace foo {\n"
" class bar;\n"
"};");
ASSERT_EQUALS("", errout_str());
check("class foo : public bar < int, int> {\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void symboldatabase2() {
check("class foo {\n"
"public:\n"
"foo() { }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("class foo {\n"
"class bar;\n"
"foo() { }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void symboldatabase3() {
check("typedef void (func_type)();\n"
"struct A {\n"
" friend func_type f : 2;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void symboldatabase4() {
check("static void function_declaration_before(void) __attribute__((__used__));\n"
"static void function_declaration_before(void) {}\n"
"static void function_declaration_after(void) {}\n"
"static void function_declaration_after(void) __attribute__((__used__));");
ASSERT_EQUALS("", errout_str());
check("main(int argc, char *argv[]) { }", true, false);
ASSERT_EQUALS("", errout_str());
const Settings s = settingsBuilder(settings1).severity(Severity::portability).build();
check("main(int argc, char *argv[]) { }", false, false, &s);
ASSERT_EQUALS("[test.c:1]: (portability) Omitted return type of function 'main' defaults to int, this is not supported by ISO C99 and later standards.\n",
errout_str());
check("namespace boost {\n"
" std::locale generate_locale()\n"
" {\n"
" return std::locale();\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("namespace X {\n"
" static void function_declaration_before(void) __attribute__((__used__));\n"
" static void function_declaration_before(void) {}\n"
" static void function_declaration_after(void) {}\n"
" static void function_declaration_after(void) __attribute__((__used__));\n"
"}");
ASSERT_EQUALS("", errout_str());
check("testing::testing()\n"
"{\n"
"}");
ASSERT_EQUALS(
"[test.cpp:1]: (debug) Executable scope 'testing' with unknown function.\n"
"[test.cpp:1]: (debug) Executable scope 'testing' with unknown function.\n", // duplicate
errout_str());
}
void symboldatabase5() {
// ticket #2178 - segmentation fault
ASSERT_THROW_INTERNAL(check("int CL_INLINE_DECL(integer_decode_float) (int x) {\n"
" return (sign ? cl_I() : 0);\n"
"}"), UNKNOWN_MACRO);
}
void symboldatabase6() {
// ticket #2221 - segmentation fault
check("template<int i> class X { };\n"
"X< 1>2 > x1;\n"
"X<(1>2)> x2;\n"
"template<class T> class Y { };\n"
"Y<X<1>> x3;\n"
"Y<X<6>>1>> x4;\n"
"Y<X<(6>>1)>> x5;\n", false);
ASSERT_EQUALS("", errout_str());
}
void symboldatabase7() {
// ticket #2230 - segmentation fault
check("template<template<class> class E,class D> class C : E<D>\n"
"{\n"
"public:\n"
" int f();\n"
"};\n"
"class E : C<D,int>\n"
"{\n"
"public:\n"
" int f() { return C< ::D,int>::f(); }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void symboldatabase8() {
// ticket #2252 - segmentation fault
check("struct PaletteColorSpaceHolder: public rtl::StaticWithInit<uno::Reference<rendering::XColorSpace>,\n"
" PaletteColorSpaceHolder>\n"
"{\n"
" uno::Reference<rendering::XColorSpace> operator()()\n"
" {\n"
" return vcl::unotools::createStandardColorSpace();\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void symboldatabase9() {
// ticket #2425 - segmentation fault
check("class CHyperlink : public CString\n"
"{\n"
"public:\n"
" const CHyperlink& operator=(LPCTSTR lpsz) {\n"
" CString::operator=(lpsz);\n"
" return *this;\n"
" }\n"
"};\n", false);
ASSERT_EQUALS("", errout_str());
}
void symboldatabase10() {
// ticket #2537 - segmentation fault
check("class A {\n"
"private:\n"
" void f();\n"
"};\n"
"class B {\n"
" friend void A::f();\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void symboldatabase11() {
// ticket #2539 - segmentation fault
check("int g ();\n"
"struct S {\n"
" int i : (false ? g () : 1);\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void symboldatabase12() {
// ticket #2547 - segmentation fault
check("class foo {\n"
" void bar2 () = __null;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void symboldatabase13() {
// ticket #2577 - segmentation fault
check("class foo {\n"
" void bar2 () = A::f;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void symboldatabase14() {
// ticket #2589 - segmentation fault
ASSERT_THROW_INTERNAL(check("struct B : A\n"), SYNTAX);
}
void symboldatabase17() {
// ticket #2657 - segmentation fault
check("{return f(){}}");
ASSERT_EQUALS("", errout_str());
}
void symboldatabase19() {
// ticket #2991 - segmentation fault
check("::y(){x}");
ASSERT_EQUALS(
"[test.cpp:1]: (debug) Executable scope 'y' with unknown function.\n"
"[test.cpp:1]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable x\n"
"[test.cpp:1]: (debug) Executable scope 'y' with unknown function.\n", // duplicate
errout_str());
}
void symboldatabase20() {
// ticket #3013 - segmentation fault
ASSERT_THROW_INTERNAL(check("struct x : virtual y\n"), SYNTAX);
}
void symboldatabase21() {
check("class Fred {\n"
" class Foo { };\n"
" void func() const;\n"
"};\n"
"Fred::func() const {\n"
" Foo foo;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
// ticket 3437 (segmentation fault)
void symboldatabase22() {
check("template <class C> struct A {};\n"
"A<int> a;");
ASSERT_EQUALS("", errout_str());
}
// ticket 3435 (std::vector)
void symboldatabase23() {
GET_SYMBOL_DB("class A { std::vector<int*> ints; };");
ASSERT_EQUALS(2U, db->scopeList.size());
const Scope &scope = db->scopeList.back();
ASSERT_EQUALS(1U, scope.varlist.size());
const Variable &var = scope.varlist.front();
ASSERT_EQUALS(std::string("ints"), var.name());
ASSERT_EQUALS(true, var.isClass());
}
// ticket 3508 (constructor, destructor)
void symboldatabase24() {
GET_SYMBOL_DB("struct Fred {\n"
" ~Fred();\n"
" Fred();\n"
"};\n"
"Fred::Fred() { }\n"
"Fred::~Fred() { }");
// Global scope, Fred, Fred::Fred, Fred::~Fred
ASSERT_EQUALS(4U, db->scopeList.size());
// Find the scope for the Fred struct..
auto it = std::find_if(db->scopeList.cbegin(), db->scopeList.cend(), [&](const Scope& scope) {
return scope.isClassOrStruct() && scope.className == "Fred";
});
const Scope* fredScope = (it == db->scopeList.end()) ? nullptr : &*it;
ASSERT(fredScope != nullptr);
// The struct Fred has two functions, a constructor and a destructor
ASSERT_EQUALS(2U, fredScope->functionList.size());
// Get linenumbers where the bodies for the constructor and destructor are..
unsigned int constructor = 0;
unsigned int destructor = 0;
for (const Function& f : fredScope->functionList) {
if (f.type == Function::eConstructor)
constructor = f.token->linenr(); // line number for constructor body
if (f.type == Function::eDestructor)
destructor = f.token->linenr(); // line number for destructor body
}
// The body for the constructor is located at line 5..
ASSERT_EQUALS(5U, constructor);
// The body for the destructor is located at line 6..
ASSERT_EQUALS(6U, destructor);
}
// ticket #3561 (throw C++)
void symboldatabase25() {
const char str[] = "int main() {\n"
" foo bar;\n"
" throw bar;\n"
"}";
GET_SYMBOL_DB(str);
ASSERT_EQUALS("", errout_str());
ASSERT(db && db->variableList().size() == 2); // index 0 + 1 variable
}
// ticket #3561 (throw C)
void symboldatabase26() {
const char str[] = "int main() {\n"
" throw bar;\n"
"}";
GET_SYMBOL_DB_C(str);
ASSERT_EQUALS("", errout_str());
ASSERT(db && db->variableList().size() == 2); // index 0 + 1 variable
}
// ticket #3543 (segmentation fault)
void symboldatabase27() {
check("class C : public B1\n"
"{\n"
" B1()\n"
" {} C(int) : B1() class\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void symboldatabase28() {
GET_SYMBOL_DB("struct S {};\n"
"void foo(struct S s) {}");
ASSERT(db && db->getVariableFromVarId(1) && db->getVariableFromVarId(1)->typeScope() && db->getVariableFromVarId(1)->typeScope()->className == "S");
}
// ticket #4442 (segmentation fault)
void symboldatabase29() {
check("struct B : A {\n"
" B() : A {}\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void symboldatabase30() {
GET_SYMBOL_DB("struct A { void foo(const int a); };\n"
"void A::foo(int a) { }");
ASSERT(db && db->functionScopes.size() == 1 && db->functionScopes[0]->functionOf);
}
void symboldatabase31() {
GET_SYMBOL_DB("class Foo;\n"
"class Bar;\n"
"class Sub;\n"
"class Foo { class Sub; };\n"
"class Bar { class Sub; };\n"
"class Bar::Sub {\n"
" int b;\n"
"public:\n"
" Sub() { }\n"
" Sub(int);\n"
"};\n"
"Bar::Sub::Sub(int) { };\n"
"class ::Foo::Sub {\n"
" int f;\n"
"public:\n"
" ~Sub();\n"
" Sub();\n"
"};\n"
"::Foo::Sub::~Sub() { }\n"
"::Foo::Sub::Sub() { }\n"
"class Foo;\n"
"class Bar;\n"
"class Sub;");
ASSERT(db && db->typeList.size() == 5);
auto i = db->typeList.cbegin();
const Type* Foo = &(*i++);
const Type* Bar = &(*i++);
const Type* Sub = &(*i++);
const Type* Foo_Sub = &(*i++);
const Type* Bar_Sub = &(*i);
ASSERT(Foo && Foo->classDef && Foo->classScope && Foo->enclosingScope && Foo->name() == "Foo");
ASSERT(Bar && Bar->classDef && Bar->classScope && Bar->enclosingScope && Bar->name() == "Bar");
ASSERT(Sub && Sub->classDef && !Sub->classScope && Sub->enclosingScope && Sub->name() == "Sub");
ASSERT(Foo_Sub && Foo_Sub->classDef && Foo_Sub->classScope && Foo_Sub->enclosingScope == Foo->classScope && Foo_Sub->name() == "Sub");
ASSERT(Bar_Sub && Bar_Sub->classDef && Bar_Sub->classScope && Bar_Sub->enclosingScope == Bar->classScope && Bar_Sub->name() == "Sub");
ASSERT(Foo_Sub && Foo_Sub->classScope && Foo_Sub->classScope->numConstructors == 1 && Foo_Sub->classScope->className == "Sub");
ASSERT(Bar_Sub && Bar_Sub->classScope && Bar_Sub->classScope->numConstructors == 2 && Bar_Sub->classScope->className == "Sub");
}
void symboldatabase32() {
GET_SYMBOL_DB("struct Base {\n"
" void foo() {}\n"
"};\n"
"class Deri : Base {\n"
"};");
ASSERT(db && db->findScopeByName("Deri") && db->findScopeByName("Deri")->definedType->getFunction("foo"));
}
void symboldatabase33() { // ticket #4682
GET_SYMBOL_DB("static struct A::B s;\n"
"static struct A::B t = { 0 };\n"
"static struct A::B u(0);\n"
"static struct A::B v{0};\n"
"static struct A::B w({0});\n"
"void foo() { }");
ASSERT(db && db->functionScopes.size() == 1);
}
void symboldatabase34() { // ticket #4694
check("typedef _Atomic(int(A::*)) atomic_mem_ptr_to_int;\n"
"typedef _Atomic(int)&atomic_int_ref;\n"
"struct S {\n"
" _Atomic union { int n; };\n"
"};");
ASSERT_EQUALS("[test.cpp:2]: (debug) Failed to parse 'typedef _Atomic ( int ) & atomic_int_ref ;'. The checking continues anyway.\n", errout_str());
}
void symboldatabase35() { // ticket #4806 and #4841
check("class FragmentQueue : public CL_NS(util)::PriorityQueue<CL_NS(util)::Deletor::Object<TextFragment> >\n"
"{};");
ASSERT_EQUALS("", errout_str());
}
void symboldatabase36() { // ticket #4892
check("void struct ( ) { if ( 1 ) } int main ( ) { }");
ASSERT_EQUALS("", errout_str());
}
void symboldatabase37() {
GET_SYMBOL_DB("class Fred {\n"
"public:\n"
" struct Wilma { };\n"
" struct Barney {\n"
" bool operator == (const struct Barney & b) const { return true; }\n"
" bool operator == (const struct Wilma & w) const { return true; }\n"
" };\n"
" Fred(const struct Barney & b) { barney = b; }\n"
"private:\n"
" struct Barney barney;\n"
"};");
ASSERT(db && db->typeList.size() == 3);
auto i = db->typeList.cbegin();
const Type* Fred = &(*i++);
const Type* Wilma = &(*i++);
const Type* Barney = &(*i++);
ASSERT(Fred && Fred->classDef && Fred->classScope && Fred->enclosingScope && Fred->name() == "Fred");
ASSERT(Wilma && Wilma->classDef && Wilma->classScope && Wilma->enclosingScope && Wilma->name() == "Wilma");
ASSERT(Barney && Barney->classDef && Barney->classScope && Barney->enclosingScope && Barney->name() == "Barney");
ASSERT(db->variableList().size() == 5);
ASSERT(db->getVariableFromVarId(1) && db->getVariableFromVarId(1)->type() && db->getVariableFromVarId(1)->type()->name() == "Barney");
ASSERT(db->getVariableFromVarId(2) && db->getVariableFromVarId(2)->type() && db->getVariableFromVarId(2)->type()->name() == "Wilma");
ASSERT(db->getVariableFromVarId(3) && db->getVariableFromVarId(3)->type() && db->getVariableFromVarId(3)->type()->name() == "Barney");
}
void symboldatabase38() { // ticket #5125
check("template <typename T = class service> struct scoped_service;\n"
"struct service {};\n"
"template <> struct scoped_service<service> {};\n"
"template <typename T>\n"
"struct scoped_service : scoped_service<service>\n"
"{\n"
" scoped_service( T* ptr ) : scoped_service<service>(ptr), m_ptr(ptr) {}\n"
" T* const m_ptr;\n"
"};");
}
void symboldatabase40() { // ticket #5153
check("void f() {\n"
" try { }\n"
" catch (std::bad_alloc) { }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void symboldatabase41() { // ticket #5197 (unknown macro)
GET_SYMBOL_DB("struct X1 { MACRO1 f(int spd) MACRO2; };");
ASSERT(db && db->findScopeByName("X1") && db->findScopeByName("X1")->functionList.size() == 1 && !db->findScopeByName("X1")->functionList.front().hasBody());
}
void symboldatabase42() { // only put variables in variable list
GET_SYMBOL_DB("void f() { extern int x(); }");
ASSERT(db != nullptr);
const Scope * const fscope = db ? db->findScopeByName("f") : nullptr;
ASSERT(fscope != nullptr);
ASSERT_EQUALS(0U, fscope ? fscope->varlist.size() : ~0U); // "x" is not a variable
}
void symboldatabase43() { // ticket #4738
check("void f() {\n"
" new int;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void symboldatabase44() {
GET_SYMBOL_DB("int i { 1 };\n"
"int j ( i );\n"
"void foo() {\n"
" int k { 1 };\n"
" int l ( 1 );\n"
"}");
ASSERT(db != nullptr);
ASSERT_EQUALS(4U, db->variableList().size() - 1);
ASSERT_EQUALS(2U, db->scopeList.size());
for (std::size_t i = 1U; i < db->variableList().size(); i++)
ASSERT(db->getVariableFromVarId(i) != nullptr);
}
void symboldatabase45() {
GET_SYMBOL_DB("typedef struct {\n"
" unsigned long bits;\n"
"} S;\n"
"struct T {\n"
" S span;\n"
" int flags;\n"
"};\n"
"struct T f(int x) {\n"
" return (struct T) {\n"
" .span = (S) { 0UL },\n"
" .flags = (x ? 256 : 0),\n"
" };\n"
"}");
ASSERT(db != nullptr);
ASSERT_EQUALS(4U, db->variableList().size() - 1);
for (std::size_t i = 1U; i < db->variableList().size(); i++)
ASSERT(db->getVariableFromVarId(i) != nullptr);
ASSERT_EQUALS(4U, db->scopeList.size());
auto scope = db->scopeList.cbegin();
ASSERT_EQUALS(Scope::eGlobal, scope->type);
++scope;
ASSERT_EQUALS(Scope::eStruct, scope->type);
++scope;
ASSERT_EQUALS(Scope::eStruct, scope->type);
++scope;
ASSERT_EQUALS(Scope::eFunction, scope->type);
}
void symboldatabase46() { // #6171 (anonymous namespace)
GET_SYMBOL_DB("struct S { };\n"
"namespace {\n"
" struct S { };\n"
"}");
ASSERT(db != nullptr);
ASSERT_EQUALS(4U, db->scopeList.size());
auto scope = db->scopeList.cbegin();
ASSERT_EQUALS(Scope::eGlobal, scope->type);
++scope;
ASSERT_EQUALS(Scope::eStruct, scope->type);
ASSERT_EQUALS(scope->className, "S");
++scope;
ASSERT_EQUALS(Scope::eNamespace, scope->type);
ASSERT_EQUALS(scope->className, "");
++scope;
ASSERT_EQUALS(Scope::eStruct, scope->type);
ASSERT_EQUALS(scope->className, "S");
}
void symboldatabase47() { // #6308 - associate Function and Scope for destructors
GET_SYMBOL_DB("namespace NS {\n"
" class MyClass {\n"
" ~MyClass();\n"
" };\n"
"}\n"
"using namespace NS;\n"
"MyClass::~MyClass() {\n"
" delete Example;\n"
"}");
ASSERT(db && !db->functionScopes.empty() && db->functionScopes.front()->function && db->functionScopes.front()->function->functionScope == db->functionScopes.front());
}
void symboldatabase48() { // #6417
GET_SYMBOL_DB("namespace NS {\n"
" class MyClass {\n"
" MyClass();\n"
" ~MyClass();\n"
" };\n"
"}\n"
"using namespace NS;\n"
"MyClass::~MyClass() { }\n"
"MyClass::MyClass() { }");
ASSERT(db && !db->functionScopes.empty() && db->functionScopes.front()->function && db->functionScopes.front()->function->functionScope == db->functionScopes.front());
const Token *f = Token::findsimplematch(tokenizer.tokens(), "MyClass ( ) ;");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 3 && f->function()->token->linenr() == 9);
f = Token::findsimplematch(tokenizer.tokens(), "~ MyClass ( ) ;");
f = f->next();
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 4 && f->function()->token->linenr() == 8);
}
void symboldatabase49() { // #6424
GET_SYMBOL_DB("namespace Ns { class C; }\n"
"void f1() { char *p; *p = 0; }\n"
"class Ns::C* p;\n"
"void f2() { char *p; *p = 0; }");
ASSERT(db != nullptr);
const Token *f = Token::findsimplematch(tokenizer.tokens(), "p ; void f2");
ASSERT_EQUALS(true, db && f && f->variable());
f = Token::findsimplematch(tokenizer.tokens(), "f2");
ASSERT_EQUALS(true, db && f && f->function());
}
void symboldatabase50() { // #6432
GET_SYMBOL_DB("template <bool del, class T>\n"
"class _ConstTessMemberResultCallback_0_0<del, void, T>\n"
" {\n"
" public:\n"
" typedef void (T::*MemberSignature)() const;\n"
"\n"
" private:\n"
" const T* object_;\n"
" MemberSignature member_;\n"
"\n"
" public:\n"
" inline _ConstTessMemberResultCallback_0_0(\n"
" const T* object, MemberSignature member)\n"
" : object_(object),\n"
" member_(member) {\n"
" }\n"
"};");
ASSERT(db != nullptr);
const Token *f = Token::findsimplematch(tokenizer.tokens(), "_ConstTessMemberResultCallback_0_0 (");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->isConstructor());
}
void symboldatabase51() { // #6538
GET_SYMBOL_DB("static const float f1 = 2 * foo1(a, b);\n"
"static const float f2 = 2 * ::foo2(a, b);\n"
"static const float f3 = 2 * std::foo3(a, b);\n"
"static const float f4 = c * foo4(a, b);\n"
"static const int i1 = 2 & foo5(a, b);\n"
"static const bool b1 = 2 > foo6(a, b);");
ASSERT(db != nullptr);
ASSERT(findFunctionByName("foo1", &db->scopeList.front()) == nullptr);
ASSERT(findFunctionByName("foo2", &db->scopeList.front()) == nullptr);
ASSERT(findFunctionByName("foo3", &db->scopeList.front()) == nullptr);
ASSERT(findFunctionByName("foo4", &db->scopeList.front()) == nullptr);
ASSERT(findFunctionByName("foo5", &db->scopeList.front()) == nullptr);
ASSERT(findFunctionByName("foo6", &db->scopeList.front()) == nullptr);
}
void symboldatabase52() { // #6581
GET_SYMBOL_DB("void foo() {\n"
" int i = 0;\n"
" S s{ { i }, 0 };\n"
"}");
ASSERT(db != nullptr);
ASSERT_EQUALS(2, db->scopeList.size());
ASSERT_EQUALS(2, db->variableList().size()-1);
ASSERT(db->getVariableFromVarId(1) != nullptr);
ASSERT(db->getVariableFromVarId(2) != nullptr);
}
void symboldatabase53() { // #7124
GET_SYMBOL_DB("int32_t x;"
"std::int32_t y;");
ASSERT(db != nullptr);
ASSERT(db->getVariableFromVarId(1) != nullptr);
ASSERT(db->getVariableFromVarId(2) != nullptr);
ASSERT_EQUALS(false, db->getVariableFromVarId(1)->isClass());
ASSERT_EQUALS(false, db->getVariableFromVarId(2)->isClass());
}
void symboldatabase54() { // #7343
GET_SYMBOL_DB("class A {\n"
" void getReg() const override {\n"
" assert(Kind == k_ShiftExtend);\n"
" }\n"
"};");
ASSERT(db != nullptr);
ASSERT_EQUALS(1U, db->functionScopes.size());
ASSERT_EQUALS("getReg", db->functionScopes.front()->className);
ASSERT_EQUALS(true, db->functionScopes.front()->function->hasOverrideSpecifier());
}
void symboldatabase55() { // #7767
GET_SYMBOL_DB("PRIVATE S32 testfunc(void) {\n"
" return 0;\n"
"}");
ASSERT(db != nullptr);
ASSERT_EQUALS(1U, db->functionScopes.size());
ASSERT_EQUALS("testfunc", db->functionScopes.front()->className);
}
void symboldatabase56() { // #7909
{
GET_SYMBOL_DB("class Class {\n"
" class NestedClass {\n"
" public:\n"
" virtual void f();\n"
" };\n"
" friend void NestedClass::f();\n"
"}");
ASSERT(db != nullptr);
ASSERT_EQUALS(0U, db->functionScopes.size());
ASSERT(db->scopeList.back().type == Scope::eClass && db->scopeList.back().className == "NestedClass");
ASSERT(db->scopeList.back().functionList.size() == 1U && !db->scopeList.back().functionList.front().hasBody());
}
{
GET_SYMBOL_DB("class Class {\n"
" friend void f1();\n"
" friend void f2() { }\n"
"}");
ASSERT(db != nullptr);
ASSERT_EQUALS(1U, db->functionScopes.size());
ASSERT(db->scopeList.back().type == Scope::eFunction && db->scopeList.back().className == "f2");
ASSERT(db->scopeList.back().function && db->scopeList.back().function->hasBody());
}
{
GET_SYMBOL_DB_C("friend f1();\n"
"friend f2() { }");
ASSERT(db != nullptr);
ASSERT_EQUALS(2U, db->scopeList.size());
ASSERT_EQUALS(2U, db->scopeList.cbegin()->functionList.size());
}
}
void symboldatabase57() {
GET_SYMBOL_DB("int bar(bool b)\n"
"{\n"
" if(b)\n"
" return 1;\n"
" else\n"
" return 1;\n"
"}");
ASSERT(db != nullptr);
ASSERT(db->scopeList.size() == 4U);
auto it = db->scopeList.cbegin();
ASSERT(it->type == Scope::eGlobal);
ASSERT((++it)->type == Scope::eFunction);
ASSERT((++it)->type == Scope::eIf);
ASSERT((++it)->type == Scope::eElse);
}
void symboldatabase58() { // #6985 (using namespace type lookup)
GET_SYMBOL_DB("namespace N2\n"
"{\n"
"class B { };\n"
"}\n"
"using namespace N2;\n"
"class C {\n"
" class A : public B\n"
" {\n"
" };\n"
"};");
ASSERT(db != nullptr);
ASSERT(db->typeList.size() == 3U);
auto it = db->typeList.cbegin();
const Type * classB = &(*it);
const Type * classC = &(*(++it));
const Type * classA = &(*(++it));
ASSERT(classA->name() == "A" && classB->name() == "B" && classC->name() == "C");
ASSERT(classA->derivedFrom.size() == 1U);
ASSERT(classA->derivedFrom[0].type != nullptr);
ASSERT(classA->derivedFrom[0].type == classB);
}
void symboldatabase59() { // #8465
GET_SYMBOL_DB("struct A::B ab[10];\n"
"void f() {}");
ASSERT(db != nullptr);
ASSERT(db && db->scopeList.size() == 2);
}
void symboldatabase60() { // #8470
GET_SYMBOL_DB("struct A::someType A::bar() { return 0; }");
ASSERT(db != nullptr);
ASSERT(db && db->scopeList.size() == 2);
}
void symboldatabase61() {
GET_SYMBOL_DB("struct Fred {\n"
" struct Info { };\n"
"};\n"
"void foo() {\n"
" struct Fred::Info* info;\n"
" info = new (nothrow) struct Fred::Info();\n"
" info = new struct Fred::Info();\n"
" memset(info, 0, sizeof(struct Fred::Info));\n"
"}");
ASSERT(db != nullptr);
ASSERT(db && db->scopeList.size() == 4);
}
void symboldatabase62() {
{
GET_SYMBOL_DB("struct A {\n"
"public:\n"
" struct X { int a; };\n"
" void Foo(const std::vector<struct X> &includes);\n"
"};\n"
"void A::Foo(const std::vector<struct A::X> &includes) {\n"
" for (std::vector<struct A::X>::const_iterator it = includes.begin(); it != includes.end(); ++it) {\n"
" const struct A::X currentIncList = *it;\n"
" }\n"
"}");
ASSERT(db != nullptr);
ASSERT(db && db->scopeList.size() == 5);
const Scope *scope = db->findScopeByName("A");
ASSERT(scope != nullptr);
const Function *function = findFunctionByName("Foo", scope);
ASSERT(function != nullptr);
ASSERT(function->hasBody());
}
{
GET_SYMBOL_DB("class A {\n"
"public:\n"
" class X { public: int a; };\n"
" void Foo(const std::vector<class X> &includes);\n"
"};\n"
"void A::Foo(const std::vector<class A::X> &includes) {\n"
" for (std::vector<class A::X>::const_iterator it = includes.begin(); it != includes.end(); ++it) {\n"
" const class A::X currentIncList = *it;\n"
" }\n"
"}");
ASSERT(db != nullptr);
ASSERT(db && db->scopeList.size() == 5);
const Scope *scope = db->findScopeByName("A");
ASSERT(scope != nullptr);
const Function *function = findFunctionByName("Foo", scope);
ASSERT(function != nullptr);
ASSERT(function->hasBody());
}
{
GET_SYMBOL_DB("struct A {\n"
"public:\n"
" union X { int a; float b; };\n"
" void Foo(const std::vector<union X> &includes);\n"
"};\n"
"void A::Foo(const std::vector<union A::X> &includes) {\n"
" for (std::vector<union A::X>::const_iterator it = includes.begin(); it != includes.end(); ++it) {\n"
" const union A::X currentIncList = *it;\n"
" }\n"
"}");
ASSERT(db != nullptr);
ASSERT(db && db->scopeList.size() == 5);
const Scope *scope = db->findScopeByName("A");
ASSERT(scope != nullptr);
const Function *function = findFunctionByName("Foo", scope);
ASSERT(function != nullptr);
ASSERT(function->hasBody());
}
{
GET_SYMBOL_DB("struct A {\n"
"public:\n"
" enum X { a, b };\n"
" void Foo(const std::vector<enum X> &includes);\n"
"};\n"
"void A::Foo(const std::vector<enum A::X> &includes) {\n"
" for (std::vector<enum A::X>::const_iterator it = includes.begin(); it != includes.end(); ++it) {\n"
" const enum A::X currentIncList = *it;\n"
" }\n"
"}");
ASSERT(db != nullptr);
ASSERT(db && db->scopeList.size() == 5);
const Scope *scope = db->findScopeByName("A");
ASSERT(scope != nullptr);
const Function *function = findFunctionByName("Foo", scope);
ASSERT(function != nullptr);
ASSERT(function->hasBody());
}
}
void symboldatabase63() {
{
GET_SYMBOL_DB("template class T<int> ; void foo() { }");
ASSERT(db != nullptr);
ASSERT(db && db->scopeList.size() == 2);
}
{
GET_SYMBOL_DB("template struct T<int> ; void foo() { }");
ASSERT(db != nullptr);
ASSERT(db && db->scopeList.size() == 2);
}
}
void symboldatabase64() {
{
GET_SYMBOL_DB("class Fred { struct impl; };\n"
"struct Fred::impl {\n"
" impl() { }\n"
" ~impl() { }\n"
" impl(const impl &) { }\n"
" void foo(const impl &, const impl &) const { }\n"
"};");
ASSERT(db != nullptr);
ASSERT(db && db->scopeList.size() == 7);
ASSERT(db && db->classAndStructScopes.size() == 2);
ASSERT(db && db->typeList.size() == 2);
ASSERT(db && db->functionScopes.size() == 4);
const Token * functionToken = Token::findsimplematch(tokenizer.tokens(), "impl ( ) { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 3 &&
functionToken->function()->token->linenr() == 3);
functionToken = Token::findsimplematch(tokenizer.tokens(), "~ impl ( ) { }");
ASSERT(db && functionToken && functionToken->next()->function() &&
functionToken->next()->function()->functionScope &&
functionToken->next()->function()->tokenDef->linenr() == 4 &&
functionToken->next()->function()->token->linenr() == 4);
functionToken = Token::findsimplematch(tokenizer.tokens(), "impl ( const impl & ) { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 5 &&
functionToken->function()->token->linenr() == 5);
functionToken = Token::findsimplematch(tokenizer.tokens(), "foo ( const impl & , const impl & ) const { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 6 &&
functionToken->function()->token->linenr() == 6);
}
{
GET_SYMBOL_DB("class Fred { struct impl; };\n"
"struct Fred::impl {\n"
" impl();\n"
" ~impl();\n"
" impl(const impl &);\n"
" void foo(const impl &, const impl &) const;\n"
"};\n"
"Fred::impl::impl() { }\n"
"Fred::impl::~impl() { }\n"
"Fred::impl::impl(const Fred::impl &) { }\n"
"void Fred::impl::foo(const Fred::impl &, const Fred::impl &) const { }");
ASSERT(db != nullptr);
ASSERT(db && db->scopeList.size() == 7);
ASSERT(db && db->classAndStructScopes.size() == 2);
ASSERT(db && db->typeList.size() == 2);
ASSERT(db && db->functionScopes.size() == 4);
const Token * functionToken = Token::findsimplematch(tokenizer.tokens(), "impl ( ) { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 3 &&
functionToken->function()->token->linenr() == 8);
functionToken = Token::findsimplematch(tokenizer.tokens(), "~ impl ( ) { }");
ASSERT(db && functionToken && functionToken->next()->function() &&
functionToken->next()->function()->functionScope &&
functionToken->next()->function()->tokenDef->linenr() == 4 &&
functionToken->next()->function()->token->linenr() == 9);
functionToken = Token::findsimplematch(tokenizer.tokens(), "impl ( const Fred :: impl & ) { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 5 &&
functionToken->function()->token->linenr() == 10);
functionToken = Token::findsimplematch(tokenizer.tokens(), "foo ( const Fred :: impl & , const Fred :: impl & ) const { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 6 &&
functionToken->function()->token->linenr() == 11);
}
{
GET_SYMBOL_DB("namespace NS {\n"
" class Fred { struct impl; };\n"
" struct Fred::impl {\n"
" impl() { }\n"
" ~impl() { }\n"
" impl(const impl &) { }\n"
" void foo(const impl &, const impl &) const { }\n"
" };\n"
"}");
ASSERT(db != nullptr);
ASSERT(db && db->scopeList.size() == 8);
ASSERT(db && db->classAndStructScopes.size() == 2);
ASSERT(db && db->typeList.size() == 2);
ASSERT(db && db->functionScopes.size() == 4);
const Token * functionToken = Token::findsimplematch(tokenizer.tokens(), "impl ( ) { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 4 &&
functionToken->function()->token->linenr() == 4);
functionToken = Token::findsimplematch(tokenizer.tokens(), "~ impl ( ) { }");
ASSERT(db && functionToken && functionToken->next()->function() &&
functionToken->next()->function()->functionScope &&
functionToken->next()->function()->tokenDef->linenr() == 5 &&
functionToken->next()->function()->token->linenr() == 5);
functionToken = Token::findsimplematch(tokenizer.tokens(), "impl ( const impl & ) { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 6 &&
functionToken->function()->token->linenr() == 6);
functionToken = Token::findsimplematch(tokenizer.tokens(), "foo ( const impl & , const impl & ) const { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 7 &&
functionToken->function()->token->linenr() == 7);
}
{
GET_SYMBOL_DB("namespace NS {\n"
" class Fred { struct impl; };\n"
" struct Fred::impl {\n"
" impl();\n"
" ~impl();\n"
" impl(const impl &);\n"
" void foo(const impl &, const impl &) const;\n"
" };\n"
" Fred::impl::impl() { }\n"
" Fred::impl::~impl() { }\n"
" Fred::impl::impl(const Fred::impl &) { }\n"
" void Fred::impl::foo(const Fred::impl &, const Fred::impl &) const { }\n"
"}");
ASSERT(db != nullptr);
ASSERT(db && db->scopeList.size() == 8);
ASSERT(db && db->classAndStructScopes.size() == 2);
ASSERT(db && db->typeList.size() == 2);
ASSERT(db && db->functionScopes.size() == 4);
const Token * functionToken = Token::findsimplematch(tokenizer.tokens(), "impl ( ) { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 4 &&
functionToken->function()->token->linenr() == 9);
functionToken = Token::findsimplematch(tokenizer.tokens(), "~ impl ( ) { }");
ASSERT(db && functionToken && functionToken->next()->function() &&
functionToken->next()->function()->functionScope &&
functionToken->next()->function()->tokenDef->linenr() == 5 &&
functionToken->next()->function()->token->linenr() == 10);
functionToken = Token::findsimplematch(tokenizer.tokens(), "impl ( const Fred :: impl & ) { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 6 &&
functionToken->function()->token->linenr() == 11);
functionToken = Token::findsimplematch(tokenizer.tokens(), "foo ( const Fred :: impl & , const Fred :: impl & ) const { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 7 &&
functionToken->function()->token->linenr() == 12);
}
{
GET_SYMBOL_DB("namespace NS {\n"
" class Fred { struct impl; };\n"
" struct Fred::impl {\n"
" impl();\n"
" ~impl();\n"
" impl(const impl &);\n"
" void foo(const impl &, const impl &) const;\n"
" };\n"
"}\n"
"NS::Fred::impl::impl() { }\n"
"NS::Fred::impl::~impl() { }\n"
"NS::Fred::impl::impl(const NS::Fred::impl &) { }\n"
"void NS::Fred::impl::foo(const NS::Fred::impl &, const NS::Fred::impl &) const { }");
ASSERT(db != nullptr);
ASSERT(db && db->scopeList.size() == 8);
ASSERT(db && db->classAndStructScopes.size() == 2);
ASSERT(db && db->typeList.size() == 2);
ASSERT(db && db->functionScopes.size() == 4);
const Token * functionToken = Token::findsimplematch(tokenizer.tokens(), "impl ( ) { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 4 &&
functionToken->function()->token->linenr() == 10);
functionToken = Token::findsimplematch(tokenizer.tokens(), "~ impl ( ) { }");
ASSERT(db && functionToken && functionToken->next()->function() &&
functionToken->next()->function()->functionScope &&
functionToken->next()->function()->tokenDef->linenr() == 5 &&
functionToken->next()->function()->token->linenr() == 11);
functionToken = Token::findsimplematch(tokenizer.tokens(), "impl ( const NS :: Fred :: impl & ) { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 6 &&
functionToken->function()->token->linenr() == 12);
functionToken = Token::findsimplematch(tokenizer.tokens(), "foo ( const NS :: Fred :: impl & , const NS :: Fred :: impl & ) const { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 7 &&
functionToken->function()->token->linenr() == 13);
}
{
GET_SYMBOL_DB("namespace NS {\n"
" class Fred { struct impl; };\n"
"}\n"
"struct NS::Fred::impl {\n"
" impl() { }\n"
" ~impl() { }\n"
" impl(const impl &) { }\n"
" void foo(const impl &, const impl &) const { }\n"
"};");
ASSERT(db != nullptr);
ASSERT(db && db->scopeList.size() == 8);
ASSERT(db && db->classAndStructScopes.size() == 2);
ASSERT(db && db->typeList.size() == 2);
ASSERT(db && db->functionScopes.size() == 4);
const Token * functionToken = Token::findsimplematch(tokenizer.tokens(), "impl ( ) { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 5 &&
functionToken->function()->token->linenr() == 5);
functionToken = Token::findsimplematch(tokenizer.tokens(), "~ impl ( ) { }");
ASSERT(db && functionToken && functionToken->next()->function() &&
functionToken->next()->function()->functionScope &&
functionToken->next()->function()->tokenDef->linenr() == 6 &&
functionToken->next()->function()->token->linenr() == 6);
functionToken = Token::findsimplematch(tokenizer.tokens(), "impl ( const impl & ) { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 7 &&
functionToken->function()->token->linenr() == 7);
functionToken = Token::findsimplematch(tokenizer.tokens(), "foo ( const impl & , const impl & ) const { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 8 &&
functionToken->function()->token->linenr() == 8);
}
{
GET_SYMBOL_DB("namespace NS {\n"
" class Fred { struct impl; };\n"
"}\n"
"struct NS::Fred::impl {\n"
" impl();\n"
" ~impl();\n"
" impl(const impl &);\n"
" void foo(const impl &, const impl &) const;\n"
"};\n"
"NS::Fred::impl::impl() { }\n"
"NS::Fred::impl::~impl() { }\n"
"NS::Fred::impl::impl(const NS::Fred::impl &) { }\n"
"void NS::Fred::impl::foo(const NS::Fred::impl &, const NS::Fred::impl &) const { }");
ASSERT(db != nullptr);
ASSERT(db && db->scopeList.size() == 8);
ASSERT(db && db->classAndStructScopes.size() == 2);
ASSERT(db && db->typeList.size() == 2);
ASSERT(db && db->functionScopes.size() == 4);
const Token * functionToken = Token::findsimplematch(tokenizer.tokens(), "impl ( ) { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 5 &&
functionToken->function()->token->linenr() == 10);
functionToken = Token::findsimplematch(tokenizer.tokens(), "~ impl ( ) { }");
ASSERT(db && functionToken && functionToken->next()->function() &&
functionToken->next()->function()->functionScope &&
functionToken->next()->function()->tokenDef->linenr() == 6 &&
functionToken->next()->function()->token->linenr() == 11);
functionToken = Token::findsimplematch(tokenizer.tokens(), "impl ( const NS :: Fred :: impl & ) { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 7 &&
functionToken->function()->token->linenr() == 12);
functionToken = Token::findsimplematch(tokenizer.tokens(), "foo ( const NS :: Fred :: impl & , const NS :: Fred :: impl & ) const { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 8 &&
functionToken->function()->token->linenr() == 13);
}
{
GET_SYMBOL_DB("namespace NS {\n"
" class Fred { struct impl; };\n"
"}\n"
"struct NS::Fred::impl {\n"
" impl();\n"
" ~impl();\n"
" impl(const impl &);\n"
" void foo(const impl &, const impl &) const;\n"
"};\n"
"namespace NS {\n"
" Fred::impl::impl() { }\n"
" Fred::impl::~impl() { }\n"
" Fred::impl::impl(const Fred::impl &) { }\n"
" void Fred::impl::foo(const Fred::impl &, const Fred::impl &) const { }\n"
"}");
ASSERT(db != nullptr);
ASSERT(db && db->scopeList.size() == 8);
ASSERT(db && db->classAndStructScopes.size() == 2);
ASSERT(db && db->typeList.size() == 2);
ASSERT(db && db->functionScopes.size() == 4);
const Token * functionToken = Token::findsimplematch(tokenizer.tokens(), "impl ( ) { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 5 &&
functionToken->function()->token->linenr() == 11);
functionToken = Token::findsimplematch(tokenizer.tokens(), "~ impl ( ) { }");
ASSERT(db && functionToken && functionToken->next()->function() &&
functionToken->next()->function()->functionScope &&
functionToken->next()->function()->tokenDef->linenr() == 6 &&
functionToken->next()->function()->token->linenr() == 12);
functionToken = Token::findsimplematch(tokenizer.tokens(), "impl ( const Fred :: impl & ) { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 7 &&
functionToken->function()->token->linenr() == 13);
functionToken = Token::findsimplematch(tokenizer.tokens(), "foo ( const Fred :: impl & , const Fred :: impl & ) const { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 8 &&
functionToken->function()->token->linenr() == 14);
}
{
GET_SYMBOL_DB("namespace NS {\n"
" class Fred { struct impl; };\n"
"}\n"
"struct NS::Fred::impl {\n"
" impl();\n"
" ~impl();\n"
" impl(const impl &);\n"
" void foo(const impl &, const impl &) const;\n"
"};\n"
"using namespace NS;\n"
"Fred::impl::impl() { }\n"
"Fred::impl::~impl() { }\n"
"Fred::impl::impl(const Fred::impl &) { }\n"
"void Fred::impl::foo(const Fred::impl &, const Fred::impl &) const { }");
ASSERT(db != nullptr);
ASSERT(db && db->scopeList.size() == 8);
ASSERT(db && db->classAndStructScopes.size() == 2);
ASSERT(db && db->typeList.size() == 2);
ASSERT(db && db->functionScopes.size() == 4);
const Token * functionToken = Token::findsimplematch(tokenizer.tokens(), "impl ( ) { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 5 &&
functionToken->function()->token->linenr() == 11);
functionToken = Token::findsimplematch(tokenizer.tokens(), "~ impl ( ) { }");
ASSERT(db && functionToken && functionToken->next()->function() &&
functionToken->next()->function()->functionScope &&
functionToken->next()->function()->tokenDef->linenr() == 6 &&
functionToken->next()->function()->token->linenr() == 12);
functionToken = Token::findsimplematch(tokenizer.tokens(), "impl ( const Fred :: impl & ) { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 7 &&
functionToken->function()->token->linenr() == 13);
functionToken = Token::findsimplematch(tokenizer.tokens(), "foo ( const Fred :: impl & , const Fred :: impl & ) const { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 8 &&
functionToken->function()->token->linenr() == 14);
}
{
GET_SYMBOL_DB("template <typename A> class Fred { struct impl; };\n"
"template <typename A> struct Fred<A>::impl {\n"
" impl() { }\n"
" ~impl() { }\n"
" impl(const impl &) { }\n"
" void foo(const impl &, const impl &) const { }\n"
"};");
ASSERT(db != nullptr);
ASSERT(db && db->scopeList.size() == 7);
ASSERT(db && db->classAndStructScopes.size() == 2);
ASSERT(db && db->typeList.size() == 2);
ASSERT(db && db->functionScopes.size() == 4);
const Token * functionToken = Token::findsimplematch(tokenizer.tokens(), "impl ( ) { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 3 &&
functionToken->function()->token->linenr() == 3);
functionToken = Token::findsimplematch(tokenizer.tokens(), "~ impl ( ) { }");
ASSERT(db && functionToken && functionToken->next()->function() &&
functionToken->next()->function()->functionScope &&
functionToken->next()->function()->tokenDef->linenr() == 4 &&
functionToken->next()->function()->token->linenr() == 4);
functionToken = Token::findsimplematch(tokenizer.tokens(), "impl ( const impl & ) { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 5 &&
functionToken->function()->token->linenr() == 5);
functionToken = Token::findsimplematch(tokenizer.tokens(), "foo ( const impl & , const impl & ) const { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 6 &&
functionToken->function()->token->linenr() == 6);
}
{
GET_SYMBOL_DB("template <typename A> class Fred { struct impl; };\n"
"template <typename A> struct Fred<A>::impl {\n"
" impl();\n"
" ~impl();\n"
" impl(const impl &);\n"
" void foo(const impl &, const impl &) const;\n"
"};\n"
"template <typename A> Fred<A>::impl::impl() { }\n"
"template <typename A> Fred<A>::impl::~impl() { }\n"
"template <typename A> Fred<A>::impl::impl(const Fred<A>::impl &) { }\n"
"template <typename A> void Fred<A>::impl::foo(const Fred<A>::impl &, const Fred<A>::impl &) const { }");
ASSERT(db != nullptr);
ASSERT(db && db->scopeList.size() == 7);
ASSERT(db && db->classAndStructScopes.size() == 2);
ASSERT(db && db->typeList.size() == 2);
ASSERT(db && db->functionScopes.size() == 4);
const Token * functionToken = Token::findsimplematch(tokenizer.tokens(), "impl ( ) { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 3 &&
functionToken->function()->token->linenr() == 8);
functionToken = Token::findsimplematch(tokenizer.tokens(), "~ impl ( ) { }");
ASSERT(db && functionToken && functionToken->next()->function() &&
functionToken->next()->function()->functionScope &&
functionToken->next()->function()->tokenDef->linenr() == 4 &&
functionToken->next()->function()->token->linenr() == 9);
functionToken = Token::findsimplematch(tokenizer.tokens(), "impl ( const Fred < A > :: impl & ) { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 5 &&
functionToken->function()->token->linenr() == 10);
functionToken = Token::findsimplematch(tokenizer.tokens(), "foo ( const Fred < A > :: impl & , const Fred < A > :: impl & ) const { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 6 &&
functionToken->function()->token->linenr() == 11);
}
{
GET_SYMBOL_DB("namespace NS {\n"
" template <typename A> class Fred { struct impl; };\n"
" template <typename A> struct Fred<A>::impl {\n"
" impl() { }\n"
" ~impl() { }\n"
" impl(const impl &) { }\n"
" void foo(const impl &, const impl &) const { }\n"
" };\n"
"}");
ASSERT(db != nullptr);
ASSERT(db && db->scopeList.size() == 8);
ASSERT(db && db->classAndStructScopes.size() == 2);
ASSERT(db && db->typeList.size() == 2);
ASSERT(db && db->functionScopes.size() == 4);
const Token * functionToken = Token::findsimplematch(tokenizer.tokens(), "impl ( ) { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 4 &&
functionToken->function()->token->linenr() == 4);
functionToken = Token::findsimplematch(tokenizer.tokens(), "~ impl ( ) { }");
ASSERT(db && functionToken && functionToken->next()->function() &&
functionToken->next()->function()->functionScope &&
functionToken->next()->function()->tokenDef->linenr() == 5 &&
functionToken->next()->function()->token->linenr() == 5);
functionToken = Token::findsimplematch(tokenizer.tokens(), "impl ( const impl & ) { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 6 &&
functionToken->function()->token->linenr() == 6);
functionToken = Token::findsimplematch(tokenizer.tokens(), "foo ( const impl & , const impl & ) const { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 7 &&
functionToken->function()->token->linenr() == 7);
}
{
GET_SYMBOL_DB("namespace NS {\n"
" template <typename A> class Fred { struct impl; };\n"
" template <typename A> struct Fred<A>::impl {\n"
" impl();\n"
" ~impl();\n"
" impl(const impl &);\n"
" void foo(const impl &, const impl &) const;\n"
" };\n"
" template <typename A> Fred<A>::impl::impl() { }\n"
" template <typename A> Fred<A>::impl::~impl() { }\n"
" template <typename A> Fred<A>::impl::impl(const Fred<A>::impl &) { }\n"
" template <typename A> void Fred<A>::impl::foo(const Fred<A>::impl &, const Fred<A>::impl &) const { }\n"
"}");
ASSERT(db != nullptr);
ASSERT(db && db->scopeList.size() == 8);
ASSERT(db && db->classAndStructScopes.size() == 2);
ASSERT(db && db->typeList.size() == 2);
ASSERT(db && db->functionScopes.size() == 4);
const Token * functionToken = Token::findsimplematch(tokenizer.tokens(), "impl ( ) { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 4 &&
functionToken->function()->token->linenr() == 9);
functionToken = Token::findsimplematch(tokenizer.tokens(), "~ impl ( ) { }");
ASSERT(db && functionToken && functionToken->next()->function() &&
functionToken->next()->function()->functionScope &&
functionToken->next()->function()->tokenDef->linenr() == 5 &&
functionToken->next()->function()->token->linenr() == 10);
functionToken = Token::findsimplematch(tokenizer.tokens(), "impl ( const Fred < A > :: impl & ) { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 6 &&
functionToken->function()->token->linenr() == 11);
functionToken = Token::findsimplematch(tokenizer.tokens(), "foo ( const Fred < A > :: impl & , const Fred < A > :: impl & ) const { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 7 &&
functionToken->function()->token->linenr() == 12);
}
{
GET_SYMBOL_DB("namespace NS {\n"
" template <typename A> class Fred { struct impl; };\n"
" template <typename A> struct Fred<A>::impl {\n"
" impl();\n"
" ~impl();\n"
" impl(const impl &);\n"
" void foo(const impl &, const impl &) const;\n"
" };\n"
"}\n"
"template <typename A> NS::Fred<A>::impl::impl() { }\n"
"template <typename A> NS::Fred<A>::impl::~impl() { }\n"
"template <typename A> NS::Fred<A>::impl::impl(const NS::Fred<A>::impl &) { }\n"
"template <typename A> void NS::Fred<A>::impl::foo(const NS::Fred<A>::impl &, const NS::Fred<A>::impl &) const { }");
ASSERT(db != nullptr);
ASSERT(db && db->scopeList.size() == 8);
ASSERT(db && db->classAndStructScopes.size() == 2);
ASSERT(db && db->typeList.size() == 2);
ASSERT(db && db->functionScopes.size() == 4);
const Token * functionToken = Token::findsimplematch(tokenizer.tokens(), "impl ( ) { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 4 &&
functionToken->function()->token->linenr() == 10);
functionToken = Token::findsimplematch(tokenizer.tokens(), "~ impl ( ) { }");
ASSERT(db && functionToken && functionToken->next()->function() &&
functionToken->next()->function()->functionScope &&
functionToken->next()->function()->tokenDef->linenr() == 5 &&
functionToken->next()->function()->token->linenr() == 11);
functionToken = Token::findsimplematch(tokenizer.tokens(), "impl ( const NS :: Fred < A > :: impl & ) { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 6 &&
functionToken->function()->token->linenr() == 12);
functionToken = Token::findsimplematch(tokenizer.tokens(), "foo ( const NS :: Fred < A > :: impl & , const NS :: Fred < A > :: impl & ) const { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 7 &&
functionToken->function()->token->linenr() == 13);
}
{
GET_SYMBOL_DB("namespace NS {\n"
" template <typename A> class Fred { struct impl; };\n"
"}\n"
"template <typename A> struct NS::Fred<A>::impl {\n"
" impl() { }\n"
" ~impl() { }\n"
" impl(const impl &) { }\n"
" void foo(const impl &, const impl &) const { }\n"
"};");
ASSERT(db != nullptr);
ASSERT(db && db->scopeList.size() == 8);
ASSERT(db && db->classAndStructScopes.size() == 2);
ASSERT(db && db->typeList.size() == 2);
ASSERT(db && db->functionScopes.size() == 4);
const Token * functionToken = Token::findsimplematch(tokenizer.tokens(), "impl ( ) { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 5 &&
functionToken->function()->token->linenr() == 5);
functionToken = Token::findsimplematch(tokenizer.tokens(), "~ impl ( ) { }");
ASSERT(db && functionToken && functionToken->next()->function() &&
functionToken->next()->function()->functionScope &&
functionToken->next()->function()->tokenDef->linenr() == 6 &&
functionToken->next()->function()->token->linenr() == 6);
functionToken = Token::findsimplematch(tokenizer.tokens(), "impl ( const impl & ) { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 7 &&
functionToken->function()->token->linenr() == 7);
functionToken = Token::findsimplematch(tokenizer.tokens(), "foo ( const impl & , const impl & ) const { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 8 &&
functionToken->function()->token->linenr() == 8);
}
{
GET_SYMBOL_DB("namespace NS {\n"
" template <typename A> class Fred { struct impl; };\n"
"}\n"
"template <typename A> struct NS::Fred<A>::impl {\n"
" impl();\n"
" ~impl();\n"
" impl(const impl &);\n"
" void foo(const impl &, const impl &) const;\n"
"};\n"
"template <typename A> NS::Fred<A>::impl::impl() { }\n"
"template <typename A> NS::Fred<A>::impl::~impl() { }\n"
"template <typename A> NS::Fred<A>::impl::impl(const NS::Fred<A>::impl &) { }\n"
"template <typename A> void NS::Fred<A>::impl::foo(const NS::Fred<A>::impl &, const NS::Fred<A>::impl &) const { }");
ASSERT(db != nullptr);
ASSERT(db && db->scopeList.size() == 8);
ASSERT(db && db->classAndStructScopes.size() == 2);
ASSERT(db && db->typeList.size() == 2);
ASSERT(db && db->functionScopes.size() == 4);
const Token * functionToken = Token::findsimplematch(tokenizer.tokens(), "impl ( ) { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 5 &&
functionToken->function()->token->linenr() == 10);
functionToken = Token::findsimplematch(tokenizer.tokens(), "~ impl ( ) { }");
ASSERT(db && functionToken && functionToken->next()->function() &&
functionToken->next()->function()->functionScope &&
functionToken->next()->function()->tokenDef->linenr() == 6 &&
functionToken->next()->function()->token->linenr() == 11);
functionToken = Token::findsimplematch(tokenizer.tokens(), "impl ( const NS :: Fred < A > :: impl & ) { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 7 &&
functionToken->function()->token->linenr() == 12);
functionToken = Token::findsimplematch(tokenizer.tokens(), "foo ( const NS :: Fred < A > :: impl & , const NS :: Fred < A > :: impl & ) const { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 8 &&
functionToken->function()->token->linenr() == 13);
}
{
GET_SYMBOL_DB("namespace NS {\n"
" template <typename A> class Fred { struct impl; };\n"
"}\n"
"template <typename A> struct NS::Fred<A>::impl {\n"
" impl();\n"
" ~impl();\n"
" impl(const impl &);\n"
" void foo(const impl &, const impl &) const;\n"
"};\n"
"namespace NS {\n"
" template <typename A> Fred<A>::impl::impl() { }\n"
" template <typename A> Fred<A>::impl::~impl() { }\n"
" template <typename A> Fred<A>::impl::impl(const Fred<A>::impl &) { }\n"
" template <typename A> void Fred<A>::impl::foo(const Fred<A>::impl &, const Fred<A>::impl &) const { }\n"
"}");
ASSERT(db != nullptr);
ASSERT(db && db->scopeList.size() == 8);
ASSERT(db && db->classAndStructScopes.size() == 2);
ASSERT(db && db->typeList.size() == 2);
ASSERT(db && db->functionScopes.size() == 4);
const Token * functionToken = Token::findsimplematch(tokenizer.tokens(), "impl ( ) { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 5 &&
functionToken->function()->token->linenr() == 11);
functionToken = Token::findsimplematch(tokenizer.tokens(), "~ impl ( ) { }");
ASSERT(db && functionToken && functionToken->next()->function() &&
functionToken->next()->function()->functionScope &&
functionToken->next()->function()->tokenDef->linenr() == 6 &&
functionToken->next()->function()->token->linenr() == 12);
functionToken = Token::findsimplematch(tokenizer.tokens(), "impl ( const Fred < A > :: impl & ) { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 7 &&
functionToken->function()->token->linenr() == 13);
functionToken = Token::findsimplematch(tokenizer.tokens(), "foo ( const Fred < A > :: impl & , const Fred < A > :: impl & ) const { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 8 &&
functionToken->function()->token->linenr() == 14);
}
{
GET_SYMBOL_DB("namespace NS {\n"
" template <typename A> class Fred { struct impl; };\n"
"}\n"
"template <typename A> struct NS::Fred::impl {\n"
" impl();\n"
" ~impl();\n"
" impl(const impl &);\n"
" void foo(const impl &, const impl &) const;\n"
"};\n"
"using namespace NS;\n"
"template <typename A> Fred<A>::impl::impl() { }\n"
"template <typename A> Fred<A>::impl::~impl() { }\n"
"template <typename A> Fred<A>::impl::impl(const Fred<A>::impl &) { }\n"
"template <typename A> void Fred<A>::impl::foo(const Fred<A>::impl &, const Fred<A>::impl &) const { }");
ASSERT(db != nullptr);
ASSERT(db && db->scopeList.size() == 8);
ASSERT(db && db->classAndStructScopes.size() == 2);
ASSERT(db && db->typeList.size() == 2);
ASSERT(db && db->functionScopes.size() == 4);
const Token * functionToken = Token::findsimplematch(tokenizer.tokens(), "impl ( ) { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 5 &&
functionToken->function()->token->linenr() == 11);
functionToken = Token::findsimplematch(tokenizer.tokens(), "~ impl ( ) { }");
ASSERT(db && functionToken && functionToken->next()->function() &&
functionToken->next()->function()->functionScope &&
functionToken->next()->function()->tokenDef->linenr() == 6 &&
functionToken->next()->function()->token->linenr() == 12);
functionToken = Token::findsimplematch(tokenizer.tokens(), "impl ( const Fred < A > :: impl & ) { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 7 &&
functionToken->function()->token->linenr() == 13);
functionToken = Token::findsimplematch(tokenizer.tokens(), "foo ( const Fred < A > :: impl & , const Fred < A > :: impl & ) const { }");
ASSERT(db && functionToken && functionToken->function() &&
functionToken->function()->functionScope &&
functionToken->function()->tokenDef->linenr() == 8 &&
functionToken->function()->token->linenr() == 14);
}
}
void symboldatabase65() {
// don't crash on missing links from instantiation of template with typedef
check("int ( * X0 ) ( long ) < int ( ) ( long ) > :: f0 ( int * ) { return 0 ; }");
ASSERT_EQUALS("", errout_str());
check("int g();\n" // #11385
"void f(int i) {\n"
" if (i > ::g()) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void symboldatabase66() { // #8540
GET_SYMBOL_DB("enum class ENUM1;\n"
"enum class ENUM2 { MEMBER2 };\n"
"enum class ENUM3 : int { MEMBER1, };");
ASSERT(db != nullptr);
ASSERT(db && db->scopeList.size() == 3);
ASSERT(db && db->typeList.size() == 3);
}
void symboldatabase67() { // #8538
GET_SYMBOL_DB("std::string get_endpoint_url() const noexcept override;");
const Function *f = db ? &db->scopeList.front().functionList.front() : nullptr;
ASSERT(f != nullptr);
ASSERT(f && f->hasOverrideSpecifier());
ASSERT(f && f->isConst());
ASSERT(f && f->isNoExcept());
}
void symboldatabase68() { // #8560
GET_SYMBOL_DB("struct Bar {\n"
" virtual std::string get_endpoint_url() const noexcept;\n"
"};\n"
"struct Foo : Bar {\n"
" virtual std::string get_endpoint_url() const noexcept override final;\n"
"};");
const Token *f = db ? Token::findsimplematch(tokenizer.tokens(), "get_endpoint_url ( ) const noexcept ( true ) ;") : nullptr;
ASSERT(f != nullptr);
ASSERT(f && f->function() && f->function()->token->linenr() == 2);
ASSERT(f && f->function() && f->function()->hasVirtualSpecifier());
ASSERT(f && f->function() && !f->function()->hasOverrideSpecifier());
ASSERT(f && f->function() && !f->function()->hasFinalSpecifier());
ASSERT(f && f->function() && f->function()->isConst());
ASSERT(f && f->function() && f->function()->isNoExcept());
f = db ? Token::findsimplematch(tokenizer.tokens(), "get_endpoint_url ( ) const noexcept ( true ) override final ;") : nullptr;
ASSERT(f != nullptr);
ASSERT(f && f->function() && f->function()->token->linenr() == 5);
ASSERT(f && f->function() && f->function()->hasVirtualSpecifier());
ASSERT(f && f->function() && f->function()->hasOverrideSpecifier());
ASSERT(f && f->function() && f->function()->hasFinalSpecifier());
ASSERT(f && f->function() && f->function()->isConst());
ASSERT(f && f->function() && f->function()->isNoExcept());
}
void symboldatabase69() {
GET_SYMBOL_DB("struct Fred {\n"
" int x, y;\n"
" void foo() const volatile { }\n"
" void foo() volatile { }\n"
" void foo() const { }\n"
" void foo() { }\n"
"};");
const Token *f = db ? Token::findsimplematch(tokenizer.tokens(), "foo ( ) const volatile {") : nullptr;
ASSERT(f != nullptr);
ASSERT(f && f->function() && f->function()->token->linenr() == 3);
ASSERT(f && f->function() && f->function()->isConst());
ASSERT(f && f->function() && f->function()->isVolatile());
f = db ? Token::findsimplematch(tokenizer.tokens(), "foo ( ) volatile {") : nullptr;
ASSERT(f != nullptr);
ASSERT(f && f->function() && f->function()->token->linenr() == 4);
ASSERT(f && f->function() && !f->function()->isConst());
ASSERT(f && f->function() && f->function()->isVolatile());
f = db ? Token::findsimplematch(tokenizer.tokens(), "foo ( ) const {") : nullptr;
ASSERT(f != nullptr);
ASSERT(f && f->function() && f->function()->token->linenr() == 5);
ASSERT(f && f->function() && f->function()->isConst());
ASSERT(f && f->function() && !f->function()->isVolatile());
f = db ? Token::findsimplematch(tokenizer.tokens(), "foo ( ) {") : nullptr;
ASSERT(f != nullptr);
ASSERT(f && f->function() && f->function()->token->linenr() == 6);
ASSERT(f && f->function() && !f->function()->isVolatile());
ASSERT(f && f->function() && !f->function()->isConst());
}
void symboldatabase70() {
{
GET_SYMBOL_DB("class Map<String,Entry>::Entry* e;");
ASSERT(db != nullptr);
ASSERT(db && db->scopeList.size() == 1);
ASSERT(db && db->variableList().size() == 2);
}
{
GET_SYMBOL_DB("template class boost::token_iterator_generator<boost::offset_separator>::type; void foo() { }");
ASSERT(db != nullptr);
ASSERT(db && db->scopeList.size() == 2);
}
{
GET_SYMBOL_DB("void foo() {\n"
" return class Arm_relocate_functions<big_endian>::thumb32_branch_offset(upper_insn, lower_insn);\n"
"}");
ASSERT(db != nullptr);
ASSERT(db && db->scopeList.size() == 2);
}
}
void symboldatabase71() {
GET_SYMBOL_DB("class A { };\n"
"class B final : public A { };");
ASSERT(db && db->scopeList.size() == 3);
ASSERT(db && db->typeList.size() == 2);
}
void symboldatabase72() { // #8600
GET_SYMBOL_DB("struct A { struct B; };\n"
"struct A::B {\n"
" B() = default;\n"
" B(const B&) {}\n"
"};");
ASSERT(db && db->scopeList.size() == 4);
ASSERT(db && db->typeList.size() == 2);
const Token * f = db ? Token::findsimplematch(tokenizer.tokens(), "B ( const B & ) { }") : nullptr;
ASSERT(f != nullptr);
ASSERT(f && f->function() && f->function()->token->linenr() == 4);
ASSERT(f && f->function() && f->function()->type == Function::eCopyConstructor);
}
void symboldatabase74() { // #8838 - final
GET_SYMBOL_DB("class Base { virtual int f() const = 0; };\n"
"class Derived : Base { virtual int f() const final { return 6; } };");
ASSERT_EQUALS(4, db->scopeList.size());
ASSERT_EQUALS(1, db->functionScopes.size());
const Scope *f1 = db->functionScopes[0];
ASSERT(f1->function->hasFinalSpecifier());
}
void symboldatabase75() {
{
GET_SYMBOL_DB("template <typename T>\n"
"class optional {\n"
" auto value() & -> T &;\n"
" auto value() && -> T &&;\n"
" auto value() const& -> T const &;\n"
"};\n"
"template <typename T>\n"
"auto optional<T>::value() & -> T & {}\n"
"template <typename T>\n"
"auto optional<T>::value() && -> T && {}\n"
"template <typename T>\n"
"auto optional<T>::value() const & -> T const & {}\n"
"optional<int> i;");
ASSERT_EQUALS(5, db->scopeList.size());
ASSERT_EQUALS(3, db->functionScopes.size());
const Scope *f = db->functionScopes[0];
ASSERT(f->function->hasBody());
ASSERT(!f->function->isConst());
ASSERT(f->function->hasTrailingReturnType());
ASSERT(f->function->hasLvalRefQualifier());
f = db->functionScopes[1];
ASSERT(f->function->hasBody());
ASSERT(!f->function->isConst());
ASSERT(f->function->hasTrailingReturnType());
ASSERT(f->function->hasRvalRefQualifier());
f = db->functionScopes[2];
ASSERT(f->function->hasBody());
ASSERT(f->function->isConst());
ASSERT(f->function->hasTrailingReturnType());
ASSERT(f->function->hasLvalRefQualifier());
}
{
GET_SYMBOL_DB("struct S {\n" // #12962
" auto bar() const noexcept -> std::string const& { return m; }\n"
" std::string m;\n"
"};\n");
ASSERT_EQUALS(3, db->scopeList.size());
ASSERT_EQUALS(1, db->functionScopes.size());
const Scope* f = db->functionScopes[0];
ASSERT(f->function->hasBody());
ASSERT(f->function->isConst());
ASSERT(f->function->hasTrailingReturnType());
ASSERT(f->function->isNoExcept());
ASSERT(Function::returnsReference(f->function));
}
}
void symboldatabase76() { // #9056
GET_SYMBOL_DB("namespace foo {\n"
" using namespace bar::baz;\n"
" auto func(int arg) -> bar::quux {}\n"
"}");
ASSERT_EQUALS(2, db->mVariableList.size());
}
void symboldatabase77() { // #8663
GET_SYMBOL_DB("template <class T1, class T2>\n"
"void f() {\n"
" using T3 = typename T1::template T3<T2>;\n"
" T3 t;\n"
"}");
ASSERT_EQUALS(2, db->mVariableList.size());
}
void symboldatabase78() { // #9147
GET_SYMBOL_DB("template <class...> struct a;\n"
"namespace {\n"
"template <class, class> struct b;\n"
"template <template <class> class c, class... f, template <class...> class d>\n"
"struct b<c<f...>, d<>>;\n"
"}\n"
"void e() { using c = a<>; }");
ASSERT(db != nullptr);
ASSERT_EQUALS("", errout_str());
}
void symboldatabase79() { // #9392
{
GET_SYMBOL_DB("class C { C(); };\n"
"C::C() = default;");
ASSERT(db->scopeList.size() == 2);
ASSERT(db->scopeList.back().functionList.size() == 1);
ASSERT(db->scopeList.back().functionList.front().isDefault() == true);
}
{
GET_SYMBOL_DB("namespace ns {\n"
"class C { C(); };\n"
"}\n"
"using namespace ns;\n"
"C::C() = default;");
ASSERT(db->scopeList.size() == 3);
ASSERT(db->scopeList.back().functionList.size() == 1);
ASSERT(db->scopeList.back().functionList.front().isDefault() == true);
}
{
GET_SYMBOL_DB("class C { ~C(); };\n"
"C::~C() = default;");
ASSERT(db->scopeList.size() == 2);
ASSERT(db->scopeList.back().functionList.size() == 1);
ASSERT(db->scopeList.back().functionList.front().isDefault() == true);
ASSERT(db->scopeList.back().functionList.front().isDestructor() == true);
}
{
GET_SYMBOL_DB("namespace ns {\n"
"class C { ~C(); };\n"
"}\n"
"using namespace ns;\n"
"C::~C() = default;");
ASSERT(db->scopeList.size() == 3);
ASSERT(db->scopeList.back().functionList.size() == 1);
ASSERT(db->scopeList.back().functionList.front().isDefault() == true);
ASSERT(db->scopeList.back().functionList.front().isDestructor() == true);
}
}
void symboldatabase80() { // #9389
{
GET_SYMBOL_DB("namespace ns {\n"
"class A {};\n"
"}\n"
"class AA {\n"
"private:\n"
" void f(const ns::A&);\n"
"};\n"
"using namespace ns;\n"
"void AA::f(const A&) { }");
ASSERT(db->scopeList.size() == 5);
ASSERT(db->functionScopes.size() == 1);
const Scope *scope = db->findScopeByName("AA");
ASSERT(scope);
ASSERT(scope->functionList.size() == 1);
ASSERT(scope->functionList.front().name() == "f");
ASSERT(scope->functionList.front().hasBody() == true);
}
{
GET_SYMBOL_DB("namespace ns {\n"
"namespace ns1 {\n"
"class A {};\n"
"}\n"
"}\n"
"class AA {\n"
"private:\n"
" void f(const ns::ns1::A&);\n"
"};\n"
"using namespace ns::ns1;\n"
"void AA::f(const A&) { }");
ASSERT(db->scopeList.size() == 6);
ASSERT(db->functionScopes.size() == 1);
const Scope *scope = db->findScopeByName("AA");
ASSERT(scope);
ASSERT(scope->functionList.size() == 1);
ASSERT(scope->functionList.front().name() == "f");
ASSERT(scope->functionList.front().hasBody() == true);
}
{
GET_SYMBOL_DB("namespace ns {\n"
"namespace ns1 {\n"
"class A {};\n"
"}\n"
"}\n"
"class AA {\n"
"private:\n"
" void f(const ns::ns1::A&);\n"
"};\n"
"using namespace ns;\n"
"void AA::f(const ns1::A&) { }");
ASSERT(db->scopeList.size() == 6);
ASSERT(db->functionScopes.size() == 1);
const Scope *scope = db->findScopeByName("AA");
ASSERT(scope);
ASSERT(scope->functionList.size() == 1);
ASSERT(scope->functionList.front().name() == "f");
ASSERT(scope->functionList.front().hasBody() == true);
}
}
void symboldatabase81() { // #9411
{
GET_SYMBOL_DB("namespace Terminal {\n"
" class Complete {\n"
" public:\n"
" std::string act(const Parser::Action *act);\n"
" };\n"
"}\n"
"using namespace std;\n"
"using namespace Parser;\n"
"using namespace Terminal;\n"
"string Complete::act(const Action *act) { }");
ASSERT(db->scopeList.size() == 4);
ASSERT(db->functionScopes.size() == 1);
const Scope *scope = db->findScopeByName("Complete");
ASSERT(scope);
ASSERT(scope->functionList.size() == 1);
ASSERT(scope->functionList.front().name() == "act");
ASSERT(scope->functionList.front().hasBody() == true);
}
{
GET_SYMBOL_DB("namespace Terminal {\n"
" class Complete {\n"
" public:\n"
" std::string act(const Foo::Parser::Action *act);\n"
" };\n"
"}\n"
"using namespace std;\n"
"using namespace Foo::Parser;\n"
"using namespace Terminal;\n"
"string Complete::act(const Action *act) { }");
ASSERT(db->scopeList.size() == 4);
ASSERT(db->functionScopes.size() == 1);
const Scope *scope = db->findScopeByName("Complete");
ASSERT(scope);
ASSERT(scope->functionList.size() == 1);
ASSERT(scope->functionList.front().name() == "act");
ASSERT(scope->functionList.front().hasBody() == true);
}
}
void symboldatabase82() {
GET_SYMBOL_DB("namespace foo { void foo() {} }");
ASSERT(db->functionScopes.size() == 1);
ASSERT_EQUALS(false, db->functionScopes[0]->function->isConstructor());
}
void symboldatabase83() { // #9431
GET_SYMBOL_DB_DBG("struct a { a() noexcept; };\n"
"a::a() noexcept = default;");
const Scope *scope = db->findScopeByName("a");
ASSERT(scope);
ASSERT(scope->functionList.size() == 1);
ASSERT(scope->functionList.front().name() == "a");
ASSERT(scope->functionList.front().hasBody() == false);
ASSERT(scope->functionList.front().isConstructor() == true);
ASSERT(scope->functionList.front().isDefault() == true);
ASSERT(scope->functionList.front().isNoExcept() == true);
ASSERT_EQUALS("", errout_str());
}
void symboldatabase84() {
{
GET_SYMBOL_DB_DBG("struct a { a() noexcept(false); };\n"
"a::a() noexcept(false) = default;");
const Scope *scope = db->findScopeByName("a");
ASSERT(scope);
ASSERT(scope->functionList.size() == 1);
ASSERT(scope->functionList.front().name() == "a");
ASSERT(scope->functionList.front().hasBody() == false);
ASSERT(scope->functionList.front().isConstructor() == true);
ASSERT(scope->functionList.front().isDefault() == true);
ASSERT(scope->functionList.front().isNoExcept() == false);
ASSERT_EQUALS("", errout_str());
}
{
GET_SYMBOL_DB_DBG("struct a { a() noexcept(true); };\n"
"a::a() noexcept(true) = default;");
const Scope *scope = db->findScopeByName("a");
ASSERT(scope);
ASSERT(scope->functionList.size() == 1);
ASSERT(scope->functionList.front().name() == "a");
ASSERT(scope->functionList.front().hasBody() == false);
ASSERT(scope->functionList.front().isConstructor() == true);
ASSERT(scope->functionList.front().isDefault() == true);
ASSERT(scope->functionList.front().isNoExcept() == true);
ASSERT_EQUALS("", errout_str());
}
}
void symboldatabase85() {
GET_SYMBOL_DB("class Fred {\n"
" enum Mode { Mode1, Mode2, Mode3 };\n"
" void f() { _mode = x; }\n"
" Mode _mode;\n"
" DECLARE_PROPERTY_FIELD(_mode);\n"
"};");
const Token *vartok1 = Token::findsimplematch(tokenizer.tokens(), "_mode =");
ASSERT(vartok1);
ASSERT(vartok1->variable());
ASSERT(vartok1->variable()->scope());
const Token *vartok2 = Token::findsimplematch(tokenizer.tokens(), "( _mode ) ;")->next();
ASSERT_EQUALS(std::intptr_t(vartok1->variable()), std::intptr_t(vartok2->variable()));
}
void symboldatabase86() {
GET_SYMBOL_DB("class C { auto operator=(const C&) -> C&; };\n"
"auto C::operator=(const C&) -> C& = default;");
ASSERT(db->scopeList.size() == 2);
ASSERT(db->scopeList.back().functionList.size() == 1);
ASSERT(db->scopeList.back().functionList.front().isDefault() == true);
ASSERT(db->scopeList.back().functionList.front().hasBody() == false);
}
void symboldatabase87() { // #9922 'extern const char ( * x [ 256 ] ) ;'
GET_SYMBOL_DB("extern const char ( * x [ 256 ] ) ;");
const Token *xtok = Token::findsimplematch(tokenizer.tokens(), "x");
ASSERT(xtok->variable());
}
void symboldatabase88() { // #10040 (using namespace)
check("namespace external {\n"
"namespace ns {\n"
"enum class s { O };\n"
"}\n"
"}\n"
"namespace internal {\n"
"namespace ns1 {\n"
"template <typename T>\n"
"void make(external::ns::s) {\n"
"}\n"
"}\n"
"}\n"
"using namespace external::ns;\n"
"struct A { };\n"
"static void make(external::ns::s ss) {\n"
" internal::ns1::make<A>(ss);\n"
"}\n", true);
ASSERT_EQUALS("", errout_str());
}
void symboldatabase89() { // valuetype name
GET_SYMBOL_DB("namespace external {\n"
"namespace ns1 {\n"
"class A {\n"
"public:\n"
" struct S { };\n"
" A(const S&) { }\n"
"};\n"
"static const A::S AS = A::S();\n"
"}\n"
"}\n"
"using namespace external::ns1;\n"
"A a{AS};");
const Token *vartok1 = Token::findsimplematch(tokenizer.tokens(), "A a");
ASSERT(vartok1);
ASSERT(vartok1->next());
ASSERT(vartok1->next()->variable());
ASSERT(vartok1->next()->variable()->valueType());
ASSERT(vartok1->next()->variable()->valueType()->str() == "external::ns1::A");
}
void symboldatabase90() {
GET_SYMBOL_DB("struct Fred {\n"
" void foo(const int * const x);\n"
"};\n"
"void Fred::foo(const int * x) { }");
ASSERT_EQUALS("", errout_str());
const Token *functok = Token::findsimplematch(tokenizer.tokens(), "foo ( const int * x )");
ASSERT(functok);
ASSERT(functok->function());
ASSERT(functok->function()->name() == "foo");
}
void symboldatabase91() {
GET_SYMBOL_DB("namespace Fred {\n"
" struct Value {};\n"
" void foo(const std::vector<std::function<void(const Fred::Value &)>> &callbacks);\n"
"}\n"
"void Fred::foo(const std::vector<std::function<void(const Fred::Value &)>> &callbacks) { }");
ASSERT_EQUALS("", errout_str());
const Token *functok = Token::findsimplematch(tokenizer.tokens(),
"foo ( const std :: vector < std :: function < void ( const Fred :: Value & ) > > & callbacks ) { }");
ASSERT(functok);
ASSERT(functok->function());
ASSERT(functok->function()->name() == "foo");
}
void symboldatabase92() { // daca crash
{
GET_SYMBOL_DB("template <size_t, typename...> struct a;\n"
"template <size_t b, typename c, typename... d>\n"
"struct a<b, c, d...> : a<1, d...> {};\n"
"template <typename... e> struct f : a<0, e...> {};");
ASSERT_EQUALS("", errout_str());
}
{
GET_SYMBOL_DB("b.f();");
ASSERT_EQUALS("", errout_str());
}
}
void symboldatabase93() { // alignas attribute
GET_SYMBOL_DB("struct alignas(int) A{\n"
"};\n"
);
ASSERT(db != nullptr);
const Scope* scope = db->findScopeByName("A");
ASSERT(scope);
}
void symboldatabase94() { // structured bindings
GET_SYMBOL_DB("int foo() { auto [x,y] = xy(); return x+y; }");
ASSERT(db != nullptr);
ASSERT(db->getVariableFromVarId(1) != nullptr);
ASSERT(db->getVariableFromVarId(2) != nullptr);
}
void symboldatabase95() { // #10295
GET_SYMBOL_DB("struct B {\n"
" void foo1(void);\n"
" void foo2();\n"
"};\n"
"void B::foo1() {}\n"
"void B::foo2(void) {}\n");
ASSERT_EQUALS("", errout_str());
const Token *functok = Token::findsimplematch(tokenizer.tokens(), "foo1 ( ) { }");
ASSERT(functok);
ASSERT(functok->function());
ASSERT(functok->function()->name() == "foo1");
functok = Token::findsimplematch(tokenizer.tokens(), "foo2 ( ) { }");
ASSERT(functok);
ASSERT(functok->function());
ASSERT(functok->function()->name() == "foo2");
}
void symboldatabase96() { // #10126
GET_SYMBOL_DB("struct A {\n"
" int i, j;\n"
"};\n"
"std::map<int, A> m{ { 0, A{0,0} }, {0, A{0,0} } };\n");
ASSERT_EQUALS("", errout_str());
}
void symboldatabase97() { // #10598 - final class
GET_SYMBOL_DB("template<> struct A<void> final {\n"
" A() {}\n"
"};\n");
ASSERT(db);
ASSERT_EQUALS(3, db->scopeList.size());
const Token *functok = Token::findmatch(tokenizer.tokens(), "%name% (");
ASSERT(functok);
ASSERT(functok->function());
ASSERT_EQUALS(functok->function()->type, Function::Type::eConstructor);
}
void symboldatabase98() { // #10451
{
GET_SYMBOL_DB("struct A { typedef struct {} B; };\n"
"void f() {\n"
" auto g = [](A::B b) -> void { A::B b2 = b; };\n"
"};\n");
ASSERT(db);
ASSERT_EQUALS(5, db->scopeList.size());
}
{
GET_SYMBOL_DB("typedef union {\n"
" int i;\n"
"} U;\n"
"template <auto U::*>\n"
"void f();\n");
ASSERT(db);
ASSERT_EQUALS(2, db->scopeList.size());
}
}
void symboldatabase99() { // #10864
check("void f() { std::map<std::string, int> m; }");
ASSERT_EQUALS("", errout_str());
}
void symboldatabase100() {
{
GET_SYMBOL_DB("namespace N {\n" // #10174
" struct S {};\n"
" struct T { void f(S s); };\n"
" void T::f(N::S s) {}\n"
"}\n");
ASSERT(db);
ASSERT_EQUALS(1, db->functionScopes.size());
auto it = std::find_if(db->scopeList.cbegin(), db->scopeList.cend(), [](const Scope& s) {
return s.className == "T";
});
ASSERT(it != db->scopeList.end());
const Function* function = findFunctionByName("f", &*it);
ASSERT(function && function->token->str() == "f");
ASSERT(function->hasBody());
}
{
GET_SYMBOL_DB("namespace N {\n" // #10198
" class I {};\n"
" class A {\n"
" public:\n"
" A(I*);\n"
" };\n"
"}\n"
"using N::I;\n"
"namespace N {\n"
" A::A(I*) {}\n"
"}\n");
ASSERT(db);
ASSERT_EQUALS(1, db->functionScopes.size());
auto it = std::find_if(db->scopeList.cbegin(), db->scopeList.cend(), [](const Scope& s) {
return s.className == "A";
});
ASSERT(it != db->scopeList.end());
const Function* function = findFunctionByName("A", &*it);
ASSERT(function && function->token->str() == "A");
ASSERT(function->hasBody());
}
{
GET_SYMBOL_DB("namespace N {\n" // #10260
" namespace O {\n"
" struct B;\n"
" }\n"
"}\n"
"struct I {\n"
" using B = N::O::B;\n"
"};\n"
"struct A : I {\n"
" void f(B*);\n"
"};\n"
"void A::f(N::O::B*) {}\n");
ASSERT(db);
ASSERT_EQUALS(1, db->functionScopes.size());
auto it = std::find_if(db->scopeList.cbegin(), db->scopeList.cend(), [](const Scope& s) {
return s.className == "A";
});
ASSERT(it != db->scopeList.end());
const Function* function = findFunctionByName("f", &*it);
ASSERT(function && function->token->str() == "f");
ASSERT(function->hasBody());
}
}
void symboldatabase101() {
GET_SYMBOL_DB("struct A { bool b; };\n"
"void f(const std::vector<A>& v) {\n"
" std::vector<A>::const_iterator it = b.begin();\n"
" if (it->b) {}\n"
"}\n");
ASSERT(db);
const Token* it = Token::findsimplematch(tokenizer.tokens(), "it . b");
ASSERT(it);
ASSERT(it->tokAt(2));
ASSERT(it->tokAt(2)->variable());
}
void symboldatabase102() {
GET_SYMBOL_DB("std::string f() = delete;\n"
"void g() {}");
ASSERT(db);
ASSERT(db->scopeList.size() == 2);
ASSERT(db->scopeList.front().type == Scope::eGlobal);
ASSERT(db->scopeList.back().className == "g");
}
void symboldatabase103() {
GET_SYMBOL_DB("void f() {\n"
"using lambda = decltype([]() { return true; });\n"
"lambda{}();\n"
"}\n");
ASSERT(db != nullptr);
ASSERT_EQUALS("", errout_str());
}
void symboldatabase104() {
{
GET_SYMBOL_DB_DBG("struct S {\n" // #11535
" void f1(char* const c);\n"
" void f2(char* const c);\n"
" void f3(char* const);\n"
" void f4(char* c);\n"
" void f5(char* c);\n"
" void f6(char*);\n"
"};\n"
"void S::f1(char* c) {}\n"
"void S::f2(char*) {}\n"
"void S::f3(char* c) {}\n"
"void S::f4(char* const c) {}\n"
"void S::f5(char* const) {}\n"
"void S::f6(char* const c) {}\n");
ASSERT(db != nullptr);
ASSERT_EQUALS("", errout_str());
}
{
GET_SYMBOL_DB_DBG("struct S2 {\n" // #11602
" enum E {};\n"
"};\n"
"struct S1 {\n"
" void f(S2::E) const;\n"
"};\n"
"void S1::f(const S2::E) const {}\n");
ASSERT(db != nullptr);
ASSERT_EQUALS("", errout_str());
}
{
GET_SYMBOL_DB_DBG("struct S {\n"
" void f(const bool b = false);\n"
"};\n"
"void S::f(const bool b) {}\n");
ASSERT(db != nullptr);
ASSERT_EQUALS("", errout_str());
}
}
void symboldatabase105() {
{
GET_SYMBOL_DB_DBG("template <class T>\n"
"struct S : public std::deque<T> {\n"
" using std::deque<T>::clear;\n"
" void f();\n"
"};\n"
"template <class T>\n"
"void S<T>::f() {\n"
" clear();\n"
"}\n");
ASSERT(db != nullptr);
ASSERT_EQUALS("", errout_str());
const Token* const c = Token::findsimplematch(tokenizer.tokens(), "clear (");
ASSERT(!c->type());
}
}
void symboldatabase106() {
{
GET_SYMBOL_DB_DBG("namespace N {\n" // #12958 - don't crash
" namespace O {\n"
" using namespace N::O;\n"
" }\n"
"}\n");
ASSERT(db != nullptr);
ASSERT_EQUALS("", errout_str());
}
{
GET_SYMBOL_DB_DBG("namespace N {\n"
" struct S {};\n"
"}\n"
"namespace O {\n"
" using namespace N;\n"
"}\n"
"namespace N {\n"
" using namespace O;\n"
" struct T {};\n"
"}\n");
ASSERT(db != nullptr);
ASSERT_EQUALS("", errout_str());
}
}
void symboldatabase107() {
{
GET_SYMBOL_DB_DBG("void g(int);\n" // #13329
"void f(int** pp) {\n"
" for (int i = 0; i < 2; i++) {\n"
" g(*pp[i]);\n"
" }\n"
"}\n");
ASSERT(db != nullptr);
ASSERT_EQUALS("", errout_str());
ASSERT_EQUALS(3, db->scopeList.size());
ASSERT_EQUALS(Scope::ScopeType::eFor, db->scopeList.back().type);
ASSERT_EQUALS(1, db->scopeList.back().varlist.size());
}
}
void symboldatabase108() {
{
GET_SYMBOL_DB("struct S {\n" // #13442
" S() = delete;\n"
" S(int a) : i(a) {}\n"
" ~S();\n"
" int i;\n"
"};\n"
"S::~S() = default;\n");
ASSERT_EQUALS(db->scopeList.size(), 3);
auto scope = db->scopeList.begin();
++scope;
ASSERT_EQUALS(scope->className, "S");
const auto& flist = scope->functionList;
ASSERT_EQUALS(flist.size(), 3);
auto it = flist.begin();
ASSERT_EQUALS(it->name(), "S");
ASSERT_EQUALS(it->tokenDef->linenr(), 2);
ASSERT(it->isDelete());
ASSERT(!it->isDefault());
ASSERT_EQUALS(it->type, Function::Type::eConstructor);
++it;
ASSERT_EQUALS(it->name(), "S");
ASSERT_EQUALS(it->tokenDef->linenr(), 3);
ASSERT(!it->isDelete());
ASSERT(!it->isDefault());
ASSERT_EQUALS(it->type, Function::Type::eConstructor);
++it;
ASSERT_EQUALS(it->name(), "S");
ASSERT_EQUALS(it->tokenDef->linenr(), 4);
ASSERT(!it->isDelete());
ASSERT(it->isDefault());
ASSERT_EQUALS(it->type, Function::Type::eDestructor);
}
}
void createSymbolDatabaseFindAllScopes1() {
GET_SYMBOL_DB("void f() { union {int x; char *p;} a={0}; }");
ASSERT(db->scopeList.size() == 3);
ASSERT_EQUALS(Scope::eUnion, db->scopeList.back().type);
}
void createSymbolDatabaseFindAllScopes2() {
GET_SYMBOL_DB("namespace ns { auto var1{0}; }\n"
"namespace ns { auto var2{0}; }\n");
ASSERT(db);
ASSERT_EQUALS(2, db->scopeList.size());
ASSERT_EQUALS(2, db->scopeList.back().varlist.size());
const Token* const var1 = Token::findsimplematch(tokenizer.tokens(), "var1");
const Token* const var2 = Token::findsimplematch(tokenizer.tokens(), "var2");
ASSERT(var1->variable());
ASSERT(var2->variable());
}
void createSymbolDatabaseFindAllScopes3() {
GET_SYMBOL_DB("namespace ns {\n"
"\n"
"namespace ns_details {\n"
"template <typename T, typename = void> struct has_A : std::false_type {};\n"
"template <typename T> struct has_A<T, typename make_void<typename T::A>::type> : std::true_type {};\n"
"template <typename T, bool> struct is_A_impl : public std::is_trivially_copyable<T> {};\n"
"template <typename T> struct is_A_impl<T, true> : public std::is_same<typename T::A, std::true_type> {};\n"
"}\n"
"\n"
"template <typename T> struct is_A : ns_details::is_A_impl<T, ns_details::has_A<T>::value> {};\n"
"template <class T, class U> struct is_A<std::pair<T, U>> : std::integral_constant<bool, is_A<T>::value && is_A<U>::value> {};\n"
"}\n"
"\n"
"extern \"C\" {\n"
"static const int foo = 8;\n"
"}\n");
ASSERT(db);
ASSERT_EQUALS(9, db->scopeList.size());
ASSERT_EQUALS(1, db->scopeList.front().varlist.size());
auto list = db->scopeList;
list.pop_front();
ASSERT_EQUALS(true, std::all_of(list.cbegin(), list.cend(), [](const Scope& scope) {
return scope.varlist.empty();
}));
}
void createSymbolDatabaseFindAllScopes4()
{
GET_SYMBOL_DB("struct a {\n"
" void b() {\n"
" std::set<int> c;\n"
" a{[&] {\n"
" auto d{c.lower_bound(0)};\n"
" c.emplace_hint(d);\n"
" }};\n"
" }\n"
" template <class e> a(e);\n"
"};\n");
ASSERT(db);
ASSERT_EQUALS(4, db->scopeList.size());
const Token* const var1 = Token::findsimplematch(tokenizer.tokens(), "d");
ASSERT(var1->variable());
}
void createSymbolDatabaseFindAllScopes5()
{
GET_SYMBOL_DB("class C {\n" // #11444
"public:\n"
" template<typename T>\n"
" class D;\n"
" template<typename T>\n"
" struct O : public std::false_type {};\n"
"};\n"
"template<typename T>\n"
"struct C::O<std::optional<T>> : public std::true_type {};\n"
"template<typename T>\n"
"class C::D {};\n"
"struct S {\n"
" S(int i) : m(i) {}\n"
" static const S IN;\n"
" int m;\n"
"};\n"
"const S S::IN(1);\n");
ASSERT(db);
ASSERT_EQUALS(7, db->scopeList.size());
const Token* const var = Token::findsimplematch(tokenizer.tokens(), "IN (");
ASSERT(var && var->variable());
ASSERT_EQUALS(var->variable()->name(), "IN");
auto it = db->scopeList.cbegin();
std::advance(it, 5);
ASSERT_EQUALS(it->className, "S");
ASSERT_EQUALS(var->variable()->scope(), &*it);
}
void createSymbolDatabaseFindAllScopes6()
{
GET_SYMBOL_DB("class A {\n"
"public:\n"
" class Nested {\n"
" public:\n"
" virtual ~Nested() = default;\n"
" };\n"
"};\n"
"class B {\n"
"public:\n"
" class Nested {\n"
" public:\n"
" virtual ~Nested() = default;\n"
" };\n"
"};\n"
"class C : public A, public B {\n"
"public:\n"
" class Nested : public A::Nested, public B::Nested {};\n"
"};\n");
ASSERT(db);
ASSERT_EQUALS(6, db->typeList.size());
auto it = db->typeList.cbegin();
const Type& classA = *it++;
const Type& classNA = *it++;
const Type& classB = *it++;
const Type& classNB = *it++;
const Type& classC = *it++;
const Type& classNC = *it++;
ASSERT(classA.name() == "A" && classB.name() == "B" && classC.name() == "C");
ASSERT(classNA.name() == "Nested" && classNB.name() == "Nested" && classNC.name() == "Nested");
ASSERT(classA.derivedFrom.empty() && classB.derivedFrom.empty());
ASSERT_EQUALS(classC.derivedFrom.size(), 2U);
ASSERT_EQUALS(classC.derivedFrom[0].type, &classA);
ASSERT_EQUALS(classC.derivedFrom[1].type, &classB);
ASSERT(classNA.derivedFrom.empty() && classNB.derivedFrom.empty());
ASSERT_EQUALS(classNC.derivedFrom.size(), 2U);
ASSERT_EQUALS(classNC.derivedFrom[0].type, &classNA);
ASSERT_EQUALS(classNC.derivedFrom[1].type, &classNB);
}
void createSymbolDatabaseFindAllScopes7()
{
{
GET_SYMBOL_DB("namespace {\n"
" struct S {\n"
" void f();\n"
" };\n"
"}\n"
"void S::f() {}\n");
ASSERT(db);
ASSERT_EQUALS(4, db->scopeList.size());
auto anon = db->scopeList.begin();
++anon;
ASSERT(anon->className.empty());
ASSERT_EQUALS(anon->type, Scope::eNamespace);
auto S = anon;
++S;
ASSERT_EQUALS(S->type, Scope::eStruct);
ASSERT_EQUALS(S->className, "S");
ASSERT_EQUALS(S->nestedIn, &*anon);
const Token* f = Token::findsimplematch(tokenizer.tokens(), "f ( ) {");
ASSERT(f && f->function() && f->function()->functionScope && f->function()->functionScope->bodyStart);
ASSERT_EQUALS(f->function()->functionScope->functionOf, &*S);
ASSERT_EQUALS(f->function()->functionScope->bodyStart->linenr(), 6);
}
{
GET_SYMBOL_DB("namespace {\n"
" int i = 0;\n"
"}\n"
"namespace N {\n"
" namespace {\n"
" template<typename T>\n"
" struct S {\n"
" void f();\n"
" };\n"
" template<typename T>\n"
" void S<T>::f() {}\n"
" }\n"
" S<int> g() { return {}; }\n"
"}\n");
ASSERT(db); // don't crash
ASSERT_EQUALS("", errout_str());
}
}
void createSymbolDatabaseFindAllScopes8() // #12761
{
// There are 2 myst constructors. They should belong to different scopes.
GET_SYMBOL_DB("template <class A = void, class B = void, class C = void>\n"
"class Test {\n"
"private:\n"
" template <class T>\n"
" struct myst {\n"
" T* x;\n"
" myst(T* y) : x(y){};\n" // <- myst constructor
" };\n"
"};\n"
"\n"
"template <class A, class B> class Test<A, B, void> {};\n"
"\n"
"template <>\n"
"class Test<void, void, void> {\n"
"private:\n"
" template <class T>\n"
" struct myst {\n"
" T* x;\n"
" myst(T* y) : x(y){};\n" // <- myst constructor
" };\n"
"};");
ASSERT(db);
const Token* myst1 = Token::findsimplematch(tokenizer.tokens(), "myst ( T * y )");
const Token* myst2 = Token::findsimplematch(myst1->next(), "myst ( T * y )");
ASSERT(myst1);
ASSERT(myst2);
ASSERT(myst1->scope() != myst2->scope());
}
void createSymbolDatabaseFindAllScopes9() // #12943
{
GET_SYMBOL_DB("void f(int n) {\n"
" if ([](int i) { return i == 2; }(n)) {}\n"
"}\n");
ASSERT(db && db->scopeList.size() == 4);
ASSERT_EQUALS(db->scopeList.back().type, Scope::eLambda);
}
void createSymbolDatabaseIncompleteVars()
{
{
GET_SYMBOL_DB("void f() {\n"
" auto s1 = std::string{ \"abc\" };\n"
" auto s2 = std::string(\"def\");\n"
"}\n");
ASSERT(db && errout_str().empty());
const Token* s1 = Token::findsimplematch(tokenizer.tokens(), "string {");
ASSERT(s1 && !s1->isIncompleteVar());
const Token* s2 = Token::findsimplematch(s1, "string (");
ASSERT(s2 && !s2->isIncompleteVar());
}
{
GET_SYMBOL_DB("std::string f(int n, std::type_info t) {\n"
" std::vector<std::string*> v(n);\n"
" g<const std::string &>();\n"
" if (static_cast<int>(x)) {}\n"
" if (t == typeid(std::string)) {}\n"
" return (std::string) \"abc\";\n"
"}\n");
ASSERT(db && errout_str().empty());
const Token* s1 = Token::findsimplematch(tokenizer.tokens(), "string *");
ASSERT(s1 && !s1->isIncompleteVar());
const Token* s2 = Token::findsimplematch(s1, "string &");
ASSERT(s2 && !s2->isIncompleteVar());
const Token* x = Token::findsimplematch(s2, "x");
ASSERT(x && x->isIncompleteVar());
const Token* s3 = Token::findsimplematch(x, "string )");
ASSERT(s3 && !s3->isIncompleteVar());
const Token* s4 = Token::findsimplematch(s3->next(), "string )");
ASSERT(s4 && !s4->isIncompleteVar());
}
{
GET_SYMBOL_DB("void destroy(int*, void (*cb_dealloc)(void *));\n"
"void f(int* p, int* q, int* r) {\n"
" destroy(p, free);\n"
" destroy(q, std::free);\n"
" destroy(r, N::free);\n"
"}\n");
ASSERT(db && errout_str().empty());
const Token* free1 = Token::findsimplematch(tokenizer.tokens(), "free");
ASSERT(free1 && !free1->isIncompleteVar());
const Token* free2 = Token::findsimplematch(free1->next(), "free");
ASSERT(free2 && !free2->isIncompleteVar());
const Token* free3 = Token::findsimplematch(free2->next(), "free");
ASSERT(free3 && free3->isIncompleteVar());
}
{
GET_SYMBOL_DB("void f(QObject* p, const char* s) {\n"
" QWidget* w = dynamic_cast<QWidget*>(p);\n"
" g(static_cast<const std::string>(s));\n"
" const std::uint64_t* const data = nullptr;\n"
"}\n");
ASSERT(db && errout_str().empty());
const Token* qw = Token::findsimplematch(tokenizer.tokens(), "QWidget * >");
ASSERT(qw && !qw->isIncompleteVar());
const Token* s = Token::findsimplematch(qw, "string >");
ASSERT(s && !s->isIncompleteVar());
const Token* u = Token::findsimplematch(s, "uint64_t");
ASSERT(u && !u->isIncompleteVar());
}
{
GET_SYMBOL_DB("void f() {\n"
" std::string* p = new std::string;\n"
" std::string* q = new std::string(\"abc\");\n"
" std::string* r = new std::string{ \"def\" };\n"
" std::string* s = new std::string[3]{ \"ghi\" };\n"
"}\n");
ASSERT(db && errout_str().empty());
const Token* s1 = Token::findsimplematch(tokenizer.tokens(), "string ;");
ASSERT(s1 && !s1->isIncompleteVar());
const Token* s2 = Token::findsimplematch(s1->next(), "string (");
ASSERT(s2 && !s2->isIncompleteVar());
const Token* s3 = Token::findsimplematch(s2->next(), "string {");
ASSERT(s3 && !s3->isIncompleteVar());
const Token* s4 = Token::findsimplematch(s3->next(), "string [");
ASSERT(s4 && !s4->isIncompleteVar());
}
{
GET_SYMBOL_DB("void f() {\n"
" T** p;\n"
" T*** q;\n"
" T** const * r;\n"
"}\n");
ASSERT(db && errout_str().empty());
const Token* p = Token::findsimplematch(tokenizer.tokens(), "p");
ASSERT(p && !p->isIncompleteVar());
const Token* q = Token::findsimplematch(p, "q");
ASSERT(q && !q->isIncompleteVar());
const Token* r = Token::findsimplematch(q, "r");
ASSERT(r && !r->isIncompleteVar());
}
{
GET_SYMBOL_DB("void f() {\n" // #12571
" auto g = []() -> std::string* {\n"
" return nullptr;\n"
" };\n"
"}\n");
ASSERT(db && errout_str().empty());
const Token* s = Token::findsimplematch(tokenizer.tokens(), "string");
ASSERT(s && !s->isIncompleteVar());
}
{
GET_SYMBOL_DB("void f() {\n" // #12583
" using namespace N;\n"
"}\n");
ASSERT(db && errout_str().empty());
const Token* N = Token::findsimplematch(tokenizer.tokens(), "N");
ASSERT(N && !N->isIncompleteVar());
}
}
void enum1() {
GET_SYMBOL_DB("enum BOOL { FALSE, TRUE }; enum BOOL b;");
/* there is a enum scope with the name BOOL */
ASSERT(db && db->scopeList.back().type == Scope::eEnum && db->scopeList.back().className == "BOOL");
/* b is a enum variable, type is BOOL */
ASSERT(db && db->getVariableFromVarId(1)->isEnumType());
}
void enum2() {
GET_SYMBOL_DB("enum BOOL { FALSE, TRUE } b;");
/* there is a enum scope with the name BOOL */
ASSERT(db && db->scopeList.back().type == Scope::eEnum && db->scopeList.back().className == "BOOL");
/* b is a enum variable, type is BOOL */
ASSERT(db && db->getVariableFromVarId(1)->isEnumType());
}
void enum3() {
GET_SYMBOL_DB("enum ABC { A=11,B,C=A+B };");
ASSERT(db && db->scopeList.back().type == Scope::eEnum);
/* There is an enum A with value 11 */
const Enumerator *A = db->scopeList.back().findEnumerator("A");
ASSERT(A && A->value==11 && A->value_known);
/* There is an enum B with value 12 */
const Enumerator *B = db->scopeList.back().findEnumerator("B");
ASSERT(B && B->value==12 && B->value_known);
/* There is an enum C with value 23 */
const Enumerator *C = db->scopeList.back().findEnumerator("C");
ASSERT(C && C->value==23 && C->value_known);
}
void enum4() { // #7493
GET_SYMBOL_DB("enum Offsets { O1, O2, O3=5, O4 };\n"
"enum MyEnums { E1=O1+1, E2, E3=O3+1 };");
ASSERT(db != nullptr);
ASSERT_EQUALS(3U, db->scopeList.size());
// Assert that all enum values are known
auto scope = db->scopeList.cbegin();
// Offsets
++scope;
ASSERT_EQUALS((unsigned int)Scope::eEnum, (unsigned int)scope->type);
ASSERT_EQUALS(4U, scope->enumeratorList.size());
ASSERT(scope->enumeratorList[0].name->enumerator() == &scope->enumeratorList[0]);
ASSERT_EQUALS((unsigned int)Token::eEnumerator, (unsigned int)scope->enumeratorList[0].name->tokType());
ASSERT(scope->enumeratorList[0].scope == &*scope);
ASSERT_EQUALS("O1", scope->enumeratorList[0].name->str());
ASSERT(scope->enumeratorList[0].start == nullptr);
ASSERT(scope->enumeratorList[0].end == nullptr);
ASSERT_EQUALS(true, scope->enumeratorList[0].value_known);
ASSERT_EQUALS(0, scope->enumeratorList[0].value);
ASSERT(scope->enumeratorList[1].name->enumerator() == &scope->enumeratorList[1]);
ASSERT_EQUALS((unsigned int)Token::eEnumerator, (unsigned int)scope->enumeratorList[1].name->tokType());
ASSERT(scope->enumeratorList[1].scope == &*scope);
ASSERT_EQUALS("O2", scope->enumeratorList[1].name->str());
ASSERT(scope->enumeratorList[1].start == nullptr);
ASSERT(scope->enumeratorList[1].end == nullptr);
ASSERT_EQUALS(true, scope->enumeratorList[1].value_known);
ASSERT_EQUALS(1, scope->enumeratorList[1].value);
ASSERT(scope->enumeratorList[2].name->enumerator() == &scope->enumeratorList[2]);
ASSERT_EQUALS((unsigned int)Token::eEnumerator, (unsigned int)scope->enumeratorList[2].name->tokType());
ASSERT(scope->enumeratorList[2].scope == &*scope);
ASSERT_EQUALS("O3", scope->enumeratorList[2].name->str());
ASSERT(scope->enumeratorList[2].start != nullptr);
ASSERT(scope->enumeratorList[2].end != nullptr);
ASSERT_EQUALS(true, scope->enumeratorList[2].value_known);
ASSERT_EQUALS(5, scope->enumeratorList[2].value);
ASSERT(scope->enumeratorList[3].name->enumerator() == &scope->enumeratorList[3]);
ASSERT_EQUALS((unsigned int)Token::eEnumerator, (unsigned int)scope->enumeratorList[3].name->tokType());
ASSERT(scope->enumeratorList[3].scope == &*scope);
ASSERT_EQUALS("O4", scope->enumeratorList[3].name->str());
ASSERT(scope->enumeratorList[3].start == nullptr);
ASSERT(scope->enumeratorList[3].end == nullptr);
ASSERT_EQUALS(true, scope->enumeratorList[3].value_known);
ASSERT_EQUALS(6, scope->enumeratorList[3].value);
// MyEnums
++scope;
ASSERT_EQUALS((unsigned int)Scope::eEnum, (unsigned int)scope->type);
ASSERT_EQUALS(3U, scope->enumeratorList.size());
ASSERT(scope->enumeratorList[0].name->enumerator() == &scope->enumeratorList[0]);
ASSERT_EQUALS((unsigned int)Token::eEnumerator, (unsigned int)scope->enumeratorList[0].name->tokType());
ASSERT(scope->enumeratorList[0].scope == &*scope);
ASSERT_EQUALS("E1", scope->enumeratorList[0].name->str());
ASSERT(scope->enumeratorList[0].start != nullptr);
ASSERT(scope->enumeratorList[0].end != nullptr);
ASSERT_EQUALS(true, scope->enumeratorList[0].value_known);
ASSERT_EQUALS(1, scope->enumeratorList[0].value);
ASSERT(scope->enumeratorList[1].name->enumerator() == &scope->enumeratorList[1]);
ASSERT_EQUALS((unsigned int)Token::eEnumerator, (unsigned int)scope->enumeratorList[1].name->tokType());
ASSERT(scope->enumeratorList[1].scope == &*scope);
ASSERT_EQUALS("E2", scope->enumeratorList[1].name->str());
ASSERT(scope->enumeratorList[1].start == nullptr);
ASSERT(scope->enumeratorList[1].end == nullptr);
ASSERT_EQUALS(true, scope->enumeratorList[1].value_known);
ASSERT_EQUALS(2, scope->enumeratorList[1].value);
ASSERT(scope->enumeratorList[2].name->enumerator() == &scope->enumeratorList[2]);
ASSERT_EQUALS((unsigned int)Token::eEnumerator, (unsigned int)scope->enumeratorList[2].name->tokType());
ASSERT(scope->enumeratorList[2].scope == &*scope);
ASSERT_EQUALS("E3", scope->enumeratorList[2].name->str());
ASSERT(scope->enumeratorList[2].start != nullptr);
ASSERT(scope->enumeratorList[2].end != nullptr);
ASSERT_EQUALS(true, scope->enumeratorList[2].value_known);
ASSERT_EQUALS(6, scope->enumeratorList[2].value);
}
void enum5() {
GET_SYMBOL_DB("enum { A = 10, B = 2 };\n"
"int a[10 + 2];\n"
"int b[A];\n"
"int c[A + 2];\n"
"int d[10 + B];\n"
"int e[A + B];");
ASSERT(db != nullptr);
ASSERT_EQUALS(2U, db->scopeList.size());
// Assert that all enum values are known
auto scope = db->scopeList.cbegin();
++scope;
ASSERT_EQUALS((unsigned int)Scope::eEnum, (unsigned int)scope->type);
ASSERT_EQUALS(2U, scope->enumeratorList.size());
ASSERT_EQUALS(true, scope->enumeratorList[0].value_known);
ASSERT_EQUALS(10, scope->enumeratorList[0].value);
ASSERT_EQUALS(true, scope->enumeratorList[1].value_known);
ASSERT_EQUALS(2, scope->enumeratorList[1].value);
ASSERT(db->variableList().size() == 6); // the first one is not used
const Variable * v = db->getVariableFromVarId(1);
ASSERT(v != nullptr);
ASSERT(v->isArray());
ASSERT_EQUALS(1U, v->dimensions().size());
ASSERT_EQUALS(12U, v->dimension(0));
v = db->getVariableFromVarId(2);
ASSERT(v != nullptr);
ASSERT(v->isArray());
ASSERT_EQUALS(1U, v->dimensions().size());
ASSERT_EQUALS(10U, v->dimension(0));
v = db->getVariableFromVarId(3);
ASSERT(v != nullptr);
ASSERT(v->isArray());
ASSERT_EQUALS(1U, v->dimensions().size());
ASSERT_EQUALS(12U, v->dimension(0));
v = db->getVariableFromVarId(4);
ASSERT(v != nullptr);
ASSERT(v->isArray());
ASSERT_EQUALS(1U, v->dimensions().size());
ASSERT_EQUALS(12U, v->dimension(0));
v = db->getVariableFromVarId(5);
ASSERT(v != nullptr);
ASSERT(v->isArray());
ASSERT_EQUALS(1U, v->dimensions().size());
ASSERT_EQUALS(12U, v->dimension(0));
}
void enum6() {
GET_SYMBOL_DB("struct Fred {\n"
" enum Enum { E0, E1 };\n"
"};\n"
"struct Barney : public Fred {\n"
" Enum func(Enum e) { return e; }\n"
"};");
ASSERT(db != nullptr);
const Token * const functionToken = Token::findsimplematch(tokenizer.tokens(), "func");
ASSERT(functionToken != nullptr);
const Function *function = functionToken->function();
ASSERT(function != nullptr);
ASSERT(function->token->str() == "func");
ASSERT(function->retDef && function->retDef->str() == "Enum");
ASSERT(function->retType && function->retType->name() == "Enum");
}
#define TEST(S) \
v = db->getVariableFromVarId(id++); \
ASSERT(v != nullptr); \
ASSERT(v->isArray()); \
ASSERT_EQUALS(1U, v->dimensions().size()); \
ASSERT_EQUALS(S, v->dimension(0))
void enum7() {
GET_SYMBOL_DB("enum E { X };\n"
"enum EC : char { C };\n"
"enum ES : short { S };\n"
"enum EI : int { I };\n"
"enum EL : long { L };\n"
"enum ELL : long long { LL };\n"
"char array1[sizeof(E)];\n"
"char array2[sizeof(X)];\n"
"char array3[sizeof(EC)];\n"
"char array4[sizeof(C)];\n"
"char array5[sizeof(ES)];\n"
"char array6[sizeof(S)];\n"
"char array7[sizeof(EI)];\n"
"char array8[sizeof(I)];\n"
"char array9[sizeof(EL)];\n"
"char array10[sizeof(L)];\n"
"char array11[sizeof(ELL)];\n"
"char array12[sizeof(LL)];");
ASSERT(db != nullptr);
ASSERT(db->variableList().size() == 13); // the first one is not used
const Variable * v;
unsigned int id = 1;
TEST(settings1.platform.sizeof_int);
TEST(settings1.platform.sizeof_int);
TEST(1);
TEST(1);
TEST(settings1.platform.sizeof_short);
TEST(settings1.platform.sizeof_short);
TEST(settings1.platform.sizeof_int);
TEST(settings1.platform.sizeof_int);
TEST(settings1.platform.sizeof_long);
TEST(settings1.platform.sizeof_long);
TEST(settings1.platform.sizeof_long_long);
TEST(settings1.platform.sizeof_long_long);
}
void enum8() {
GET_SYMBOL_DB("enum E { X0 = x, X1, X2 = 2, X3, X4 = y, X5 };\n");
ASSERT(db != nullptr);
const Enumerator *X0 = db->scopeList.back().findEnumerator("X0");
ASSERT(X0);
ASSERT(!X0->value_known);
const Enumerator *X1 = db->scopeList.back().findEnumerator("X1");
ASSERT(X1);
ASSERT(!X1->value_known);
const Enumerator *X2 = db->scopeList.back().findEnumerator("X2");
ASSERT(X2);
ASSERT(X2->value_known);
ASSERT_EQUALS(X2->value, 2);
const Enumerator *X3 = db->scopeList.back().findEnumerator("X3");
ASSERT(X3);
ASSERT(X3->value_known);
ASSERT_EQUALS(X3->value, 3);
const Enumerator *X4 = db->scopeList.back().findEnumerator("X4");
ASSERT(X4);
ASSERT(!X4->value_known);
const Enumerator *X5 = db->scopeList.back().findEnumerator("X5");
ASSERT(X5);
ASSERT(!X5->value_known);
}
void enum9() {
GET_SYMBOL_DB("const int x = 7; enum E { X0 = x, X1 };\n");
ASSERT(db != nullptr);
const Enumerator *X0 = db->scopeList.back().findEnumerator("X0");
ASSERT(X0);
ASSERT(X0->value_known);
ASSERT_EQUALS(X0->value, 7);
const Enumerator *X1 = db->scopeList.back().findEnumerator("X1");
ASSERT(X1);
ASSERT(X1->value_known);
ASSERT_EQUALS(X1->value, 8);
}
void enum10() { // #11001
GET_SYMBOL_DB_C("int b = sizeof(enum etag {X, Y});\n");
ASSERT(db != nullptr);
const Enumerator *X = db->scopeList.back().findEnumerator("X");
ASSERT(X);
ASSERT(X->value_known);
ASSERT_EQUALS(X->value, 0);
const Enumerator *Y = db->scopeList.back().findEnumerator("Y");
ASSERT(Y);
ASSERT(Y->value_known);
ASSERT_EQUALS(Y->value, 1);
}
void enum11() {
check("enum class E;\n");
ASSERT_EQUALS("", errout_str());
}
void enum12() {
GET_SYMBOL_DB_C("struct { enum E { E0 }; } t;\n"
"void f() {\n"
" if (t.E0) {}\n"
"}\n");
ASSERT(db != nullptr);
auto it = db->scopeList.begin();
std::advance(it, 2);
const Enumerator* E0 = it->findEnumerator("E0");
ASSERT(E0 && E0->value_known);
ASSERT_EQUALS(E0->value, 0);
const Token* const e = Token::findsimplematch(tokenizer.tokens(), "E0 )");
ASSERT(e && e->enumerator());
ASSERT_EQUALS(e->enumerator(), E0);
}
void enum13() {
GET_SYMBOL_DB("struct S { enum E { E0, E1 }; };\n"
"void f(bool b) {\n"
" auto e = b ? S::E0 : S::E1;\n"
"}\n");
ASSERT(db != nullptr);
auto it = db->scopeList.begin();
std::advance(it, 2);
const Enumerator* E1 = it->findEnumerator("E1");
ASSERT(E1 && E1->value_known);
ASSERT_EQUALS(E1->value, 1);
const Token* const a = Token::findsimplematch(tokenizer.tokens(), "auto");
ASSERT(a && a->valueType());
ASSERT(E1->scope == a->valueType()->typeScope);
}
void enum14() {
GET_SYMBOL_DB("void f() {\n" // #11421
" enum E { A = 0, B = 0xFFFFFFFFFFFFFFFFull, C = 0x7FFFFFFFFFFFFFFF };\n"
" E e = B;\n"
" auto s1 = e >> 32;\n"
" auto s2 = B >> 32;\n"
" enum F { F0 = sizeof(int) };\n"
" F f = F0;\n"
"}\n");
ASSERT(db != nullptr);
auto it = db->scopeList.begin();
std::advance(it, 2);
const Enumerator* B = it->findEnumerator("B");
ASSERT(B);
TODO_ASSERT(B->value_known);
const Enumerator* C = it->findEnumerator("C");
ASSERT(C && C->value_known);
const Token* const s1 = Token::findsimplematch(tokenizer.tokens(), "s1 =");
ASSERT(s1 && s1->valueType());
ASSERT_EQUALS(s1->valueType()->type, ValueType::Type::LONGLONG);
const Token* const s2 = Token::findsimplematch(s1, "s2 =");
ASSERT(s2 && s2->valueType());
ASSERT_EQUALS(s2->valueType()->type, ValueType::Type::LONGLONG);
++it;
const Enumerator* F0 = it->findEnumerator("F0");
ASSERT(F0 && F0->value_known);
const Token* const f = Token::findsimplematch(s2, "f =");
ASSERT(f && f->valueType());
ASSERT_EQUALS(f->valueType()->type, ValueType::Type::INT);
}
void enum15() {
{
GET_SYMBOL_DB("struct S {\n"
" S();\n"
" enum E { E0 };\n"
"};\n"
"S::S() {\n"
" E e = E::E0;\n"
"}\n");
ASSERT(db != nullptr);
auto it = db->scopeList.begin();
std::advance(it, 2);
const Enumerator* E0 = it->findEnumerator("E0");
ASSERT(E0 && E0->value_known && E0->value == 0);
const Token* const e = Token::findsimplematch(tokenizer.tokens(), "E0 ;");
ASSERT(e && e->enumerator());
ASSERT_EQUALS(E0, e->enumerator());
}
{
GET_SYMBOL_DB("struct S {\n"
" S(bool x);\n"
" enum E { E0 };\n"
"};\n"
"S::S(bool x) {\n"
" if (x)\n"
" E e = E::E0;\n"
"}\n");
ASSERT(db != nullptr);
auto it = db->scopeList.begin();
std::advance(it, 2);
const Enumerator* E0 = it->findEnumerator("E0");
ASSERT(E0 && E0->value_known && E0->value == 0);
const Token* const e = Token::findsimplematch(tokenizer.tokens(), "E0 ;");
ASSERT(e && e->enumerator());
ASSERT_EQUALS(E0, e->enumerator());
}
{
GET_SYMBOL_DB("struct S {\n"
" enum E { E0 };\n"
" void f(int i);\n"
" S();\n"
" int m;\n"
"};\n"
"S::S() : m(E0) {}\n"
"void S::f(int i) {\n"
" if (i != E0) {}\n"
"}\n");
ASSERT(db != nullptr);
auto it = db->scopeList.begin();
std::advance(it, 2);
const Enumerator* E0 = it->findEnumerator("E0");
ASSERT(E0 && E0->value_known && E0->value == 0);
const Token* e = Token::findsimplematch(tokenizer.tokens(), "E0 )");
ASSERT(e && e->enumerator());
ASSERT_EQUALS(E0, e->enumerator());
e = Token::findsimplematch(e->next(), "E0 )");
ASSERT(e && e->enumerator());
ASSERT_EQUALS(E0, e->enumerator());
}
{
GET_SYMBOL_DB("struct S {\n"
" enum class E {\n"
" A, D\n"
" } e = E::D;\n"
"};\n"
"struct E {\n"
" enum { A, B, C, D };\n"
"};\n");
ASSERT(db != nullptr);
auto it = db->scopeList.begin();
std::advance(it, 2);
ASSERT_EQUALS(it->className, "E");
ASSERT(it->nestedIn);
ASSERT_EQUALS(it->nestedIn->className, "S");
const Enumerator* D = it->findEnumerator("D");
ASSERT(D && D->value_known && D->value == 1);
const Token* tok = Token::findsimplematch(tokenizer.tokens(), "D ;");
ASSERT(tok && tok->enumerator());
ASSERT_EQUALS(D, tok->enumerator());
}
}
void enum16() {
{
GET_SYMBOL_DB("struct B {\n" // #12538
" struct S {\n"
" enum E { E0 = 0 };\n"
" };\n"
"};\n"
"struct D : B {\n"
" S::E f() const {\n"
" return S::E0;\n"
" }\n"
"};\n");
ASSERT(db != nullptr);
auto it = db->scopeList.begin();
std::advance(it, 3);
const Enumerator* E0 = it->findEnumerator("E0");
ASSERT(E0 && E0->value_known && E0->value == 0);
const Token* const e = Token::findsimplematch(tokenizer.tokens(), "E0 ;");
ASSERT(e && e->enumerator());
ASSERT_EQUALS(E0, e->enumerator());
}
{
GET_SYMBOL_DB("namespace ns {\n" // #12567
" struct S1 {\n"
" enum E { E1 } e;\n"
" };\n"
" struct S2 {\n"
" static void f();\n"
" };\n"
"}\n"
"void ns::S2::f() {\n"
" S1 s;\n"
" s.e = S1::E1;\n"
"}\n");
ASSERT(db != nullptr);
auto it = db->scopeList.begin();
std::advance(it, 3);
const Enumerator* E1 = it->findEnumerator("E1");
ASSERT(E1 && E1->value_known && E1->value == 0);
const Token* const e = Token::findsimplematch(tokenizer.tokens(), "E1 ;");
ASSERT(e && e->enumerator());
ASSERT_EQUALS(E1, e->enumerator());
}
{
GET_SYMBOL_DB("namespace N {\n"
" struct S1 {\n"
" enum E { E1 } e;\n"
" };\n"
" namespace O {\n"
" struct S2 {\n"
" static void f();\n"
" };\n"
" }\n"
"}\n"
"void N::O::S2::f() {\n"
" S1 s;\n"
" s.e = S1::E1;\n"
"}\n");
ASSERT(db != nullptr);
auto it = db->scopeList.begin();
std::advance(it, 3);
const Enumerator* E1 = it->findEnumerator("E1");
ASSERT(E1 && E1->value_known && E1->value == 0);
const Token* const e = Token::findsimplematch(tokenizer.tokens(), "E1 ;");
ASSERT(e && e->enumerator());
ASSERT_EQUALS(E1, e->enumerator());
}
{
GET_SYMBOL_DB("enum class E { inc };\n" // #12585
"struct C {\n"
" void f1();\n"
" bool f2(bool inc);\n"
"};\n"
"void C::f1() { const E e = E::inc; }\n"
"void C::f2(bool inc) { return false; }\n");
ASSERT(db != nullptr);
auto it = db->scopeList.begin();
std::advance(it, 1);
const Enumerator* inc = it->findEnumerator("inc");
ASSERT(inc && inc->value_known && inc->value == 0);
const Token* const i = Token::findsimplematch(tokenizer.tokens(), "inc ;");
ASSERT(i && i->enumerator());
ASSERT_EQUALS(inc, i->enumerator());
}
}
void enum17() {
{
GET_SYMBOL_DB("struct S {\n" // #12564
" enum class E : std::uint8_t;\n"
" enum class E : std::uint8_t { E0 };\n"
" static void f(S::E e) {\n"
" if (e == S::E::E0) {}\n"
" }\n"
"};\n");
ASSERT(db != nullptr);
auto it = db->scopeList.begin();
std::advance(it, 2);
const Enumerator* E0 = it->findEnumerator("E0");
ASSERT(E0 && E0->value_known && E0->value == 0);
const Token* const e = Token::findsimplematch(tokenizer.tokens(), "E0 )");
ASSERT(e && e->enumerator());
ASSERT_EQUALS(E0, e->enumerator());
}
}
void enum18() {
{
GET_SYMBOL_DB("namespace {\n"
" enum { E0 };\n"
"}\n"
"void f() {\n"
" if (0 > E0) {}\n"
"}\n");
ASSERT(db != nullptr);
auto it = db->scopeList.begin();
std::advance(it, 2);
const Enumerator* E0 = it->findEnumerator("E0");
ASSERT(E0 && E0->value_known && E0->value == 0);
const Token* const e = Token::findsimplematch(tokenizer.tokens(), "E0 )");
ASSERT(e && e->enumerator());
ASSERT_EQUALS(E0, e->enumerator());
}
{
GET_SYMBOL_DB("namespace ns {\n" // #12114
" enum { V1 };\n"
" struct C1 {\n"
" enum { V2 };\n"
" };\n"
"}\n"
"using namespace ns;\n"
"void f() {\n"
" if (0 > V1) {}\n"
" if (0 > C1::V2) {}\n"
"}\n");
ASSERT(db != nullptr);
auto it = db->scopeList.begin();
std::advance(it, 2);
const Enumerator* V1 = it->findEnumerator("V1");
ASSERT(V1 && V1->value_known && V1->value == 0);
const Token* const e1 = Token::findsimplematch(tokenizer.tokens(), "V1 )");
ASSERT(e1 && e1->enumerator());
ASSERT_EQUALS(V1, e1->enumerator());
std::advance(it, 2);
const Enumerator* V2 = it->findEnumerator("V2");
ASSERT(V2 && V2->value_known && V2->value == 0);
const Token* const e2 = Token::findsimplematch(tokenizer.tokens(), "V2 )");
ASSERT(e2 && e2->enumerator());
ASSERT_EQUALS(V2, e2->enumerator());
}
{
GET_SYMBOL_DB("namespace ns {\n"
" enum { V1 };\n"
" struct C1 {\n"
" enum { V2 };\n"
" };\n"
"}\n"
"void f() {\n"
" using namespace ns;\n"
" if (0 > V1) {}\n"
" if (0 > C1::V2) {}\n"
"}\n");
ASSERT(db != nullptr);
auto it = db->scopeList.begin();
std::advance(it, 2);
const Enumerator* V1 = it->findEnumerator("V1");
ASSERT(V1 && V1->value_known && V1->value == 0);
const Token* const e1 = Token::findsimplematch(tokenizer.tokens(), "V1 )");
ASSERT(e1 && e1->enumerator());
ASSERT_EQUALS(V1, e1->enumerator());
std::advance(it, 2);
const Enumerator* V2 = it->findEnumerator("V2");
ASSERT(V2 && V2->value_known && V2->value == 0);
const Token* const e2 = Token::findsimplematch(tokenizer.tokens(), "V2 )");
ASSERT(e2 && e2->enumerator());
ASSERT_EQUALS(V2, e2->enumerator());
}
}
void sizeOfType() {
// #7615 - crash in Symboldatabase::sizeOfType()
GET_SYMBOL_DB("enum e;\n"
"void foo() {\n"
" e abc[] = {A,B,C};\n"
" int i = abc[ARRAY_SIZE(cats)];\n"
"}");
const Token *e = Token::findsimplematch(tokenizer.tokens(), "e abc");
(void)db->sizeOfType(e); // <- don't crash
}
void isImplicitlyVirtual() {
{
GET_SYMBOL_DB("class Base {\n"
" virtual void foo() {}\n"
"};\n"
"class Deri : Base {\n"
" void foo() {}\n"
"};");
ASSERT(db && db->findScopeByName("Deri") && db->findScopeByName("Deri")->functionList.front().isImplicitlyVirtual());
}
{
GET_SYMBOL_DB("class Base {\n"
" virtual void foo() {}\n"
"};\n"
"class Deri1 : Base {\n"
" void foo() {}\n"
"};\n"
"class Deri2 : Deri1 {\n"
" void foo() {}\n"
"};");
ASSERT(db && db->findScopeByName("Deri2") && db->findScopeByName("Deri2")->functionList.front().isImplicitlyVirtual());
}
{
GET_SYMBOL_DB("class Base {\n"
" void foo() {}\n"
"};\n"
"class Deri : Base {\n"
" void foo() {}\n"
"};");
ASSERT(db && db->findScopeByName("Deri") && !db->findScopeByName("Deri")->functionList.front().isImplicitlyVirtual(true));
}
{
GET_SYMBOL_DB("class Base {\n"
" virtual void foo() {}\n"
"};\n"
"class Deri : Base {\n"
" void foo(std::string& s) {}\n"
"};");
ASSERT(db && db->findScopeByName("Deri") && !db->findScopeByName("Deri")->functionList.front().isImplicitlyVirtual(true));
}
{
GET_SYMBOL_DB("class Base {\n"
" virtual void foo() {}\n"
"};\n"
"class Deri1 : Base {\n"
" void foo(int i) {}\n"
"};\n"
"class Deri2 : Deri1 {\n"
" void foo() {}\n"
"};");
ASSERT(db && db->findScopeByName("Deri2") && db->findScopeByName("Deri2")->functionList.front().isImplicitlyVirtual());
}
{
GET_SYMBOL_DB("class Base : Base2 {\n" // We don't know Base2
" void foo() {}\n"
"};\n"
"class Deri : Base {\n"
" void foo() {}\n"
"};");
ASSERT(db && db->findScopeByName("Deri") && db->findScopeByName("Deri")->functionList.front().isImplicitlyVirtual(true)); // Default true -> true
}
{
GET_SYMBOL_DB("class Base : Base2 {\n" // We don't know Base2
" void foo() {}\n"
"};\n"
"class Deri : Base {\n"
" void foo() {}\n"
"};");
ASSERT(db && db->findScopeByName("Deri") && !db->findScopeByName("Deri")->functionList.front().isImplicitlyVirtual(false)); // Default false -> false
}
{
GET_SYMBOL_DB("class Base : Base2 {\n" // We don't know Base2
" virtual void foo() {}\n"
"};\n"
"class Deri : Base {\n"
" void foo() {}\n"
"};");
ASSERT(db && db->findScopeByName("Deri") && db->findScopeByName("Deri")->functionList.front().isImplicitlyVirtual(false)); // Default false, but we saw "virtual" -> true
}
// #5289
{
GET_SYMBOL_DB("template<>\n"
"class Bar<void, void> {\n"
"};\n"
"template<typename K, typename V, int KeySize>\n"
"class Bar : private Bar<void, void> {\n"
" void foo() {\n"
" }\n"
"};");
ASSERT(db && db->findScopeByName("Bar") && !db->findScopeByName("Bar")->functionList.empty() && !db->findScopeByName("Bar")->functionList.front().isImplicitlyVirtual(false));
ASSERT_EQUALS(1, db->findScopeByName("Bar")->functionList.size());
}
// #5590
{
GET_SYMBOL_DB("class InfiniteB : InfiniteA {\n"
" class D {\n"
" };\n"
"};\n"
"namespace N {\n"
" class InfiniteA : InfiniteB {\n"
" };\n"
"}\n"
"class InfiniteA : InfiniteB {\n"
" void foo();\n"
"};\n"
"void InfiniteA::foo() {\n"
" C a;\n"
"}");
//ASSERT(db && db->findScopeByName("InfiniteA") && !db->findScopeByName("InfiniteA")->functionList.front().isImplicitlyVirtual());
TODO_ASSERT_EQUALS(1, 0, db->findScopeByName("InfiniteA")->functionList.size());
}
}
void isPure() {
GET_SYMBOL_DB("class C {\n"
" void f() = 0;\n"
" C(B b) = 0;\n"
" C(C& c) = default;"
" void g();\n"
"};");
ASSERT(db && db->scopeList.back().functionList.size() == 4);
auto it = db->scopeList.back().functionList.cbegin();
ASSERT((it++)->isPure());
ASSERT((it++)->isPure());
ASSERT(!(it++)->isPure());
ASSERT(!(it++)->isPure());
}
void isFunction1() { // #5602 - UNKNOWN_MACRO(a,b) { .. }
GET_SYMBOL_DB("TEST(a,b) {\n"
" std::vector<int> messages;\n"
" foo(messages[2].size());\n"
"}");
const Variable * const var = db ? db->getVariableFromVarId(1U) : nullptr;
ASSERT(db &&
db->findScopeByName("TEST") &&
var &&
var->typeStartToken() &&
var->typeStartToken()->str() == "std");
}
void isFunction2() {
GET_SYMBOL_DB("void set_cur_cpu_spec()\n"
"{\n"
" t = PTRRELOC(t);\n"
"}\n"
"\n"
"cpu_spec * __init setup_cpu_spec()\n"
"{\n"
" t = PTRRELOC(t);\n"
" *PTRRELOC(&x) = &y;\n"
"}");
ASSERT(db != nullptr);
const Token *funcStart, *argStart, *declEnd;
ASSERT(db && !db->isFunction(Token::findsimplematch(tokenizer.tokens(), "PTRRELOC ( &"), &db->scopeList.back(), funcStart, argStart, declEnd));
ASSERT(db->findScopeByName("set_cur_cpu_spec") != nullptr);
ASSERT(db->findScopeByName("setup_cpu_spec") != nullptr);
ASSERT(db->findScopeByName("PTRRELOC") == nullptr);
}
void isFunction3() {
GET_SYMBOL_DB("std::vector<int>&& f(std::vector<int>& v) {\n"
" v.push_back(1);\n"
" return std::move(v);\n"
"}");
ASSERT(db != nullptr);
ASSERT_EQUALS(2, db->scopeList.size());
const Token* ret = Token::findsimplematch(tokenizer.tokens(), "return");
ASSERT(ret != nullptr);
ASSERT(ret->scope() && ret->scope()->type == Scope::eFunction);
}
void findFunction1() {
GET_SYMBOL_DB("int foo(int x);\n" /* 1 */
"void foo();\n" /* 2 */
"void bar() {\n" /* 3 */
" foo();\n" /* 4 */
" foo(1);\n" /* 5 */
"}"); /* 6 */
ASSERT_EQUALS("", errout_str());
ASSERT(db);
const Scope * bar = db->findScopeByName("bar");
ASSERT(bar != nullptr);
constexpr unsigned int linenrs[2] = { 2, 1 };
unsigned int index = 0;
for (const Token * tok = bar->bodyStart->next(); tok != bar->bodyEnd; tok = tok->next()) {
if (Token::Match(tok, "%name% (") && !tok->varId() && Token::simpleMatch(tok->linkAt(1), ") ;")) {
const Function * function = db->findFunction(tok);
ASSERT(function != nullptr);
if (function) {
std::stringstream expected;
expected << "Function call on line " << tok->linenr() << " calls function on line " << linenrs[index] << std::endl;
std::stringstream actual;
actual << "Function call on line " << tok->linenr() << " calls function on line " << function->tokenDef->linenr() << std::endl;
ASSERT_EQUALS(expected.str(), actual.str());
}
index++;
}
}
}
void findFunction2() {
// The function does not match the function call.
GET_SYMBOL_DB("void func(const int x, const Fred &fred);\n"
"void otherfunc() {\n"
" float t;\n"
" func(x, &t);\n"
"}");
const Token *callfunc = Token::findsimplematch(tokenizer.tokens(), "func ( x , & t ) ;");
ASSERT_EQUALS("", errout_str());
ASSERT_EQUALS(true, db != nullptr); // not null
ASSERT_EQUALS(true, callfunc != nullptr); // not null
ASSERT_EQUALS(false, (callfunc && callfunc->function())); // callfunc->function() should be null
}
void findFunction3() {
GET_SYMBOL_DB("struct base { void foo() { } };\n"
"struct derived : public base { void foo() { } };\n"
"void foo() {\n"
" derived d;\n"
" d.foo();\n"
"}");
const Token *callfunc = Token::findsimplematch(tokenizer.tokens(), "d . foo ( ) ;");
ASSERT_EQUALS("", errout_str());
ASSERT_EQUALS(true, db != nullptr); // not null
ASSERT_EQUALS(true, callfunc != nullptr); // not null
ASSERT_EQUALS(true, callfunc && callfunc->tokAt(2)->function() && callfunc->tokAt(2)->function()->tokenDef->linenr() == 2); // should find function on line 2
}
void findFunction4() {
GET_SYMBOL_DB("void foo(UNKNOWN) { }\n"
"void foo(int a) { }\n"
"void foo(unsigned int a) { }\n"
"void foo(unsigned long a) { }\n"
"void foo(unsigned long long a) { }\n"
"void foo(float a) { }\n"
"void foo(double a) { }\n"
"void foo(long double a) { }\n"
"int i;\n"
"unsigned int ui;\n"
"unsigned long ul;\n"
"unsigned long long ull;\n"
"float f;\n"
"double d;\n"
"long double ld;\n"
"int & ri = i;\n"
"unsigned int & rui = ui;\n"
"unsigned long & rul = ul;\n"
"unsigned long long & rull = ull;\n"
"float & rf = f;\n"
"double & rd = d;\n"
"long double & rld = ld;\n"
"const int & cri = i;\n"
"const unsigned int & crui = ui;\n"
"const unsigned long & crul = ul;\n"
"const unsigned long long & crull = ull;\n"
"const float & crf = f;\n"
"const double & crd = d;\n"
"const long double & crld = ld;\n"
"void foo() {\n"
" foo(1);\n"
" foo(1U);\n"
" foo(1UL);\n"
" foo(1ULL);\n"
" foo(1.0F);\n"
" foo(1.0);\n"
" foo(1.0L);\n"
" foo(i);\n"
" foo(ui);\n"
" foo(ul);\n"
" foo(ull);\n"
" foo(f);\n"
" foo(d);\n"
" foo(ld);\n"
" foo(ri);\n"
" foo(rui);\n"
" foo(rul);\n"
" foo(rull);\n"
" foo(rf);\n"
" foo(rd);\n"
" foo(rld);\n"
" foo(cri);\n"
" foo(crui);\n"
" foo(crul);\n"
" foo(crull);\n"
" foo(crf);\n"
" foo(crd);\n"
" foo(crld);\n"
"}");
ASSERT_EQUALS("", errout_str());
const Token *f = Token::findsimplematch(tokenizer.tokens(), "foo ( 1 ) ;");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 2);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( 1U ) ;");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 3);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( 1UL ) ;");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 4);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( 1ULL ) ;");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 5);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( 1.0F ) ;");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 6);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( 1.0 ) ;");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 7);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( 1.0L ) ;");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 8);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( i ) ;");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 2);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( ui ) ;");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 3);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( ul ) ;");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 4);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( ull ) ;");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 5);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( f ) ;");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 6);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( d ) ;");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 7);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( ld ) ;");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 8);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( ri ) ;");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 2);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( rui ) ;");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 3);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( rul ) ;");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 4);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( rull ) ;");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 5);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( rf ) ;");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 6);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( rd ) ;");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 7);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( rld ) ;");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 8);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( cri ) ;");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 2);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( crui ) ;");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 3);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( crul ) ;");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 4);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( crull ) ;");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 5);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( crf ) ;");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 6);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( crd ) ;");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 7);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( crld ) ;");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 8);
}
void findFunction5() {
GET_SYMBOL_DB("struct Fred {\n"
" void Sync(dsmp_t& type, int& len, int limit = 123);\n"
" void Sync(int& syncpos, dsmp_t& type, int& len, int limit = 123);\n"
" void FindSyncPoint();\n"
"};\n"
"void Fred::FindSyncPoint() {\n"
" dsmp_t type;\n"
" int syncpos, len;\n"
" Sync(syncpos, type, len);\n"
" Sync(type, len);\n"
"}");
const Token *f = Token::findsimplematch(tokenizer.tokens(), "Sync ( syncpos");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 3);
f = Token::findsimplematch(tokenizer.tokens(), "Sync ( type");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 2);
}
void findFunction6() { // avoid null pointer access
GET_SYMBOL_DB("void addtoken(Token** rettail, const Token *tok);\n"
"void CheckMemoryLeakInFunction::getcode(const Token *tok ) {\n"
" addtoken(&rettail, tok);\n"
"}");
const Token *f = Token::findsimplematch(tokenizer.tokens(), "void addtoken ( Token * *");
ASSERT_EQUALS(true, db && f && !f->function()); // regression value only
}
void findFunction7() {
GET_SYMBOL_DB("class ResultEnsemble {\n"
"public:\n"
" std::vector<int> &nodeResults() const;\n"
" std::vector<int> &nodeResults();\n"
"};\n"
"class Simulator {\n"
" int generatePinchResultEnsemble(const ResultEnsemble &power, const ResultEnsemble &ground) {\n"
" power.nodeResults().size();\n"
" assert(power.nodeResults().size()==ground.nodeResults().size());\n"
" }\n"
"};");
const Token *callfunc = Token::findsimplematch(tokenizer.tokens(), "power . nodeResults ( ) . size ( ) ;");
ASSERT_EQUALS("", errout_str());
ASSERT_EQUALS(true, db != nullptr); // not null
ASSERT_EQUALS(true, callfunc != nullptr); // not null
ASSERT_EQUALS(true, callfunc && callfunc->tokAt(2)->function() && callfunc->tokAt(2)->function()->tokenDef->linenr() == 3);
}
void findFunction8() {
GET_SYMBOL_DB("struct S {\n"
" void f() { }\n"
" void f() & { }\n"
" void f() &&{ }\n"
" void f() const { }\n"
" void f() const & { }\n"
" void f() const &&{ }\n"
" void g() ;\n"
" void g() & ;\n"
" void g() &&;\n"
" void g() const ;\n"
" void g() const & ;\n"
" void g() const &&;\n"
"};\n"
"void S::g() { }\n"
"void S::g() & { }\n"
"void S::g() &&{ }\n"
"void S::g() const { }\n"
"void S::g() const & { }\n"
"void S::g() const &&{ }");
ASSERT_EQUALS("", errout_str());
const Token *f = Token::findsimplematch(tokenizer.tokens(), "f ( ) {");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 2);
f = Token::findsimplematch(tokenizer.tokens(), "f ( ) & {");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 3);
f = Token::findsimplematch(tokenizer.tokens(), "f ( ) && {");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 4);
f = Token::findsimplematch(tokenizer.tokens(), "f ( ) const {");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 5);
f = Token::findsimplematch(tokenizer.tokens(), "f ( ) const & {");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 6);
f = Token::findsimplematch(tokenizer.tokens(), "f ( ) const && {");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 7);
f = Token::findsimplematch(tokenizer.tokens(), "g ( ) {");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 8 && f->function()->token->linenr() == 15);
f = Token::findsimplematch(tokenizer.tokens(), "g ( ) & {");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 9 && f->function()->token->linenr() == 16);
f = Token::findsimplematch(tokenizer.tokens(), "g ( ) && {");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 10 && f->function()->token->linenr() == 17);
f = Token::findsimplematch(tokenizer.tokens(), "g ( ) const {");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 11 && f->function()->token->linenr() == 18);
f = Token::findsimplematch(tokenizer.tokens(), "g ( ) const & {");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 12 && f->function()->token->linenr() == 19);
f = Token::findsimplematch(tokenizer.tokens(), "g ( ) const && {");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 13 && f->function()->token->linenr() == 20);
f = Token::findsimplematch(tokenizer.tokens(), "S :: g ( ) {");
ASSERT_EQUALS(true, db && f && f->tokAt(2)->function() && f->tokAt(2)->function()->tokenDef->linenr() == 8 && f->tokAt(2)->function()->token->linenr() == 15);
f = Token::findsimplematch(tokenizer.tokens(), "S :: g ( ) & {");
ASSERT_EQUALS(true, db && f && f->tokAt(2)->function() && f->tokAt(2)->function()->tokenDef->linenr() == 9 && f->tokAt(2)->function()->token->linenr() == 16);
f = Token::findsimplematch(tokenizer.tokens(), "S :: g ( ) && {");
ASSERT_EQUALS(true, db && f && f->tokAt(2)->function() && f->tokAt(2)->function()->tokenDef->linenr() == 10 && f->tokAt(2)->function()->token->linenr() == 17);
f = Token::findsimplematch(tokenizer.tokens(), "S :: g ( ) const {");
ASSERT_EQUALS(true, db && f && f->tokAt(2)->function() && f->tokAt(2)->function()->tokenDef->linenr() == 11 && f->tokAt(2)->function()->token->linenr() == 18);
f = Token::findsimplematch(tokenizer.tokens(), "S :: g ( ) const & {");
ASSERT_EQUALS(true, db && f && f->tokAt(2)->function() && f->tokAt(2)->function()->tokenDef->linenr() == 12 && f->tokAt(2)->function()->token->linenr() == 19);
f = Token::findsimplematch(tokenizer.tokens(), "S :: g ( ) const && {");
ASSERT_EQUALS(true, db && f && f->tokAt(2)->function() && f->tokAt(2)->function()->tokenDef->linenr() == 13 && f->tokAt(2)->function()->token->linenr() == 20);
}
void findFunction9() {
GET_SYMBOL_DB("struct Fred {\n"
" void foo(const int * p);\n"
"};\n"
"void Fred::foo(const int * const p) { }");
ASSERT_EQUALS("", errout_str());
const Token *f = Token::findsimplematch(tokenizer.tokens(), "foo ( const int * const p ) {");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 2);
}
void findFunction10() { // #7673
GET_SYMBOL_DB("struct Fred {\n"
" void foo(const int * p);\n"
"};\n"
"void Fred::foo(const int p []) { }");
ASSERT_EQUALS("", errout_str());
const Token *f = Token::findsimplematch(tokenizer.tokens(), "foo ( const int p [ ] ) {");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 2);
}
void findFunction12() {
GET_SYMBOL_DB("void foo(std::string a) { }\n"
"void foo(long long a) { }\n"
"void func(char* cp) {\n"
" foo(0);\n"
" foo(0L);\n"
" foo(0.f);\n"
" foo(bar());\n"
" foo(cp);\n"
" foo(\"\");\n"
"}");
ASSERT_EQUALS("", errout_str());
const Token *f = Token::findsimplematch(tokenizer.tokens(), "foo ( 0 ) ;");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 2);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( 0L ) ;");
ASSERT_EQUALS(true, f && f->function() && f->function()->tokenDef->linenr() == 2);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( 0.f ) ;");
ASSERT_EQUALS(true, f && f->function() && f->function()->tokenDef->linenr() == 2);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( bar ( ) ) ;");
ASSERT_EQUALS(true, f && f->function() == nullptr);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( cp ) ;");
ASSERT_EQUALS(true, f && f->function() && f->function()->tokenDef->linenr() == 1);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( \"\" ) ;");
ASSERT_EQUALS(true, f && f->function() && f->function()->tokenDef->linenr() == 1);
}
void findFunction13() {
GET_SYMBOL_DB("void foo(std::string a) { }\n"
"void foo(double a) { }\n"
"void foo(long long a) { }\n"
"void foo(int* a) { }\n"
"void foo(void* a) { }\n"
"void func(int i, const float f, int* ip, float* fp, char* cp) {\n"
" foo(0.f);\n"
" foo(bar());\n"
" foo(f);\n"
" foo(&i);\n"
" foo(ip);\n"
" foo(fp);\n"
" foo(cp);\n"
" foo(\"\");\n"
"}");
ASSERT_EQUALS("", errout_str());
const Token* f = Token::findsimplematch(tokenizer.tokens(), "foo ( 0.f ) ;");
ASSERT_EQUALS(true, f && f->function());
TODO_ASSERT_EQUALS(2, 3, f->function()->tokenDef->linenr());
f = Token::findsimplematch(tokenizer.tokens(), "foo ( bar ( ) ) ;");
ASSERT_EQUALS(true, f && f->function() == nullptr);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( f ) ;");
ASSERT_EQUALS(true, f && f->function() && f->function()->tokenDef->linenr() == 2);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( & i ) ;");
ASSERT_EQUALS(true, f && f->function() && f->function()->tokenDef->linenr() == 4);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( ip ) ;");
ASSERT_EQUALS(true, f && f->function() && f->function()->tokenDef->linenr() == 4);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( fp ) ;");
ASSERT_EQUALS(true, f && f->function() && f->function()->tokenDef->linenr() == 5);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( cp ) ;");
ASSERT_EQUALS(true, f && f->function() && f->function()->tokenDef->linenr() == 5);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( \"\" ) ;");
ASSERT_EQUALS(true, f && f->function() && f->function()->tokenDef->linenr() == 1);
}
void findFunction14() {
GET_SYMBOL_DB("void foo(int* a) { }\n"
"void foo(const int* a) { }\n"
"void foo(void* a) { }\n"
"void foo(const float a) { }\n"
"void foo(bool a) { }\n"
"void foo2(Foo* a) { }\n"
"void foo2(Foo a) { }\n"
"void func(int* ip, const int* cip, const char* ccp, char* cp, float f, bool b) {\n"
" foo(ip);\n"
" foo(cip);\n"
" foo(cp);\n"
" foo(ccp);\n"
" foo(f);\n"
" foo(b);\n"
" foo2(0);\n"
" foo2(nullptr);\n"
" foo2(NULL);\n"
"}");
ASSERT_EQUALS("", errout_str());
const Token *f = Token::findsimplematch(tokenizer.tokens(), "foo ( ip ) ;");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 1);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( cip ) ;");
ASSERT_EQUALS(true, f && f->function() && f->function()->tokenDef->linenr() == 2);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( cp ) ;");
TODO_ASSERT(f && f->function() && f->function()->tokenDef->linenr() == 3);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( ccp ) ;");
ASSERT_EQUALS(true, f && f->function() && f->function()->tokenDef->linenr() == 5);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( f ) ;");
ASSERT_EQUALS(true, f && f->function() && f->function()->tokenDef->linenr() == 4);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( b ) ;");
ASSERT_EQUALS(true, f && f->function() && f->function()->tokenDef->linenr() == 5);
f = Token::findsimplematch(tokenizer.tokens(), "foo2 ( 0 ) ;");
ASSERT_EQUALS(true, f && f->function() && f->function()->tokenDef->linenr() == 6);
f = Token::findsimplematch(tokenizer.tokens(), "foo2 ( nullptr ) ;");
ASSERT_EQUALS(true, f && f->function() && f->function()->tokenDef->linenr() == 6);
f = Token::findsimplematch(tokenizer.tokens(), "foo2 ( NULL ) ;");
ASSERT_EQUALS(true, f && f->function() && f->function()->tokenDef->linenr() == 6);
}
void findFunction15() {
GET_SYMBOL_DB("void foo1(int, char* a) { }\n"
"void foo1(int, char a) { }\n"
"void foo1(int, wchar_t a) { }\n"
"void foo1(int, char16_t a) { }\n"
"void foo2(int, float a) { }\n"
"void foo2(int, wchar_t a) { }\n"
"void foo3(int, float a) { }\n"
"void foo3(int, char a) { }\n"
"void func() {\n"
" foo1(1, 'c');\n"
" foo1(2, L'c');\n"
" foo1(3, u'c');\n"
" foo2(4, 'c');\n"
" foo2(5, L'c');\n"
" foo3(6, 'c');\n"
" foo3(7, L'c');\n"
"}");
ASSERT_EQUALS("", errout_str());
const Token *f = Token::findsimplematch(tokenizer.tokens(), "foo1 ( 1");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 2);
f = Token::findsimplematch(tokenizer.tokens(), "foo1 ( 2");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 3);
f = Token::findsimplematch(tokenizer.tokens(), "foo1 ( 3");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 4);
f = Token::findsimplematch(tokenizer.tokens(), "foo2 ( 4");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 6);
f = Token::findsimplematch(tokenizer.tokens(), "foo2 ( 5");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 6);
f = Token::findsimplematch(tokenizer.tokens(), "foo3 ( 6");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 8);
// Error: ambiguous function call
//f = Token::findsimplematch(tokenizer.tokens(), "foo3 ( 7");
//ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 8);
}
void findFunction16() {
GET_SYMBOL_DB("struct C { int i; static int si; float f; int* ip; float* fp};\n"
"void foo(float a) { }\n"
"void foo(int a) { }\n"
"void foo(int* a) { }\n"
"void func(C c, C* cp) {\n"
" foo(c.i);\n"
" foo(cp->i);\n"
" foo(c.f);\n"
" foo(c.si);\n"
" foo(C::si);\n"
" foo(c.ip);\n"
" foo(c.fp);\n"
"}");
ASSERT_EQUALS("", errout_str());
const Token *f = Token::findsimplematch(tokenizer.tokens(), "foo ( c . i ) ;");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 3);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( cp . i ) ;");
ASSERT_EQUALS(true, f && f->function() && f->function()->tokenDef->linenr() == 3);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( c . f ) ;");
ASSERT_EQUALS(true, f && f->function() && f->function()->tokenDef->linenr() == 2);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( c . si ) ;");
ASSERT_EQUALS(true, f && f->function() && f->function()->tokenDef->linenr() == 3);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( C :: si ) ;");
ASSERT_EQUALS(true, f && f->function() && f->function()->tokenDef->linenr() == 3);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( c . ip ) ;");
ASSERT_EQUALS(true, f && f->function() && f->function()->tokenDef->linenr() == 4);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( c . fp ) ;");
ASSERT_EQUALS(true, f && f->function() == nullptr);
}
void findFunction17() {
GET_SYMBOL_DB("void foo(int a) { }\n"
"void foo(float a) { }\n"
"void foo(void* a) { }\n"
"void foo(bool a) { }\n"
"void func(int i, float f, bool b) {\n"
" foo(i + i);\n"
" foo(f + f);\n"
" foo(!b);\n"
" foo(i > 0);\n"
" foo(f + i);\n"
"}");
ASSERT_EQUALS("", errout_str());
const Token *f = Token::findsimplematch(tokenizer.tokens(), "foo ( i + i ) ;");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 1);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( f + f ) ;");
ASSERT_EQUALS(true, f && f->function() && f->function()->tokenDef->linenr() == 2);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( ! b ) ;");
ASSERT_EQUALS(true, f && f->function() && f->function()->tokenDef->linenr() == 4);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( i > 0 ) ;");
ASSERT_EQUALS(true, f && f->function() && f->function()->tokenDef->linenr() == 4);
f = Token::findsimplematch(tokenizer.tokens(), "foo ( f + i ) ;");
ASSERT_EQUALS(true, f && f->function() && f->function()->tokenDef->linenr() == 2);
}
void findFunction18() {
GET_SYMBOL_DB("class Fred {\n"
" void f(int i) { }\n"
" void f(float f) const { }\n"
" void a() { f(1); }\n"
" void b() { f(1.f); }\n"
"};");
ASSERT_EQUALS("", errout_str());
const Token *f = Token::findsimplematch(tokenizer.tokens(), "f ( 1 ) ;");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 2);
f = Token::findsimplematch(tokenizer.tokens(), "f ( 1.f ) ;");
ASSERT_EQUALS(true, f && f->function() && f->function()->tokenDef->linenr() == 3);
}
void findFunction19() {
GET_SYMBOL_DB("class Fred {\n"
" enum E1 { e1 };\n"
" enum class E2 : unsigned short { e2 };\n"
" bool get(bool x) { return x; }\n"
" char get(char x) { return x; }\n"
" short get(short x) { return x; }\n"
" int get(int x) { return x; }\n"
" long get(long x) { return x; }\n"
" long long get(long long x) { return x; }\n"
" unsigned char get(unsigned char x) { return x; }\n"
" signed char get(signed char x) { return x; }\n"
" unsigned short get(unsigned short x) { return x; }\n"
" unsigned int get(unsigned int x) { return x; }\n"
" unsigned long get(unsigned long x) { return x; }\n"
" unsigned long long get(unsigned long long x) { return x; }\n"
" E1 get(E1 x) { return x; }\n"
" E2 get(E2 x) { return x; }\n"
" void foo() {\n"
" bool v1 = true; v1 = get(get(v1));\n"
" char v2 = '1'; v2 = get(get(v2));\n"
" short v3 = 1; v3 = get(get(v3));\n"
" int v4 = 1; v4 = get(get(v4));\n"
" long v5 = 1; v5 = get(get(v5));\n"
" long long v6 = 1; v6 = get(get(v6));\n"
" unsigned char v7 = '1'; v7 = get(get(v7));\n"
" signed char v8 = '1'; v8 = get(get(v8));\n"
" unsigned short v9 = 1; v9 = get(get(v9));\n"
" unsigned int v10 = 1; v10 = get(get(v10));\n"
" unsigned long v11 = 1; v11 = get(get(v11));\n"
" unsigned long long v12 = 1; v12 = get(get(v12));\n"
" E1 v13 = e1; v13 = get(get(v13));\n"
" E2 v14 = E2::e2; v14 = get(get(v14));\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
ASSERT(db);
const Token *f = Token::findsimplematch(tokenizer.tokens(), "get ( get ( v1 ) ) ;");
ASSERT(f);
ASSERT(f->function());
ASSERT_EQUALS(4, f->function()->tokenDef->linenr());
f = Token::findsimplematch(tokenizer.tokens(), "get ( get ( v2 ) ) ;");
ASSERT(f);
ASSERT(f->function());
ASSERT_EQUALS(5, f->function()->tokenDef->linenr());
f = Token::findsimplematch(tokenizer.tokens(), "get ( get ( v3 ) ) ;");
ASSERT(f);
ASSERT(f->function());
ASSERT_EQUALS(6, f->function()->tokenDef->linenr());
f = Token::findsimplematch(tokenizer.tokens(), "get ( get ( v4 ) ) ;");
ASSERT(f);
ASSERT(f->function());
ASSERT_EQUALS(7, f->function()->tokenDef->linenr());
f = Token::findsimplematch(tokenizer.tokens(), "get ( get ( v5 ) ) ;");
ASSERT(f);
ASSERT(f->function());
ASSERT_EQUALS(8, f->function()->tokenDef->linenr());
f = Token::findsimplematch(tokenizer.tokens(), "get ( get ( v6 ) ) ;");
ASSERT(f);
ASSERT(f->function());
ASSERT_EQUALS(9, f->function()->tokenDef->linenr());
f = Token::findsimplematch(tokenizer.tokens(), "get ( get ( v7 ) ) ;");
ASSERT(f);
ASSERT(f->function());
if (std::numeric_limits<char>::is_signed) {
ASSERT_EQUALS(10, f->function()->tokenDef->linenr());
} else {
ASSERT_EQUALS(5, f->function()->tokenDef->linenr());
}
f = Token::findsimplematch(tokenizer.tokens(), "get ( get ( v8 ) ) ;");
ASSERT(f);
ASSERT(f->function());
if (std::numeric_limits<char>::is_signed) {
ASSERT_EQUALS(5, f->function()->tokenDef->linenr());
} else {
ASSERT_EQUALS(11, f->function()->tokenDef->linenr());
}
f = Token::findsimplematch(tokenizer.tokens(), "get ( get ( v9 ) ) ;");
ASSERT(f);
ASSERT(f->function());
ASSERT_EQUALS(12, f->function()->tokenDef->linenr());
f = Token::findsimplematch(tokenizer.tokens(), "get ( get ( v10 ) ) ;");
ASSERT(f);
ASSERT(f->function());
ASSERT_EQUALS(13, f->function()->tokenDef->linenr());
f = Token::findsimplematch(tokenizer.tokens(), "get ( get ( v11 ) ) ;");
ASSERT(f);
ASSERT(f->function());
ASSERT_EQUALS(14, f->function()->tokenDef->linenr());
f = Token::findsimplematch(tokenizer.tokens(), "get ( get ( v12 ) ) ;");
ASSERT(f);
ASSERT(f->function());
ASSERT_EQUALS(15, f->function()->tokenDef->linenr());
f = Token::findsimplematch(tokenizer.tokens(), "get ( get ( v13 ) ) ;");
ASSERT(f);
ASSERT(f->function());
ASSERT_EQUALS(16, f->function()->tokenDef->linenr());
f = Token::findsimplematch(tokenizer.tokens(), "get ( get ( v14 ) ) ;");
ASSERT(f);
ASSERT(f->function());
ASSERT_EQUALS(17, f->function()->tokenDef->linenr());
}
void findFunction20() { // # 8280
GET_SYMBOL_DB("class Foo {\n"
"public:\n"
" Foo() : _x(0), _y(0) {}\n"
" Foo(const Foo& f) {\n"
" copy(&f);\n"
" }\n"
" void copy(const Foo* f) {\n"
" _x=f->_x;\n"
" copy(*f);\n"
" }\n"
"private:\n"
" void copy(const Foo& f) {\n"
" _y=f._y;\n"
" }\n"
" int _x;\n"
" int _y;\n"
"};");
ASSERT_EQUALS("", errout_str());
const Token *f = Token::findsimplematch(tokenizer.tokens(), "copy ( & f ) ;");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 7);
f = Token::findsimplematch(tokenizer.tokens(), "copy ( * f ) ;");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 12);
}
void findFunction21() { // # 8558
GET_SYMBOL_DB("struct foo {\n"
" int GetThing( ) const { return m_thing; }\n"
" int* GetThing( ) { return &m_thing; }\n"
"};\n"
"\n"
"void f(foo *myFoo) {\n"
" int* myThing = myFoo->GetThing();\n"
"}");
ASSERT(db != nullptr);
const Token *tok1 = Token::findsimplematch(tokenizer.tokens(), "myFoo . GetThing ( ) ;");
const Function *f = tok1 && tok1->tokAt(2) ? tok1->tokAt(2)->function() : nullptr;
ASSERT(f != nullptr);
ASSERT_EQUALS(true, f && !f->isConst());
}
void findFunction22() { // # 8558
GET_SYMBOL_DB("struct foo {\n"
" int GetThing( ) const { return m_thing; }\n"
" int* GetThing( ) { return &m_thing; }\n"
"};\n"
"\n"
"void f(const foo *myFoo) {\n"
" int* myThing = myFoo->GetThing();\n"
"}");
ASSERT(db != nullptr);
const Token *tok1 = Token::findsimplematch(tokenizer.tokens(), ". GetThing ( ) ;")->next();
const Function *f = tok1 ? tok1->function() : nullptr;
ASSERT(f != nullptr);
ASSERT_EQUALS(true, f && f->isConst());
}
void findFunction23() { // # 8558
GET_SYMBOL_DB("struct foo {\n"
" int GetThing( ) const { return m_thing; }\n"
" int* GetThing( ) { return &m_thing; }\n"
"};\n"
"\n"
"void f(foo *myFoo) {\n"
" int* myThing = ((const foo *)myFoo)->GetThing();\n"
"}");
ASSERT(db != nullptr);
const Token *tok1 = Token::findsimplematch(tokenizer.tokens(), ". GetThing ( ) ;")->next();
const Function *f = tok1 ? tok1->function() : nullptr;
ASSERT(f != nullptr);
ASSERT_EQUALS(true, f && f->isConst());
}
void findFunction24() { // smart pointers
GET_SYMBOL_DB("struct foo {\n"
" void dostuff();\n"
"}\n"
"\n"
"void f(std::shared_ptr<foo> p) {\n"
" p->dostuff();\n"
"}");
ASSERT(db != nullptr);
const Token *tok1 = Token::findsimplematch(tokenizer.tokens(), ". dostuff ( ) ;")->next();
ASSERT(tok1->function());
}
void findFunction25() { // std::vector<std::shared_ptr<Fred>>
GET_SYMBOL_DB("struct foo {\n"
" void dostuff();\n"
"}\n"
"\n"
"void f1(std::vector<std::shared_ptr<foo>> v)\n"
"{\n"
" for (auto p : v)\n"
" {\n"
" p->dostuff();\n"
" }\n"
"}");
ASSERT(db != nullptr);
const Token *tok1 = Token::findsimplematch(tokenizer.tokens(), ". dostuff ( ) ;")->next();
ASSERT(tok1->function());
}
void findFunction26() {
GET_SYMBOL_DB("void dostuff(const int *p) {}\n"
"void dostuff(float) {}\n"
"void f(int *p) {\n"
" dostuff(p);\n"
"}");
ASSERT(db != nullptr);
const Token *dostuff1 = Token::findsimplematch(tokenizer.tokens(), "dostuff ( p ) ;");
ASSERT(dostuff1->function());
ASSERT(dostuff1->function() && dostuff1->function()->token);
ASSERT(dostuff1->function() && dostuff1->function()->token && dostuff1->function()->token->linenr() == 1);
}
void findFunction27() {
GET_SYMBOL_DB("namespace { void a(int); }\n"
"void f() { a(9); }");
const Token *a = Token::findsimplematch(tokenizer.tokens(), "a ( 9 )");
ASSERT(a);
ASSERT(a->function());
}
void findFunction28() {
GET_SYMBOL_DB("namespace { void a(int); }\n"
"struct S {\n"
" void foo() { a(7); }\n"
" void a(int);\n"
"};");
const Token *a = Token::findsimplematch(tokenizer.tokens(), "a ( 7 )");
ASSERT(a);
ASSERT(a->function());
ASSERT(a->function()->token);
ASSERT_EQUALS(4, a->function()->token->linenr());
}
void findFunction29() {
GET_SYMBOL_DB("struct A {\n"
" int foo() const;\n"
"};\n"
"\n"
"struct B {\n"
" A a;\n"
"};\n"
"\n"
"typedef std::shared_ptr<B> BPtr;\n"
"\n"
"void bar(BPtr b) {\n"
" int x = b->a.foo();\n"
"}");
const Token *foo = Token::findsimplematch(tokenizer.tokens(), "foo ( ) ;");
ASSERT(foo);
ASSERT(foo->function());
ASSERT(foo->function()->token);
ASSERT_EQUALS(2, foo->function()->token->linenr());
}
void findFunction30() {
GET_SYMBOL_DB("struct A;\n"
"void foo(std::shared_ptr<A> ptr) {\n"
" int x = ptr->bar();\n"
"}");
const Token *bar = Token::findsimplematch(tokenizer.tokens(), "bar ( ) ;");
ASSERT(bar);
ASSERT(!bar->function());
}
void findFunction31() {
GET_SYMBOL_DB("void foo(bool);\n"
"void foo(std::string s);\n"
"void bar() { foo(\"123\"); }");
const Token *foo = Token::findsimplematch(tokenizer.tokens(), "foo ( \"123\" ) ;");
ASSERT(foo);
ASSERT(foo->function());
ASSERT(foo->function()->tokenDef);
ASSERT_EQUALS(1, foo->function()->tokenDef->linenr());
}
void findFunction32() {
GET_SYMBOL_DB_C("void foo(char *p);\n"
"void bar() { foo(\"123\"); }");
(void)db;
const Token *foo = Token::findsimplematch(tokenizer.tokens(), "foo ( \"123\" ) ;");
ASSERT(foo);
ASSERT(foo->function());
ASSERT(foo->function()->tokenDef);
ASSERT_EQUALS(1, foo->function()->tokenDef->linenr());
}
void findFunction33() {
{
GET_SYMBOL_DB("class Base {\n"
" int i{};\n"
"public:\n"
" void foo(...) const { bar(); }\n"
" int bar() const { return i; }\n"
"};\n"
"class Derived : public Base {\n"
"public:\n"
" void doIt() const {\n"
" foo();\n"
" }\n"
"};");
(void)db;
const Token *foo = Token::findsimplematch(tokenizer.tokens(), "foo ( ) ;");
ASSERT(foo);
ASSERT(foo->function());
ASSERT(foo->function()->tokenDef);
ASSERT_EQUALS(4, foo->function()->tokenDef->linenr());
}
{
GET_SYMBOL_DB("class Base {\n"
" int i{};\n"
"public:\n"
" void foo(...) const { bar(); }\n"
" int bar() const { return i; }\n"
"};\n"
"class Derived : public Base {\n"
"public:\n"
" void doIt() const {\n"
" foo(1);\n"
" }\n"
"};");
(void)db;
const Token *foo = Token::findsimplematch(tokenizer.tokens(), "foo ( 1 ) ;");
ASSERT(foo);
ASSERT(foo->function());
ASSERT(foo->function()->tokenDef);
ASSERT_EQUALS(4, foo->function()->tokenDef->linenr());
}
{
GET_SYMBOL_DB("class Base {\n"
" int i{};\n"
"public:\n"
" void foo(...) const { bar(); }\n"
" int bar() const { return i; }\n"
"};\n"
"class Derived : public Base {\n"
"public:\n"
" void doIt() const {\n"
" foo(1,2);\n"
" }\n"
"};");
(void)db;
const Token *foo = Token::findsimplematch(tokenizer.tokens(), "foo ( 1 , 2 ) ;");
ASSERT(foo);
ASSERT(foo->function());
ASSERT(foo->function()->tokenDef);
ASSERT_EQUALS(4, foo->function()->tokenDef->linenr());
}
{
GET_SYMBOL_DB("class Base {\n"
" int i{};\n"
"public:\n"
" void foo(int, ...) const { bar(); }\n"
" int bar() const { return i; }\n"
"};\n"
"class Derived : public Base {\n"
"public:\n"
" void doIt() const {\n"
" foo(1);\n"
" }\n"
"};");
(void)db;
const Token *foo = Token::findsimplematch(tokenizer.tokens(), "foo ( 1 ) ;");
ASSERT(foo);
ASSERT(foo->function());
ASSERT(foo->function()->tokenDef);
ASSERT_EQUALS(4, foo->function()->tokenDef->linenr());
}
{
GET_SYMBOL_DB("class Base {\n"
" int i{};\n"
"public:\n"
" void foo(int,...) const { bar(); }\n"
" int bar() const { return i; }\n"
"};\n"
"class Derived : public Base {\n"
"public:\n"
" void doIt() const {\n"
" foo(1,2);\n"
" }\n"
"};");
(void)db;
const Token *foo = Token::findsimplematch(tokenizer.tokens(), "foo ( 1 , 2 ) ;");
ASSERT(foo);
ASSERT(foo->function());
ASSERT(foo->function()->tokenDef);
ASSERT_EQUALS(4, foo->function()->tokenDef->linenr());
}
{
GET_SYMBOL_DB("class Base {\n"
" int i{};\n"
"public:\n"
" void foo(int,...) const { bar(); }\n"
" int bar() const { return i; }\n"
"};\n"
"class Derived : public Base {\n"
"public:\n"
" void doIt() const {\n"
" foo(1, 2, 3);\n"
" }\n"
"};");
(void)db;
const Token *foo = Token::findsimplematch(tokenizer.tokens(), "foo ( 1 , 2 , 3 ) ;");
ASSERT(foo);
ASSERT(foo->function());
ASSERT(foo->function()->tokenDef);
ASSERT_EQUALS(4, foo->function()->tokenDef->linenr());
}
}
void findFunction34() {
GET_SYMBOL_DB("namespace cppcheck {\n"
" class Platform {\n"
" public:\n"
" enum PlatformType { Unspecified };\n"
" };\n"
"}\n"
"class ImportProject {\n"
" void selectOneVsConfig(cppcheck::Platform::PlatformType);\n"
"};\n"
"class Settings : public cppcheck::Platform { };\n"
"void ImportProject::selectOneVsConfig(Settings::PlatformType) { }");
(void)db;
const Token *foo = Token::findsimplematch(tokenizer.tokens(), "selectOneVsConfig ( Settings :: PlatformType ) { }");
ASSERT(foo);
ASSERT(foo->function());
ASSERT(foo->function()->tokenDef);
ASSERT_EQUALS(8, foo->function()->tokenDef->linenr());
}
void findFunction35() {
GET_SYMBOL_DB("namespace clangimport {\n"
" class AstNode {\n"
" public:\n"
" AstNode();\n"
" void createTokens();\n"
" };\n"
"}\n"
"::clangimport::AstNode::AstNode() { }\n"
"void ::clangimport::AstNode::createTokens() { }");
(void)db;
const Token *foo = Token::findsimplematch(tokenizer.tokens(), "AstNode ( ) { }");
ASSERT(foo);
ASSERT(foo->function());
ASSERT(foo->function()->tokenDef);
ASSERT_EQUALS(4, foo->function()->tokenDef->linenr());
foo = Token::findsimplematch(tokenizer.tokens(), "createTokens ( ) { }");
ASSERT(foo);
ASSERT(foo->function());
ASSERT(foo->function()->tokenDef);
ASSERT_EQUALS(5, foo->function()->tokenDef->linenr());
}
void findFunction36() { // #10122
GET_SYMBOL_DB("namespace external {\n"
" enum class T { };\n"
"}\n"
"namespace ns {\n"
" class A {\n"
" public:\n"
" void f(external::T);\n"
" };\n"
"}\n"
"namespace ns {\n"
" void A::f(external::T link_type) { }\n"
"}");
ASSERT_EQUALS("", errout_str());
const Token *functok = Token::findsimplematch(tokenizer.tokens(), "f ( external :: T link_type )");
ASSERT(functok);
ASSERT(functok->function());
ASSERT(functok->function()->name() == "f");
ASSERT_EQUALS(7, functok->function()->tokenDef->linenr());
}
void findFunction37() { // #10124
GET_SYMBOL_DB("namespace ns {\n"
" class V { };\n"
"}\n"
"class A {\n"
"public:\n"
" void f(const ns::V&);\n"
"};\n"
"using ::ns::V;\n"
"void A::f(const V&) { }");
ASSERT_EQUALS("", errout_str());
const Token *functok = Token::findsimplematch(tokenizer.tokens(), "f ( const :: ns :: V & )");
ASSERT(functok);
ASSERT(functok->function());
ASSERT(functok->function()->name() == "f");
ASSERT_EQUALS(6, functok->function()->tokenDef->linenr());
}
void findFunction38() { // #10125
GET_SYMBOL_DB("namespace ns {\n"
" class V { };\n"
" using Var = V;\n"
"}\n"
"class A {\n"
" void f(const ns::Var&);\n"
"};\n"
"using ::ns::Var;\n"
"void A::f(const Var&) {}");
ASSERT_EQUALS("", errout_str());
const Token *functok = Token::findsimplematch(tokenizer.tokens(), "f ( const :: ns :: V & )");
ASSERT(functok);
ASSERT(functok->function());
ASSERT(functok->function()->name() == "f");
ASSERT_EQUALS(6, functok->function()->tokenDef->linenr());
}
void findFunction39() { // #10127
GET_SYMBOL_DB("namespace external {\n"
" class V {\n"
" public:\n"
" using I = int;\n"
" };\n"
"}\n"
"class A {\n"
" void f(external::V::I);\n"
"};\n"
"using ::external::V;\n"
"void A::f(V::I) {}");
ASSERT_EQUALS("", errout_str());
const Token *functok = Token::findsimplematch(tokenizer.tokens(), "f ( int )");
ASSERT(functok);
ASSERT(functok->function());
ASSERT(functok->function()->name() == "f");
ASSERT_EQUALS(8, functok->function()->tokenDef->linenr());
}
void findFunction40() { // #10135
GET_SYMBOL_DB("class E : public std::exception {\n"
"public:\n"
" const char* what() const noexcept override;\n"
"};\n"
"const char* E::what() const noexcept {\n"
" return nullptr;\n"
"}");
ASSERT_EQUALS("", errout_str());
const Token *functok = Token::findsimplematch(tokenizer.tokens(), "what ( ) const noexcept ( true ) {");
ASSERT(functok);
ASSERT(functok->function());
ASSERT(functok->function()->name() == "what");
ASSERT_EQUALS(3, functok->function()->tokenDef->linenr());
}
void findFunction41() { // #10202
{
GET_SYMBOL_DB("struct A {};\n"
"const int* g(const A&);\n"
"int* g(A&);\n"
"void f(A& x) {\n"
" int* y = g(x);\n"
" *y = 0;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
const Token *functok = Token::findsimplematch(tokenizer.tokens(), "g ( x )");
ASSERT(functok);
ASSERT(functok->function());
ASSERT(functok->function()->name() == "g");
ASSERT_EQUALS(3, functok->function()->tokenDef->linenr());
}
{
GET_SYMBOL_DB("struct A {};\n"
"const int* g(const A&);\n"
"int* g(A&);\n"
"void f(const A& x) {\n"
" int* y = g(x);\n"
" *y = 0;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
const Token *functok = Token::findsimplematch(tokenizer.tokens(), "g ( x )");
ASSERT(functok);
ASSERT(functok->function());
ASSERT(functok->function()->name() == "g");
ASSERT_EQUALS(2, functok->function()->tokenDef->linenr());
}
}
void findFunction42() {
GET_SYMBOL_DB("void a(const std::string &, const std::string &);\n"
"void a(long, long);\n"
"void b() { a(true, false); }\n");
ASSERT_EQUALS("", errout_str());
const Token *functok = Token::findsimplematch(tokenizer.tokens(), "a ( true , false )");
ASSERT(functok);
ASSERT(functok->function());
ASSERT(functok->function()->name() == "a");
ASSERT_EQUALS(2, functok->function()->tokenDef->linenr());
}
void findFunction43() { // #10087
{
GET_SYMBOL_DB("struct A {};\n"
"const A* g(const std::string&);\n"
"const A& g(std::vector<A>::size_type i);\n"
"const A& f(std::vector<A>::size_type i) { return g(i); }\n");
ASSERT_EQUALS("", errout_str());
const Token *functok = Token::findsimplematch(tokenizer.tokens(), "g ( i )");
ASSERT(functok);
ASSERT(functok->function());
ASSERT(functok->function()->name() == "g");
ASSERT_EQUALS(3, functok->function()->tokenDef->linenr());
}
{
GET_SYMBOL_DB("struct A {};\n"
"const A& g(std::vector<A>::size_type i);\n"
"const A* g(const std::string&);\n"
"const A& f(std::vector<A>::size_type i) { return g(i); }\n");
ASSERT_EQUALS("", errout_str());
const Token *functok = Token::findsimplematch(tokenizer.tokens(), "g ( i )");
ASSERT(functok);
ASSERT(functok->function());
ASSERT(functok->function()->name() == "g");
ASSERT_EQUALS(2, functok->function()->tokenDef->linenr());
}
}
void findFunction44() { // #11182
{
GET_SYMBOL_DB("struct T { enum E { E0 }; };\n"
"struct S {\n"
" void f(const void*, T::E) {}\n"
" void f(const int&, T::E) {}\n"
" void g() { f(nullptr, T::E0); }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
const Token *functok = Token::findsimplematch(tokenizer.tokens(), "f ( nullptr");
ASSERT(functok);
ASSERT(functok->function());
ASSERT(functok->function()->name() == "f");
ASSERT_EQUALS(3, functok->function()->tokenDef->linenr());
}
{
GET_SYMBOL_DB("enum E { E0 };\n"
"struct S {\n"
" void f(int*, int) {}\n"
" void f(int, int) {}\n"
" void g() { f(nullptr, E0); }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
const Token *functok = Token::findsimplematch(tokenizer.tokens(), "f ( nullptr");
ASSERT(functok);
ASSERT(functok->function());
ASSERT(functok->function()->name() == "f");
ASSERT_EQUALS(3, functok->function()->tokenDef->linenr());
}
{
GET_SYMBOL_DB("struct T { enum E { E0 }; } t; \n" // #11559
"void f(const void*, T::E) {}\n"
"void f(const int&, T::E) {}\n"
"void g() {\n"
" f(nullptr, t.E0);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
const Token *functok = Token::findsimplematch(tokenizer.tokens(), "f ( nullptr");
ASSERT(functok);
ASSERT(functok->function());
ASSERT(functok->function()->name() == "f");
ASSERT_EQUALS(2, functok->function()->tokenDef->linenr());
}
}
void findFunction45() {
GET_SYMBOL_DB("struct S { void g(int); };\n"
"void f(std::vector<S>& v) {\n"
" std::vector<S>::iterator it = v.begin();\n"
" it->g(1);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
const Token *functok = Token::findsimplematch(tokenizer.tokens(), "g ( 1");
ASSERT(functok);
ASSERT(functok->function());
ASSERT(functok->function()->name() == "g");
ASSERT_EQUALS(1, functok->function()->tokenDef->linenr());
}
void findFunction46() {
GET_SYMBOL_DB("struct S {\n" // #11531
" const int* g(int i, int j) const;\n"
" int* g(int i, int j);\n"
"};\n"
"enum E { E0 };\n"
"void f(S& s, int i) {\n"
" int* p = s.g(E0, i);\n"
" *p = 0;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
const Token *functok = Token::findsimplematch(tokenizer.tokens(), "g ( E0");
ASSERT(functok && functok->function());
ASSERT(functok->function()->name() == "g");
ASSERT_EQUALS(3, functok->function()->tokenDef->linenr());
}
void findFunction47() { // #8592
{
GET_SYMBOL_DB("namespace N {\n"
" void toupper(std::string& str);\n"
"}\n"
"void f(std::string s) {\n"
" using namespace N;\n"
" toupper(s);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
const Token *functok = Token::findsimplematch(tokenizer.tokens(), "toupper ( s");
ASSERT(functok && functok->function());
ASSERT(functok->function()->name() == "toupper");
ASSERT_EQUALS(2, functok->function()->tokenDef->linenr());
}
{
GET_SYMBOL_DB("namespace N {\n"
" void toupper(std::string& str);\n"
"}\n"
"using namespace N;\n"
"void f(std::string s) {\n"
" toupper(s);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
const Token *functok = Token::findsimplematch(tokenizer.tokens(), "toupper ( s");
ASSERT(functok && functok->function());
ASSERT(functok->function()->name() == "toupper");
ASSERT_EQUALS(2, functok->function()->tokenDef->linenr());
}
}
void findFunction48() {
GET_SYMBOL_DB("struct S {\n"
" S() {}\n"
" std::list<S> l;\n"
"};\n");
ASSERT_EQUALS("", errout_str());
const Token* typeTok = Token::findsimplematch(tokenizer.tokens(), "S >");
ASSERT(typeTok && typeTok->type());
ASSERT(typeTok->type()->name() == "S");
ASSERT_EQUALS(1, typeTok->type()->classDef->linenr());
}
void findFunction49() {
GET_SYMBOL_DB("struct B {};\n"
"struct D : B {};\n"
"void f(bool = false, bool = true);\n"
"void f(B*, bool, bool = true);\n"
"void g() {\n"
" D d;\n"
" f(&d, true);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
const Token* ftok = Token::findsimplematch(tokenizer.tokens(), "f ( &");
ASSERT(ftok && ftok->function());
ASSERT(ftok->function()->name() == "f");
ASSERT_EQUALS(4, ftok->function()->tokenDef->linenr());
}
void findFunction50() {
{
GET_SYMBOL_DB("struct B { B(); void init(unsigned int value); };\n"
"struct D: B { D(); void init(unsigned int value); };\n"
"D::D() { init(0); }\n"
"void D::init(unsigned int value) {}\n");
const Token* call = Token::findsimplematch(tokenizer.tokens(), "init ( 0 ) ;");
ASSERT(call && call->function() && call->function()->functionScope);
}
{
GET_SYMBOL_DB("struct B { B(); void init(unsigned int value); };\n"
"struct D: B { D(); void init(unsigned int value); };\n"
"D::D() { init(0ULL); }\n"
"void D::init(unsigned int value) {}\n");
const Token* call = Token::findsimplematch(tokenizer.tokens(), "init ( 0ULL ) ;");
ASSERT(call && call->function() && call->function()->functionScope);
}
}
void findFunction51() {
// Both A and B defines the method test but with different arguments.
// The call to test in B should match the method in B. The match is close enough.
{
GET_SYMBOL_DB("class A {\n"
"public:\n"
" void test(bool a = true);\n"
"};\n"
"\n"
"class B : public A {\n"
"public:\n"
" B(): b_obj(this) { b_obj->test(\"1\"); }\n"
" void test(const std::string& str_obj);\n"
" B* b_obj;\n"
"};");
const Token* call = Token::findsimplematch(tokenizer.tokens(), "test ( \"1\" ) ;");
ASSERT(call);
ASSERT(call->function());
ASSERT(call->function()->tokenDef);
ASSERT_EQUALS(9, call->function()->tokenDef->linenr());
}
{
GET_SYMBOL_DB("struct STR { STR(const char * p); };\n"
"class A {\n"
"public:\n"
" void test(bool a = true);\n"
"};\n"
"\n"
"class B : public A {\n"
"public:\n"
" B(): b_obj(this) { b_obj->test(\"1\"); }\n"
" void test(const STR& str_obj);\n"
" B* b_obj;\n"
"};");
const Token* call = Token::findsimplematch(tokenizer.tokens(), "test ( \"1\" ) ;");
ASSERT(call);
ASSERT(call->function());
ASSERT(call->function()->tokenDef);
ASSERT_EQUALS(10, call->function()->tokenDef->linenr());
}
{
GET_SYMBOL_DB("struct STR { STR(const char * p); };\n"
"class A {\n"
"public:\n"
" void test(bool a = true, int b = 0);\n"
"};\n"
"\n"
"class B : public A {\n"
"public:\n"
" B(): b_obj(this) { b_obj->test(\"1\"); }\n"
" void test(const STR& str_obj);\n"
" B* b_obj;\n"
"};");
const Token* call = Token::findsimplematch(tokenizer.tokens(), "test ( \"1\" ) ;");
ASSERT(call);
ASSERT(call->function());
ASSERT(call->function()->tokenDef);
ASSERT_EQUALS(10, call->function()->tokenDef->linenr());
}
}
void findFunction52() {
GET_SYMBOL_DB("int g();\n"
"void f() {\n"
" if (g != 0) {}\n"
"}\n");
const Token* g = Token::findsimplematch(tokenizer.tokens(), "g !=");
ASSERT(g->function() && g->function()->tokenDef);
ASSERT(g->function()->tokenDef->linenr() == 1);
}
void findFunction53() {
GET_SYMBOL_DB("namespace N {\n" // #12208
" struct S {\n"
" S(const int*);\n"
" };\n"
"}\n"
"void f(int& r) {\n"
" N::S(&r);\n"
"}\n");
const Token* S = Token::findsimplematch(tokenizer.tokens(), "S ( &");
ASSERT(S->function() && S->function()->tokenDef);
ASSERT(S->function()->tokenDef->linenr() == 3);
ASSERT(S->function()->isConstructor());
}
void findFunction54() {
{
GET_SYMBOL_DB("struct S {\n"
" explicit S(int& r) { if (r) {} }\n"
" bool f(const std::map<int, S>& m);\n"
"};\n");
const Token* S = Token::findsimplematch(tokenizer.tokens(), "S (");
ASSERT(S && S->function());
ASSERT(S->function()->isConstructor());
ASSERT(!S->function()->functionPointerUsage);
S = Token::findsimplematch(S->next(), "S >");
ASSERT(S && S->type());
ASSERT_EQUALS(S->type()->name(), "S");
}
{
GET_SYMBOL_DB("struct S {\n"
" explicit S(int& r) { if (r) {} }\n"
" bool f(const std::map<int, S, std::allocator<S>>& m);\n"
"};\n");
const Token* S = Token::findsimplematch(tokenizer.tokens(), "S (");
ASSERT(S && S->function());
ASSERT(S->function()->isConstructor());
ASSERT(!S->function()->functionPointerUsage);
S = Token::findsimplematch(S->next(), "S ,");
ASSERT(S && S->type());
ASSERT_EQUALS(S->type()->name(), "S");
S = Token::findsimplematch(S->next(), "S >");
ASSERT(S && S->type());
ASSERT_EQUALS(S->type()->name(), "S");
}
}
void findFunction55() {
GET_SYMBOL_DB("struct Token { int x; };\n"
"static void f(std::size_t s);\n"
"static void f(const Token* ptr);\n"
"static void f2(const std::vector<Token*>& args) { f(args[0]); }\n");
const Token* f = Token::findsimplematch(tokenizer.tokens(), "f ( args [ 0 ] )");
ASSERT(f && f->function());
ASSERT(Token::simpleMatch(f->function()->tokenDef, "f ( const Token * ptr ) ;"));
}
void findFunction56() { // #13125
GET_SYMBOL_DB("void f(const char* fn, int i, const char e[], const std::string& a);\n"
"void f(const char* fn, int i, const char e[], const char a[]);\n"
"void g(const char x[], const std::string& s) {\n"
" f(\"abc\", 65, x, s);\n"
"}\n");
const Token* f = Token::findsimplematch(tokenizer.tokens(), "f ( \"abc\"");
ASSERT(f && f->function());
ASSERT_EQUALS(f->function()->tokenDef->linenr(), 1);
}
void findFunction57() { // #13051
GET_SYMBOL_DB("struct S {\n"
" ~S();\n"
" void f();\n"
"};\n"
"struct T {\n"
" T();\n"
"};\n"
"void S::f() {\n"
" auto s1 = new S;\n"
" auto s2 = new S();\n"
" auto t = new T();\n"
"}\n");
const Token* S = Token::findsimplematch(tokenizer.tokens(), "S ;");
ASSERT(S && S->type());
ASSERT_EQUALS(S->type()->classDef->linenr(), 1);
S = Token::findsimplematch(S, "S (");
ASSERT(S && S->type());
ASSERT_EQUALS(S->type()->classDef->linenr(), 1);
const Token* T = Token::findsimplematch(S, "T (");
ASSERT(T && T->function());
ASSERT_EQUALS(T->function()->tokenDef->linenr(), 6);
}
void findFunction58() { // #13310
GET_SYMBOL_DB("class C {\n"
" enum class abc : uint8_t {\n"
" a,b,c\n"
" };\n"
" void a();\n"
"};\n");
const Token *a1 = Token::findsimplematch(tokenizer.tokens(), "a ,");
ASSERT(a1 && !a1->function());
const Token *a2 = Token::findsimplematch(tokenizer.tokens(), "a (");
ASSERT(a2 && a2->function());
}
void findFunctionRef1() {
GET_SYMBOL_DB("struct X {\n"
" const std::vector<int> getInts() const & { return mInts; }\n"
" std::vector<int> getInts() && { return mInts; }\n"
" std::vector<int> mInts;\n"
"}\n"
"\n"
"void foo(X &x) {\n"
" x.getInts();\n"
"}\n");
const Token* x = Token::findsimplematch(tokenizer.tokens(), "x . getInts ( ) ;");
ASSERT(x);
const Token* f = x->tokAt(2);
ASSERT(f);
ASSERT(f->function());
ASSERT(f->function()->tokenDef);
ASSERT_EQUALS(2, f->function()->tokenDef->linenr());
}
void findFunctionRef2() {
GET_SYMBOL_DB("struct X {\n"
" const int& foo() const &;\n" // <- this function is called
" int foo() &&;\n"
"}\n"
"\n"
"void foo() {\n"
" X x;\n"
" x.foo();\n"
"}\n");
const Token* x = Token::findsimplematch(tokenizer.tokens(), "x . foo ( ) ;");
ASSERT(x);
const Token* f = x->tokAt(2);
ASSERT(f);
ASSERT(f->function());
ASSERT(f->function()->tokenDef);
ASSERT_EQUALS(2, f->function()->tokenDef->linenr());
}
void findFunctionContainer() {
{
GET_SYMBOL_DB("void dostuff(std::vector<int> v);\n"
"void f(std::vector<int> v) {\n"
" dostuff(v);\n"
"}");
(void)db;
const Token *dostuff = Token::findsimplematch(tokenizer.tokens(), "dostuff ( v ) ;");
ASSERT(dostuff->function());
ASSERT(dostuff->function() && dostuff->function()->tokenDef);
ASSERT(dostuff->function() && dostuff->function()->tokenDef && dostuff->function()->tokenDef->linenr() == 1);
}
{
GET_SYMBOL_DB("void dostuff(std::vector<int> v);\n"
"void dostuff(int *i);\n"
"void f(std::vector<char> v) {\n"
" dostuff(v);\n"
"}");
(void)db;
const Token *dostuff = Token::findsimplematch(tokenizer.tokens(), "dostuff ( v ) ;");
ASSERT(!dostuff->function());
}
}
void findFunctionExternC() {
GET_SYMBOL_DB("extern \"C\" { void foo(int); }\n"
"void bar() {\n"
" foo(42);\n"
"}");
const Token *a = Token::findsimplematch(tokenizer.tokens(), "foo ( 42 )");
ASSERT(a);
ASSERT(a->function());
}
void findFunctionGlobalScope() {
GET_SYMBOL_DB("struct S {\n"
" void foo();\n"
" int x;\n"
"};\n"
"\n"
"int bar(int x);\n"
"\n"
"void S::foo() {\n"
" x = ::bar(x);\n"
"}");
const Token *bar = Token::findsimplematch(tokenizer.tokens(), "bar ( x )");
ASSERT(bar);
ASSERT(bar->function());
}
void overloadedFunction1() {
GET_SYMBOL_DB("struct S {\n"
" int operator()(int);\n"
"};\n"
"\n"
"void foo(S x) {\n"
" x(123);\n"
"}");
const Token *tok = Token::findsimplematch(tokenizer.tokens(), "x . operator() ( 123 )");
ASSERT(tok);
ASSERT(tok->tokAt(2)->function());
}
void valueTypeMatchParameter() const {
ValueType vt_int(ValueType::Sign::SIGNED, ValueType::Type::INT, 0);
ValueType vt_const_int(ValueType::Sign::SIGNED, ValueType::Type::INT, 0, 1);
ASSERT_EQUALS((int)ValueType::MatchResult::SAME, (int)ValueType::matchParameter(&vt_int, &vt_int));
ASSERT_EQUALS((int)ValueType::MatchResult::SAME, (int)ValueType::matchParameter(&vt_const_int, &vt_int));
ASSERT_EQUALS((int)ValueType::MatchResult::SAME, (int)ValueType::matchParameter(&vt_int, &vt_const_int));
ValueType vt_char_pointer(ValueType::Sign::SIGNED, ValueType::Type::CHAR, 1);
ValueType vt_void_pointer(ValueType::Sign::SIGNED, ValueType::Type::VOID, 1); // compatible
ValueType vt_int_pointer(ValueType::Sign::SIGNED, ValueType::Type::INT, 1); // not compatible
ASSERT_EQUALS((int)ValueType::MatchResult::FALLBACK1, (int)ValueType::matchParameter(&vt_char_pointer, &vt_void_pointer));
ASSERT_EQUALS((int)ValueType::MatchResult::NOMATCH, (int)ValueType::matchParameter(&vt_char_pointer, &vt_int_pointer));
ValueType vt_char_pointer2(ValueType::Sign::SIGNED, ValueType::Type::CHAR, 2);
ASSERT_EQUALS((int)ValueType::MatchResult::FALLBACK1, (int)ValueType::matchParameter(&vt_char_pointer2, &vt_void_pointer));
ValueType vt_const_float_pointer(ValueType::Sign::UNKNOWN_SIGN, ValueType::Type::FLOAT, 1, 1);
ValueType vt_long_long(ValueType::Sign::SIGNED, ValueType::Type::LONGLONG, 0, 0);
ASSERT_EQUALS((int)ValueType::MatchResult::NOMATCH, (int)ValueType::matchParameter(&vt_const_float_pointer, &vt_long_long));
}
#define FUNC(x) do { \
const Function *x = findFunctionByName(#x, &db->scopeList.front()); \
ASSERT_EQUALS(true, x != nullptr); \
ASSERT_EQUALS(true, x->isNoExcept()); \
} while (false)
void noexceptFunction1() {
GET_SYMBOL_DB("void func1() noexcept;\n"
"void func2() noexcept { }\n"
"void func3() noexcept(true);\n"
"void func4() noexcept(true) { }");
ASSERT_EQUALS("", errout_str());
ASSERT_EQUALS(true, db != nullptr); // not null
FUNC(func1);
FUNC(func2);
FUNC(func3);
FUNC(func4);
}
void noexceptFunction2() {
GET_SYMBOL_DB("template <class T> void self_assign(T& t) noexcept(noexcept(t = t)) {t = t; }");
ASSERT_EQUALS("", errout_str());
ASSERT_EQUALS(true, db != nullptr); // not null
FUNC(self_assign);
}
#define CLASS_FUNC(x, y, z) do { \
const Function *x = findFunctionByName(#x, y); \
ASSERT_EQUALS(true, x != nullptr); \
ASSERT_EQUALS(z, x->isNoExcept()); \
} while (false)
void noexceptFunction3() {
GET_SYMBOL_DB("struct Fred {\n"
" void func1() noexcept;\n"
" void func2() noexcept { }\n"
" void func3() noexcept(true);\n"
" void func4() noexcept(true) { }\n"
" void func5() const noexcept;\n"
" void func6() const noexcept { }\n"
" void func7() const noexcept(true);\n"
" void func8() const noexcept(true) { }\n"
" void func9() noexcept = 0;\n"
" void func10() noexcept = 0;\n"
" void func11() const noexcept(true) = 0;\n"
" void func12() const noexcept(true) = 0;\n"
" void func13() const noexcept(false) = 0;\n"
"};");
ASSERT_EQUALS("", errout_str());
ASSERT_EQUALS(true, db != nullptr); // not null
const Scope *fred = db->findScopeByName("Fred");
ASSERT_EQUALS(true, fred != nullptr);
CLASS_FUNC(func1, fred, true);
CLASS_FUNC(func2, fred, true);
CLASS_FUNC(func3, fred, true);
CLASS_FUNC(func4, fred, true);
CLASS_FUNC(func5, fred, true);
CLASS_FUNC(func6, fred, true);
CLASS_FUNC(func7, fred, true);
CLASS_FUNC(func8, fred, true);
CLASS_FUNC(func9, fred, true);
CLASS_FUNC(func10, fred, true);
CLASS_FUNC(func11, fred, true);
CLASS_FUNC(func12, fred, true);
CLASS_FUNC(func13, fred, false);
}
void noexceptFunction4() {
GET_SYMBOL_DB("class A {\n"
"public:\n"
" A(A&& a) {\n"
" throw std::runtime_error(\"err\");\n"
" }\n"
"};\n"
"class B {\n"
" A a;\n"
" B(B&& b) noexcept\n"
" :a(std::move(b.a)) { }\n"
"};");
ASSERT_EQUALS("", errout_str());
ASSERT(db != nullptr); // not null
const Scope *b = db->findScopeByName("B");
ASSERT(b != nullptr);
CLASS_FUNC(B, b, true);
}
#define FUNC_THROW(x) do { \
const Function *x = findFunctionByName(#x, &db->scopeList.front()); \
ASSERT_EQUALS(true, x != nullptr); \
ASSERT_EQUALS(true, x->isThrow()); \
} while (false)
void throwFunction1() {
GET_SYMBOL_DB("void func1() throw();\n"
"void func2() throw() { }\n"
"void func3() throw(int);\n"
"void func4() throw(int) { }");
ASSERT_EQUALS("", errout_str());
ASSERT(db != nullptr); // not null
FUNC_THROW(func1);
FUNC_THROW(func2);
FUNC_THROW(func3);
FUNC_THROW(func4);
}
#define CLASS_FUNC_THROW(x, y) do { \
const Function *x = findFunctionByName(#x, y); \
ASSERT_EQUALS(true, x != nullptr); \
ASSERT_EQUALS(true, x->isThrow()); \
} while (false)
void throwFunction2() {
GET_SYMBOL_DB("struct Fred {\n"
" void func1() throw();\n"
" void func2() throw() { }\n"
" void func3() throw(int);\n"
" void func4() throw(int) { }\n"
" void func5() const throw();\n"
" void func6() const throw() { }\n"
" void func7() const throw(int);\n"
" void func8() const throw(int) { }\n"
" void func9() throw() = 0;\n"
" void func10() throw(int) = 0;\n"
" void func11() const throw() = 0;\n"
" void func12() const throw(int) = 0;\n"
"};");
ASSERT_EQUALS("", errout_str());
ASSERT_EQUALS(true, db != nullptr); // not null
const Scope *fred = db->findScopeByName("Fred");
ASSERT_EQUALS(true, fred != nullptr);
CLASS_FUNC_THROW(func1, fred);
CLASS_FUNC_THROW(func2, fred);
CLASS_FUNC_THROW(func3, fred);
CLASS_FUNC_THROW(func4, fred);
CLASS_FUNC_THROW(func5, fred);
CLASS_FUNC_THROW(func6, fred);
CLASS_FUNC_THROW(func7, fred);
CLASS_FUNC_THROW(func8, fred);
CLASS_FUNC_THROW(func9, fred);
CLASS_FUNC_THROW(func10, fred);
CLASS_FUNC_THROW(func11, fred);
CLASS_FUNC_THROW(func12, fred);
}
void constAttributeFunction() {
GET_SYMBOL_DB("void func(void) __attribute__((const));");
ASSERT_EQUALS("", errout_str());
ASSERT_EQUALS(true, db != nullptr); // not null
const Function* func = findFunctionByName("func", &db->scopeList.front());
ASSERT_EQUALS(true, func != nullptr);
ASSERT_EQUALS(true, func->isAttributeConst());
}
void pureAttributeFunction() {
GET_SYMBOL_DB("void func(void) __attribute__((pure));");
ASSERT_EQUALS("", errout_str());
ASSERT_EQUALS(true, db != nullptr); // not null
const Function* func = findFunctionByName("func", &db->scopeList.front());
ASSERT_EQUALS(true, func != nullptr);
ASSERT_EQUALS(true, func->isAttributePure());
}
void nothrowAttributeFunction() {
GET_SYMBOL_DB("void func() __attribute__((nothrow));\n"
"void func() { }");
ASSERT_EQUALS("", errout_str());
ASSERT_EQUALS(true, db != nullptr); // not null
const Function *func = findFunctionByName("func", &db->scopeList.front());
ASSERT_EQUALS(true, func != nullptr);
ASSERT_EQUALS(true, func->isAttributeNothrow());
}
void nothrowDeclspecFunction() {
GET_SYMBOL_DB("void __declspec(nothrow) func() { }");
ASSERT_EQUALS("", errout_str());
ASSERT_EQUALS(true, db != nullptr); // not null
const Function *func = findFunctionByName("func", &db->scopeList.front());
ASSERT_EQUALS(true, func != nullptr);
ASSERT_EQUALS(true, func->isAttributeNothrow());
}
void noreturnAttributeFunction() {
GET_SYMBOL_DB("[[noreturn]] void func1();\n"
"void func1() { }\n"
"[[noreturn]] void func2();\n"
"[[noreturn]] void func3() { }\n"
"template <class T> [[noreturn]] void func4() { }\n"
"[[noreturn]] [[gnu::format(printf, 1, 2)]] void func5(const char*, ...);\n"
"[[gnu::format(printf, 1, 2)]] [[noreturn]] void func6(const char*, ...);\n"
);
ASSERT_EQUALS("", errout_str());
ASSERT_EQUALS(true, db != nullptr); // not null
const Function *func = findFunctionByName("func1", &db->scopeList.front());
ASSERT_EQUALS(true, func != nullptr);
ASSERT_EQUALS(true, func->isAttributeNoreturn());
func = findFunctionByName("func2", &db->scopeList.front());
ASSERT_EQUALS(true, func != nullptr);
ASSERT_EQUALS(true, func->isAttributeNoreturn());
func = findFunctionByName("func3", &db->scopeList.front());
ASSERT_EQUALS(true, func != nullptr);
ASSERT_EQUALS(true, func->isAttributeNoreturn());
func = findFunctionByName("func4", &db->scopeList.front());
ASSERT_EQUALS(true, func != nullptr);
ASSERT_EQUALS(true, func->isAttributeNoreturn());
func = findFunctionByName("func5", &db->scopeList.front());
ASSERT_EQUALS(true, func != nullptr);
ASSERT_EQUALS(true, func->isAttributeNoreturn());
func = findFunctionByName("func6", &db->scopeList.front());
ASSERT_EQUALS(true, func != nullptr);
ASSERT_EQUALS(true, func->isAttributeNoreturn());
}
void nodiscardAttributeFunction() {
GET_SYMBOL_DB("[[nodiscard]] int func1();\n"
"int func1() { }\n"
"[[nodiscard]] int func2();\n"
"[[nodiscard]] int func3() { }\n"
"template <class T> [[nodiscard]] int func4() { }"
"std::pair<bool, char> [[nodiscard]] func5();\n"
"[[nodiscard]] std::pair<bool, char> func6();\n"
);
ASSERT_EQUALS("", errout_str());
ASSERT_EQUALS(true, db != nullptr); // not null
const Function *func = findFunctionByName("func1", &db->scopeList.front());
ASSERT_EQUALS(true, func != nullptr);
ASSERT_EQUALS(true, func->isAttributeNodiscard());
func = findFunctionByName("func2", &db->scopeList.front());
ASSERT_EQUALS(true, func != nullptr);
ASSERT_EQUALS(true, func->isAttributeNodiscard());
func = findFunctionByName("func3", &db->scopeList.front());
ASSERT_EQUALS(true, func != nullptr);
ASSERT_EQUALS(true, func->isAttributeNodiscard());
func = findFunctionByName("func4", &db->scopeList.front());
ASSERT_EQUALS(true, func != nullptr);
ASSERT_EQUALS(true, func->isAttributeNodiscard());
func = findFunctionByName("func5", &db->scopeList.front());
ASSERT_EQUALS(true, func != nullptr);
ASSERT_EQUALS(true, func->isAttributeNodiscard());
func = findFunctionByName("func6", &db->scopeList.front());
ASSERT_EQUALS(true, func != nullptr);
ASSERT_EQUALS(true, func->isAttributeNodiscard());
}
void varTypesIntegral() {
GET_SYMBOL_DB("void f() { bool b; char c; unsigned char uc; short s; unsigned short us; int i; unsigned u; unsigned int ui; long l; unsigned long ul; long long ll; }");
const Variable *b = db->getVariableFromVarId(1);
ASSERT(b != nullptr);
ASSERT_EQUALS("b", b->nameToken()->str());
ASSERT_EQUALS(false, b->isFloatingType());
const Variable *c = db->getVariableFromVarId(2);
ASSERT(c != nullptr);
ASSERT_EQUALS("c", c->nameToken()->str());
ASSERT_EQUALS(false, c->isFloatingType());
const Variable *uc = db->getVariableFromVarId(3);
ASSERT(uc != nullptr);
ASSERT_EQUALS("uc", uc->nameToken()->str());
ASSERT_EQUALS(false, uc->isFloatingType());
const Variable *s = db->getVariableFromVarId(4);
ASSERT(s != nullptr);
ASSERT_EQUALS("s", s->nameToken()->str());
ASSERT_EQUALS(false, s->isFloatingType());
const Variable *us = db->getVariableFromVarId(5);
ASSERT(us != nullptr);
ASSERT_EQUALS("us", us->nameToken()->str());
ASSERT_EQUALS(false, us->isFloatingType());
const Variable *i = db->getVariableFromVarId(6);
ASSERT(i != nullptr);
ASSERT_EQUALS("i", i->nameToken()->str());
ASSERT_EQUALS(false, i->isFloatingType());
const Variable *u = db->getVariableFromVarId(7);
ASSERT(u != nullptr);
ASSERT_EQUALS("u", u->nameToken()->str());
ASSERT_EQUALS(false, u->isFloatingType());
const Variable *ui = db->getVariableFromVarId(8);
ASSERT(ui != nullptr);
ASSERT_EQUALS("ui", ui->nameToken()->str());
ASSERT_EQUALS(false, ui->isFloatingType());
const Variable *l = db->getVariableFromVarId(9);
ASSERT(l != nullptr);
ASSERT_EQUALS("l", l->nameToken()->str());
ASSERT_EQUALS(false, l->isFloatingType());
const Variable *ul = db->getVariableFromVarId(10);
ASSERT(ul != nullptr);
ASSERT_EQUALS("ul", ul->nameToken()->str());
ASSERT_EQUALS(false, ul->isFloatingType());
const Variable *ll = db->getVariableFromVarId(11);
ASSERT(ll != nullptr);
ASSERT_EQUALS("ll", ll->nameToken()->str());
ASSERT_EQUALS(false, ll->isFloatingType());
}
void varTypesFloating() {
{
GET_SYMBOL_DB("void f() { float f; double d; long double ld; }");
const Variable *f = db->getVariableFromVarId(1);
ASSERT(f != nullptr);
ASSERT_EQUALS("f", f->nameToken()->str());
ASSERT_EQUALS(true, f->isFloatingType());
const Variable *d = db->getVariableFromVarId(2);
ASSERT(d != nullptr);
ASSERT_EQUALS("d", d->nameToken()->str());
ASSERT_EQUALS(true, d->isFloatingType());
const Variable *ld = db->getVariableFromVarId(3);
ASSERT(ld != nullptr);
ASSERT_EQUALS("ld", ld->nameToken()->str());
ASSERT_EQUALS(true, ld->isFloatingType());
}
{
GET_SYMBOL_DB("void f() { float * f; static const float * scf; }");
const Variable *f = db->getVariableFromVarId(1);
ASSERT(f != nullptr);
ASSERT_EQUALS("f", f->nameToken()->str());
ASSERT_EQUALS(true, f->isFloatingType());
ASSERT_EQUALS(true, f->isArrayOrPointer());
const Variable *scf = db->getVariableFromVarId(2);
ASSERT(scf != nullptr);
ASSERT_EQUALS("scf", scf->nameToken()->str());
ASSERT_EQUALS(true, scf->isFloatingType());
ASSERT_EQUALS(true, scf->isArrayOrPointer());
}
{
GET_SYMBOL_DB("void f() { float fa[42]; }");
const Variable *fa = db->getVariableFromVarId(1);
ASSERT(fa != nullptr);
ASSERT_EQUALS("fa", fa->nameToken()->str());
ASSERT_EQUALS(true, fa->isFloatingType());
ASSERT_EQUALS(true, fa->isArrayOrPointer());
}
}
void varTypesOther() {
GET_SYMBOL_DB("void f() { class A {} a; void *b; }");
const Variable *a = db->getVariableFromVarId(1);
ASSERT(a != nullptr);
ASSERT_EQUALS("a", a->nameToken()->str());
ASSERT_EQUALS(false, a->isFloatingType());
const Variable *b = db->getVariableFromVarId(2);
ASSERT(b != nullptr);
ASSERT_EQUALS("b", b->nameToken()->str());
ASSERT_EQUALS(false, b->isFloatingType());
}
void functionPrototype() {
check("int foo(int x) {\n"
" extern int func1();\n"
" extern int func2(int);\n"
" int func3();\n"
" int func4(int);\n"
" return func4(x);\n"
"}\n", true);
ASSERT_EQUALS("", errout_str());
}
void lambda() {
GET_SYMBOL_DB("void func() {\n"
" float y = 0.0f;\n"
" auto lambda = [&]()\n"
" {\n"
" float x = 1.0f;\n"
" y += 10.0f - x;\n"
" }\n"
" lambda();\n"
"}");
ASSERT(db && db->scopeList.size() == 3);
auto scope = db->scopeList.cbegin();
ASSERT_EQUALS(Scope::eGlobal, scope->type);
++scope;
ASSERT_EQUALS(Scope::eFunction, scope->type);
++scope;
ASSERT_EQUALS(Scope::eLambda, scope->type);
}
void lambda2() {
GET_SYMBOL_DB("void func() {\n"
" float y = 0.0f;\n"
" auto lambda = [&]() -> bool\n"
" {\n"
" float x = 1.0f;\n"
" };\n"
" lambda();\n"
"}");
ASSERT(db && db->scopeList.size() == 3);
auto scope = db->scopeList.cbegin();
ASSERT_EQUALS(Scope::eGlobal, scope->type);
++scope;
ASSERT_EQUALS(Scope::eFunction, scope->type);
++scope;
ASSERT_EQUALS(Scope::eLambda, scope->type);
}
void lambda3() {
GET_SYMBOL_DB("void func() {\n"
" auto f = []() mutable {};\n"
"}");
ASSERT(db && db->scopeList.size() == 3);
auto scope = db->scopeList.cbegin();
ASSERT_EQUALS(Scope::eGlobal, scope->type);
++scope;
ASSERT_EQUALS(Scope::eFunction, scope->type);
++scope;
ASSERT_EQUALS(Scope::eLambda, scope->type);
}
void lambda4() { // #11719
GET_SYMBOL_DB("struct S { int* p; };\n"
"auto g = []() {\n"
" S s;\n"
" s.p = new int;\n"
"};\n");
ASSERT(db && db->scopeList.size() == 3);
auto scope = db->scopeList.cbegin();
ASSERT_EQUALS(Scope::eGlobal, scope->type);
++scope;
ASSERT_EQUALS(Scope::eStruct, scope->type);
++scope;
ASSERT_EQUALS(Scope::eLambda, scope->type);
ASSERT_EQUALS(1, scope->varlist.size());
const Variable& s = scope->varlist.front();
ASSERT_EQUALS(s.name(), "s");
ASSERT(s.type());
--scope;
ASSERT_EQUALS(s.type()->classScope, &*scope);
}
void lambda5() { // #11275
GET_SYMBOL_DB("int* f() {\n"
" auto g = []<typename T>() {\n"
" return true;\n"
" };\n"
" return nullptr;\n"
"}\n");
ASSERT(db && db->scopeList.size() == 3);
auto scope = db->scopeList.cbegin();
ASSERT_EQUALS(Scope::eGlobal, scope->type);
++scope;
ASSERT_EQUALS(Scope::eFunction, scope->type);
++scope;
ASSERT_EQUALS(Scope::eLambda, scope->type);
const Token* ret = Token::findsimplematch(tokenizer.tokens(), "return true");
ASSERT(ret && ret->scope());
ASSERT_EQUALS(ret->scope()->type, Scope::eLambda);
}
// #6298 "stack overflow in Scope::findFunctionInBase (endless recursion)"
void circularDependencies() {
check("template<template<class> class E,class D> class C : E<D> {\n"
" public:\n"
" int f();\n"
"};\n"
"class E : C<D,int> {\n"
" public:\n"
" int f() { return C< ::D,int>::f(); }\n"
"};\n"
"int main() {\n"
" E c;\n"
" c.f();\n"
"}");
}
void executableScopeWithUnknownFunction() {
{
GET_SYMBOL_DB("class Fred {\n"
" void foo(const std::string & a = \"\");\n"
"};\n"
"Fred::foo(const std::string & b) { }");
ASSERT(db && db->scopeList.size() == 3);
auto scope = db->scopeList.cbegin();
ASSERT_EQUALS(Scope::eGlobal, scope->type);
++scope;
ASSERT_EQUALS(Scope::eClass, scope->type);
const Scope* class_scope = &*scope;
++scope;
ASSERT(class_scope->functionList.size() == 1);
ASSERT(class_scope->functionList.cbegin()->hasBody());
ASSERT(class_scope->functionList.cbegin()->functionScope == &*scope);
}
{
GET_SYMBOL_DB("bool f(bool (*g)(int));\n"
"bool f(bool (*g)(int)) { return g(0); }\n");
ASSERT(db && db->scopeList.size() == 2);
auto scope = db->scopeList.cbegin();
ASSERT_EQUALS(Scope::eGlobal, scope->type);
ASSERT(scope->functionList.size() == 1);
++scope;
ASSERT_EQUALS(Scope::eFunction, scope->type);
}
}
#define typeOf(...) typeOf_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
std::string typeOf_(const char* file, int line, const char (&code)[size], const char pattern[], bool cpp = true, const Settings *settings = nullptr) {
SimpleTokenizer tokenizer(settings ? *settings : settings2, *this);
ASSERT_LOC(tokenizer.tokenize(code, cpp), file, line);
const Token* tok;
for (tok = tokenizer.list.back(); tok; tok = tok->previous())
if (Token::simpleMatch(tok, pattern, strlen(pattern)))
break;
return tok->valueType() ? tok->valueType()->str() : std::string();
}
void valueType1() {
// stringification
ASSERT_EQUALS("", ValueType().str());
/*const*/ Settings s;
s.platform.int_bit = 16;
s.platform.long_bit = 32;
s.platform.long_long_bit = 64;
/*const*/ Settings sSameSize;
sSameSize.platform.int_bit = 32;
sSameSize.platform.long_bit = 64;
sSameSize.platform.long_long_bit = 64;
// numbers
ASSERT_EQUALS("signed int", typeOf("1;", "1", false, &s));
ASSERT_EQUALS("signed int", typeOf("(-1);", "-1", false, &s));
ASSERT_EQUALS("signed int", typeOf("32767;", "32767", false, &s));
ASSERT_EQUALS("signed int", typeOf("(-32767);", "-32767", false, &s));
ASSERT_EQUALS("signed long", typeOf("32768;", "32768", false, &s));
ASSERT_EQUALS("signed long", typeOf("(-32768);", "-32768", false, &s));
ASSERT_EQUALS("signed long", typeOf("32768l;", "32768l", false, &s));
ASSERT_EQUALS("unsigned int", typeOf("32768U;", "32768U", false, &s));
ASSERT_EQUALS("signed long long", typeOf("2147483648;", "2147483648", false, &s));
ASSERT_EQUALS("unsigned long", typeOf("2147483648u;", "2147483648u", false, &s));
ASSERT_EQUALS("signed long long", typeOf("2147483648L;", "2147483648L", false, &s));
ASSERT_EQUALS("unsigned long long", typeOf("18446744069414584320;", "18446744069414584320", false, &s));
ASSERT_EQUALS("signed int", typeOf("0xFF;", "0xFF", false, &s));
ASSERT_EQUALS("unsigned int", typeOf("0xFFU;", "0xFFU", false, &s));
ASSERT_EQUALS("unsigned int", typeOf("0xFFFF;", "0xFFFF", false, &s));
ASSERT_EQUALS("signed long", typeOf("0xFFFFFF;", "0xFFFFFF", false, &s));
ASSERT_EQUALS("unsigned long", typeOf("0xFFFFFFU;", "0xFFFFFFU", false, &s));
ASSERT_EQUALS("unsigned long", typeOf("0xFFFFFFFF;", "0xFFFFFFFF", false, &s));
ASSERT_EQUALS("signed long long", typeOf("0xFFFFFFFFFFFF;", "0xFFFFFFFFFFFF", false, &s));
ASSERT_EQUALS("unsigned long long", typeOf("0xFFFFFFFFFFFFU;", "0xFFFFFFFFFFFFU", false, &s));
ASSERT_EQUALS("unsigned long long", typeOf("0xFFFFFFFF00000000;", "0xFFFFFFFF00000000", false, &s));
ASSERT_EQUALS("signed long", typeOf("2147483648;", "2147483648", false, &sSameSize));
ASSERT_EQUALS("unsigned long", typeOf("0xc000000000000000;", "0xc000000000000000", false, &sSameSize));
ASSERT_EQUALS("unsigned int", typeOf("1U;", "1U"));
ASSERT_EQUALS("signed long", typeOf("1L;", "1L"));
ASSERT_EQUALS("unsigned long", typeOf("1UL;", "1UL"));
ASSERT_EQUALS("signed long long", typeOf("1LL;", "1LL"));
ASSERT_EQUALS("unsigned long long", typeOf("1ULL;", "1ULL"));
ASSERT_EQUALS("unsigned long long", typeOf("1LLU;", "1LLU"));
ASSERT_EQUALS("signed long long", typeOf("1i64;", "1i64"));
ASSERT_EQUALS("unsigned long long", typeOf("1ui64;", "1ui64"));
ASSERT_EQUALS("unsigned int", typeOf("1u;", "1u"));
ASSERT_EQUALS("signed long", typeOf("1l;", "1l"));
ASSERT_EQUALS("unsigned long", typeOf("1ul;", "1ul"));
ASSERT_EQUALS("signed long long", typeOf("1ll;", "1ll"));
ASSERT_EQUALS("unsigned long long", typeOf("1ull;", "1ull"));
ASSERT_EQUALS("unsigned long long", typeOf("1llu;", "1llu"));
ASSERT_EQUALS("signed int", typeOf("01;", "01"));
ASSERT_EQUALS("unsigned int", typeOf("01U;", "01U"));
ASSERT_EQUALS("signed long", typeOf("01L;", "01L"));
ASSERT_EQUALS("unsigned long", typeOf("01UL;", "01UL"));
ASSERT_EQUALS("signed long long", typeOf("01LL;", "01LL"));
ASSERT_EQUALS("unsigned long long", typeOf("01ULL;", "01ULL"));
ASSERT_EQUALS("signed int", typeOf("0B1;", "0B1"));
ASSERT_EQUALS("signed int", typeOf("0b1;", "0b1"));
ASSERT_EQUALS("unsigned int", typeOf("0b1U;", "0b1U"));
ASSERT_EQUALS("signed long", typeOf("0b1L;", "0b1L"));
ASSERT_EQUALS("unsigned long", typeOf("0b1UL;", "0b1UL"));
ASSERT_EQUALS("signed long long", typeOf("0b1LL;", "0b1LL"));
ASSERT_EQUALS("unsigned long long", typeOf("0b1ULL;", "0b1ULL"));
ASSERT_EQUALS("float", typeOf("1.0F;", "1.0F"));
ASSERT_EQUALS("float", typeOf("1.0f;", "1.0f"));
ASSERT_EQUALS("double", typeOf("1.0;", "1.0"));
ASSERT_EQUALS("double", typeOf("1E3;", "1E3"));
ASSERT_EQUALS("double", typeOf("0x1.2p3;", "0x1.2p3"));
ASSERT_EQUALS("long double", typeOf("1.23L;", "1.23L"));
ASSERT_EQUALS("long double", typeOf("1.23l;", "1.23l"));
// Constant calculations
ASSERT_EQUALS("signed int", typeOf("1 + 2;", "+"));
ASSERT_EQUALS("signed long", typeOf("1L + 2;", "+"));
ASSERT_EQUALS("signed long long", typeOf("1LL + 2;", "+"));
ASSERT_EQUALS("float", typeOf("1.2f + 3;", "+"));
ASSERT_EQUALS("float", typeOf("1 + 2.3f;", "+"));
// promotions
ASSERT_EQUALS("signed int", typeOf("(char)1 + (char)2;", "+"));
ASSERT_EQUALS("signed int", typeOf("(short)1 + (short)2;", "+"));
ASSERT_EQUALS("signed int", typeOf("(signed int)1 + (signed char)2;", "+"));
ASSERT_EQUALS("signed int", typeOf("(signed int)1 + (unsigned char)2;", "+"));
ASSERT_EQUALS("unsigned int", typeOf("(unsigned int)1 + (signed char)2;", "+"));
ASSERT_EQUALS("unsigned int", typeOf("(unsigned int)1 + (unsigned char)2;", "+"));
ASSERT_EQUALS("unsigned int", typeOf("(unsigned int)1 + (signed int)2;", "+"));
ASSERT_EQUALS("unsigned int", typeOf("(unsigned int)1 + (unsigned int)2;", "+"));
ASSERT_EQUALS("signed long", typeOf("(signed long)1 + (unsigned int)2;", "+"));
ASSERT_EQUALS("unsigned long", typeOf("(unsigned long)1 + (signed int)2;", "+"));
// char
ASSERT_EQUALS("char", typeOf("'a';", "'a'", true));
ASSERT_EQUALS("char", typeOf("'\\\'';", "'\\\''", true));
ASSERT_EQUALS("signed int", typeOf("'a';", "'a'", false));
ASSERT_EQUALS("wchar_t", typeOf("L'a';", "L'a'", true));
ASSERT_EQUALS("wchar_t", typeOf("L'a';", "L'a'", false));
ASSERT_EQUALS("signed int", typeOf("'aaa';", "'aaa'", true));
ASSERT_EQUALS("signed int", typeOf("'aaa';", "'aaa'", false));
// char *
ASSERT_EQUALS("const char *", typeOf("\"hello\" + 1;", "+"));
ASSERT_EQUALS("const char", typeOf("\"hello\"[1];", "["));
ASSERT_EQUALS("const char", typeOf(";*\"hello\";", "*"));
ASSERT_EQUALS("const wchar_t *", typeOf("L\"hello\" + 1;", "+"));
// Variable calculations
ASSERT_EQUALS("void *", typeOf("void *p; a = p + 1;", "+"));
ASSERT_EQUALS("signed int", typeOf("int x; a = x + 1;", "+"));
ASSERT_EQUALS("signed int", typeOf("int x; a = x | 1;", "|"));
ASSERT_EQUALS("float", typeOf("float x; a = x + 1;", "+"));
ASSERT_EQUALS("signed int", typeOf("signed x; a = x + 1;", "x +"));
ASSERT_EQUALS("unsigned int", typeOf("unsigned x; a = x + 1;", "x +"));
ASSERT_EQUALS("unsigned int", typeOf("unsigned int u1, u2; a = u1 + 1;", "u1 +"));
ASSERT_EQUALS("unsigned int", typeOf("unsigned int u1, u2; a = u1 + 1U;", "u1 +"));
ASSERT_EQUALS("unsigned int", typeOf("unsigned int u1, u2; a = u1 + u2;", "u1 +"));
ASSERT_EQUALS("unsigned int", typeOf("unsigned int u1, u2; a = u1 * 2;", "u1 *"));
ASSERT_EQUALS("unsigned int", typeOf("unsigned int u1, u2; a = u1 * u2;", "u1 *"));
ASSERT_EQUALS("signed int *", typeOf("int x; a = &x;", "&"));
ASSERT_EQUALS("signed int *", typeOf("int x; a = &x;", "&"));
ASSERT_EQUALS("long double", typeOf("long double x; dostuff(x,1);", "x ,"));
ASSERT_EQUALS("long double *", typeOf("long double x; dostuff(&x,1);", "& x ,"));
ASSERT_EQUALS("signed int", typeOf("struct X {int i;}; void f(struct X x) { x.i }", "."));
ASSERT_EQUALS("signed int *", typeOf("int *p; a = p++;", "++"));
ASSERT_EQUALS("signed int", typeOf("int x; a = x++;", "++"));
ASSERT_EQUALS("signed int *", typeOf("enum AB {A,B}; AB *ab; x=ab+2;", "+"));
ASSERT_EQUALS("signed int *", typeOf("enum AB {A,B}; enum AB *ab; x=ab+2;", "+"));
ASSERT_EQUALS("AB *", typeOf("struct AB {int a; int b;}; AB ab; x=&ab;", "&"));
ASSERT_EQUALS("AB *", typeOf("struct AB {int a; int b;}; struct AB ab; x=&ab;", "&"));
ASSERT_EQUALS("A::BC *", typeOf("namespace A { struct BC { int b; int c; }; }; struct A::BC abc; x=&abc;", "&"));
ASSERT_EQUALS("A::BC *", typeOf("namespace A { struct BC { int b; int c; }; }; struct A::BC *abc; x=abc+1;", "+"));
ASSERT_EQUALS("signed int", typeOf("auto a(int& x, int& y) { return x + y; }", "+"));
ASSERT_EQUALS("signed int", typeOf("auto a(int& x) { return x << 1; }", "<<"));
ASSERT_EQUALS("signed int", typeOf("void a(int& x, int& y) { x = y; }", "=")); //Debatably this should be a signed int & but we'll stick with the current behavior for now
ASSERT_EQUALS("signed int", typeOf("auto a(int* y) { return *y; }", "*")); //Debatably this should be a signed int & but we'll stick with the current behavior for now
// Unary arithmetic/bit operators
ASSERT_EQUALS("signed int", typeOf("int x; a = -x;", "-"));
ASSERT_EQUALS("signed int", typeOf("int x; a = ~x;", "~"));
ASSERT_EQUALS("double", typeOf("double x; a = -x;", "-"));
// Ternary operator
ASSERT_EQUALS("signed int", typeOf("int x; a = (b ? x : x);", "?"));
ASSERT_EQUALS("", typeOf("int x; a = (b ? x : y);", "?"));
ASSERT_EQUALS("double", typeOf("int x; double y; a = (b ? x : y);", "?"));
ASSERT_EQUALS("const char *", typeOf("int x; double y; a = (b ? \"a\" : \"b\");", "?"));
ASSERT_EQUALS("", typeOf("int x; double y; a = (b ? \"a\" : std::string(\"b\"));", "?"));
ASSERT_EQUALS("bool", typeOf("int x; a = (b ? false : true);", "?"));
// Boolean operators/literals
ASSERT_EQUALS("bool", typeOf("a > b;", ">"));
ASSERT_EQUALS("bool", typeOf(";!b;", "!"));
ASSERT_EQUALS("bool", typeOf("c = a && b;", "&&"));
ASSERT_EQUALS("bool", typeOf("a = false;", "false"));
ASSERT_EQUALS("bool", typeOf("a = true;", "true"));
// shift => result has same type as lhs
ASSERT_EQUALS("signed int", typeOf("int x; a = x << 1U;", "<<"));
ASSERT_EQUALS("signed int", typeOf("int x; a = x >> 1U;", ">>"));
ASSERT_EQUALS("", typeOf("a = 12 >> x;", ">>", true)); // >> might be overloaded
ASSERT_EQUALS("signed int", typeOf("a = 12 >> x;", ">>", false));
ASSERT_EQUALS("", typeOf("a = 12 << x;", "<<", true)); // << might be overloaded
ASSERT_EQUALS("signed int", typeOf("a = 12 << x;", "<<", false));
ASSERT_EQUALS("signed int", typeOf("a = true << 1U;", "<<"));
// assignment => result has same type as lhs
ASSERT_EQUALS("unsigned short", typeOf("unsigned short x; x = 3;", "="));
// array..
ASSERT_EQUALS("void * *", typeOf("void * x[10]; a = x + 0;", "+"));
ASSERT_EQUALS("signed int *", typeOf("int x[10]; a = x + 1;", "+"));
ASSERT_EQUALS("signed int", typeOf("int x[10]; a = x[0] + 1;", "+"));
ASSERT_EQUALS("", typeOf("a = x[\"hello\"];", "[", true));
ASSERT_EQUALS("const char", typeOf("a = x[\"hello\"];", "[", false));
ASSERT_EQUALS("signed int *", typeOf("int x[10]; a = &x;", "&"));
ASSERT_EQUALS("signed int *", typeOf("int x[10]; a = &x[1];", "&"));
// cast..
ASSERT_EQUALS("void *", typeOf("a = (void *)0;", "("));
ASSERT_EQUALS("char", typeOf("a = (char)32;", "("));
ASSERT_EQUALS("signed long", typeOf("a = (long)32;", "("));
ASSERT_EQUALS("signed long", typeOf("a = (long int)32;", "("));
ASSERT_EQUALS("signed long long", typeOf("a = (long long)32;", "("));
ASSERT_EQUALS("long double", typeOf("a = (long double)32;", "("));
ASSERT_EQUALS("char", typeOf("a = static_cast<char>(32);", "("));
ASSERT_EQUALS("", typeOf("a = (unsigned x)0;", "("));
ASSERT_EQUALS("unsigned int", typeOf("a = unsigned(123);", "("));
// sizeof..
ASSERT_EQUALS("char", typeOf("sizeof(char);", "char"));
// const..
ASSERT_EQUALS("const char *", typeOf("a = \"123\";", "\"123\""));
ASSERT_EQUALS("const signed int *", typeOf("const int *a; x = a + 1;", "a +"));
ASSERT_EQUALS("signed int * const", typeOf("int * const a; x = a + 1;", "+"));
ASSERT_EQUALS("const signed int *", typeOf("const int a[20]; x = a + 1;", "+"));
ASSERT_EQUALS("const signed int *", typeOf("const int x; a = &x;", "&"));
ASSERT_EQUALS("signed int", typeOf("int * const a; x = *a;", "*"));
ASSERT_EQUALS("const signed int", typeOf("const int * const a; x = *a;", "*"));
// function call..
ASSERT_EQUALS("signed int", typeOf("int a(int); a(5);", "( 5"));
ASSERT_EQUALS("signed int", typeOf("auto a(int) -> int; a(5);", "( 5"));
ASSERT_EQUALS("unsigned long", typeOf("sizeof(x);", "("));
ASSERT_EQUALS("signed int", typeOf("int (*a)(int); a(5);", "( 5"));
ASSERT_EQUALS("s", typeOf("struct s { s foo(); s(int, int); }; s s::foo() { return s(1, 2); } ", "( 1 , 2 )"));
// Some standard template functions.. TODO library configuration
ASSERT_EQUALS("signed int &&", typeOf("std::move(5);", "( 5 )"));
ASSERT_EQUALS("signed int", typeOf("using F = int(int*); F* f; f(ptr);", "( ptr")); // #9792
// calling constructor..
ASSERT_EQUALS("s", typeOf("struct s { s(int); }; s::s(int){} void foo() { throw s(1); } ", "( 1 )")); // #13100
// struct member..
ASSERT_EQUALS("signed int", typeOf("struct AB { int a; int b; } ab; x = ab.a;", "."));
ASSERT_EQUALS("signed int", typeOf("struct AB { int a; int b; } *ab; x = ab[1].a;", "."));
// Overloaded operators
ASSERT_EQUALS("Fred &", typeOf("class Fred { Fred& operator<(int); }; void f() { Fred fred; x=fred<123; }", "<"));
// Static members
ASSERT_EQUALS("signed int", typeOf("struct AB { static int a; }; x = AB::a;", "::"));
// Pointer to unknown type
ASSERT_EQUALS("*", typeOf("Bar* b;", "b"));
// Enum
ASSERT_EQUALS("char", typeOf("enum E : char { }; void foo() { E e[3]; bar(e[0]); }", "[ 0"));
ASSERT_EQUALS("signed char", typeOf("enum E : signed char { }; void foo() { E e[3]; bar(e[0]); }", "[ 0"));
ASSERT_EQUALS("unsigned char", typeOf("enum E : unsigned char { }; void foo() { E e[3]; bar(e[0]); }", "[ 0"));
ASSERT_EQUALS("signed short", typeOf("enum E : short { }; void foo() { E e[3]; bar(e[0]); }", "[ 0"));
ASSERT_EQUALS("unsigned short", typeOf("enum E : unsigned short { }; void foo() { E e[3]; bar(e[0]); }", "[ 0"));
ASSERT_EQUALS("signed int", typeOf("enum E : int { }; void foo() { E e[3]; bar(e[0]); }", "[ 0"));
ASSERT_EQUALS("unsigned int", typeOf("enum E : unsigned int { }; void foo() { E e[3]; bar(e[0]); }", "[ 0"));
ASSERT_EQUALS("signed long", typeOf("enum E : long { }; void foo() { E e[3]; bar(e[0]); }", "[ 0"));
ASSERT_EQUALS("unsigned long", typeOf("enum E : unsigned long { }; void foo() { E e[3]; bar(e[0]); }", "[ 0"));
ASSERT_EQUALS("signed long long", typeOf("enum E : long long { }; void foo() { E e[3]; bar(e[0]); }", "[ 0"));
ASSERT_EQUALS("unsigned long long", typeOf("enum E : unsigned long long { }; void foo() { E e[3]; bar(e[0]); }", "[ 0"));
#define CHECK_LIBRARY_FUNCTION_RETURN_TYPE(type) do { \
const char xmldata[] = "<?xml version=\"1.0\"?>\n" \
"<def>\n" \
"<function name=\"g\">\n" \
"<returnValue type=\"" #type "\"/>\n" \
"</function>\n" \
"</def>"; \
const Settings sF = settingsBuilder().libraryxml(xmldata, sizeof(xmldata)).build(); \
ASSERT_EQUALS(#type, typeOf("void f() { auto x = g(); }", "x", true, &sF)); \
} while (false)
// *INDENT-OFF*
CHECK_LIBRARY_FUNCTION_RETURN_TYPE(bool);
CHECK_LIBRARY_FUNCTION_RETURN_TYPE(signed char);
CHECK_LIBRARY_FUNCTION_RETURN_TYPE(unsigned char);
CHECK_LIBRARY_FUNCTION_RETURN_TYPE(signed short);
CHECK_LIBRARY_FUNCTION_RETURN_TYPE(unsigned short);
CHECK_LIBRARY_FUNCTION_RETURN_TYPE(signed int);
CHECK_LIBRARY_FUNCTION_RETURN_TYPE(unsigned int);
CHECK_LIBRARY_FUNCTION_RETURN_TYPE(signed long);
CHECK_LIBRARY_FUNCTION_RETURN_TYPE(unsigned long);
CHECK_LIBRARY_FUNCTION_RETURN_TYPE(signed long long);
CHECK_LIBRARY_FUNCTION_RETURN_TYPE(unsigned long long);
CHECK_LIBRARY_FUNCTION_RETURN_TYPE(void *);
CHECK_LIBRARY_FUNCTION_RETURN_TYPE(void * *);
CHECK_LIBRARY_FUNCTION_RETURN_TYPE(const void *);
// *INDENT-ON*
#undef CHECK_LIBRARY_FUNCTION_RETURN_TYPE
// Library types
{
// Char types
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <podtype name=\"char8_t\" sign=\"u\" size=\"1\"/>\n"
" <podtype name=\"char16_t\" sign=\"u\" size=\"2\"/>\n"
" <podtype name=\"char32_t\" sign=\"u\" size=\"4\"/>\n"
"</def>";
/*const*/ Settings settings = settingsBuilder().libraryxml(xmldata, sizeof(xmldata)).build();
settings.platform.sizeof_short = 2;
settings.platform.sizeof_int = 4;
ASSERT_EQUALS("unsigned char", typeOf("u8'a';", "u8'a'", true, &settings));
ASSERT_EQUALS("unsigned short", typeOf("u'a';", "u'a'", true, &settings));
ASSERT_EQUALS("unsigned int", typeOf("U'a';", "U'a'", true, &settings));
ASSERT_EQUALS("const unsigned char *", typeOf("u8\"a\";", "u8\"a\"", true, &settings));
ASSERT_EQUALS("const unsigned short *", typeOf("u\"a\";", "u\"a\"", true, &settings));
ASSERT_EQUALS("const unsigned int *", typeOf("U\"a\";", "U\"a\"", true, &settings));
}
{
// PodType
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <podtype name=\"u32\" sign=\"u\" size=\"4\"/>\n"
" <podtype name=\"xyz::x\" sign=\"u\" size=\"4\"/>\n"
" <podtype name=\"podtype2\" sign=\"u\" size=\"0\" stdtype=\"int\"/>\n"
"</def>";
const Settings settingsWin64 = settingsBuilder().platform(Platform::Type::Win64).libraryxml(xmldata, sizeof(xmldata)).build();
ValueType vt;
ASSERT_EQUALS(true, vt.fromLibraryType("u32", settingsWin64));
ASSERT_EQUALS(true, vt.fromLibraryType("xyz::x", settingsWin64));
ASSERT_EQUALS(ValueType::Type::INT, vt.type);
ValueType vt2;
ASSERT_EQUALS(true, vt2.fromLibraryType("podtype2", settingsWin64));
ASSERT_EQUALS(ValueType::Type::INT, vt2.type);
ASSERT_EQUALS("unsigned int *", typeOf(";void *data = new u32[10];", "new", true, &settingsWin64));
ASSERT_EQUALS("unsigned int *", typeOf(";void *data = new xyz::x[10];", "new", true, &settingsWin64));
ASSERT_EQUALS("unsigned int", typeOf("; x = (xyz::x)12;", "(", true, &settingsWin64));
ASSERT_EQUALS("unsigned int", typeOf(";u32(12);", "(", true, &settingsWin64));
ASSERT_EQUALS("unsigned int", typeOf("x = u32(y[i]);", "(", true, &settingsWin64));
}
{
// PlatformType
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <platformtype name=\"s32\" value=\"int\">\n"
" <platform type=\"unix32\"/>\n"
" </platformtype>\n"
"</def>";
const Settings settingsUnix32 = settingsBuilder().platform(Platform::Type::Unix32).libraryxml(xmldata, sizeof(xmldata)).build();
ValueType vt;
ASSERT_EQUALS(true, vt.fromLibraryType("s32", settingsUnix32));
ASSERT_EQUALS(ValueType::Type::INT, vt.type);
}
{
// PlatformType - wchar_t
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <platformtype name=\"LPCTSTR\" value=\"wchar_t\">\n"
" <platform type=\"win64\"/>\n"
" </platformtype>\n"
"</def>";
const Settings settingsWin64 = settingsBuilder().platform(Platform::Type::Win64).libraryxml(xmldata, sizeof(xmldata)).build();
ValueType vt;
ASSERT_EQUALS(true, vt.fromLibraryType("LPCTSTR", settingsWin64));
ASSERT_EQUALS(ValueType::Type::WCHAR_T, vt.type);
}
{
// Container
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <container id=\"C\" startPattern=\"C\"/>\n"
"</def>";
const Settings sC = settingsBuilder().libraryxml(xmldata, sizeof(xmldata)).build();
ASSERT_EQUALS("container(C) *", typeOf("C*c=new C;","new",true,&sC));
ASSERT_EQUALS("container(C) *", typeOf("x=(C*)c;","(",true,&sC));
ASSERT_EQUALS("container(C)", typeOf("C c = C();","(",true,&sC));
}
{
// Container (vector)
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <container id=\"Vector\" startPattern=\"Vector <\">\n"
" <type templateParameter=\"0\"/>\n"
" <access indexOperator=\"array-like\">\n"
" <function name=\"front\" yields=\"item\"/>\n"
" <function name=\"data\" yields=\"buffer\"/>\n"
" <function name=\"begin\" yields=\"start-iterator\"/>\n"
" </access>\n"
" </container>\n"
" <container id=\"test::string\" startPattern=\"test :: string\">\n"
" <type string=\"std-like\"/>\n"
" <access indexOperator=\"array-like\"/>\n"
" </container>\n"
"</def>";
const Settings set = settingsBuilder().libraryxml(xmldata, sizeof(xmldata)).build();
ASSERT_EQUALS("signed int", typeOf("Vector<int> v; v[0]=3;", "[", true, &set));
ASSERT_EQUALS("container(test :: string)", typeOf("{return test::string();}", "(", true, &set));
ASSERT_EQUALS(
"container(test :: string)",
typeOf("void foo(Vector<test::string> v) { for (auto s: v) { x=s+s; } }", "s", true, &set));
ASSERT_EQUALS(
"container(test :: string)",
typeOf("void foo(Vector<test::string> v) { for (auto s: v) { x=s+s; } }", "+", true, &set));
ASSERT_EQUALS("container(test :: string) &",
typeOf("Vector<test::string> v; x = v.front();", "(", true, &set));
ASSERT_EQUALS("container(test :: string) *",
typeOf("Vector<test::string> v; x = v.data();", "(", true, &set));
ASSERT_EQUALS("signed int &", typeOf("Vector<int> v; x = v.front();", "(", true, &set));
ASSERT_EQUALS("signed int *", typeOf("Vector<int> v; x = v.data();", "(", true, &set));
ASSERT_EQUALS("signed int * *", typeOf("Vector<int*> v; x = v.data();", "(", true, &set));
ASSERT_EQUALS("iterator(Vector <)", typeOf("Vector<int> v; x = v.begin();", "(", true, &set));
ASSERT_EQUALS("signed int &", typeOf("Vector<int> v; x = *v.begin();", "*", true, &set));
ASSERT_EQUALS("container(test :: string)",
typeOf("void foo(){test::string s; return \"x\"+s;}", "+", true, &set));
ASSERT_EQUALS("container(test :: string)",
typeOf("void foo(){test::string s; return s+\"x\";}", "+", true, &set));
ASSERT_EQUALS("container(test :: string)",
typeOf("void foo(){test::string s; return 'x'+s;}", "+", true, &set));
ASSERT_EQUALS("container(test :: string)",
typeOf("void foo(){test::string s; return s+'x';}", "+", true, &set));
}
// new
ASSERT_EQUALS("C *", typeOf("class C {}; x = new C();", "new"));
// auto variables
ASSERT_EQUALS("signed int", typeOf("; auto x = 3;", "x"));
ASSERT_EQUALS("signed int *", typeOf("; auto *p = (int *)0;", "p"));
ASSERT_EQUALS("const signed int *", typeOf("; auto *p = (const int *)0;", "p"));
ASSERT_EQUALS("const signed int *", typeOf("; auto *p = (constexpr int *)0;", "p"));
ASSERT_EQUALS("const signed int *", typeOf("; const auto *p = (int *)0;", "p"));
ASSERT_EQUALS("const signed int *", typeOf("; constexpr auto *p = (int *)0;", "p"));
ASSERT_EQUALS("const signed int *", typeOf("; const auto *p = (const int *)0;", "p"));
ASSERT_EQUALS("const signed int *", typeOf("; constexpr auto *p = (constexpr int *)0;", "p"));
ASSERT_EQUALS("const signed int *", typeOf("; const constexpr auto *p = (int *)0;", "p"));
ASSERT_EQUALS("signed int *", typeOf("; auto data = new int[100];", "data"));
ASSERT_EQUALS("signed int", typeOf("; auto data = new X::Y; int x=1000; x=x/5;", "/")); // #7970
ASSERT_EQUALS("signed int *", typeOf("; auto data = new (nothrow) int[100];", "data"));
ASSERT_EQUALS("signed int *", typeOf("; auto data = new (std::nothrow) int[100];", "data"));
ASSERT_EQUALS("const signed short", typeOf("short values[10]; void f() { for (const auto x : values); }", "x"));
ASSERT_EQUALS("const signed short &", typeOf("short values[10]; void f() { for (const auto& x : values); }", "x"));
ASSERT_EQUALS("signed short &", typeOf("short values[10]; void f() { for (auto& x : values); }", "x"));
ASSERT_EQUALS("signed int * &", typeOf("int* values[10]; void f() { for (auto& p : values); }", "p"));
ASSERT_EQUALS("signed int * const &", typeOf("int* values[10]; void f() { for (const auto& p : values); }", "p"));
ASSERT_EQUALS("const signed int *", typeOf("int* values[10]; void f() { for (const auto* p : values); }", "p"));
ASSERT_EQUALS("const signed int", typeOf("; const auto x = 3;", "x"));
ASSERT_EQUALS("const signed int", typeOf("; constexpr auto x = 3;", "x"));
ASSERT_EQUALS("const signed int", typeOf("; const constexpr auto x = 3;", "x"));
ASSERT_EQUALS("void * const", typeOf("typedef void* HWND; const HWND x = 0;", "x"));
// Variable declaration
ASSERT_EQUALS("char *", typeOf("; char abc[] = \"abc\";", "["));
ASSERT_EQUALS("", typeOf("; int x[10] = { [3]=1 };", "[ 3 ]"));
// std::make_shared
{
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <smart-pointer class-name=\"std::shared_ptr\"/>\n"
"</def>";
const Settings set = settingsBuilder().libraryxml(xmldata, sizeof(xmldata)).build();
ASSERT_EQUALS("smart-pointer(std::shared_ptr)",
typeOf("class C {}; x = std::make_shared<C>();", "(", true, &set));
}
// return
{
// Container
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <container id=\"C\" startPattern=\"C\"/>\n"
"</def>";
const Settings sC = settingsBuilder().libraryxml(xmldata, sizeof(xmldata)).build();
ASSERT_EQUALS("container(C)", typeOf("C f(char *p) { char data[10]; return data; }", "return", true, &sC));
}
// Smart pointer
{
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <smart-pointer class-name=\"MyPtr\"/>\n"
"</def>";
const Settings set = settingsBuilder().libraryxml(xmldata, sizeof(xmldata)).build();
ASSERT_EQUALS("smart-pointer(MyPtr)",
typeOf("void f() { MyPtr<int> p; return p; }", "p ;", true, &set));
ASSERT_EQUALS("signed int", typeOf("void f() { MyPtr<int> p; return *p; }", "* p ;", true, &set));
ASSERT_EQUALS("smart-pointer(MyPtr)", typeOf("void f() {return MyPtr<int>();}", "(", true, &set));
}
}
void valueType2() {
GET_SYMBOL_DB("int i;\n"
"bool b;\n"
"Unknown u;\n"
"std::string s;\n"
"std::vector<int> v;\n"
"std::map<int, void*>::const_iterator it;\n"
"void* p;\n"
"\n"
"void f() {\n"
" func(i, b, u, s, v, it, p);\n"
"}");
const Token* tok = tokenizer.tokens();
for (int i = 0; i < 2; i++) {
tok = Token::findsimplematch(tok, "i");
ASSERT(tok && tok->valueType());
ASSERT_EQUALS("signed int", tok->valueType()->str());
tok = Token::findsimplematch(tok, "b");
ASSERT(tok && tok->valueType());
ASSERT_EQUALS("bool", tok->valueType()->str());
tok = Token::findsimplematch(tok, "u");
ASSERT(tok && !tok->valueType());
tok = Token::findsimplematch(tok, "s");
ASSERT(tok && tok->valueType());
ASSERT_EQUALS("container(std :: string|wstring|u16string|u32string)", tok->valueType()->str());
ASSERT(tok->valueType()->container && tok->valueType()->container->stdStringLike);
tok = Token::findsimplematch(tok, "v");
ASSERT(tok && tok->valueType());
ASSERT_EQUALS("container(std :: vector <)", tok->valueType()->str());
ASSERT(tok->valueType()->container && !tok->valueType()->container->stdStringLike);
tok = Token::findsimplematch(tok, "it");
ASSERT(tok && tok->valueType());
ASSERT_EQUALS("iterator(std :: map|unordered_map <)", tok->valueType()->str());
}
}
void valueType3() {
{
GET_SYMBOL_DB("void f(std::vector<std::unordered_map<int, std::unordered_set<int>>>& v, int i, int j) {\n"
" auto& s = v[i][j];\n"
" s.insert(0);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
const Token* tok = tokenizer.tokens();
tok = Token::findsimplematch(tok, "s .");
ASSERT(tok && tok->valueType());
ASSERT_EQUALS("container(std :: set|unordered_set <) &", tok->valueType()->str());
}
{
GET_SYMBOL_DB("void f(std::vector<int> v) {\n"
" auto it = std::find(v.begin(), v.end(), 0);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
const Token* tok = tokenizer.tokens();
tok = Token::findsimplematch(tok, "auto");
ASSERT(tok && tok->valueType());
ASSERT_EQUALS("iterator(std :: vector <)", tok->valueType()->str());
}
{
GET_SYMBOL_DB("void f(std::vector<int>::iterator beg, std::vector<int>::iterator end) {\n"
" auto it = std::find(beg, end, 0);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
const Token* tok = tokenizer.tokens();
tok = Token::findsimplematch(tok, "auto");
ASSERT(tok && tok->valueType());
ASSERT_EQUALS("iterator(std :: vector <)", tok->valueType()->str());
}
{
GET_SYMBOL_DB("struct S {\n"
" S() {}\n"
" std::vector<std::shared_ptr<S>> v;\n"
" void f(int i) const;\n"
"};\n"
"void S::f(int i) const {\n"
" for (const auto& c : v)\n"
" c->f(i);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
const Token* tok = tokenizer.tokens();
tok = Token::findsimplematch(tok, "auto");
ASSERT(tok && tok->valueType() && tok->scope() && tok->scope()->functionOf);
const Type* smpType = tok->valueType()->smartPointerType;
ASSERT(smpType && smpType == tok->scope()->functionOf->definedType);
}
{
GET_SYMBOL_DB("struct S { int i; };\n"
"void f(const std::vector<S>& v) {\n"
" auto it = std::find_if(std::begin(v), std::end(v), [](const S& s) { return s.i != 0; });\n"
"}\n");
ASSERT_EQUALS("", errout_str());
const Token* tok = tokenizer.tokens();
tok = Token::findsimplematch(tok, "auto");
ASSERT(tok && tok->valueType());
ASSERT_EQUALS("iterator(std :: vector <)", tok->valueType()->str());
}
{
GET_SYMBOL_DB("struct S { std::vector<int> v; };\n"
"struct T { S s; };\n"
"void f(T* t) {\n"
" auto it = std::find(t->s.v.begin(), t->s.v.end(), 0);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
const Token* tok = tokenizer.tokens();
tok = Token::findsimplematch(tok, "auto");
ASSERT(tok && tok->valueType());
ASSERT_EQUALS("iterator(std :: vector <)", tok->valueType()->str());
}
{
GET_SYMBOL_DB("struct S { std::vector<int> v[1][1]; };\n"
"struct T { S s[1]; };\n"
"void f(T * t) {\n"
" auto it = std::find(t->s[0].v[0][0].begin(), t->s[0].v[0][0].end(), 0);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
const Token* tok = tokenizer.tokens();
tok = Token::findsimplematch(tok, "auto");
ASSERT(tok && tok->valueType());
ASSERT_EQUALS("iterator(std :: vector <)", tok->valueType()->str());
}
{
GET_SYMBOL_DB("std::vector<int>& g();\n"
"void f() {\n"
" auto it = std::find(g().begin(), g().end(), 0);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
const Token* tok = tokenizer.tokens();
tok = Token::findsimplematch(tok, "auto");
ASSERT(tok && tok->valueType());
ASSERT_EQUALS("iterator(std :: vector <)", tok->valueType()->str());
}
{
GET_SYMBOL_DB("struct T { std::set<std::string> s; };\n"
"struct U { std::shared_ptr<T> get(); };\n"
"void f(U* u) {\n"
" for (const auto& str : u->get()->s) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
const Token* tok = tokenizer.tokens();
tok = Token::findsimplematch(tok, "auto");
ASSERT(tok && tok->valueType());
ASSERT_EQUALS("const container(std :: string|wstring|u16string|u32string) &", tok->valueType()->str());
}
{
GET_SYMBOL_DB("void f(std::vector<int>& v) {\n"
" for (auto& i : v)\n"
" i = 0;\n"
" for (auto&& j : v)\n"
" j = 1;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
const Token* tok = tokenizer.tokens();
tok = Token::findsimplematch(tok, "auto &");
ASSERT(tok && tok->valueType());
ASSERT_EQUALS("signed int &", tok->valueType()->str());
tok = Token::findsimplematch(tok, "i :");
ASSERT(tok && tok->valueType());
ASSERT(tok->valueType()->reference == Reference::LValue);
tok = Token::findsimplematch(tok, "i =");
ASSERT(tok && tok->valueType());
ASSERT(tok->valueType()->reference == Reference::LValue);
tok = Token::findsimplematch(tok, "auto &&");
ASSERT(tok && tok->valueType());
ASSERT_EQUALS("signed int &&", tok->valueType()->str());
tok = Token::findsimplematch(tok, "j =");
ASSERT(tok && tok->valueType());
ASSERT(tok->valueType()->reference == Reference::RValue);
}
{
GET_SYMBOL_DB("void f(std::vector<int*>& v) {\n"
" for (const auto& p : v)\n"
" if (p == nullptr) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
const Token* tok = tokenizer.tokens();
tok = Token::findsimplematch(tok, "auto");
ASSERT(tok && tok->valueType());
ASSERT_EQUALS("signed int * const &", tok->valueType()->str());
tok = Token::findsimplematch(tok, "p :");
ASSERT(tok && tok->valueType());
ASSERT_EQUALS("signed int * const &", tok->valueType()->str());
ASSERT(tok->variable() && tok->variable()->valueType());
ASSERT_EQUALS("signed int * const &", tok->variable()->valueType()->str());
tok = Token::findsimplematch(tok, "p ==");
ASSERT(tok && tok->valueType());
ASSERT_EQUALS("signed int * const &", tok->valueType()->str());
ASSERT(tok->variable() && tok->variable()->valueType());
ASSERT_EQUALS("signed int * const &", tok->variable()->valueType()->str());
}
{
GET_SYMBOL_DB("auto a = 1;\n");
ASSERT_EQUALS("", errout_str());
const Token* tok = tokenizer.tokens();
tok = Token::findsimplematch(tok, "auto");
ASSERT(tok && tok->valueType());
ASSERT_EQUALS("signed int", tok->valueType()->str());
}
{
GET_SYMBOL_DB("void f(const std::string& s) {\n"
" const auto* const p = s.data();\n"
"}\n");
ASSERT_EQUALS("", errout_str());
const Token* tok = tokenizer.tokens();
tok = Token::findsimplematch(tok, "auto");
ASSERT(tok && tok->valueType());
ASSERT_EQUALS(ValueType::CHAR, tok->valueType()->type);
ASSERT_EQUALS(1, tok->valueType()->constness);
ASSERT_EQUALS(0, tok->valueType()->pointer);
tok = Token::findsimplematch(tok, "p");
ASSERT(tok && tok->variable() && tok->variable()->valueType());
ASSERT_EQUALS(ValueType::CHAR, tok->variable()->valueType()->type);
ASSERT_EQUALS(3, tok->variable()->valueType()->constness);
ASSERT_EQUALS(1, tok->variable()->valueType()->pointer);
}
{
GET_SYMBOL_DB("std::string f(const std::string& s) {\n"
" auto t = s.substr(3, 7);\n"
" auto r = t.substr(1, 2);\n"
" return r;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
const Token* tok = tokenizer.tokens();
tok = Token::findsimplematch(tok, "auto r");
ASSERT(tok);
TODO_ASSERT(tok->valueType() && "container(std :: string|wstring|u16string|u32string)" == tok->valueType()->str());
}
}
void valueTypeThis() {
ASSERT_EQUALS("C *", typeOf("class C { C() { *this = 0; } };", "this"));
ASSERT_EQUALS("const C *", typeOf("class C { void foo() const; }; void C::foo() const { *this = 0; }", "this"));
}
void variadic1() { // #7453
{
GET_SYMBOL_DB("CBase* create(const char *c1, ...);\n"
"int create(COther& ot, const char *c1, ...);\n"
"int foo(COther & ot)\n"
"{\n"
" CBase* cp1 = create(\"AAAA\", 44, (char*)0);\n"
" CBase* cp2 = create(ot, \"AAAA\", 44, (char*)0);\n"
"}");
const Token *f = Token::findsimplematch(tokenizer.tokens(), "create ( \"AAAA\"");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 1);
f = Token::findsimplematch(tokenizer.tokens(), "create ( ot");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 2);
}
{
GET_SYMBOL_DB("int create(COther& ot, const char *c1, ...);\n"
"CBase* create(const char *c1, ...);\n"
"int foo(COther & ot)\n"
"{\n"
" CBase* cp1 = create(\"AAAA\", 44, (char*)0);\n"
" CBase* cp2 = create(ot, \"AAAA\", 44, (char*)0);\n"
"}");
const Token *f = Token::findsimplematch(tokenizer.tokens(), "create ( \"AAAA\"");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 2);
f = Token::findsimplematch(tokenizer.tokens(), "create ( ot");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 1);
}
}
void variadic2() { // #7649
{
GET_SYMBOL_DB("CBase* create(const char *c1, ...);\n"
"CBase* create(const wchar_t *c1, ...);\n"
"int foo(COther & ot)\n"
"{\n"
" CBase* cp1 = create(\"AAAA\", 44, (char*)0);\n"
" CBase* cp2 = create(L\"AAAA\", 44, (char*)0);\n"
"}");
const Token *f = Token::findsimplematch(tokenizer.tokens(), "cp1 = create (");
ASSERT_EQUALS(true, db && f && f->tokAt(2) && f->tokAt(2)->function() && f->tokAt(2)->function()->tokenDef->linenr() == 1);
f = Token::findsimplematch(tokenizer.tokens(), "cp2 = create (");
ASSERT_EQUALS(true, db && f && f->tokAt(2) && f->tokAt(2)->function() && f->tokAt(2)->function()->tokenDef->linenr() == 2);
}
{
GET_SYMBOL_DB("CBase* create(const wchar_t *c1, ...);\n"
"CBase* create(const char *c1, ...);\n"
"int foo(COther & ot)\n"
"{\n"
" CBase* cp1 = create(\"AAAA\", 44, (char*)0);\n"
" CBase* cp2 = create(L\"AAAA\", 44, (char*)0);\n"
"}");
const Token *f = Token::findsimplematch(tokenizer.tokens(), "cp1 = create (");
ASSERT_EQUALS(true, db && f && f->tokAt(2) && f->tokAt(2)->function() && f->tokAt(2)->function()->tokenDef->linenr() == 2);
f = Token::findsimplematch(tokenizer.tokens(), "cp2 = create (");
ASSERT_EQUALS(true, db && f && f->tokAt(2) && f->tokAt(2)->function() && f->tokAt(2)->function()->tokenDef->linenr() == 1);
}
}
void variadic3() { // #7387
{
GET_SYMBOL_DB("int zdcalc(const XYZ & per, short rs = 0);\n"
"double zdcalc(long& length, const XYZ * per);\n"
"long mycalc( ) {\n"
" long length;\n"
" XYZ per;\n"
" zdcalc(length, &per);\n"
"}");
const Token *f = Token::findsimplematch(tokenizer.tokens(), "zdcalc ( length");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 2);
}
{
GET_SYMBOL_DB("double zdcalc(long& length, const XYZ * per);\n"
"int zdcalc(const XYZ & per, short rs = 0);\n"
"long mycalc( ) {\n"
" long length;\n"
" XYZ per;\n"
" zdcalc(length, &per);\n"
"}");
const Token *f = Token::findsimplematch(tokenizer.tokens(), "zdcalc ( length");
ASSERT_EQUALS(true, db && f && f->function() && f->function()->tokenDef->linenr() == 1);
}
}
void noReturnType() {
GET_SYMBOL_DB_C("func() { }");
ASSERT(db && db->functionScopes.size() == 1);
ASSERT(db->functionScopes[0]->function != nullptr);
const Token *retDef = db->functionScopes[0]->function->retDef;
ASSERT_EQUALS("func", retDef ? retDef->str() : "");
}
void auto1() {
GET_SYMBOL_DB("; auto x = \"abc\";");
const Token *autotok = tokenizer.tokens()->next();
ASSERT(autotok && autotok->isStandardType());
const Variable *var = db ? db->getVariableFromVarId(1) : nullptr;
ASSERT(var && var->isPointer() && !var->isConst());
}
void auto2() {
GET_SYMBOL_DB("struct S { int i; };\n"
"int foo() {\n"
" auto a = new S;\n"
" auto * b = new S;\n"
" auto c = new S[10];\n"
" auto * d = new S[10];\n"
" return a->i + b->i + c[0]->i + d[0]->i;\n"
"}");
const Token *autotok = Token::findsimplematch(tokenizer.tokens(), "auto");
ASSERT(db && autotok && autotok->valueType() && autotok->valueType()->pointer == 1 && autotok->valueType()->typeScope && autotok->valueType()->typeScope->definedType && autotok->valueType()->typeScope->definedType->name() == "S" && autotok->type() == nullptr);
autotok = Token::findsimplematch(autotok->next(), "auto");
ASSERT(db && autotok && autotok->valueType() && autotok->valueType()->pointer == 0 && autotok->valueType()->typeScope && autotok->valueType()->typeScope->definedType && autotok->valueType()->typeScope->definedType->name() == "S" && autotok->type() && autotok->type()->name() == "S");
autotok = Token::findsimplematch(autotok->next(), "auto");
ASSERT(db && autotok && autotok->valueType() && autotok->valueType()->pointer == 1 && autotok->valueType()->typeScope && autotok->valueType()->typeScope->definedType && autotok->valueType()->typeScope->definedType->name() == "S" && autotok->type() == nullptr);
autotok = Token::findsimplematch(autotok->next(), "auto");
ASSERT(db && autotok && autotok->valueType() && autotok->valueType()->pointer == 0 && autotok->valueType()->typeScope && autotok->valueType()->typeScope->definedType && autotok->valueType()->typeScope->definedType->name() == "S" && autotok->type() && autotok->type()->name() == "S");
vartok = Token::findsimplematch(tokenizer.tokens(), "a =");
ASSERT(db && vartok && vartok->variable() && vartok->variable()->isPointer() && vartok->variable()->type() && vartok->variable()->type()->name() == "S");
vartok = Token::findsimplematch(vartok->next(), "b =");
ASSERT(db && vartok && vartok->variable() && vartok->variable()->isPointer() && vartok->variable()->type() && vartok->variable()->type()->name() == "S");
vartok = Token::findsimplematch(vartok->next(), "c =");
ASSERT(db && vartok && vartok->variable() && vartok->variable()->isPointer() && vartok->variable()->type() && vartok->variable()->type()->name() == "S");
vartok = Token::findsimplematch(vartok->next(), "d =");
ASSERT(db && vartok && vartok->variable() && vartok->variable()->isPointer() && vartok->variable()->type() && vartok->variable()->type()->name() == "S");
vartok = Token::findsimplematch(tokenizer.tokens(), "return");
vartok = Token::findsimplematch(vartok, "a");
ASSERT(db && vartok && vartok->variable() && vartok->variable()->isPointer() && vartok->variable()->type() && vartok->variable()->type()->name() == "S");
vartok = Token::findsimplematch(vartok->next(), "b");
ASSERT(db && vartok && vartok->variable() && vartok->variable()->isPointer() && vartok->variable()->type() && vartok->variable()->type()->name() == "S");
vartok = Token::findsimplematch(vartok->next(), "c");
ASSERT(db && vartok && vartok->variable() && vartok->variable()->isPointer() && vartok->variable()->type() && vartok->variable()->type()->name() == "S");
vartok = Token::findsimplematch(vartok->next(), "d");
ASSERT(db && vartok && vartok->variable() && vartok->variable()->isPointer() && vartok->variable()->type() && vartok->variable()->type()->name() == "S");
vartok = Token::findsimplematch(tokenizer.tokens(), "return");
vartok = Token::findsimplematch(vartok, "i");
ASSERT(db && vartok && vartok->variable() && vartok->variable()->typeStartToken()->str() == "int");
vartok = Token::findsimplematch(vartok->next(), "i");
ASSERT(db && vartok && vartok->variable() && vartok->variable()->typeStartToken()->str() == "int");
vartok = Token::findsimplematch(vartok->next(), "i");
ASSERT(db && vartok && vartok->variable() && vartok->variable()->typeStartToken()->str() == "int");
vartok = Token::findsimplematch(vartok->next(), "i");
ASSERT(db && vartok && vartok->variable() && vartok->variable()->typeStartToken()->str() == "int");
}
void auto3() {
GET_SYMBOL_DB("enum E : unsigned short { A, B, C };\n"
"int foo() {\n"
" auto a = new E;\n"
" auto * b = new E;\n"
" auto c = new E[10];\n"
" auto * d = new E[10];\n"
" return *a + *b + c[0] + d[0];\n"
"}");
const Token *autotok = Token::findsimplematch(tokenizer.tokens(), "auto");
ASSERT(db && autotok && autotok->valueType() && autotok->valueType()->pointer == 1 && autotok->valueType()->typeScope && autotok->valueType()->typeScope->definedType && autotok->valueType()->typeScope->definedType->name() == "E" && autotok->type() == nullptr);
autotok = Token::findsimplematch(autotok->next(), "auto");
ASSERT(db && autotok && autotok->valueType() && autotok->valueType()->pointer == 0 && autotok->valueType()->typeScope && autotok->valueType()->typeScope->definedType && autotok->valueType()->typeScope->definedType->name() == "E" && autotok->type() && autotok->type()->name() == "E");
autotok = Token::findsimplematch(autotok->next(), "auto");
ASSERT(db && autotok && autotok->valueType() && autotok->valueType()->pointer == 1 && autotok->valueType()->typeScope && autotok->valueType()->typeScope->definedType && autotok->valueType()->typeScope->definedType->name() == "E" && autotok->type() == nullptr);
autotok = Token::findsimplematch(autotok->next(), "auto");
ASSERT(db && autotok && autotok->valueType() && autotok->valueType()->pointer == 0 && autotok->valueType()->typeScope && autotok->valueType()->typeScope->definedType && autotok->valueType()->typeScope->definedType->name() == "E" && autotok->type() && autotok->type()->name() == "E");
vartok = Token::findsimplematch(tokenizer.tokens(), "a =");
ASSERT(db && vartok && vartok->variable() && vartok->variable()->isPointer() && vartok->variable()->type() && vartok->variable()->type()->name() == "E");
vartok = Token::findsimplematch(vartok->next(), "b =");
ASSERT(db && vartok && vartok->variable() && vartok->variable()->isPointer() && vartok->variable()->type() && vartok->variable()->type()->name() == "E");
vartok = Token::findsimplematch(vartok->next(), "c =");
ASSERT(db && vartok && vartok->variable() && vartok->variable()->isPointer() && vartok->variable()->type() && vartok->variable()->type()->name() == "E");
vartok = Token::findsimplematch(vartok->next(), "d =");
ASSERT(db && vartok && vartok->variable() && vartok->variable()->isPointer() && vartok->variable()->type() && vartok->variable()->type()->name() == "E");
vartok = Token::findsimplematch(tokenizer.tokens(), "return");
vartok = Token::findsimplematch(vartok, "a");
ASSERT(db && vartok && vartok->variable() && vartok->variable()->isPointer() && vartok->variable()->type() && vartok->variable()->type()->name() == "E");
vartok = Token::findsimplematch(vartok->next(), "b");
ASSERT(db && vartok && vartok->variable() && vartok->variable()->isPointer() && vartok->variable()->type() && vartok->variable()->type()->name() == "E");
vartok = Token::findsimplematch(vartok->next(), "c");
ASSERT(db && vartok && vartok->variable() && vartok->variable()->isPointer() && vartok->variable()->type() && vartok->variable()->type()->name() == "E");
vartok = Token::findsimplematch(vartok->next(), "d");
ASSERT(db && vartok && vartok->variable() && vartok->variable()->isPointer() && vartok->variable()->type() && vartok->variable()->type()->name() == "E");
}
void auto4() {
GET_SYMBOL_DB("struct S { int i; };\n"
"int foo() {\n"
" S array[10];\n"
" for (auto a : array)\n"
" a.i = 0;\n"
" for (auto & b : array)\n"
" b.i = 1;\n"
" for (const auto & c : array)\n"
" auto ci = c.i;\n"
" for (auto * d : array)\n"
" d->i = 0;\n"
" for (const auto * e : array)\n"
" auto ei = e->i;\n"
" return array[0].i;\n"
"}");
const Token *autotok = Token::findsimplematch(tokenizer.tokens(), "auto a");
ASSERT(db && autotok && autotok->valueType() && autotok->valueType()->pointer == 0 && autotok->valueType()->constness == 0 && autotok->valueType()->typeScope && autotok->valueType()->typeScope->definedType && autotok->valueType()->typeScope->definedType->name() == "S");
ASSERT(db && autotok && autotok->type() && autotok->type()->name() == "S");
autotok = Token::findsimplematch(autotok->next(), "auto & b");
ASSERT(db && autotok && autotok->valueType() && autotok->valueType()->pointer == 0 && autotok->valueType()->constness == 0 && autotok->valueType()->typeScope && autotok->valueType()->typeScope->definedType && autotok->valueType()->typeScope->definedType->name() == "S");
ASSERT(db && autotok && autotok->type() && autotok->type()->name() == "S");
autotok = Token::findsimplematch(autotok->next(), "auto & c");
ASSERT(db && autotok && autotok->valueType() && autotok->valueType()->pointer == 0 && autotok->valueType()->constness == 0 && autotok->valueType()->typeScope && autotok->valueType()->typeScope->definedType && autotok->valueType()->typeScope->definedType->name() == "S");
ASSERT(db && autotok && autotok->type() && autotok->type()->name() == "S");
autotok = Token::findsimplematch(autotok->next(), "auto * d");
ASSERT(db && autotok && autotok->valueType() && autotok->valueType()->pointer == 0 && autotok->valueType()->constness == 0 && autotok->valueType()->typeScope && autotok->valueType()->typeScope->definedType && autotok->valueType()->typeScope->definedType->name() == "S");
ASSERT(db && autotok && autotok->type() && autotok->type()->name() == "S");
autotok = Token::findsimplematch(autotok->next(), "auto * e");
ASSERT(db && autotok && autotok->valueType() && autotok->valueType()->pointer == 0 && autotok->valueType()->constness == 0 && autotok->valueType()->typeScope && autotok->valueType()->typeScope->definedType && autotok->valueType()->typeScope->definedType->name() == "S");
ASSERT(db && autotok && autotok->type() && autotok->type()->name() == "S");
vartok = Token::findsimplematch(tokenizer.tokens(), "a :");
ASSERT(db && vartok && vartok->valueType() && vartok->valueType()->typeScope && vartok->valueType()->typeScope->definedType && vartok->valueType()->typeScope->definedType->name() == "S");
ASSERT(db && vartok && vartok->variable() && !vartok->variable()->isReference() && !vartok->variable()->isPointer());
ASSERT(db && vartok && vartok->variable() && vartok->variable()->type() && vartok->variable()->type()->name() == "S");
vartok = Token::findsimplematch(vartok->next(), "b :");
ASSERT(db && vartok && vartok->valueType() && vartok->valueType()->typeScope && vartok->valueType()->typeScope->definedType && vartok->valueType()->typeScope->definedType->name() == "S");
ASSERT(db && vartok && vartok->variable() && vartok->variable()->isReference() && !vartok->variable()->isPointer() && !vartok->variable()->isConst());
vartok = Token::findsimplematch(vartok->next(), "c :");
ASSERT(db && vartok && vartok->valueType() && vartok->valueType()->typeScope && vartok->valueType()->typeScope->definedType && vartok->valueType()->typeScope->definedType->name() == "S");
ASSERT(db && vartok && vartok->variable() && vartok->variable()->isReference() && !vartok->variable()->isPointer() && vartok->variable()->isConst());
vartok = Token::findsimplematch(vartok->next(), "d :");
ASSERT(db && vartok && vartok->valueType() && vartok->valueType()->typeScope && vartok->valueType()->typeScope->definedType && vartok->valueType()->typeScope->definedType->name() == "S");
ASSERT(db && vartok && vartok->variable() && !vartok->variable()->isReference() && vartok->variable()->isPointer() && !vartok->variable()->isConst());
vartok = Token::findsimplematch(vartok->next(), "e :");
ASSERT(db && vartok && vartok->valueType() && vartok->valueType()->typeScope && vartok->valueType()->typeScope->definedType && vartok->valueType()->typeScope->definedType->name() == "S");
ASSERT(db && vartok && vartok->variable() && !vartok->variable()->isReference() && vartok->variable()->isPointer() && vartok->variable()->isConst());
vartok = Token::findsimplematch(tokenizer.tokens(), "a . i");
ASSERT(db && vartok && vartok->variable() && !vartok->variable()->isPointer() && !vartok->variable()->isReference() && vartok->variable()->type() && vartok->variable()->type()->name() == "S");
vartok = Token::findsimplematch(vartok, "i");
ASSERT(db && vartok && vartok->variable() && vartok->variable()->typeStartToken()->str() == "int");
vartok = Token::findsimplematch(vartok->next(), "b . i");
ASSERT(db && vartok && vartok->variable() && !vartok->variable()->isPointer() && vartok->variable()->isReference() && vartok->variable()->type() && vartok->variable()->type()->name() == "S");
vartok = Token::findsimplematch(vartok->next(), "i");
ASSERT(db && vartok && vartok->variable() && vartok->variable()->typeStartToken()->str() == "int");
vartok = Token::findsimplematch(vartok->next(), "c . i");
ASSERT(db && vartok && vartok->variable() && !vartok->variable()->isPointer() && vartok->variable()->isReference() && vartok->variable()->type() && vartok->variable()->type()->name() == "S");
vartok = Token::findsimplematch(vartok->next(), "i");
ASSERT(db && vartok && vartok->variable() && vartok->variable()->typeStartToken()->str() == "int");
vartok = Token::findsimplematch(vartok->next(), "d . i");
ASSERT(db && vartok && vartok->variable() && vartok->variable()->isPointer() && !vartok->variable()->isReference() && vartok->variable()->type() && vartok->variable()->type()->name() == "S");
vartok = Token::findsimplematch(vartok->next(), "i");
ASSERT(db && vartok && vartok->variable() && vartok->variable()->typeStartToken()->str() == "int");
vartok = Token::findsimplematch(vartok->next(), "e . i");
ASSERT(db && vartok && vartok->variable() && vartok->variable()->isPointer() && !vartok->variable()->isReference() && vartok->variable()->type() && vartok->variable()->type()->name() == "S");
vartok = Token::findsimplematch(vartok->next(), "i");
ASSERT(db && vartok && vartok->variable() && vartok->variable()->typeStartToken()->str() == "int");
vartok = Token::findsimplematch(vartok->next(), "i");
ASSERT(db && vartok && vartok->variable() && vartok->variable()->typeStartToken()->str() == "int");
}
void auto5() {
GET_SYMBOL_DB("struct S { int i; };\n"
"int foo() {\n"
" std::vector<S> vec(10);\n"
" for (auto a : vec)\n"
" a.i = 0;\n"
" for (auto & b : vec)\n"
" b.i = 0;\n"
" for (const auto & c : vec)\n"
" auto ci = c.i;\n"
" for (auto * d : vec)\n"
" d.i = 0;\n"
" for (const auto * e : vec)\n"
" auto ei = e->i;\n"
" return vec[0].i;\n"
"}");
const Token *autotok = Token::findsimplematch(tokenizer.tokens(), "auto a");
ASSERT(autotok && autotok->valueType() && autotok->valueType()->pointer == 0 && autotok->valueType()->constness == 0 && autotok->valueType()->typeScope && autotok->valueType()->typeScope->definedType && autotok->valueType()->typeScope->definedType->name() == "S");
ASSERT(autotok && autotok->type() && autotok->type()->name() == "S");
autotok = Token::findsimplematch(autotok->next(), "auto & b");
ASSERT(autotok && autotok->valueType() && autotok->valueType()->pointer == 0 && autotok->valueType()->constness == 0 && autotok->valueType()->typeScope && autotok->valueType()->typeScope->definedType && autotok->valueType()->typeScope->definedType->name() == "S");
ASSERT(autotok && autotok->type() && autotok->type()->name() == "S");
autotok = Token::findsimplematch(autotok->next(), "auto & c");
ASSERT(autotok && autotok->valueType() && autotok->valueType()->pointer == 0 && autotok->valueType()->constness == 1 && autotok->valueType()->typeScope && autotok->valueType()->typeScope->definedType && autotok->valueType()->typeScope->definedType->name() == "S");
ASSERT(autotok && autotok->type() && autotok->type()->name() == "S");
autotok = Token::findsimplematch(autotok->next(), "auto * d");
ASSERT(autotok && autotok->valueType() && autotok->valueType()->pointer == 0 && autotok->valueType()->constness == 0 && autotok->valueType()->typeScope && autotok->valueType()->typeScope->definedType && autotok->valueType()->typeScope->definedType->name() == "S");
ASSERT(autotok && autotok->type() && autotok->type()->name() == "S");
autotok = Token::findsimplematch(autotok->next(), "auto * e");
ASSERT(autotok && autotok->valueType() && autotok->valueType()->pointer == 0 && autotok->valueType()->constness == 1 && autotok->valueType()->typeScope && autotok->valueType()->typeScope->definedType && autotok->valueType()->typeScope->definedType->name() == "S");
ASSERT(autotok && autotok->type() && autotok->type()->name() == "S");
vartok = Token::findsimplematch(tokenizer.tokens(), "a :");
ASSERT(vartok && vartok->valueType() && vartok->valueType()->typeScope && vartok->valueType()->typeScope->definedType && vartok->valueType()->typeScope->definedType->name() == "S");
ASSERT(vartok && vartok->variable() && !vartok->variable()->isReference() && !vartok->variable()->isPointer());
ASSERT(vartok && vartok->variable() && vartok->variable()->type() && vartok->variable()->type()->name() == "S");
vartok = Token::findsimplematch(vartok->next(), "b :");
ASSERT(vartok && vartok->valueType() && vartok->valueType()->typeScope && vartok->valueType()->typeScope->definedType && vartok->valueType()->typeScope->definedType->name() == "S");
ASSERT(vartok && vartok->variable() && vartok->variable()->isReference() && !vartok->variable()->isPointer() && !vartok->variable()->isConst());
vartok = Token::findsimplematch(vartok->next(), "c :");
ASSERT(vartok && vartok->valueType() && vartok->valueType()->typeScope && vartok->valueType()->typeScope->definedType && vartok->valueType()->typeScope->definedType->name() == "S");
ASSERT(vartok && vartok->variable() && vartok->variable()->isReference() && !vartok->variable()->isPointer() && vartok->variable()->isConst());
vartok = Token::findsimplematch(vartok->next(), "d :");
ASSERT(vartok && vartok->valueType() && vartok->valueType()->typeScope && vartok->valueType()->typeScope->definedType && vartok->valueType()->typeScope->definedType->name() == "S");
ASSERT(vartok && vartok->variable() && !vartok->variable()->isReference() && vartok->variable()->isPointer() && !vartok->variable()->isConst());
vartok = Token::findsimplematch(vartok->next(), "e :");
ASSERT(vartok && vartok->valueType() && vartok->valueType()->typeScope && vartok->valueType()->typeScope->definedType && vartok->valueType()->typeScope->definedType->name() == "S");
ASSERT(vartok && vartok->variable() && !vartok->variable()->isReference() && vartok->variable()->isPointer() && vartok->variable()->isConst());
vartok = Token::findsimplematch(tokenizer.tokens(), "a . i");
ASSERT(vartok && vartok->variable() && !vartok->variable()->isPointer() && !vartok->variable()->isReference() && vartok->variable()->type() && vartok->variable()->type()->name() == "S");
vartok = Token::findsimplematch(vartok, "i");
ASSERT(vartok && vartok->variable() && vartok->variable()->typeStartToken()->str() == "int");
vartok = Token::findsimplematch(vartok->next(), "b . i");
ASSERT(vartok && vartok->variable() && !vartok->variable()->isPointer() && vartok->variable()->isReference() && vartok->variable()->type() && vartok->variable()->type()->name() == "S");
vartok = Token::findsimplematch(vartok->next(), "i");
ASSERT(vartok && vartok->variable() && vartok->variable()->typeStartToken()->str() == "int");
vartok = Token::findsimplematch(vartok->next(), "c . i");
ASSERT(vartok && vartok->variable() && !vartok->variable()->isPointer() && vartok->variable()->isReference() && vartok->variable()->type() && vartok->variable()->type()->name() == "S");
vartok = Token::findsimplematch(vartok->next(), "i");
ASSERT(vartok && vartok->variable() && vartok->variable()->typeStartToken()->str() == "int");
vartok = Token::findsimplematch(vartok->next(), "d . i");
ASSERT(vartok && vartok->variable() && vartok->variable()->isPointer() && !vartok->variable()->isReference() && vartok->variable()->type() && vartok->variable()->type()->name() == "S");
vartok = Token::findsimplematch(vartok->next(), "i");
ASSERT(vartok && vartok->variable() && vartok->variable()->typeStartToken()->str() == "int");
vartok = Token::findsimplematch(vartok->next(), "e . i");
ASSERT(vartok && vartok->variable() && vartok->variable()->isPointer() && !vartok->variable()->isReference() && vartok->variable()->type() && vartok->variable()->type()->name() == "S");
vartok = Token::findsimplematch(vartok->next(), "i");
ASSERT(vartok && vartok->variable() && vartok->variable()->typeStartToken()->str() == "int");
vartok = Token::findsimplematch(vartok->next(), "i");
ASSERT(vartok && vartok->variable() && vartok->variable()->typeStartToken()->str() == "int");
}
void auto6() { // #7963 (segmentation fault)
GET_SYMBOL_DB("class WebGLTransformFeedback final\n"
": public nsWrapperCache\n"
", public WebGLRefCountedObject < WebGLTransformFeedback >\n"
", public LinkedListElement < WebGLTransformFeedback >\n"
"{\n"
"private :\n"
"std :: vector < IndexedBufferBinding > mIndexedBindings ;\n"
"} ;\n"
"struct IndexedBufferBinding\n"
"{\n"
"IndexedBufferBinding ( ) ;\n"
"} ;\n"
"const decltype ( WebGLTransformFeedback :: mBuffersForTF ) &\n"
"WebGLTransformFeedback :: BuffersForTF ( ) const\n"
"{\n"
"mBuffersForTF . clear ( ) ;\n"
"for ( const auto & cur : mIndexedBindings ) {}\n"
"return mBuffersForTF ;\n"
"}");
}
void auto7() {
GET_SYMBOL_DB("struct Foo { int a; int b[10]; };\n"
"class Bar {\n"
" Foo foo1;\n"
" Foo foo2[10];\n"
"public:\n"
" const Foo & getFoo1() { return foo1; }\n"
" const Foo * getFoo2() { return foo2; }\n"
"};\n"
"int main() {\n"
" Bar bar;\n"
" auto v1 = bar.getFoo1().a;\n"
" auto v2 = bar.getFoo1().b[0];\n"
" auto v3 = bar.getFoo1().b;\n"
" const auto v4 = bar.getFoo1().b;\n"
" const auto * v5 = bar.getFoo1().b;\n"
" auto v6 = bar.getFoo2()[0].a;\n"
" auto v7 = bar.getFoo2()[0].b[0];\n"
" auto v8 = bar.getFoo2()[0].b;\n"
" const auto v9 = bar.getFoo2()[0].b;\n"
" const auto * v10 = bar.getFoo2()[0].b;\n"
" auto v11 = v1 + v2 + v3[0] + v4[0] + v5[0] + v6 + v7 + v8[0] + v9[0] + v10[0];\n"
" return v11;\n"
"}");
const Token *autotok = Token::findsimplematch(tokenizer.tokens(), "auto v1");
// auto = int, v1 = int
ASSERT(autotok);
ASSERT(autotok->valueType());
ASSERT_EQUALS(0, autotok->valueType()->constness);
ASSERT_EQUALS(0, autotok->valueType()->pointer);
ASSERT_EQUALS(ValueType::SIGNED, autotok->valueType()->sign);
ASSERT_EQUALS(ValueType::INT, autotok->valueType()->type);
vartok = Token::findsimplematch(autotok, "v1 =");
ASSERT(autotok);
ASSERT(autotok->valueType());
ASSERT_EQUALS(0, vartok->valueType()->constness);
ASSERT_EQUALS(0, vartok->valueType()->pointer);
ASSERT_EQUALS(ValueType::SIGNED, vartok->valueType()->sign);
ASSERT_EQUALS(ValueType::INT, vartok->valueType()->type);
// auto = int, v2 = int
autotok = Token::findsimplematch(autotok, "auto v2");
ASSERT(autotok);
ASSERT(autotok->valueType());
ASSERT_EQUALS(0, autotok->valueType()->constness);
ASSERT_EQUALS(0, autotok->valueType()->pointer);
ASSERT_EQUALS(ValueType::SIGNED, autotok->valueType()->sign);
ASSERT_EQUALS(ValueType::INT, autotok->valueType()->type);
vartok = Token::findsimplematch(autotok, "v2 =");
ASSERT(autotok);
ASSERT(autotok->valueType());
ASSERT_EQUALS(0, vartok->valueType()->constness);
ASSERT_EQUALS(0, vartok->valueType()->pointer);
ASSERT_EQUALS(ValueType::SIGNED, vartok->valueType()->sign);
ASSERT_EQUALS(ValueType::INT, vartok->valueType()->type);
// auto = const int *, v3 = const int * (const int[10])
autotok = Token::findsimplematch(autotok, "auto v3");
ASSERT(autotok);
ASSERT(autotok->valueType());
ASSERT_EQUALS(1, autotok->valueType()->constness);
ASSERT_EQUALS(1, autotok->valueType()->pointer);
ASSERT_EQUALS(ValueType::SIGNED, autotok->valueType()->sign);
ASSERT_EQUALS(ValueType::INT, autotok->valueType()->type);
vartok = Token::findsimplematch(autotok, "v3 =");
ASSERT(autotok);
ASSERT(autotok->valueType());
ASSERT_EQUALS(1, vartok->valueType()->constness);
ASSERT_EQUALS(1, vartok->valueType()->pointer);
ASSERT_EQUALS(ValueType::SIGNED, vartok->valueType()->sign);
ASSERT_EQUALS(ValueType::INT, vartok->valueType()->type);
// auto = int *, v4 = const int * (const int[10])
autotok = Token::findsimplematch(autotok, "auto v4");
ASSERT(autotok);
ASSERT(autotok->valueType());
ASSERT_EQUALS(3, autotok->valueType()->constness);
ASSERT_EQUALS(1, autotok->valueType()->pointer);
ASSERT_EQUALS(ValueType::SIGNED, autotok->valueType()->sign);
ASSERT_EQUALS(ValueType::INT, autotok->valueType()->type);
vartok = Token::findsimplematch(autotok, "v4 =");
ASSERT(autotok);
ASSERT(autotok->valueType());
ASSERT_EQUALS(3, vartok->valueType()->constness);
ASSERT_EQUALS(1, vartok->valueType()->pointer);
ASSERT_EQUALS(ValueType::SIGNED, vartok->valueType()->sign);
ASSERT_EQUALS(ValueType::INT, vartok->valueType()->type);
// auto = int, v5 = const int * (const int[10])
autotok = Token::findsimplematch(autotok, "auto * v5");
ASSERT(autotok);
ASSERT(autotok->valueType());
TODO_ASSERT_EQUALS(0, 1, autotok->valueType()->constness);
ASSERT_EQUALS(0, autotok->valueType()->pointer);
ASSERT_EQUALS(ValueType::SIGNED, autotok->valueType()->sign);
ASSERT_EQUALS(ValueType::INT, autotok->valueType()->type);
vartok = Token::findsimplematch(autotok, "v5 =");
ASSERT(autotok);
ASSERT(autotok->valueType());
ASSERT_EQUALS(1, vartok->valueType()->constness);
ASSERT_EQUALS(1, vartok->valueType()->pointer);
ASSERT_EQUALS(ValueType::SIGNED, vartok->valueType()->sign);
ASSERT_EQUALS(ValueType::INT, vartok->valueType()->type);
// auto = int, v6 = int
autotok = Token::findsimplematch(autotok, "auto v6");
ASSERT(autotok);
ASSERT(autotok->valueType());
ASSERT_EQUALS(0, autotok->valueType()->constness);
ASSERT_EQUALS(0, autotok->valueType()->pointer);
ASSERT_EQUALS(ValueType::SIGNED, autotok->valueType()->sign);
ASSERT_EQUALS(ValueType::INT, autotok->valueType()->type);
vartok = Token::findsimplematch(autotok, "v6 =");
ASSERT(autotok);
ASSERT(autotok->valueType());
ASSERT_EQUALS(0, vartok->valueType()->constness);
ASSERT_EQUALS(0, vartok->valueType()->pointer);
ASSERT_EQUALS(ValueType::SIGNED, vartok->valueType()->sign);
ASSERT_EQUALS(ValueType::INT, vartok->valueType()->type);
// auto = int, v7 = int
autotok = Token::findsimplematch(autotok, "auto v7");
ASSERT(autotok);
ASSERT(autotok->valueType());
ASSERT_EQUALS(0, autotok->valueType()->constness);
ASSERT_EQUALS(0, autotok->valueType()->pointer);
ASSERT_EQUALS(ValueType::SIGNED, autotok->valueType()->sign);
ASSERT_EQUALS(ValueType::INT, autotok->valueType()->type);
vartok = Token::findsimplematch(autotok, "v7 =");
ASSERT(autotok);
ASSERT(autotok->valueType());
ASSERT_EQUALS(0, vartok->valueType()->constness);
ASSERT_EQUALS(0, vartok->valueType()->pointer);
ASSERT_EQUALS(ValueType::SIGNED, vartok->valueType()->sign);
ASSERT_EQUALS(ValueType::INT, vartok->valueType()->type);
// auto = const int *, v8 = const int * (const int[10])
autotok = Token::findsimplematch(autotok, "auto v8");
ASSERT(autotok);
ASSERT(autotok->valueType());
ASSERT_EQUALS(1, autotok->valueType()->constness);
ASSERT_EQUALS(1, autotok->valueType()->pointer);
ASSERT_EQUALS(ValueType::SIGNED, autotok->valueType()->sign);
ASSERT_EQUALS(ValueType::INT, autotok->valueType()->type);
vartok = Token::findsimplematch(autotok, "v8 =");
ASSERT(autotok);
ASSERT(autotok->valueType());
ASSERT_EQUALS(1, vartok->valueType()->constness);
ASSERT_EQUALS(1, vartok->valueType()->pointer);
ASSERT_EQUALS(ValueType::SIGNED, vartok->valueType()->sign);
ASSERT_EQUALS(ValueType::INT, vartok->valueType()->type);
// auto = int *, v9 = const int * (const int[10])
autotok = Token::findsimplematch(autotok, "auto v9");
ASSERT(autotok);
ASSERT(autotok->valueType());
ASSERT_EQUALS(3, autotok->valueType()->constness);
ASSERT_EQUALS(1, autotok->valueType()->pointer);
ASSERT_EQUALS(ValueType::SIGNED, autotok->valueType()->sign);
ASSERT_EQUALS(ValueType::INT, autotok->valueType()->type);
vartok = Token::findsimplematch(autotok, "v9 =");
ASSERT(autotok);
ASSERT(autotok->valueType());
ASSERT_EQUALS(3, vartok->valueType()->constness);
ASSERT_EQUALS(1, vartok->valueType()->pointer);
ASSERT_EQUALS(ValueType::SIGNED, vartok->valueType()->sign);
ASSERT_EQUALS(ValueType::INT, vartok->valueType()->type);
// auto = int, v10 = const int * (const int[10])
autotok = Token::findsimplematch(autotok, "auto * v10");
ASSERT(autotok);
ASSERT(autotok->valueType());
TODO_ASSERT_EQUALS(0, 1, autotok->valueType()->constness);
ASSERT_EQUALS(0, autotok->valueType()->pointer);
ASSERT_EQUALS(ValueType::SIGNED, autotok->valueType()->sign);
ASSERT_EQUALS(ValueType::INT, autotok->valueType()->type);
vartok = Token::findsimplematch(autotok, "v10 =");
ASSERT(autotok);
ASSERT(autotok->valueType());
ASSERT_EQUALS(1, vartok->valueType()->constness);
ASSERT_EQUALS(1, vartok->valueType()->pointer);
ASSERT_EQUALS(ValueType::SIGNED, vartok->valueType()->sign);
ASSERT_EQUALS(ValueType::INT, vartok->valueType()->type);
// auto = int, v11 = int
autotok = Token::findsimplematch(autotok, "auto v11");
ASSERT(autotok);
ASSERT(autotok->valueType());
ASSERT_EQUALS(0, autotok->valueType()->constness);
ASSERT_EQUALS(0, autotok->valueType()->pointer);
ASSERT_EQUALS(ValueType::SIGNED, autotok->valueType()->sign);
ASSERT_EQUALS(ValueType::INT, autotok->valueType()->type);
vartok = autotok->next();
ASSERT(autotok);
ASSERT(autotok->valueType());
ASSERT_EQUALS(0, vartok->valueType()->constness);
ASSERT_EQUALS(0, vartok->valueType()->pointer);
ASSERT_EQUALS(ValueType::SIGNED, vartok->valueType()->sign);
ASSERT_EQUALS(ValueType::INT, vartok->valueType()->type);
}
void auto8() {
GET_SYMBOL_DB("std::vector<int> vec;\n"
"void foo() {\n"
" for (auto it = vec.begin(); it != vec.end(); ++it) { }\n"
"}");
const Token *autotok = Token::findsimplematch(tokenizer.tokens(), "auto it");
ASSERT(autotok);
ASSERT(autotok->valueType());
ASSERT_EQUALS(0, autotok->valueType()->constness);
ASSERT_EQUALS(0, autotok->valueType()->pointer);
ASSERT_EQUALS(ValueType::UNKNOWN_SIGN, autotok->valueType()->sign);
ASSERT_EQUALS(ValueType::ITERATOR, autotok->valueType()->type);
vartok = Token::findsimplematch(autotok, "it =");
ASSERT(vartok);
ASSERT(vartok->valueType());
ASSERT_EQUALS(0, vartok->valueType()->constness);
ASSERT_EQUALS(0, vartok->valueType()->pointer);
ASSERT_EQUALS(ValueType::UNKNOWN_SIGN, vartok->valueType()->sign);
ASSERT_EQUALS(ValueType::ITERATOR, vartok->valueType()->type);
}
void auto9() { // #8044 (segmentation fault)
GET_SYMBOL_DB("class DHTTokenTracker {\n"
" static const size_t SECRET_SIZE = 4;\n"
" unsigned char secret_[2][SECRET_SIZE];\n"
" void validateToken();\n"
"};\n"
"template <typename T> struct DerefEqual<T> derefEqual(const T& t) {\n"
" return DerefEqual<T>(t);\n"
"}\n"
"template <typename T>\n"
"struct RefLess {\n"
" bool operator()(const std::shared_ptr<T>& lhs,\n"
" const std::shared_ptr<T>& rhs)\n"
" {\n"
" return lhs.get() < rhs.get();\n"
" }\n"
"};\n"
"void DHTTokenTracker::validateToken()\n"
"{\n"
" for (auto& elem : secret_) {\n"
" }\n"
"}");
}
void auto10() { // #8020
GET_SYMBOL_DB("void f() {\n"
" std::vector<int> ints(4);\n"
" auto iter = ints.begin() + (ints.size() - 1);\n"
"}");
const Token *autotok = Token::findsimplematch(tokenizer.tokens(), "auto iter");
ASSERT(autotok);
ASSERT(autotok->valueType());
ASSERT_EQUALS(0, autotok->valueType()->constness);
ASSERT_EQUALS(0, autotok->valueType()->pointer);
ASSERT_EQUALS(ValueType::UNKNOWN_SIGN, autotok->valueType()->sign);
ASSERT_EQUALS(ValueType::ITERATOR, autotok->valueType()->type);
}
void auto11() {
GET_SYMBOL_DB("void f() {\n"
" const auto v1 = 3;\n"
" const auto *v2 = 0;\n"
"}");
const Token *v1tok = Token::findsimplematch(tokenizer.tokens(), "v1");
ASSERT(v1tok && v1tok->variable() && v1tok->variable()->isConst());
const Token *v2tok = Token::findsimplematch(tokenizer.tokens(), "v2");
ASSERT(v2tok && v2tok->variable() && !v2tok->variable()->isConst());
}
void auto12() {
GET_SYMBOL_DB("void f(const std::string &x) {\n"
" auto y = x;\n"
" if (y.empty()) {}\n"
"}");
const Token *tok;
tok = Token::findsimplematch(tokenizer.tokens(), "y =");
ASSERT(tok && tok->valueType() && tok->valueType()->container);
tok = Token::findsimplematch(tokenizer.tokens(), "y .");
ASSERT(tok && tok->valueType() && tok->valueType()->container);
}
void auto13() {
GET_SYMBOL_DB("uint8_t *get();\n"
"\n"
"uint8_t *test()\n"
"{\n"
" auto *next = get();\n"
" return next;\n"
"}");
const Token *tok;
tok = Token::findsimplematch(tokenizer.tokens(), "return")->next();
ASSERT(tok);
ASSERT(tok->valueType());
ASSERT(tok->valueType()->pointer);
ASSERT(tok->variable()->valueType());
ASSERT(tok->variable()->valueType()->pointer);
}
void auto14() { // #9892 - crash in Token::declType
GET_SYMBOL_DB("static void foo() {\n"
" auto combo = widget->combo = new Combo{};\n"
" combo->addItem();\n"
"}");
const Token *tok;
tok = Token::findsimplematch(tokenizer.tokens(), "combo =");
ASSERT(tok && !tok->valueType());
}
void auto15() {
GET_SYMBOL_DB("auto var1{3};\n"
"auto var2{4.0};");
ASSERT_EQUALS(3, db->variableList().size());
const Variable *var1 = db->variableList()[1];
ASSERT(var1->valueType());
ASSERT_EQUALS(ValueType::Type::INT, var1->valueType()->type);
const Variable *var2 = db->variableList()[2];
ASSERT(var2->valueType());
ASSERT_EQUALS(ValueType::Type::DOUBLE, var2->valueType()->type);
}
void auto16() {
GET_SYMBOL_DB("void foo(std::map<std::string, bool> x) {\n"
" for (const auto& i: x) {}\n"
"}\n");
ASSERT_EQUALS(3, db->variableList().size());
const Variable *i = db->variableList().back();
ASSERT(i->valueType());
ASSERT_EQUALS(ValueType::Type::RECORD, i->valueType()->type);
}
void auto17() { // #11163 don't hang
GET_SYMBOL_DB("void f() {\n"
" std::shared_ptr<int> s1;\n"
" auto s2 = std::shared_ptr(s1);\n"
"}\n"
"void g() {\n"
" std::shared_ptr<int> s;\n"
" auto w = std::weak_ptr(s);\n"
"}\n");
ASSERT_EQUALS(5, db->variableList().size());
}
void auto18() {
GET_SYMBOL_DB("void f(const int* p) {\n"
" const int* const& r = p;\n"
" const auto& s = p;\n"
"}\n");
ASSERT_EQUALS(4, db->variableList().size());
const Variable* r = db->variableList()[2];
ASSERT(r->isReference());
ASSERT(r->isConst());
ASSERT(r->isPointer());
const Token* varTok = Token::findsimplematch(tokenizer.tokens(), "r");
ASSERT(varTok && varTok->valueType());
ASSERT_EQUALS(varTok->valueType()->constness, 3);
ASSERT_EQUALS(varTok->valueType()->pointer, 1);
ASSERT(varTok->valueType()->reference == Reference::LValue);
const Variable* s = db->variableList()[3];
ASSERT(s->isReference());
ASSERT(s->isConst());
ASSERT(s->isPointer());
const Token* autoTok = Token::findsimplematch(tokenizer.tokens(), "auto");
ASSERT(autoTok && autoTok->valueType());
ASSERT_EQUALS(autoTok->valueType()->constness, 3);
ASSERT_EQUALS(autoTok->valueType()->pointer, 1);
}
void auto19() { // #11517
{
GET_SYMBOL_DB("void f(const std::vector<void*>& v) {\n"
" for (const auto* h : v)\n"
" if (h) {}\n"
"}\n");
ASSERT_EQUALS(3, db->variableList().size());
const Variable* h = db->variableList()[2];
ASSERT(h->isPointer());
ASSERT(!h->isConst());
const Token* varTok = Token::findsimplematch(tokenizer.tokens(), "h )");
ASSERT(varTok && varTok->valueType());
ASSERT_EQUALS(varTok->valueType()->constness, 1);
ASSERT_EQUALS(varTok->valueType()->pointer, 1);
}
{
GET_SYMBOL_DB("struct B { virtual void f() {} };\n"
"struct D : B {};\n"
"void g(const std::vector<B*>& v) {\n"
" for (auto* b : v)\n"
" if (auto d = dynamic_cast<D*>(b))\n"
" d->f();\n"
"}\n");
ASSERT_EQUALS(4, db->variableList().size());
const Variable* b = db->variableList()[2];
ASSERT(b->isPointer());
ASSERT(!b->isConst());
const Token* varTok = Token::findsimplematch(tokenizer.tokens(), "b )");
ASSERT(varTok && varTok->valueType());
ASSERT_EQUALS(varTok->valueType()->constness, 0);
ASSERT_EQUALS(varTok->valueType()->pointer, 1);
}
}
void auto20() {
GET_SYMBOL_DB("enum A { A0 };\n"
"enum B { B0 };\n"
"const int& g(A a);\n"
"const int& g(B b);\n"
"void f() {\n"
" const auto& r = g(B::B0);\n"
"}\n");
const Token* a = Token::findsimplematch(tokenizer.tokens(), "auto");
ASSERT(a && a->valueType());
ASSERT_EQUALS(a->valueType()->type, ValueType::INT);
const Token* g = Token::findsimplematch(a, "g ( B ::");
ASSERT(g && g->function());
ASSERT_EQUALS(g->function()->tokenDef->linenr(), 4);
}
void auto21() {
GET_SYMBOL_DB("int f(bool b) {\n"
" std::vector<int> v1(1), v2(2);\n"
" auto& v = b ? v1 : v2;\n"
" v.push_back(1);\n"
" return v.size();\n"
"}\n");
ASSERT_EQUALS("", errout_str());
const Token* a = Token::findsimplematch(tokenizer.tokens(), "auto");
ASSERT(a && a->valueType());
ASSERT_EQUALS(a->valueType()->type, ValueType::CONTAINER);
const Token* v = Token::findsimplematch(a, "v . size");
ASSERT(v && v->valueType());
ASSERT_EQUALS(v->valueType()->type, ValueType::CONTAINER);
ASSERT(v->variable() && v->variable()->isReference());
}
void auto22() {
GET_SYMBOL_DB("void f(std::vector<std::string>& v, bool b) {\n"
" auto& s = b ? v[0] : v[1];\n"
" s += \"abc\";\n"
"}\n");
ASSERT_EQUALS("", errout_str());
const Token* a = Token::findsimplematch(tokenizer.tokens(), "auto");
ASSERT(a && a->valueType());
ASSERT_EQUALS(a->valueType()->type, ValueType::CONTAINER);
const Token* s = Token::findsimplematch(a, "s +=");
ASSERT(s && s->valueType());
ASSERT_EQUALS(s->valueType()->type, ValueType::CONTAINER);
ASSERT(s->valueType()->reference == Reference::LValue);
ASSERT(s->variable() && s->variable()->isReference());
}
void unionWithConstructor() {
GET_SYMBOL_DB("union Fred {\n"
" Fred(int x) : i(x) { }\n"
" Fred(float x) : f(x) { }\n"
" int i;\n"
" float f;\n"
"};");
ASSERT_EQUALS("", errout_str());
const Token *f = Token::findsimplematch(tokenizer.tokens(), "Fred ( int");
ASSERT(f && f->function() && f->function()->tokenDef->linenr() == 2);
f = Token::findsimplematch(tokenizer.tokens(), "Fred ( float");
ASSERT(f && f->function() && f->function()->tokenDef->linenr() == 3);
}
void incomplete_type() {
GET_SYMBOL_DB("template<class _Ty,\n"
" class _Alloc = std::allocator<_Ty>>\n"
" class SLSurfaceLayerData\n"
" : public _Vector_alloc<_Vec_base_types<_Ty, _Alloc>>\n"
"{ // varying size array of values\n"
"\n"
" using reverse_iterator = _STD reverse_iterator<iterator>;\n"
" using const_reverse_iterator = _STD reverse_iterator<const_iterator>;\n"
" const_reverse_iterator crend() const noexcept\n"
" { // return iterator for end of reversed nonmutable sequence\n"
" return (rend());\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void exprIds()
{
{
const char code[] = "int f(int a) {\n"
" return a +\n"
" a;\n"
"}\n";
ASSERT_EQUALS("", testExprIdEqual(code, "a", 2U, "a", 3U));
}
{
const char code[] = "int f(int a, int b) {\n"
" return a +\n"
" b;\n"
"}\n";
ASSERT_EQUALS(true, testExprIdNotEqual(code, "a", 2U, "b", 3U));
}
{
const char code[] = "int f(int a) {\n"
" int x = a++;\n"
" int y = a++;\n"
" return x + a;\n"
"}\n";
ASSERT_EQUALS(true, testExprIdNotEqual(code, "++", 2U, "++", 3U));
}
{
const char code[] = "int f(int a) {\n"
" int x = a;\n"
" return x + a;\n"
"}\n";
ASSERT_EQUALS(true, testExprIdNotEqual(code, "x", 3U, "a", 3U));
}
{
const char code[] = "int f(int a) {\n"
" int& x = a;\n"
" return x + a;\n"
"}\n";
TODO_ASSERT_EQUALS("", "x@2 != a@1", testExprIdEqual(code, "x", 3U, "a", 3U));
}
{
const char code[] = "int f(int a) {\n"
" int& x = a;\n"
" return (x + 1) +\n"
" (a + 1);\n"
"}\n";
ASSERT_EQUALS("", testExprIdEqual(code, "+", 3U, "+", 4U));
}
{
const char code[] = "int& g(int& x) { return x; }\n"
"int f(int a) {\n"
" return (g(a) + 1) +\n"
" (a + 1);\n"
"}\n";
ASSERT_EQUALS("", testExprIdEqual(code, "+", 3U, "+", 4U));
}
{
const char code[] = "int f(int a, int b) {\n"
" int x = (b-a)-a;\n"
" int y = (b-a)-a;\n"
" return x + y;\n"
"}\n";
ASSERT_EQUALS("", testExprIdEqual(code, "- a ;", 2U, "- a ;", 3U));
ASSERT_EQUALS("", testExprIdEqual(code, "- a )", 2U, "- a )", 3U));
ASSERT_EQUALS(true, testExprIdNotEqual(code, "- a )", 2U, "- a ;", 3U));
}
{
const char code[] = "int f(int a, int b) {\n"
" int x = a-(b-a);\n"
" int y = a-(b-a);\n"
" return x + y;\n"
"}\n";
ASSERT_EQUALS("", testExprIdEqual(code, "- ( b", 2U, "- ( b", 3U));
ASSERT_EQUALS("", testExprIdEqual(code, "- a )", 2U, "- a )", 3U));
ASSERT_EQUALS(true, testExprIdNotEqual(code, "- a )", 2U, "- ( b", 3U));
}
{
const char code[] = "void f(int a, int b) {\n"
" int x = (b+a)+a;\n"
" int y = a+(b+a);\n"
" return x + y;\n"
"}\n";
ASSERT_EQUALS("", testExprIdEqual(code, "+ a ;", 2U, "+ ( b", 3U));
ASSERT_EQUALS("", testExprIdEqual(code, "+ a ) +", 2U, "+ a ) ;", 3U));
ASSERT_EQUALS(true, testExprIdNotEqual(code, "+ a ;", 2U, "+ a )", 3U));
}
{
const char code[] = "void f(int a, int b) {\n"
" int x = (b+a)+a;\n"
" int y = a+(a+b);\n"
" return x + y;\n"
"}\n";
ASSERT_EQUALS("", testExprIdEqual(code, "+ a ;", 2U, "+ ( a", 3U));
ASSERT_EQUALS("", testExprIdEqual(code, "+ a ) +", 2U, "+ b ) ;", 3U));
ASSERT_EQUALS(true, testExprIdNotEqual(code, "+ a ;", 2U, "+ b", 3U));
}
{
const char code[] = "struct A { int x; };\n"
"void f(A a, int b) {\n"
" int x = (b-a.x)-a.x;\n"
" int y = (b-a.x)-a.x;\n"
" return x + y;\n"
"}\n";
ASSERT_EQUALS("", testExprIdEqual(code, "- a . x ;", 3U, "- a . x ;", 4U));
ASSERT_EQUALS("", testExprIdEqual(code, "- a . x )", 3U, "- a . x )", 4U));
}
{
const char code[] = "struct A { int x; };\n"
"void f(A a, int b) {\n"
" int x = a.x-(b-a.x);\n"
" int y = a.x-(b-a.x);\n"
" return x + y;\n"
"}\n";
ASSERT_EQUALS("", testExprIdEqual(code, "- ( b", 3U, "- ( b", 4U));
ASSERT_EQUALS("", testExprIdEqual(code, "- a . x )", 3U, "- a . x )", 4U));
}
{
const char code[] = "struct A { int x; };\n"
"void f(A a) {\n"
" int x = a.x;\n"
" int y = a.x;\n"
" return x + y;\n"
"}\n";
ASSERT_EQUALS("", testExprIdEqual(code, ". x", 3U, ". x", 4U));
}
{
const char code[] = "struct A { int x; };\n"
"void f(A a, A b) {\n"
" int x = a.x;\n"
" int y = b.x;\n"
" return x + y;\n"
"}\n";
ASSERT_EQUALS(true, testExprIdNotEqual(code, ". x", 3U, ". x", 4U));
}
{
const char code[] = "struct A { int y; };\n"
"struct B { A x; }\n"
"void f(B a) {\n"
" int x = a.x.y;\n"
" int y = a.x.y;\n"
" return x + y;\n"
"}\n";
ASSERT_EQUALS("", testExprIdEqual(code, ". x . y", 4U, ". x . y", 5U));
ASSERT_EQUALS("", testExprIdEqual(code, ". y", 4U, ". y", 5U));
}
{
const char code[] = "struct A { int y; };\n"
"struct B { A x; }\n"
"void f(B a, B b) {\n"
" int x = a.x.y;\n"
" int y = b.x.y;\n"
" return x + y;\n"
"}\n";
ASSERT_EQUALS(true, testExprIdNotEqual(code, ". x . y", 4U, ". x . y", 5U));
ASSERT_EQUALS(true, testExprIdNotEqual(code, ". y", 4U, ". y", 5U));
}
{
const char code[] = "struct A { int g(); };\n"
"struct B { A x; }\n"
"void f(B a) {\n"
" int x = a.x.g();\n"
" int y = a.x.g();\n"
" return x + y;\n"
"}\n";
ASSERT_EQUALS("", testExprIdEqual(code, ". x . g ( )", 4U, ". x . g ( )", 5U));
ASSERT_EQUALS("", testExprIdEqual(code, ". g ( )", 4U, ". g ( )", 5U));
}
{
const char code[] = "struct A { int g(int, int); };\n"
"struct B { A x; }\n"
"void f(B a, int b, int c) {\n"
" int x = a.x.g(b, c);\n"
" int y = a.x.g(b, c);\n"
" return x + y;\n"
"}\n";
ASSERT_EQUALS("", testExprIdEqual(code, ". x . g ( b , c )", 4U, ". x . g ( b , c )", 5U));
ASSERT_EQUALS("", testExprIdEqual(code, ". g ( b , c )", 4U, ". g ( b , c )", 5U));
}
{
const char code[] = "int g();\n"
"void f() {\n"
" int x = g();\n"
" int y = g();\n"
" return x + y;\n"
"}\n";
ASSERT_EQUALS("", testExprIdEqual(code, "(", 3U, "(", 4U));
}
{
const char code[] = "struct A { int g(); };\n"
"void f() {\n"
" int x = A::g();\n"
" int y = A::g();\n"
" return x + y;\n"
"}\n";
ASSERT_EQUALS("", testExprIdEqual(code, "(", 3U, "(", 4U));
}
{
const char code[] = "int g();\n"
"void f(int a, int b) {\n"
" int x = g(a, b);\n"
" int y = g(a, b);\n"
" return x + y;\n"
"}\n";
ASSERT_EQUALS("", testExprIdEqual(code, "(", 3U, "(", 4U));
}
{
const char code[] = "struct A { int g(); };\n"
"void f() {\n"
" int x = A::g(a, b);\n"
" int y = A::g(a, b);\n"
" return x + y;\n"
"}\n";
ASSERT_EQUALS("", testExprIdEqual(code, "(", 3U, "(", 4U));
}
{
const char code[] = "int g();\n"
"void f(int a, int b) {\n"
" int x = g(a, b);\n"
" int y = g(b, a);\n"
" return x + y;\n"
"}\n";
ASSERT_EQUALS(true, testExprIdNotEqual(code, "(", 3U, "(", 4U));
}
{
const char code[] = "struct A { int g(); };\n"
"void f() {\n"
" int x = A::g(a, b);\n"
" int y = A::g(b, a);\n"
" return x + y;\n"
"}\n";
ASSERT_EQUALS(true, testExprIdNotEqual(code, "(", 3U, "(", 4U));
}
}
void testValuetypeOriginalName() {
{
GET_SYMBOL_DB("typedef void ( *fp16 )( int16_t n );\n"
"typedef void ( *fp32 )( int32_t n );\n"
"void R_11_1 ( void ) {\n"
" fp16 fp1 = NULL;\n"
" fp32 fp2 = ( fp32) fp1;\n"
"}\n");
const Token* tok = Token::findsimplematch(tokenizer.tokens(), "( void * ) fp1");
ASSERT_EQUALS(tok->isCast(), true);
ASSERT(tok->valueType());
ASSERT(tok->valueType()->originalTypeName == "fp32");
ASSERT(tok->valueType()->pointer == 1);
ASSERT(tok->valueType()->constness == 0);
}
{
GET_SYMBOL_DB("typedef void ( *fp16 )( int16_t n );\n"
"fp16 fp3 = ( fp16 ) 0x8000;");
const Token* tok = Token::findsimplematch(tokenizer.tokens(), "( void * ) 0x8000");
ASSERT_EQUALS(tok->isCast(), true);
ASSERT(tok->valueType());
ASSERT(tok->valueType()->originalTypeName == "fp16");
ASSERT(tok->valueType()->pointer == 1);
ASSERT(tok->valueType()->constness == 0);
}
}
};
REGISTER_TEST(TestSymbolDatabase)
| null |
1,003 | cpp | cppcheck | test64bit.cpp | test/test64bit.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#include "check64bit.h"
#include "errortypes.h"
#include "fixture.h"
#include "helpers.h"
#include "settings.h"
#include <cstddef>
class Test64BitPortability : public TestFixture {
public:
Test64BitPortability() : TestFixture("Test64BitPortability") {}
private:
const Settings settings = settingsBuilder().severity(Severity::portability).library("std.cfg").build();
void run() override {
TEST_CASE(novardecl);
TEST_CASE(functionpar);
TEST_CASE(structmember);
TEST_CASE(ptrcompare);
TEST_CASE(ptrarithmetic);
TEST_CASE(returnIssues);
TEST_CASE(assignment);
}
#define check(code) check_(code, __FILE__, __LINE__)
template<size_t size>
void check_(const char (&code)[size], const char* file, int line) {
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
// Check char variable usage..
Check64BitPortability check64BitPortability(&tokenizer, &settings, this);
check64BitPortability.pointerassignment();
}
void assignment() {
// #8631
check("using CharArray = char[16];\n"
"void f() {\n"
" CharArray foo = \"\";\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct T { std::vector<int>*a[2][2]; };\n" // #11560
"void f(T& t, int i, int j) {\n"
" t.a[i][j] = new std::vector<int>;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void novardecl() {
// if the variable declarations can't be seen then skip the warning
check("void foo()\n"
"{\n"
" a = p;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void functionpar() {
check("int foo(int *p)\n"
"{\n"
" int a = p;\n"
" return a + 4;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (portability) Assigning a pointer to an integer is not portable.\n", errout_str());
check("int foo(int p[])\n"
"{\n"
" int a = p;\n"
" return a + 4;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (portability) Assigning a pointer to an integer is not portable.\n", errout_str());
check("int foo(int p[])\n"
"{\n"
" int *a = p;\n"
" return a;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (portability) Returning an address value in a function with integer return type is not portable.\n", errout_str());
check("void foo(int x)\n"
"{\n"
" int *p = x;\n"
" *p = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (portability) Assigning an integer to a pointer is not portable.\n", errout_str());
check("int f(const char *p) {\n" // #4659
" return 6 + p[2] * 256;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int foo(int *p) {\n" // #6096
" bool a = p;\n"
" return a;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("std::array<int,2> f();\n"
"void g() {\n"
" std::array<int, 2> a = f();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("std::array<int,2> f(int x);\n"
"void g(int i) {\n"
" std::array<int, 2> a = f(i);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("typedef std::array<int, 2> Array;\n"
"Array f(int x);\n"
"void g(int i) {\n"
" Array a = f(i);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("typedef std::array<int, 2> Array;\n"
"Array f();\n"
"void g(int i) {\n"
" Array a = f();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct S {\n" // #9951
" enum E { E0 };\n"
" std::array<double, 1> g(S::E);\n"
"};\n"
"void f() {\n"
" std::array<double, 1> a = S::g(S::E::E0);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("char* f(char* p) {\n"
" return p ? p : 0;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void structmember() {
check("struct Foo { int *p; };\n"
"void f(struct Foo *foo) {\n"
" int i = foo->p;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (portability) Assigning a pointer to an integer is not portable.\n", errout_str());
check("struct S {\n" // #10145
" enum class E { e1, e2 };\n"
" E e;\n"
" char* e1;\n"
"};\n"
"void f(S& s) {\n"
" s.e = S::E::e1;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void ptrcompare() {
// Ticket #2892
check("void foo(int *p) {\n"
" int a = (p != NULL);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void ptrarithmetic() {
// #3073
check("void foo(int *p) {\n"
" int x = 10;\n"
" int *a = p + x;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(int *p) {\n"
" int x = 10;\n"
" int *a = x + p;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(int *p) {\n"
" int x = 10;\n"
" int *a = x * x;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (portability) Assigning an integer to a pointer is not portable.\n", errout_str());
check("void foo(int *start, int *end) {\n"
" int len;\n"
" int len = end + 10 - start;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void returnIssues() {
check("void* foo(int i) {\n"
" return i;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (portability) Returning an integer in a function with pointer return type is not portable.\n", errout_str());
check("void* foo(int* i) {\n"
" return i;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void* foo() {\n"
" return 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int foo(int i) {\n"
" return i;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct Foo {};\n"
"\n"
"int* dostuff(Foo foo) {\n"
" return foo;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int foo(char* c) {\n"
" return c;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (portability) Returning an address value in a function with integer return type is not portable.\n", errout_str());
check("int foo(char* c) {\n"
" return 1+c;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (portability) Returning an address value in a function with integer return type is not portable.\n", errout_str());
check("std::string foo(char* c) {\n"
" return c;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int foo(char *a, char *b) {\n" // #4486
" return a + 1 - b;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct s {\n" // 4642
" int i;\n"
"};\n"
"int func(struct s *p) {\n"
" return 1 + p->i;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("static void __iomem *f(unsigned int port_no) {\n"
" void __iomem *mmio = hpriv->mmio;\n"
" return mmio + (port_no * 0x80);\n"
"}");
ASSERT_EQUALS("", errout_str());
// #7247: don't check return statements in nested functions..
check("int foo() {\n"
" struct {\n"
" const char * name() { return \"abc\"; }\n"
" } table;\n"
"}");
ASSERT_EQUALS("", errout_str());
// #7451: Lambdas
check("const int* test(std::vector<int> outputs, const std::string& text) {\n"
" auto it = std::find_if(outputs.begin(), outputs.end(),\n"
" [&](int ele) { return \"test\" == text; });\n"
" return nullptr;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct S {\n" // #12159
" std::future<int> f() const {\n"
" return {};\n"
" }\n"
"};\n"
"int g() {\n"
" std::shared_ptr<S> s = std::make_shared<S>();\n"
" auto x = s->f();\n"
" return x.get();\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
};
REGISTER_TEST(Test64BitPortability)
| null |
1,004 | cpp | cppcheck | testfilelister.cpp | test/testfilelister.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#include "filelister.h"
#include "filesettings.h"
#include "path.h"
#include "pathmatch.h"
#include "fixture.h"
#include <algorithm>
#include <list>
#include <stdexcept>
#include <string>
#include <vector>
#include <utility>
class TestFileLister : public TestFixture {
public:
TestFileLister() : TestFixture("TestFileLister") {}
private:
void run() override {
TEST_CASE(recursiveAddFiles);
TEST_CASE(recursiveAddFilesEmptyPath);
TEST_CASE(excludeFile1);
TEST_CASE(excludeFile2);
}
// TODO: generate file list instead
static std::string findBaseDir() {
std::string basedir;
while (!Path::isDirectory(Path::join(basedir, ".github"))) {
const std::string abspath = Path::getAbsoluteFilePath(basedir);
basedir += "../";
// no more going up
if (Path::getAbsoluteFilePath(basedir) == abspath)
throw std::runtime_error("could not find repository root directory");
}
return basedir;
}
void recursiveAddFiles() const {
const std::string adddir = findBaseDir() + ".";
// Recursively add add files..
std::list<FileWithDetails> files;
std::vector<std::string> masks;
PathMatch matcher(std::move(masks));
std::string err = FileLister::recursiveAddFiles(files, adddir, matcher);
ASSERT_EQUALS("", err);
ASSERT(!files.empty());
#ifdef _WIN32
std::string dirprefix;
if (adddir != ".")
dirprefix = adddir + "/";
#else
const std::string dirprefix = adddir + "/";
#endif
const auto find_file = [&](const std::string& name) {
return std::find_if(files.cbegin(), files.cend(), [&name](const FileWithDetails& entry) {
return entry.path() == name;
});
};
// Make sure source files are added..
ASSERT(find_file(dirprefix + "cli/main.cpp") != files.end());
ASSERT(find_file(dirprefix + "lib/token.cpp") != files.end());
ASSERT(find_file(dirprefix + "lib/tokenize.cpp") != files.end());
ASSERT(find_file(dirprefix + "gui/main.cpp") != files.end());
ASSERT(find_file(dirprefix + "test/testfilelister.cpp") != files.end());
// Make sure headers are not added..
ASSERT(find_file(dirprefix + "lib/tokenize.h") == files.end());
}
void recursiveAddFilesEmptyPath() const {
std::list<FileWithDetails> files;
const std::string err = FileLister::recursiveAddFiles(files, "", PathMatch({}));
ASSERT_EQUALS("no path specified", err);
}
void excludeFile1() const {
const std::string basedir = findBaseDir();
std::list<FileWithDetails> files;
std::vector<std::string> ignored{"lib/token.cpp"};
PathMatch matcher(ignored);
std::string err = FileLister::recursiveAddFiles(files, basedir + "lib/token.cpp", matcher);
ASSERT_EQUALS("", err);
ASSERT(files.empty());
}
void excludeFile2() const {
const std::string basedir = findBaseDir();
std::list<FileWithDetails> files;
std::vector<std::string> ignored;
PathMatch matcher(ignored);
std::string err = FileLister::recursiveAddFiles(files, basedir + "lib/token.cpp", matcher);
ASSERT_EQUALS("", err);
ASSERT_EQUALS(1, files.size());
ASSERT_EQUALS(basedir + "lib/token.cpp", files.begin()->path());
}
// TODO: test errors
};
REGISTER_TEST(TestFileLister)
| null |
1,005 | cpp | cppcheck | testimportproject.cpp | test/testimportproject.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#include "importproject.h"
#include "settings.h"
#include "filesettings.h"
#include "fixture.h"
#include "redirect.h"
#include <list>
#include <map>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
class TestImporter : public ImportProject {
public:
using ImportProject::importCompileCommands;
using ImportProject::importCppcheckGuiProject;
bool sourceFileExists(const std::string & /*file*/) override {
return true;
}
};
class TestImportProject : public TestFixture {
public:
TestImportProject() : TestFixture("TestImportProject") {}
private:
void run() override {
TEST_CASE(setDefines);
TEST_CASE(setIncludePaths1);
TEST_CASE(setIncludePaths2);
TEST_CASE(setIncludePaths3); // macro names are case insensitive
TEST_CASE(importCompileCommands1);
TEST_CASE(importCompileCommands2); // #8563, #9567
TEST_CASE(importCompileCommands3); // check with existing trailing / in directory
TEST_CASE(importCompileCommands4); // only accept certain file types
TEST_CASE(importCompileCommands5); // Windows/CMake/Ninja generated compile_commands.json
TEST_CASE(importCompileCommands6); // Windows/CMake/Ninja generated compile_commands.json with spaces
TEST_CASE(importCompileCommands7); // linux: "/home/danielm/cppcheck 2"
TEST_CASE(importCompileCommands8); // Windows: "C:\Users\danielm\cppcheck"
TEST_CASE(importCompileCommands9);
TEST_CASE(importCompileCommands10); // #10887: include path with space
TEST_CASE(importCompileCommands11); // include path order
TEST_CASE(importCompileCommands12); // #13040: "directory" is parent directory, relative include paths
TEST_CASE(importCompileCommandsArgumentsSection); // Handle arguments section
TEST_CASE(importCompileCommandsNoCommandSection); // gracefully handles malformed json
TEST_CASE(importCppcheckGuiProject);
TEST_CASE(ignorePaths);
}
void setDefines() const {
FileSettings fs{"test.cpp"};
ImportProject::fsSetDefines(fs, "A");
ASSERT_EQUALS("A=1", fs.defines);
ImportProject::fsSetDefines(fs, "A;B;");
ASSERT_EQUALS("A=1;B=1", fs.defines);
ImportProject::fsSetDefines(fs, "A;;B;");
ASSERT_EQUALS("A=1;B=1", fs.defines);
ImportProject::fsSetDefines(fs, "A;;B");
ASSERT_EQUALS("A=1;B=1", fs.defines);
}
void setIncludePaths1() const {
FileSettings fs{"test.cpp"};
std::list<std::string> in(1, "../include");
std::map<std::string, std::string, cppcheck::stricmp> variables;
ImportProject::fsSetIncludePaths(fs, "abc/def/", in, variables);
ASSERT_EQUALS(1U, fs.includePaths.size());
ASSERT_EQUALS("abc/include/", fs.includePaths.front());
}
void setIncludePaths2() const {
FileSettings fs{"test.cpp"};
std::list<std::string> in(1, "$(SolutionDir)other");
std::map<std::string, std::string, cppcheck::stricmp> variables;
variables["SolutionDir"] = "c:/abc/";
ImportProject::fsSetIncludePaths(fs, "/home/fred", in, variables);
ASSERT_EQUALS(1U, fs.includePaths.size());
ASSERT_EQUALS("c:/abc/other/", fs.includePaths.front());
}
void setIncludePaths3() const { // macro names are case insensitive
FileSettings fs{"test.cpp"};
std::list<std::string> in(1, "$(SOLUTIONDIR)other");
std::map<std::string, std::string, cppcheck::stricmp> variables;
variables["SolutionDir"] = "c:/abc/";
ImportProject::fsSetIncludePaths(fs, "/home/fred", in, variables);
ASSERT_EQUALS(1U, fs.includePaths.size());
ASSERT_EQUALS("c:/abc/other/", fs.includePaths.front());
}
void importCompileCommands1() const {
REDIRECT;
constexpr char json[] = R"([{
"directory": "/tmp",
"command": "gcc -DTEST1 -DTEST2=2 -o /tmp/src.o -c /tmp/src.c",
"file": "/tmp/src.c"
}])";
std::istringstream istr(json);
TestImporter importer;
ASSERT_EQUALS(true, importer.importCompileCommands(istr));
ASSERT_EQUALS(1, importer.fileSettings.size());
ASSERT_EQUALS("TEST1=1;TEST2=2", importer.fileSettings.cbegin()->defines);
}
void importCompileCommands2() const {
REDIRECT;
// Absolute file path
#ifdef _WIN32
const char json[] = R"([{
"directory": "C:/foo",
"command": "gcc -c /bar.c",
"file": "/bar.c"
}])";
std::istringstream istr(json);
TestImporter importer;
ASSERT_EQUALS(true, importer.importCompileCommands(istr));
ASSERT_EQUALS(1, importer.fileSettings.size());
ASSERT_EQUALS("C:/bar.c", importer.fileSettings.cbegin()->filename());
#else
constexpr char json[] = R"([{
"directory": "/foo",
"command": "gcc -c bar.c",
"file": "/bar.c"
}])";
std::istringstream istr(json);
TestImporter importer;
ASSERT_EQUALS(true, importer.importCompileCommands(istr));
ASSERT_EQUALS(1, importer.fileSettings.size());
ASSERT_EQUALS("/bar.c", importer.fileSettings.cbegin()->filename());
#endif
}
void importCompileCommands3() const {
REDIRECT;
const char json[] = R"([{
"directory": "/tmp/",
"command": "gcc -c src.c",
"file": "src.c"
}])";
std::istringstream istr(json);
TestImporter importer;
ASSERT_EQUALS(true, importer.importCompileCommands(istr));
ASSERT_EQUALS(1, importer.fileSettings.size());
ASSERT_EQUALS("/tmp/src.c", importer.fileSettings.cbegin()->filename());
}
void importCompileCommands4() const {
REDIRECT;
constexpr char json[] = R"([{
"directory": "/tmp/",
"command": "gcc -c src.mm",
"file": "src.mm"
}])";
std::istringstream istr(json);
TestImporter importer;
ASSERT_EQUALS(true, importer.importCompileCommands(istr));
ASSERT_EQUALS(0, importer.fileSettings.size());
}
void importCompileCommands5() const {
REDIRECT;
constexpr char json[] =
R"([{
"directory": "C:/Users/dan/git/build-test-cppcheck-Desktop_Qt_5_15_0_MSVC2019_64bit-Debug",
"command": "C:\\PROGRA~2\\MICROS~1\\2019\\COMMUN~1\\VC\\Tools\\MSVC\\1427~1.291\\bin\\HostX64\\x64\\cl.exe /nologo /TP -IC:\\Users\\dan\\git\\test-cppcheck\\mylib\\src /DWIN32 /D_WINDOWS /GR /EHsc /Zi /Ob0 /Od /RTC1 -MDd -std:c++17 /Fomylib\\CMakeFiles\\mylib.dir\\src\\foobar\\mylib.cpp.obj /FdTARGET_COMPILE_PDB /FS -c C:\\Users\\dan\\git\\test-cppcheck\\mylib\\src\\foobar\\mylib.cpp",
"file": "C:\\Users\\dan\\git\\test-cppcheck\\mylib\\src\\foobar\\mylib.cpp"
},
{
"directory": "C:/Users/dan/git/build-test-cppcheck-Desktop_Qt_5_15_0_MSVC2019_64bit-Debug",
"command": "C:\\PROGRA~2\\MICROS~1\\2019\\COMMUN~1\\VC\\Tools\\MSVC\\1427~1.291\\bin\\HostX64\\x64\\cl.exe /nologo /TP -IC:\\Users\\dan\\git\\test-cppcheck\\myapp\\src -Imyapp -IC:\\Users\\dan\\git\\test-cppcheck\\mylib\\src /DWIN32 /D_WINDOWS /GR /EHsc /Zi /Ob0 /Od /RTC1 -MDd -std:c++17 /Fomyapp\\CMakeFiles\\myapp.dir\\src\\main.cpp.obj /FdTARGET_COMPILE_PDB /FS -c C:\\Users\\dan\\git\\test-cppcheck\\myapp\\src\\main.cpp",
"file": "C:\\Users\\dan\\git\\test-cppcheck\\myapp\\src\\main.cpp"
}])";
std::istringstream istr(json);
TestImporter importer;
ASSERT_EQUALS(true, importer.importCompileCommands(istr));
ASSERT_EQUALS(2, importer.fileSettings.size());
ASSERT_EQUALS("C:/Users/dan/git/test-cppcheck/mylib/src/", importer.fileSettings.cbegin()->includePaths.front());
}
void importCompileCommands6() const {
REDIRECT;
constexpr char json[] =
R"([{
"directory": "C:/Users/dan/git/build-test-cppcheck-Desktop_Qt_5_15_0_MSVC2019_64bit-Debug",
"command": "C:\\PROGRA~2\\MICROS~1\\2019\\COMMUN~1\\VC\\Tools\\MSVC\\1427~1.291\\bin\\HostX64\\x64\\cl.exe /nologo /TP -IC:\\Users\\dan\\git\\test-cppcheck\\mylib\\src -I\"C:\\Users\\dan\\git\\test-cppcheck\\mylib\\second src\" /DWIN32 /D_WINDOWS /GR /EHsc /Zi /Ob0 /Od /RTC1 -MDd -std:c++17 /Fomylib\\CMakeFiles\\mylib.dir\\src\\foobar\\mylib.cpp.obj /FdTARGET_COMPILE_PDB /FS -c C:\\Users\\dan\\git\\test-cppcheck\\mylib\\src\\foobar\\mylib.cpp",
"file": "C:\\Users\\dan\\git\\test-cppcheck\\mylib\\src\\foobar\\mylib.cpp"
},
{
"directory": "C:/Users/dan/git/build-test-cppcheck-Desktop_Qt_5_15_0_MSVC2019_64bit-Debug",
"command": "C:\\PROGRA~2\\MICROS~1\\2019\\COMMUN~1\\VC\\Tools\\MSVC\\1427~1.291\\bin\\HostX64\\x64\\cl.exe /nologo /TP -IC:\\Users\\dan\\git\\test-cppcheck\\myapp\\src -Imyapp -IC:\\Users\\dan\\git\\test-cppcheck\\mylib\\src /DWIN32 /D_WINDOWS /GR /EHsc /Zi /Ob0 /Od /RTC1 -MDd -std:c++17 /Fomyapp\\CMakeFiles\\myapp.dir\\src\\main.cpp.obj /FdTARGET_COMPILE_PDB /FS -c C:\\Users\\dan\\git\\test-cppcheck\\myapp\\src\\main.cpp",
"file": "C:\\Users\\dan\\git\\test-cppcheck\\myapp\\src\\main.cpp"
}])";
std::istringstream istr(json);
TestImporter importer;
ASSERT_EQUALS(true, importer.importCompileCommands(istr));
ASSERT_EQUALS(2, importer.fileSettings.size());
ASSERT_EQUALS("C:/Users/dan/git/test-cppcheck/mylib/src/", importer.fileSettings.cbegin()->includePaths.front());
ASSERT_EQUALS("C:/Users/dan/git/test-cppcheck/mylib/second src/", importer.fileSettings.cbegin()->includePaths.back());
}
void importCompileCommands7() const {
REDIRECT;
// cmake -DFILESDIR="/some/path" ..
constexpr char json[] =
R"([{
"directory": "/home/danielm/cppcheck 2/b/lib",
"command": "/usr/bin/c++ -DFILESDIR=\\\"/some/path\\\" -I\"/home/danielm/cppcheck 2/b/lib\" -isystem \"/home/danielm/cppcheck 2/externals\" \"/home/danielm/cppcheck 2/lib/astutils.cpp\"",
"file": "/home/danielm/cppcheck 2/lib/astutils.cpp"
}])";
std::istringstream istr(json);
TestImporter importer;
ASSERT_EQUALS(true, importer.importCompileCommands(istr));
ASSERT_EQUALS(1, importer.fileSettings.size());
ASSERT_EQUALS("FILESDIR=\"/some/path\"", importer.fileSettings.cbegin()->defines);
ASSERT_EQUALS(1, importer.fileSettings.cbegin()->includePaths.size());
ASSERT_EQUALS("/home/danielm/cppcheck 2/b/lib/", importer.fileSettings.cbegin()->includePaths.front());
TODO_ASSERT_EQUALS("/home/danielm/cppcheck 2/externals/",
"/home/danielm/cppcheck 2/b/lib/",
importer.fileSettings.cbegin()->includePaths.back());
}
void importCompileCommands8() const {
REDIRECT;
// cmake -DFILESDIR="C:\Program Files\Cppcheck" -G"NMake Makefiles" ..
constexpr char json[] =
R"([{
"directory": "C:/Users/danielm/cppcheck/build/lib",
"command": "C:\\PROGRA~2\\MICROS~2\\2017\\COMMUN~1\\VC\\Tools\\MSVC\\1412~1.258\\bin\\Hostx64\\x64\\cl.exe /nologo /TP -DFILESDIR=\"\\\"C:\\Program Files\\Cppcheck\\\"\" -IC:\\Users\\danielm\\cppcheck\\build\\lib -IC:\\Users\\danielm\\cppcheck\\lib -c C:\\Users\\danielm\\cppcheck\\lib\\astutils.cpp",
"file": "C:/Users/danielm/cppcheck/lib/astutils.cpp"
}])";
std::istringstream istr(json);
TestImporter importer;
ASSERT_EQUALS(true, importer.importCompileCommands(istr)); // Do not crash
}
void importCompileCommands9() const {
REDIRECT;
// IAR output (https://sourceforge.net/p/cppcheck/discussion/general/thread/608af51e0a/)
constexpr char json[] =
R"([{
"arguments" : [
"powershell.exe -WindowStyle Hidden -NoProfile -ExecutionPolicy Bypass -File d:\\Projekte\\xyz\\firmware\\app\\xyz-lib\\build.ps1 -IAR -COMPILER_PATH \"c:\\Program Files (x86)\\IAR Systems\\Embedded Workbench 9.0\" -CONTROLLER CC1310F128 -LIB LIB_PERMANENT -COMPILER_DEFINES \"CC1310_HFXO_FREQ=24000000 DEBUG\""
],
"directory" : "d:\\Projekte\\xyz\\firmware\\app",
"type" : "PRE",
"file": "1.c"
}])";
std::istringstream istr(json);
TestImporter importer;
ASSERT_EQUALS(true, importer.importCompileCommands(istr));
}
void importCompileCommands10() const { // #10887
REDIRECT;
constexpr char json[] =
R"([{
"file": "/home/danielm/cppcheck/1/test folder/1.c" ,
"directory": "",
"arguments": [
"iccavr.exe",
"-I",
"/home/danielm/cppcheck/test folder"
]
}])";
std::istringstream istr(json);
TestImporter importer;
ASSERT_EQUALS(true, importer.importCompileCommands(istr));
ASSERT_EQUALS(1, importer.fileSettings.size());
const FileSettings &fs = importer.fileSettings.front();
ASSERT_EQUALS("/home/danielm/cppcheck/test folder/", fs.includePaths.front());
}
void importCompileCommands11() const { // include path order
REDIRECT;
constexpr char json[] =
R"([{
"file": "1.c" ,
"directory": "/x",
"arguments": [
"cc",
"-I",
"def",
"-I",
"abc"
]
}])";
std::istringstream istr(json);
TestImporter importer;
ASSERT_EQUALS(true, importer.importCompileCommands(istr));
ASSERT_EQUALS(1, importer.fileSettings.size());
const FileSettings &fs = importer.fileSettings.front();
ASSERT_EQUALS("/x/def/", fs.includePaths.front());
ASSERT_EQUALS("/x/abc/", fs.includePaths.back());
}
void importCompileCommands12() const { // #13040
REDIRECT;
constexpr char json[] =
R"([{
"file": "/x/src/1.c" ,
"directory": "/x",
"command": "cc -c -I. src/1.c"
}])";
std::istringstream istr(json);
TestImporter importer;
ASSERT_EQUALS(true, importer.importCompileCommands(istr));
ASSERT_EQUALS(1, importer.fileSettings.size());
const FileSettings &fs = importer.fileSettings.front();
ASSERT_EQUALS(1, fs.includePaths.size());
ASSERT_EQUALS("/x/", fs.includePaths.front());
}
void importCompileCommandsArgumentsSection() const {
REDIRECT;
constexpr char json[] = "[ { \"directory\": \"/tmp/\","
"\"arguments\": [\"gcc\", \"-c\", \"src.c\"],"
"\"file\": \"src.c\" } ]";
std::istringstream istr(json);
TestImporter importer;
ASSERT_EQUALS(true, importer.importCompileCommands(istr));
ASSERT_EQUALS(1, importer.fileSettings.size());
ASSERT_EQUALS("/tmp/src.c", importer.fileSettings.cbegin()->filename());
}
void importCompileCommandsNoCommandSection() const {
REDIRECT;
constexpr char json[] = "[ { \"directory\": \"/tmp/\","
"\"file\": \"src.mm\" } ]";
std::istringstream istr(json);
TestImporter importer;
ASSERT_EQUALS(false, importer.importCompileCommands(istr));
ASSERT_EQUALS(0, importer.fileSettings.size());
ASSERT_EQUALS("cppcheck: error: no 'arguments' or 'command' field found in compilation database entry\n", GET_REDIRECT_OUTPUT);
}
void importCppcheckGuiProject() const {
REDIRECT;
constexpr char xml[] = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<project version=\"1\">\n"
" <root name=\".\"/>\n"
" <builddir>out1</builddir>\n"
" <analyze-all-vs-configs>true</analyze-all-vs-configs>\n"
" <includedir>\n"
" <dir name=\"lib/\"/>\n"
" </includedir>\n"
" <paths>\n"
" <dir name=\"cli/\"/>\n"
" </paths>\n"
" <exclude>\n"
" <path name=\"gui/temp/\"/>\n"
" </exclude>\n"
" <inline-suppression>true</inline-suppression>\n"
" <project-name>test test</project-name>\n"
"</project>\n";
std::istringstream istr(xml);
Settings s;
TestImporter project;
ASSERT_EQUALS(true, project.importCppcheckGuiProject(istr, &s));
ASSERT_EQUALS(1, project.guiProject.pathNames.size());
ASSERT_EQUALS("cli/", project.guiProject.pathNames[0]);
ASSERT_EQUALS(1, s.includePaths.size());
ASSERT_EQUALS("lib/", s.includePaths.front());
ASSERT_EQUALS(true, s.inlineSuppressions);
}
void ignorePaths() const {
FileSettings fs1{"foo/bar"};
FileSettings fs2{"qwe/rty"};
TestImporter project;
project.fileSettings = {std::move(fs1), std::move(fs2)};
project.ignorePaths({"*foo", "bar*"});
ASSERT_EQUALS(2, project.fileSettings.size());
project.ignorePaths({"foo/*"});
ASSERT_EQUALS(1, project.fileSettings.size());
ASSERT_EQUALS("qwe/rty", project.fileSettings.front().filename());
project.ignorePaths({ "*e/r*" });
ASSERT_EQUALS(0, project.fileSettings.size());
}
// TODO: test fsParseCommand()
// TODO: test vcxproj conditions
/*
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<PreprocessorDefinitions>CPPCHECKLIB_IMPORT</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="main.c" />
</ItemGroup>
</Project>
*/
};
REGISTER_TEST(TestImportProject)
| null |
1,006 | cpp | cppcheck | testerrorlogger.cpp | test/testerrorlogger.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#include "config.h"
#include "cppcheck.h"
#include "errorlogger.h"
#include "errortypes.h"
#include "fixture.h"
#include <list>
#include <string>
#include <utility>
#include "xml.h"
class TestErrorLogger : public TestFixture {
public:
TestErrorLogger() : TestFixture("TestErrorLogger") {}
private:
const ErrorMessage::FileLocation fooCpp5{"foo.cpp", 5, 1};
const ErrorMessage::FileLocation barCpp8{"bar.cpp", 8, 1};
const ErrorMessage::FileLocation barCpp8_i{"bar.cpp", "ä", 8, 1};
void run() override {
TEST_CASE(PatternSearchReplace);
TEST_CASE(FileLocationConstruct);
TEST_CASE(FileLocationSetFile);
TEST_CASE(ErrorMessageConstruct);
TEST_CASE(ErrorMessageConstructLocations);
TEST_CASE(ErrorMessageVerbose);
TEST_CASE(ErrorMessageVerboseLocations);
TEST_CASE(ErrorMessageFromInternalError);
TEST_CASE(CustomFormat);
TEST_CASE(CustomFormat2);
TEST_CASE(CustomFormatLocations);
TEST_CASE(ToXmlV2);
TEST_CASE(ToXmlV2RemarkComment);
TEST_CASE(ToXmlV2Locations);
TEST_CASE(ToXmlV2Encoding);
TEST_CASE(FromXmlV2);
TEST_CASE(ToXmlV3);
// Inconclusive results in xml reports..
TEST_CASE(InconclusiveXml);
// Serialize / Deserialize inconclusive message
TEST_CASE(SerializeInconclusiveMessage);
TEST_CASE(DeserializeInvalidInput);
TEST_CASE(SerializeSanitize);
TEST_CASE(SerializeFileLocation);
TEST_CASE(SerializeAndDeserializeRemark);
TEST_CASE(substituteTemplateFormatStatic);
TEST_CASE(substituteTemplateLocationStatic);
TEST_CASE(isCriticalErrorId);
}
void TestPatternSearchReplace(const std::string& idPlaceholder, const std::string& id) const {
const std::string plainText = "text";
ErrorMessage message;
message.id = id;
std::string serialized = message.toString(true, idPlaceholder + plainText + idPlaceholder);
ASSERT_EQUALS(id + plainText + id, serialized);
serialized = message.toString(true, idPlaceholder + idPlaceholder);
ASSERT_EQUALS(id + id, serialized);
serialized = message.toString(true, plainText + idPlaceholder + plainText);
ASSERT_EQUALS(plainText + id + plainText, serialized);
}
void PatternSearchReplace() const {
const std::string idPlaceholder = "{id}";
const std::string empty;
TestPatternSearchReplace(idPlaceholder, empty);
const std::string shortIdValue = "ID";
ASSERT_EQUALS(true, shortIdValue.length() < idPlaceholder.length());
TestPatternSearchReplace(idPlaceholder, shortIdValue);
const std::string mediumIdValue = "_ID_";
ASSERT_EQUALS(mediumIdValue.length(), idPlaceholder.length());
TestPatternSearchReplace(idPlaceholder, mediumIdValue);
const std::string longIdValue = "longId";
ASSERT_EQUALS(true, longIdValue.length() > idPlaceholder.length());
TestPatternSearchReplace(idPlaceholder, longIdValue);
}
void FileLocationConstruct() const {
const ErrorMessage::FileLocation loc("foo.cpp", 1, 2);
ASSERT_EQUALS("foo.cpp", loc.getOrigFile());
ASSERT_EQUALS("foo.cpp", loc.getfile());
ASSERT_EQUALS(1, loc.line);
ASSERT_EQUALS(2, loc.column);
}
void FileLocationSetFile() const {
ErrorMessage::FileLocation loc("foo1.cpp", 0, 0);
loc.setfile("foo.cpp");
ASSERT_EQUALS("foo1.cpp", loc.getOrigFile());
ASSERT_EQUALS("foo.cpp", loc.getfile());
ASSERT_EQUALS(0, loc.line);
ASSERT_EQUALS(0, loc.column);
}
void ErrorMessageConstruct() const {
std::list<ErrorMessage::FileLocation> locs(1, fooCpp5);
ErrorMessage msg(std::move(locs), emptyString, Severity::error, "Programming error.", "errorId", Certainty::normal);
ASSERT_EQUALS(1, msg.callStack.size());
ASSERT_EQUALS("Programming error.", msg.shortMessage());
ASSERT_EQUALS("Programming error.", msg.verboseMessage());
ASSERT_EQUALS("[foo.cpp:5]: (error) Programming error.", msg.toString(false));
ASSERT_EQUALS("[foo.cpp:5]: (error) Programming error.", msg.toString(true));
}
void ErrorMessageConstructLocations() const {
std::list<ErrorMessage::FileLocation> locs = { fooCpp5, barCpp8 };
ErrorMessage msg(std::move(locs), emptyString, Severity::error, "Programming error.", "errorId", Certainty::normal);
ASSERT_EQUALS(2, msg.callStack.size());
ASSERT_EQUALS("Programming error.", msg.shortMessage());
ASSERT_EQUALS("Programming error.", msg.verboseMessage());
ASSERT_EQUALS("[foo.cpp:5] -> [bar.cpp:8]: (error) Programming error.", msg.toString(false));
ASSERT_EQUALS("[foo.cpp:5] -> [bar.cpp:8]: (error) Programming error.", msg.toString(true));
}
void ErrorMessageVerbose() const {
std::list<ErrorMessage::FileLocation> locs(1, fooCpp5);
ErrorMessage msg(std::move(locs), emptyString, Severity::error, "Programming error.\nVerbose error", "errorId", Certainty::normal);
ASSERT_EQUALS(1, msg.callStack.size());
ASSERT_EQUALS("Programming error.", msg.shortMessage());
ASSERT_EQUALS("Verbose error", msg.verboseMessage());
ASSERT_EQUALS("[foo.cpp:5]: (error) Programming error.", msg.toString(false));
ASSERT_EQUALS("[foo.cpp:5]: (error) Verbose error", msg.toString(true));
}
void ErrorMessageVerboseLocations() const {
std::list<ErrorMessage::FileLocation> locs = { fooCpp5, barCpp8 };
ErrorMessage msg(std::move(locs), emptyString, Severity::error, "Programming error.\nVerbose error", "errorId", Certainty::normal);
ASSERT_EQUALS(2, msg.callStack.size());
ASSERT_EQUALS("Programming error.", msg.shortMessage());
ASSERT_EQUALS("Verbose error", msg.verboseMessage());
ASSERT_EQUALS("[foo.cpp:5] -> [bar.cpp:8]: (error) Programming error.", msg.toString(false));
ASSERT_EQUALS("[foo.cpp:5] -> [bar.cpp:8]: (error) Verbose error", msg.toString(true));
}
void ErrorMessageFromInternalError() const {
// TODO: test with token
{
InternalError internalError(nullptr, "message", InternalError::INTERNAL);
const auto msg = ErrorMessage::fromInternalError(internalError, nullptr, "file.c");
ASSERT_EQUALS(1, msg.callStack.size());
const auto &loc = *msg.callStack.cbegin();
ASSERT_EQUALS(0, loc.fileIndex);
ASSERT_EQUALS(0, loc.line);
ASSERT_EQUALS(0, loc.column);
ASSERT_EQUALS("message", msg.shortMessage());
ASSERT_EQUALS("message", msg.verboseMessage());
ASSERT_EQUALS("[file.c:0]: (error) message", msg.toString(false));
ASSERT_EQUALS("[file.c:0]: (error) message", msg.toString(true));
}
{
InternalError internalError(nullptr, "message", "details", InternalError::INTERNAL);
const auto msg = ErrorMessage::fromInternalError(internalError, nullptr, "file.cpp", "msg");
ASSERT_EQUALS(1, msg.callStack.size());
const auto &loc = *msg.callStack.cbegin();
ASSERT_EQUALS(0, loc.fileIndex);
ASSERT_EQUALS(0, loc.line);
ASSERT_EQUALS(0, loc.column);
ASSERT_EQUALS("msg: message", msg.shortMessage());
ASSERT_EQUALS("msg: message: details", msg.verboseMessage());
ASSERT_EQUALS("[file.cpp:0]: (error) msg: message", msg.toString(false));
ASSERT_EQUALS("[file.cpp:0]: (error) msg: message: details", msg.toString(true));
}
}
void CustomFormat() const {
std::list<ErrorMessage::FileLocation> locs(1, fooCpp5);
ErrorMessage msg(std::move(locs), emptyString, Severity::error, "Programming error.\nVerbose error", "errorId", Certainty::normal);
ASSERT_EQUALS(1, msg.callStack.size());
ASSERT_EQUALS("Programming error.", msg.shortMessage());
ASSERT_EQUALS("Verbose error", msg.verboseMessage());
ASSERT_EQUALS("foo.cpp:5,error,errorId,Programming error.", msg.toString(false, "{file}:{line},{severity},{id},{message}"));
ASSERT_EQUALS("foo.cpp:5,error,errorId,Verbose error", msg.toString(true, "{file}:{line},{severity},{id},{message}"));
}
void CustomFormat2() const {
std::list<ErrorMessage::FileLocation> locs(1, fooCpp5);
ErrorMessage msg(std::move(locs), emptyString, Severity::error, "Programming error.\nVerbose error", "errorId", Certainty::normal);
ASSERT_EQUALS(1, msg.callStack.size());
ASSERT_EQUALS("Programming error.", msg.shortMessage());
ASSERT_EQUALS("Verbose error", msg.verboseMessage());
ASSERT_EQUALS("Programming error. - foo.cpp(5):(error,errorId)", msg.toString(false, "{message} - {file}({line}):({severity},{id})"));
ASSERT_EQUALS("Verbose error - foo.cpp(5):(error,errorId)", msg.toString(true, "{message} - {file}({line}):({severity},{id})"));
}
void CustomFormatLocations() const {
// Check that first location from location stack is used in template
std::list<ErrorMessage::FileLocation> locs = { fooCpp5, barCpp8 };
ErrorMessage msg(std::move(locs), emptyString, Severity::error, "Programming error.\nVerbose error", "errorId", Certainty::normal);
ASSERT_EQUALS(2, msg.callStack.size());
ASSERT_EQUALS("Programming error.", msg.shortMessage());
ASSERT_EQUALS("Verbose error", msg.verboseMessage());
ASSERT_EQUALS("Programming error. - bar.cpp(8):(error,errorId)", msg.toString(false, "{message} - {file}({line}):({severity},{id})"));
ASSERT_EQUALS("Verbose error - bar.cpp(8):(error,errorId)", msg.toString(true, "{message} - {file}({line}):({severity},{id})"));
}
void ToXmlV2() const {
std::list<ErrorMessage::FileLocation> locs(1, fooCpp5);
ErrorMessage msg(std::move(locs), emptyString, Severity::error, "Programming error.\nVerbose error", "errorId", Certainty::normal);
std::string header("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<results version=\"2\">\n");
header += " <cppcheck version=\"";
header += CppCheck::version();
header += "\"/>\n <errors>";
ASSERT_EQUALS(header, ErrorMessage::getXMLHeader(""));
ASSERT_EQUALS(" </errors>\n</results>", ErrorMessage::getXMLFooter(2));
std::string message(" <error id=\"errorId\" severity=\"error\"");
message += " msg=\"Programming error.\" verbose=\"Verbose error\">\n";
message += " <location file=\"foo.cpp\" line=\"5\" column=\"1\"/>\n </error>";
ASSERT_EQUALS(message, msg.toXML());
}
void ToXmlV2RemarkComment() const {
ErrorMessage msg({}, emptyString, Severity::warning, "", "id", Certainty::normal);
msg.remark = "remark";
ASSERT_EQUALS(" <error id=\"id\" severity=\"warning\" msg=\"\" verbose=\"\" remark=\"remark\"/>", msg.toXML());
}
void ToXmlV2Locations() const {
std::list<ErrorMessage::FileLocation> locs = { fooCpp5, barCpp8_i };
ErrorMessage msg(std::move(locs), emptyString, Severity::error, "Programming error.\nVerbose error", "errorId", Certainty::normal);
std::string header("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<results version=\"2\">\n");
header += " <cppcheck version=\"";
header += CppCheck::version();
header += "\"/>\n <errors>";
ASSERT_EQUALS(header, ErrorMessage::getXMLHeader(""));
ASSERT_EQUALS(" </errors>\n</results>", ErrorMessage::getXMLFooter(2));
std::string message(" <error id=\"errorId\" severity=\"error\"");
message += " msg=\"Programming error.\" verbose=\"Verbose error\">\n";
message += " <location file=\"bar.cpp\" line=\"8\" column=\"1\" info=\"\\303\\244\"/>\n";
message += " <location file=\"foo.cpp\" line=\"5\" column=\"1\"/>\n </error>";
ASSERT_EQUALS(message, msg.toXML());
}
void ToXmlV2Encoding() const {
{
std::list<ErrorMessage::FileLocation> locs;
ErrorMessage msg(std::move(locs), emptyString, Severity::error, "Programming error.\nComparing \"\203\" with \"\003\"", "errorId", Certainty::normal);
const std::string expected(" <error id=\"errorId\" severity=\"error\" msg=\"Programming error.\" verbose=\"Comparing "\\203" with "\\003"\"/>");
ASSERT_EQUALS(expected, msg.toXML());
}
{
const char code1[]="äöü";
const char code2[]="\x12\x00\x00\x01";
ErrorMessage msg1({}, emptyString, Severity::error, std::string("Programming error.\nReading \"")+code1+"\"", "errorId", Certainty::normal);
ASSERT_EQUALS(" <error id=\"errorId\" severity=\"error\" msg=\"Programming error.\" verbose=\"Reading "\\303\\244\\303\\266\\303\\274"\"/>", msg1.toXML());
ErrorMessage msg2({}, emptyString, Severity::error, std::string("Programming error.\nReading \"")+code2+"\"", "errorId", Certainty::normal);
ASSERT_EQUALS(" <error id=\"errorId\" severity=\"error\" msg=\"Programming error.\" verbose=\"Reading "\\022"\"/>", msg2.toXML());
}
}
void FromXmlV2() const {
const char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<error id=\"errorId\""
" severity=\"error\""
" cwe=\"123\""
" inconclusive=\"true\""
" msg=\"Programming error.\""
" verbose=\"Verbose error\""
" hash=\"456\""
">\n"
" <location file=\"bar.cpp\" line=\"8\" column=\"1\"/>\n"
" <location file=\"foo.cpp\" line=\"5\" column=\"2\"/>\n"
"</error>";
tinyxml2::XMLDocument doc;
ASSERT(doc.Parse(xmldata, sizeof(xmldata)) == tinyxml2::XML_SUCCESS);
const auto * const rootnode = doc.FirstChildElement();
ASSERT(rootnode);
ErrorMessage msg(doc.FirstChildElement());
ASSERT_EQUALS("errorId", msg.id);
ASSERT_EQUALS_ENUM(Severity::error, msg.severity);
ASSERT_EQUALS(123u, msg.cwe.id);
ASSERT_EQUALS_ENUM(Certainty::inconclusive, msg.certainty);
ASSERT_EQUALS("Programming error.", msg.shortMessage());
ASSERT_EQUALS("Verbose error", msg.verboseMessage());
ASSERT_EQUALS(456u, msg.hash);
ASSERT_EQUALS(2u, msg.callStack.size());
ASSERT_EQUALS("foo.cpp", msg.callStack.front().getfile());
ASSERT_EQUALS(5, msg.callStack.front().line);
ASSERT_EQUALS(2u, msg.callStack.front().column);
ASSERT_EQUALS("bar.cpp", msg.callStack.back().getfile());
ASSERT_EQUALS(8, msg.callStack.back().line);
ASSERT_EQUALS(1u, msg.callStack.back().column);
}
void ToXmlV3() const {
std::string header("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<results version=\"3\">\n");
header += " <cppcheck version=\"";
header += CppCheck::version();
header += "\"/>\n <errors>";
ASSERT_EQUALS(header, ErrorMessage::getXMLHeader("", 3));
ASSERT_EQUALS("</results>", ErrorMessage::getXMLFooter(3));
}
void InconclusiveXml() const {
// Location
std::list<ErrorMessage::FileLocation> locs(1, fooCpp5);
// Inconclusive error message
ErrorMessage msg(std::move(locs), emptyString, Severity::error, "Programming error", "errorId", Certainty::inconclusive);
// xml version 2 error message
ASSERT_EQUALS(" <error id=\"errorId\" severity=\"error\" msg=\"Programming error\" verbose=\"Programming error\" inconclusive=\"true\">\n"
" <location file=\"foo.cpp\" line=\"5\" column=\"1\"/>\n"
" </error>",
msg.toXML());
}
void SerializeInconclusiveMessage() const {
// Inconclusive error message
std::list<ErrorMessage::FileLocation> locs;
ErrorMessage msg(std::move(locs), emptyString, Severity::error, "Programming error", "errorId", Certainty::inconclusive);
msg.file0 = "test.cpp";
const std::string msg_str = msg.serialize();
ASSERT_EQUALS("7 errorId"
"5 error"
"1 0"
"1 0"
"0 "
"8 test.cpp"
"1 1"
"17 Programming error"
"17 Programming error"
"0 ", msg_str);
ErrorMessage msg2;
ASSERT_NO_THROW(msg2.deserialize(msg_str));
ASSERT_EQUALS("errorId", msg2.id);
ASSERT_EQUALS_ENUM(Severity::error, msg2.severity);
ASSERT_EQUALS("test.cpp", msg2.file0);
ASSERT_EQUALS_ENUM(Certainty::inconclusive, msg2.certainty);
ASSERT_EQUALS("Programming error", msg2.shortMessage());
ASSERT_EQUALS("Programming error", msg2.verboseMessage());
}
void DeserializeInvalidInput() const {
{
// missing/invalid length
// missing separator
ErrorMessage msg;
ASSERT_THROW_INTERNAL_EQUALS(msg.deserialize("500foobar"), INTERNAL, "Internal Error: Deserialization of error message failed - invalid separator");
}
{
// invalid length
ErrorMessage msg;
ASSERT_THROW_INTERNAL_EQUALS(msg.deserialize("foo foobar"), INTERNAL, "Internal Error: Deserialization of error message failed - invalid length");
}
{
// mismatching length
ErrorMessage msg;
ASSERT_THROW_INTERNAL_EQUALS(msg.deserialize("8 errorId"), INTERNAL, "Internal Error: Deserialization of error message failed - premature end of data");
}
{
// incomplete message
ErrorMessage msg;
ASSERT_THROW_INTERNAL_EQUALS(msg.deserialize("7 errorId"), INTERNAL, "Internal Error: Deserialization of error message failed - invalid length");
}
{
// invalid CWE ID
const char str[] = "7 errorId"
"5 error"
"7 invalid" // cwe
"1 0"
"0 "
"8 test.cpp"
"17 Programming error"
"17 Programming error"
"0 ";
ErrorMessage msg;
ASSERT_THROW_INTERNAL_EQUALS(msg.deserialize(str), INTERNAL, "Internal Error: Deserialization of error message failed - invalid CWE ID - not an integer");
}
{
// invalid hash
const char str[] = "7 errorId"
"5 error"
"1 0"
"7 invalid" // hash
"1 0"
"0 "
"8 test.cpp"
"17 Programming error"
"17 Programming error"
"0 ";
ErrorMessage msg;
ASSERT_THROW_INTERNAL_EQUALS(msg.deserialize(str), INTERNAL, "Internal Error: Deserialization of error message failed - invalid hash - not an integer");
}
{
// out-of-range CWE ID
const char str[] = "7 errorId"
"5 error"
"5 65536" // max +1
"1 0"
"1 0"
"0 "
"8 test.cpp"
"17 Programming error"
"17 Programming error"
"0 ";
ErrorMessage msg;
ASSERT_THROW_INTERNAL_EQUALS(msg.deserialize(str), INTERNAL, "Internal Error: Deserialization of error message failed - invalid CWE ID - out of range (limits)");
}
}
void SerializeSanitize() const {
std::list<ErrorMessage::FileLocation> locs;
ErrorMessage msg(std::move(locs), emptyString, Severity::error, std::string("Illegal character in \"foo\001bar\""), "errorId", Certainty::normal);
msg.file0 = "1.c";
const std::string msg_str = msg.serialize();
ASSERT_EQUALS("7 errorId"
"5 error"
"1 0"
"1 0"
"0 "
"3 1.c"
"1 0"
"33 Illegal character in \"foo\\001bar\""
"33 Illegal character in \"foo\\001bar\""
"0 ", msg_str);
ErrorMessage msg2;
ASSERT_NO_THROW(msg2.deserialize(msg_str));
ASSERT_EQUALS("errorId", msg2.id);
ASSERT_EQUALS_ENUM(Severity::error, msg2.severity);
ASSERT_EQUALS("1.c", msg2.file0);
ASSERT_EQUALS("Illegal character in \"foo\\001bar\"", msg2.shortMessage());
ASSERT_EQUALS("Illegal character in \"foo\\001bar\"", msg2.verboseMessage());
}
void SerializeFileLocation() const {
ErrorMessage::FileLocation loc1(":/,;", "abcd:/,", 654, 33);
loc1.setfile("[]:;,()");
ErrorMessage msg({std::move(loc1)}, emptyString, Severity::error, "Programming error", "errorId", Certainty::inconclusive);
const std::string msg_str = msg.serialize();
ASSERT_EQUALS("7 errorId"
"5 error"
"1 0"
"1 0"
"0 "
"0 "
"1 1"
"17 Programming error"
"17 Programming error"
"1 "
"27 654\t33\t[]:;,()\t:/,;\tabcd:/,", msg_str);
ErrorMessage msg2;
ASSERT_NO_THROW(msg2.deserialize(msg_str));
ASSERT_EQUALS("[]:;,()", msg2.callStack.front().getfile(false));
ASSERT_EQUALS(":/,;", msg2.callStack.front().getOrigFile(false));
ASSERT_EQUALS(654, msg2.callStack.front().line);
ASSERT_EQUALS(33, msg2.callStack.front().column);
ASSERT_EQUALS("abcd:/,", msg2.callStack.front().getinfo());
}
void SerializeAndDeserializeRemark() const {
ErrorMessage msg({}, emptyString, Severity::warning, emptyString, "id", Certainty::normal);
msg.remark = "some remark";
ErrorMessage msg2;
ASSERT_NO_THROW(msg2.deserialize(msg.serialize()));
ASSERT_EQUALS("some remark", msg2.remark);
}
void substituteTemplateFormatStatic() const
{
{
std::string s;
::substituteTemplateFormatStatic(s);
ASSERT_EQUALS("", s);
}
{
std::string s = "template{black}\\z";
::substituteTemplateFormatStatic(s);
ASSERT_EQUALS("template{black}\\z", s);
}
{
std::string s = "{reset}{bold}{dim}{red}{blue}{magenta}{default}\\b\\n\\r\\t";
::substituteTemplateFormatStatic(s);
ASSERT_EQUALS("\b\n\r\t", s);
}
{
std::string s = "\\\\n";
::substituteTemplateFormatStatic(s);
ASSERT_EQUALS("\\\n", s);
}
{
std::string s = "{{red}";
::substituteTemplateFormatStatic(s);
ASSERT_EQUALS("{", s);
}
}
void substituteTemplateLocationStatic() const
{
{
std::string s;
::substituteTemplateLocationStatic(s);
ASSERT_EQUALS("", s);
}
{
std::string s = "template";
::substituteTemplateLocationStatic(s);
ASSERT_EQUALS("template", s);
}
{
std::string s = "template{black}\\z";
::substituteTemplateFormatStatic(s);
ASSERT_EQUALS("template{black}\\z", s);
}
{
std::string s = "{reset}{bold}{dim}{red}{blue}{magenta}{default}\\b\\n\\r\\t";
::substituteTemplateFormatStatic(s);
ASSERT_EQUALS("\b\n\r\t", s);
}
{
std::string s = "\\\\n";
::substituteTemplateFormatStatic(s);
ASSERT_EQUALS("\\\n", s);
}
{
std::string s = "{{red}";
::substituteTemplateFormatStatic(s);
ASSERT_EQUALS("{", s);
}
}
void isCriticalErrorId() const {
// It does not abort all the analysis of the file. Like "missingInclude" there can be false negatives.
ASSERT_EQUALS(false, ErrorLogger::isCriticalErrorId("misra-config"));
}
};
REGISTER_TEST(TestErrorLogger)
| null |
1,007 | cpp | cppcheck | testbufferoverrun.cpp | test/testbufferoverrun.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#include "check.h"
#include "checkbufferoverrun.h"
#include "ctu.h"
#include "errortypes.h"
#include "helpers.h"
#include "platform.h"
#include "settings.h"
#include "fixture.h"
#include "tokenize.h"
#include <cstddef>
#include <list>
#include <string>
#include <vector>
class TestBufferOverrun : public TestFixture {
public:
TestBufferOverrun() : TestFixture("TestBufferOverrun") {}
private:
/*const*/ Settings settings0 = settingsBuilder().library("std.cfg").severity(Severity::warning).severity(Severity::style).severity(Severity::portability).build();
#define check(...) check_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
void check_(const char* file, int line, const char (&code)[size], bool cpp = true) {
const Settings settings = settingsBuilder(settings0).certainty(Certainty::inconclusive).build();
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code, cpp), file, line);
// Check for buffer overruns..
runChecks<CheckBufferOverrun>(tokenizer, this);
}
template<size_t size>
void check_(const char* file, int line, const char (&code)[size], const Settings &settings, bool cpp = true) {
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code, cpp), file, line);
// Check for buffer overruns..
runChecks<CheckBufferOverrun>(tokenizer, this);
}
// TODO: get rid of this
void check_(const char* file, int line, const std::string& code) {
const Settings settings = settingsBuilder(settings0).certainty(Certainty::inconclusive).build();
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
// Check for buffer overruns..
runChecks<CheckBufferOverrun>(tokenizer, this);
}
#define checkP(...) checkP_(__FILE__, __LINE__, __VA_ARGS__)
void checkP_(const char* file, int line, const char code[], const char* filename = "test.cpp")
{
const Settings settings = settingsBuilder(settings0).severity(Severity::performance).certainty(Certainty::inconclusive).build();
std::vector<std::string> files(1, filename);
Tokenizer tokenizer(settings, *this);
PreprocessorHelper::preprocess(code, files, tokenizer, *this);
// Tokenizer..
ASSERT_LOC(tokenizer.simplifyTokens1(""), file, line);
// Check for buffer overruns..
runChecks<CheckBufferOverrun>(tokenizer, this);
}
void run() override {
TEST_CASE(noerr1);
TEST_CASE(noerr2);
TEST_CASE(noerr3);
TEST_CASE(noerr4);
TEST_CASE(sizeof3);
TEST_CASE(array_index_1);
TEST_CASE(array_index_2);
TEST_CASE(array_index_3);
TEST_CASE(array_index_4);
TEST_CASE(array_index_6);
TEST_CASE(array_index_7);
TEST_CASE(array_index_11);
TEST_CASE(array_index_12);
TEST_CASE(array_index_13);
TEST_CASE(array_index_14);
TEST_CASE(array_index_15);
TEST_CASE(array_index_16);
TEST_CASE(array_index_17);
TEST_CASE(array_index_18);
TEST_CASE(array_index_19);
TEST_CASE(array_index_20);
TEST_CASE(array_index_21);
TEST_CASE(array_index_22);
TEST_CASE(array_index_23);
TEST_CASE(array_index_24); // ticket #1492 and #1539
TEST_CASE(array_index_25); // ticket #1536
TEST_CASE(array_index_26);
TEST_CASE(array_index_27);
TEST_CASE(array_index_28); // ticket #1418
TEST_CASE(array_index_29); // ticket #1734
TEST_CASE(array_index_30); // ticket #2086 - out of bounds when type is unknown
TEST_CASE(array_index_31); // ticket #2120 - out of bounds in subfunction when type is unknown
TEST_CASE(array_index_32);
TEST_CASE(array_index_33); // ticket #3044
TEST_CASE(array_index_34); // ticket #3063
TEST_CASE(array_index_35); // ticket #2889
TEST_CASE(array_index_36); // ticket #2960
TEST_CASE(array_index_37);
TEST_CASE(array_index_38); // ticket #3273
TEST_CASE(array_index_39);
TEST_CASE(array_index_40); // loop variable calculation, taking address
TEST_CASE(array_index_41); // structs with the same name
TEST_CASE(array_index_42);
TEST_CASE(array_index_43); // struct with array
TEST_CASE(array_index_44); // #3979
TEST_CASE(array_index_45); // #4207 - calling function with variable number of parameters (...)
TEST_CASE(array_index_46); // #4840 - two-statement for loop
TEST_CASE(array_index_47); // #5849
TEST_CASE(array_index_48); // #9478
TEST_CASE(array_index_49); // #8653
TEST_CASE(array_index_50);
TEST_CASE(array_index_51); // #3763
TEST_CASE(array_index_52); // #7682
TEST_CASE(array_index_53); // #4750
TEST_CASE(array_index_54); // #10268
TEST_CASE(array_index_55); // #10254
TEST_CASE(array_index_56); // #10284
TEST_CASE(array_index_57); // #10023
TEST_CASE(array_index_58); // #7524
TEST_CASE(array_index_59); // #10413
TEST_CASE(array_index_60); // #10617, #9824
TEST_CASE(array_index_61); // #10621
TEST_CASE(array_index_62); // #7684
TEST_CASE(array_index_63); // #10979
TEST_CASE(array_index_64); // #10878
TEST_CASE(array_index_65); // #11066
TEST_CASE(array_index_66); // #10740
TEST_CASE(array_index_67); // #1596
TEST_CASE(array_index_68); // #6655
TEST_CASE(array_index_69); // #6370
TEST_CASE(array_index_70); // #11355
TEST_CASE(array_index_71); // #11461
TEST_CASE(array_index_72); // #11784
TEST_CASE(array_index_73); // #11530
TEST_CASE(array_index_74); // #11088
TEST_CASE(array_index_75);
TEST_CASE(array_index_76);
TEST_CASE(array_index_multidim);
TEST_CASE(array_index_switch_in_for);
TEST_CASE(array_index_for_in_for); // FP: #2634
TEST_CASE(array_index_bounds);
TEST_CASE(array_index_calculation);
TEST_CASE(array_index_negative1);
TEST_CASE(array_index_negative2); // ticket #3063
TEST_CASE(array_index_negative3);
TEST_CASE(array_index_negative4);
TEST_CASE(array_index_negative5); // #10526
TEST_CASE(array_index_negative6); // #11349
TEST_CASE(array_index_negative7); // #5685
TEST_CASE(array_index_negative8); // #11651
TEST_CASE(array_index_negative9);
TEST_CASE(array_index_negative10);
TEST_CASE(array_index_for_decr);
TEST_CASE(array_index_varnames); // FP: struct member #1576, FN: #1586
TEST_CASE(array_index_for_continue); // for,continue
TEST_CASE(array_index_for); // FN: for,if
TEST_CASE(array_index_for_neq); // #2211: Using != in condition
TEST_CASE(array_index_for_question); // #2561: for, ?:
TEST_CASE(array_index_for_andand_oror); // FN: using && or || in the for loop condition
TEST_CASE(array_index_for_varid0); // #4228: No varid for counter variable
TEST_CASE(array_index_vla_for); // #3221: access VLA inside for
TEST_CASE(array_index_extern); // FP when using 'extern'. #1684
TEST_CASE(array_index_cast); // FP after cast. #2841
TEST_CASE(array_index_string_literal);
TEST_CASE(array_index_same_struct_and_var_name); // #4751 - not handled well when struct name and var name is same
TEST_CASE(array_index_valueflow);
TEST_CASE(array_index_valueflow_pointer);
TEST_CASE(array_index_function_parameter);
TEST_CASE(array_index_enum_array); // #8439
TEST_CASE(array_index_container); // #9386
TEST_CASE(array_index_two_for_loops);
TEST_CASE(array_index_new); // #7690
TEST_CASE(buffer_overrun_2_struct);
TEST_CASE(buffer_overrun_3);
TEST_CASE(buffer_overrun_4);
TEST_CASE(buffer_overrun_5);
TEST_CASE(buffer_overrun_6);
TEST_CASE(buffer_overrun_7);
TEST_CASE(buffer_overrun_8);
TEST_CASE(buffer_overrun_9);
TEST_CASE(buffer_overrun_10);
TEST_CASE(buffer_overrun_11);
TEST_CASE(buffer_overrun_15); // ticket #1787
TEST_CASE(buffer_overrun_16);
TEST_CASE(buffer_overrun_18); // ticket #2576 - for, calculation with loop variable
TEST_CASE(buffer_overrun_19); // #2597 - class member with unknown type
TEST_CASE(buffer_overrun_21);
TEST_CASE(buffer_overrun_24); // index variable is changed in for-loop
TEST_CASE(buffer_overrun_26); // #4432 (segmentation fault)
TEST_CASE(buffer_overrun_27); // #4444 (segmentation fault)
TEST_CASE(buffer_overrun_29); // #7083: false positive: typedef and initialization with strings
TEST_CASE(buffer_overrun_30); // #6367
TEST_CASE(buffer_overrun_31);
TEST_CASE(buffer_overrun_32); //#10244
TEST_CASE(buffer_overrun_33); //#2019
TEST_CASE(buffer_overrun_34); //#11035
TEST_CASE(buffer_overrun_35); //#2304
TEST_CASE(buffer_overrun_36);
TEST_CASE(buffer_overrun_errorpath);
TEST_CASE(buffer_overrun_bailoutIfSwitch); // ticket #2378 : bailoutIfSwitch
TEST_CASE(buffer_overrun_function_array_argument);
TEST_CASE(possible_buffer_overrun_1); // #3035
TEST_CASE(buffer_overrun_readSizeFromCfg);
TEST_CASE(valueflow_string); // using ValueFlow string values in checking
// It is undefined behaviour to point out of bounds of an array
// the address beyond the last element is in bounds
// char a[10];
// char *p1 = a + 10; // OK
// char *p2 = a + 11 // UB
TEST_CASE(pointer_out_of_bounds_1);
TEST_CASE(pointer_out_of_bounds_2);
TEST_CASE(pointer_out_of_bounds_3);
TEST_CASE(pointer_out_of_bounds_4);
TEST_CASE(pointer_out_of_bounds_5); // #10227
TEST_CASE(pointer_out_of_bounds_sub);
TEST_CASE(strcat1);
TEST_CASE(varid1);
TEST_CASE(varid2); // ticket #4764
TEST_CASE(assign1);
TEST_CASE(alloc_new); // Buffer allocated with new
TEST_CASE(alloc_malloc); // Buffer allocated with malloc
TEST_CASE(alloc_string); // statically allocated buffer
TEST_CASE(alloc_alloca); // Buffer allocated with alloca
// TODO TEST_CASE(countSprintfLength);
TEST_CASE(minsize_argvalue);
TEST_CASE(minsize_sizeof);
TEST_CASE(minsize_strlen);
TEST_CASE(minsize_mul);
TEST_CASE(unknownType);
TEST_CASE(terminateStrncpy1);
TEST_CASE(terminateStrncpy2);
TEST_CASE(terminateStrncpy3);
TEST_CASE(terminateStrncpy4);
TEST_CASE(terminateStrncpy5); // #9944
TEST_CASE(recursive_long_time);
TEST_CASE(crash1); // Ticket #1587 - crash
TEST_CASE(crash2); // Ticket #3034 - crash
TEST_CASE(crash3); // Ticket #5426 - crash
TEST_CASE(crash4); // Ticket #8679 - crash
TEST_CASE(crash5); // Ticket #8644 - crash
TEST_CASE(crash6); // Ticket #9024 - crash
TEST_CASE(crash7); // Ticket #9073 - crash
TEST_CASE(insecureCmdLineArgs);
TEST_CASE(checkBufferAllocatedWithStrlen);
TEST_CASE(scope); // handling different scopes
TEST_CASE(getErrorMessages);
// Access array and then check if the used index is within bounds
TEST_CASE(arrayIndexThenCheck);
TEST_CASE(arrayIndexEarlyReturn); // #6884
TEST_CASE(bufferNotZeroTerminated);
TEST_CASE(negativeMemoryAllocationSizeError); // #389
TEST_CASE(negativeArraySize);
TEST_CASE(pointerAddition1);
TEST_CASE(ctu_malloc);
TEST_CASE(ctu_array);
TEST_CASE(ctu_variable);
TEST_CASE(ctu_arithmetic);
TEST_CASE(objectIndex);
TEST_CASE(checkPipeParameterSize); // ticket #3521
}
void noerr1() {
check("extern int ab;\n"
"void f()\n"
"{\n"
" if (ab)\n"
" {\n"
" char str[50];\n"
" }\n"
" if (ab)\n"
" {\n"
" char str[50];\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void noerr2() {
check("static char buf[2];\n"
"void f1(char *str)\n"
"{\n"
" strcpy(buf,str);\n"
"}\n"
"void f2(char *str)\n"
"{\n"
" strcat(buf,str);\n"
"}\n"
"void f3(char *str)\n"
"{\n"
" sprintf(buf,\"%s\",str);\n"
"}\n"
"void f4(const char str[])\n"
"{\n"
" strcpy(buf, str);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void noerr3() {
check("struct { char data[10]; } abc;\n"
"static char f()\n"
"{\n"
" char data[1];\n"
" return abc.data[1];\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void noerr4() {
// The memory isn't read or written and therefore there is no error.
check("static void f() {\n"
" char data[100];\n"
" const char *p = data + 100;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void sizeof3() {
check("struct group { int gr_gid; };\n"
"void f()\n"
"{\n"
" char group[32];\n"
" snprintf(group, 32, \"%u\", 0);\n"
" struct group *gr;\n"
" snprintf(group, 32, \"%u\", gr->gr_gid);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void array_index_1() {
check("void f()\n"
"{\n"
" char str[0x10] = {0};\n"
" str[15] = 0;\n"
" str[16] = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Array 'str[16]' accessed at index 16, which is out of bounds.\n", errout_str());
check("char f()\n"
"{\n"
" char str[16] = {0};\n"
" return str[16];\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 'str[16]' accessed at index 16, which is out of bounds.\n", errout_str());
// test stack array
check("int f()\n"
"{\n"
" int x[ 3 ] = { 0, 1, 2 };\n"
" int y;\n"
" y = x[ 4 ];\n"
" return y;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Array 'x[3]' accessed at index 4, which is out of bounds.\n", errout_str());
check("int f()\n"
"{\n"
" int x[ 3 ] = { 0, 1, 2 };\n"
" int y;\n"
" y = x[ 2 ];\n"
" return y;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int x[5] = {0};\n"
"int a = x[10];");
ASSERT_EQUALS("[test.cpp:2]: (error) Array 'x[5]' accessed at index 10, which is out of bounds.\n", errout_str());
check("int x[5] = {0};\n"
"int a = (x)[10];");
ASSERT_EQUALS("[test.cpp:2]: (error) Array 'x[5]' accessed at index 10, which is out of bounds.\n", errout_str());
}
void array_index_2() {
check("void a(int i)\n" // valueflow
"{\n"
" char *str = new char[0x10];\n"
" str[i] = 0;\n"
"}\n"
"void b() { a(16); }");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 'str[16]' accessed at index 16, which is out of bounds.\n", errout_str());
}
void array_index_4() {
check("char c = \"abc\"[4];");
ASSERT_EQUALS("[test.cpp:1]: (error) Array '\"abc\"[4]' accessed at index 4, which is out of bounds.\n", errout_str());
check("p = &\"abc\"[4];");
ASSERT_EQUALS("", errout_str());
check("char c = \"\\0abc\"[2];");
ASSERT_EQUALS("", errout_str());
check("char c = L\"abc\"[4];");
ASSERT_EQUALS("[test.cpp:1]: (error) Array 'L\"abc\"[4]' accessed at index 4, which is out of bounds.\n", errout_str());
}
void array_index_3() {
check("void f()\n"
"{\n"
" int val[50];\n"
" int i, sum=0;\n"
" for (i = 0; i < 100; i++)\n"
" sum += val[i];\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (error) Array 'val[50]' accessed at index 99, which is out of bounds.\n", errout_str());
check("void f()\n"
"{\n"
" int val[50];\n"
" int i, sum=0;\n"
" for (i = 1; i < 100; i++)\n"
" sum += val[i];\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (error) Array 'val[50]' accessed at index 99, which is out of bounds.\n", errout_str());
check("void f(int a)\n"
"{\n"
" int val[50];\n"
" int i, sum=0;\n"
" for (i = a; i < 100; i++)\n"
" sum += val[i];\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (error) Array 'val[50]' accessed at index 99, which is out of bounds.\n", errout_str());
check("typedef struct g g2[3];\n"
"void foo(char *a)\n"
"{\n"
" for (int i = 0; i < 4; i++)\n"
" {\n"
" a[i]=0;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(int argc)\n"
"{\n"
" char a[2];\n"
" for (int i = 4; i < argc; i++){}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(int a[10]) {\n"
" for (int i=0;i<50;++i) {\n"
" a[i] = 0;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Array 'a[10]' accessed at index 49, which is out of bounds.\n", errout_str());
}
void array_index_6() {
check("struct ABC\n"
"{\n"
" char str[10];\n"
"};\n"
"\n"
"static void f()\n"
"{\n"
" struct ABC abc;\n"
" abc.str[10] = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:9]: (error) Array 'abc.str[10]' accessed at index 10, which is out of bounds.\n", errout_str());
check("struct ABC\n"
"{\n"
" char str[10];\n"
"};\n"
"\n"
"static char f()\n"
"{\n"
" struct ABC abc;\n"
" return abc.str[10];\n"
"}");
ASSERT_EQUALS("[test.cpp:9]: (error) Array 'abc.str[10]' accessed at index 10, which is out of bounds.\n", errout_str());
// This is not out of bounds because it is a variable length array
check("struct ABC\n"
"{\n"
" char str[1];\n"
"};\n"
"\n"
"static void f()\n"
"{\n"
" struct ABC* x = malloc(sizeof(struct ABC) + 10);\n"
" x->str[1] = 0;"
"}");
ASSERT_EQUALS("", errout_str());
// This is not out of bounds because it is not a variable length array
check("struct ABC\n"
"{\n"
" char str[1];\n"
" int x;\n"
"};\n"
"\n"
"static void f()\n"
"{\n"
" struct ABC* x = malloc(sizeof(struct ABC) + 10);\n"
" x->str[1] = 0;"
"}");
TODO_ASSERT_EQUALS("error", "", errout_str());
// This is not out of bounds because it is a variable length array
// and the index is within the memory allocated.
/** @todo this works by accident because we ignore any access to this array */
check("struct ABC\n"
"{\n"
" char str[1];\n"
"};\n"
"\n"
"static void f()\n"
"{\n"
" struct ABC* x = malloc(sizeof(struct ABC) + 10);\n"
" x->str[10] = 0;"
"}");
ASSERT_EQUALS("", errout_str());
// This is out of bounds because it is outside the memory allocated.
/** @todo this doesn't work because of a bug in sizeof(struct) */
check("struct ABC\n"
"{\n"
" char str[1];\n"
"};\n"
"\n"
"static void f()\n"
"{\n"
" struct ABC* x = malloc(sizeof(struct ABC) + 10);\n"
" x->str[11] = 0;"
"}");
TODO_ASSERT_EQUALS("[test.cpp:9]: (error) Array 'str[1]' accessed at index 11, which is out of bounds.\n", "", errout_str());
// This is out of bounds if 'sizeof(ABC)' is 1 (No padding)
check("struct ABC\n"
"{\n"
" char str[1];\n"
"};\n"
"\n"
"static void f()\n"
"{\n"
" struct ABC* x = malloc(sizeof(ABC) + 10);\n"
" x->str[11] = 0;"
"}");
TODO_ASSERT_EQUALS("error", "", errout_str());
// This is out of bounds because it is outside the memory allocated
/** @todo this doesn't work because of a bug in sizeof(struct) */
check("struct ABC\n"
"{\n"
" char str[1];\n"
"};\n"
"\n"
"static void f()\n"
"{\n"
" struct ABC* x = malloc(sizeof(struct ABC));\n"
" x->str[1] = 0;"
"}");
TODO_ASSERT_EQUALS("[test.cpp:9]: (error) Array 'str[1]' accessed at index 1, which is out of bounds.\n", "", errout_str());
// This is out of bounds because it is outside the memory allocated
// But only if 'sizeof(ABC)' is 1 (No padding)
check("struct ABC\n"
"{\n"
" char str[1];\n"
"};\n"
"\n"
"static void f()\n"
"{\n"
" struct ABC* x = malloc(sizeof(ABC));\n"
" x->str[1] = 0;"
"}");
TODO_ASSERT_EQUALS("error", "", errout_str());
// This is out of bounds because it is not a variable array
check("struct ABC\n"
"{\n"
" char str[1];\n"
"};\n"
"\n"
"static void f()\n"
"{\n"
" struct ABC x;\n"
" x.str[1] = 0;"
"}");
ASSERT_EQUALS("[test.cpp:9]: (error) Array 'x.str[1]' accessed at index 1, which is out of bounds.\n", errout_str());
check("struct foo\n"
"{\n"
" char str[10];\n"
"};\n"
"\n"
"void x()\n"
"{\n"
" foo f;\n"
" for ( unsigned int i = 0; i < 64; ++i )\n"
" f.str[i] = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:10]: (error) Array 'f.str[10]' accessed at index 63, which is out of bounds.\n", errout_str());
check("struct AB { char a[NUM]; char b[NUM]; }\n"
"void f(struct AB *ab) {\n"
" ab->a[0] = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("union { char a[1]; int b; } ab;\n"
"void f() {\n"
" ab.a[2] = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Array 'ab.a[1]' accessed at index 2, which is out of bounds.\n", errout_str());
}
void array_index_7() {
check("struct ABC\n"
"{\n"
" char str[10];\n"
"};\n"
"\n"
"static void f(struct ABC *abc)\n"
"{\n"
" abc->str[10] = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:8]: (error) Array 'abc->str[10]' accessed at index 10, which is out of bounds.\n", errout_str());
}
void array_index_11() {
check("class ABC\n"
"{\n"
"public:\n"
" ABC();\n"
" char *str[10];\n"
" struct ABC *next();\n"
"};\n"
"\n"
"static void f(ABC *abc1)\n"
"{\n"
" for ( ABC *abc = abc1; abc; abc = abc->next() )\n"
" {\n"
" abc->str[10] = 0;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:13]: (error) Array 'abc->str[10]' accessed at index 10, which is out of bounds.\n", errout_str());
}
void array_index_12() {
check("class Fred\n"
"{\n"
"private:\n"
" char str[10];\n"
"public:\n"
" Fred();\n"
"};\n"
"Fred::Fred()\n"
"{\n"
" str[10] = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:10]: (error) Array 'str[10]' accessed at index 10, which is out of bounds.\n", errout_str());
check("class Fred\n"
"{\n"
"private:\n"
" char str[10];\n"
"public:\n"
" char c();\n"
"};\n"
"char Fred::c()\n"
"{\n"
" return str[10];\n"
"}");
ASSERT_EQUALS("[test.cpp:10]: (error) Array 'str[10]' accessed at index 10, which is out of bounds.\n", errout_str());
}
void array_index_13() {
check("void f()\n"
"{\n"
" char buf[10];\n"
" for (int i = 0; i < 100; i++)\n"
" {\n"
" if (i < 10)\n"
" int x = buf[i];\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void array_index_14() {
check("void f()\n"
"{\n"
" int a[10];\n"
" for (int i = 0; i < 10; i++)\n"
" a[i+10] = i;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Array 'a[10]' accessed at index 19, which is out of bounds.\n", errout_str());
}
void array_index_15() {
check("void f()\n"
"{\n"
" int a[10];\n"
" for (int i = 0; i < 10; i++)\n"
" a[10+i] = i;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Array 'a[10]' accessed at index 19, which is out of bounds.\n", errout_str());
}
void array_index_16() {
check("void f()\n"
"{\n"
" int a[10];\n"
" for (int i = 0; i < 10; i++)\n"
" a[i+1] = i;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Array 'a[10]' accessed at index 10, which is out of bounds.\n", errout_str());
}
void array_index_17() {
check("void f()\n"
"{\n"
" int a[10];\n"
" for (int i = 0; i < 10; i++)\n"
" a[i*2] = i;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Array 'a[10]' accessed at index 18, which is out of bounds.\n", errout_str());
check("void f()\n"
"{\n"
" int a[12];\n"
" for (int i = 0; i < 12; i+=6)\n"
" a[i+5] = i;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f()\n"
"{\n"
" int a[12];\n"
" for (int i = 0; i < 12; i+=6)\n"
" a[i+6] = i;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Array 'a[12]' accessed at index 12, which is out of bounds.\n", errout_str());
check("void f() {\n" // #4398
" int a[2];\n"
" for (int i = 0; i < 4; i+=2)\n"
" a[i] = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 'a[2]' accessed at index 2, which is out of bounds.\n", errout_str());
check("void f() {\n" // #4398
" int a[2];\n"
" for (int i = 0; i < 4; i+=2)\n"
" do_stuff(a+i);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void array_index_18() {
check("void f()\n"
"{\n"
" int a[5];\n"
" for (int i = 0; i < 6; i++)\n"
" {\n"
" a[i] = i;\n"
" i+=1;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f()\n"
"{\n"
" int a[5];\n"
" for (int i = 0; i < 6; i++)\n"
" {\n"
" a[i] = i;\n"
" i++;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f()\n"
"{\n"
" int a[5];\n"
" for (int i = 0; i < 6; i++)\n"
" {\n"
" a[i] = i;\n"
" ++i;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f()\n"
"{\n"
" int a[5];\n"
" for (int i = 0; i < 6; i++)\n"
" {\n"
" a[i] = i;\n"
" i=4;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (error) Array 'a[5]' accessed at index 5, which is out of bounds.\n", errout_str());
check("void f()\n"
"{\n"
" int a[6];\n"
" for (int i = 0; i < 7; i++)\n"
" {\n"
" a[i] = i;\n"
" i+=1;\n"
" }\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:6]: (error) Buffer overrun\n", "", errout_str());
}
void array_index_19() {
// "One Past the End" is legal, as long as pointer is not dereferenced.
check("void f()\n"
"{\n"
" char a[2];\n"
" char *end = &(a[2]);\n"
"}");
ASSERT_EQUALS("", errout_str());
// Getting more than one past the end is not legal
check("void f()\n"
"{\n"
" char a[2];\n"
" char *end = &(a[3]);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 'a[2]' accessed at index 3, which is out of bounds.\n", errout_str());
}
void array_index_20() {
check("void f()\n"
"{\n"
" char a[8];\n"
" int b[10];\n"
" for ( int i = 0; i < 9; i++ )\n"
" b[i] = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void array_index_21() {
check("class A {\n"
" int indices[2];\n"
" void foo(int indices[3]);\n"
"};\n"
"\n"
"void A::foo(int indices[3]) {\n"
" for(int j=0; j<3; ++j) {\n"
" int b = indices[j];\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void array_index_22() {
check("int main() {\n"
" size_t indices[2];\n"
" int b = indices[2];\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Array 'indices[2]' accessed at index 2, which is out of bounds.\n", errout_str());
}
void array_index_23() {
check("void foo()\n"
"{\n"
" char c[10];\n"
" c[1<<23]='a';\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 'c[10]' accessed at index 8388608, which is out of bounds.\n", errout_str());
}
void array_index_24() {
// ticket #1492 and #1539
const std::string charMaxPlusOne(settings0.platform.defaultSign == 'u' ? "256" : "128");
check("void f(char n) {\n"
" int a[n];\n" // n <= CHAR_MAX
" a[-1] = 0;\n" // negative index
" a[" + charMaxPlusOne + "] = 0;\n" // 128/256 > CHAR_MAX
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (error) Array 'a[" + charMaxPlusOne + "]' accessed at index -1, which is out of bounds.\n"
"[test.cpp:4]: (error) Array 'a[" + charMaxPlusOne + "]' accessed at index " + charMaxPlusOne + ", which is out of bounds.\n", errout_str());
check("void f(signed char n) {\n"
" int a[n];\n" // n <= SCHAR_MAX
" a[-1] = 0;\n" // negative index
" a[128] = 0;\n" // 128 > SCHAR_MAX
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Array 'a[128]' accessed at index -1, which is out of bounds.\n"
"[test.cpp:4]: (error) Array 'a[128]' accessed at index 128, which is out of bounds.\n", errout_str());
check("void f(unsigned char n) {\n"
" int a[n];\n" // n <= UCHAR_MAX
" a[-1] = 0;\n" // negative index
" a[256] = 0;\n" // 256 > UCHAR_MAX
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Array 'a[256]' accessed at index -1, which is out of bounds.\n"
"[test.cpp:4]: (error) Array 'a[256]' accessed at index 256, which is out of bounds.\n", errout_str());
check("void f(short n) {\n"
" int a[n];\n" // n <= SHRT_MAX
" a[-1] = 0;\n" // negative index
" a[32768] = 0;\n" // 32768 > SHRT_MAX
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Array 'a[32768]' accessed at index -1, which is out of bounds.\n"
"[test.cpp:4]: (error) Array 'a[32768]' accessed at index 32768, which is out of bounds.\n", errout_str());
check("void f(unsigned short n) {\n"
" int a[n];\n" // n <= USHRT_MAX
" a[-1] = 0;\n" // negative index
" a[65536] = 0;\n" // 65536 > USHRT_MAX
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Array 'a[65536]' accessed at index -1, which is out of bounds.\n"
"[test.cpp:4]: (error) Array 'a[65536]' accessed at index 65536, which is out of bounds.\n", errout_str());
check("void f(signed short n) {\n"
" int a[n];\n" // n <= SHRT_MAX
" a[-1] = 0;\n" // negative index
" a[32768] = 0;\n" // 32768 > SHRT_MAX
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Array 'a[32768]' accessed at index -1, which is out of bounds.\n"
"[test.cpp:4]: (error) Array 'a[32768]' accessed at index 32768, which is out of bounds.\n", errout_str());
check("void f(int n) {\n"
" int a[n];\n" // n <= INT_MAX
" a[-1] = 0;\n" // negative index
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Array 'a[2147483648]' accessed at index -1, which is out of bounds.\n", errout_str());
check("void f(unsigned int n) {\n"
" int a[n];\n" // n <= UINT_MAX
" a[-1] = 0;\n" // negative index
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Array 'a[4294967296]' accessed at index -1, which is out of bounds.\n", errout_str());
check("void f(signed int n) {\n"
" int a[n];\n" // n <= INT_MAX
" a[-1] = 0;\n" // negative index
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Array 'a[2147483648]' accessed at index -1, which is out of bounds.\n", errout_str());
}
void array_index_25() { // #1536
check("void foo()\n"
"{\n"
" long l[SOME_SIZE];\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void array_index_26() {
check("void f()\n"
"{\n"
" int a[3];\n"
" for (int i = 3; 0 <= i; i--)\n"
" a[i] = i;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Array 'a[3]' accessed at index 3, which is out of bounds.\n", errout_str());
check("void f()\n"
"{\n"
" int a[4];\n"
" for (int i = 3; 0 <= i; i--)\n"
" a[i] = i;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void array_index_27() {
check("void f()\n"
"{\n"
" int a[10];\n"
" for (int i = 0; i < 10; i++)\n"
" a[i-1] = a[i];\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Array 'a[10]' accessed at index -1, which is out of bounds.\n", errout_str());
}
void array_index_28() {
// ticket #1418
check("void f()\n"
"{\n"
" int i[2];\n"
" int *ip = i + 1;\n"
" ip[-10] = 1;\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:5]: (error) Array ip[-10] out of bounds.\n", "", errout_str());
}
void array_index_29() {
// ticket #1724
check("void f()\n"
"{\n"
" int iBuf[10];"
" int *i = iBuf + 9;"
" int *ii = i + -5;"
" ii[10] = 0;"
"}");
TODO_ASSERT_EQUALS("[test.cpp:6]: (error) Array ii[10] out of bounds.\n", "", errout_str());
}
void array_index_30() {
// ticket #2086 - unknown type
// extracttests.start: typedef unsigned char UINT8;
check("void f() {\n"
" UINT8 x[2];\n"
" x[5] = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Array 'x[2]' accessed at index 5, which is out of bounds.\n", errout_str());
}
void array_index_31() {
// ticket #2120 - sub function, unknown type
check("struct s1 {\n"
" unknown_type_t delay[3];\n"
"};\n"
"\n"
"void x(unknown_type_t *delay, const int *net) {\n"
" delay[0] = 0;\n"
"}\n"
"\n"
"void y() {\n"
" struct s1 obj;\n"
" x(obj.delay, 123);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct s1 {\n"
" unknown_type_t delay[3];\n"
"};\n"
"\n"
"void x(unknown_type_t *delay, const int *net) {\n"
" delay[4] = 0;\n"
"}\n"
"\n"
"void y() {\n"
" struct s1 obj;\n"
" x(obj.delay, 123);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:11] -> [test.cpp:6]: (error) Array 'obj.delay[3]' accessed at index 4, which is out of bounds.\n",
"",
errout_str());
check("struct s1 {\n"
" float a[0];\n"
"};\n"
"\n"
"void f() {\n"
" struct s1 *obj;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void array_index_32() {
check("class X\n"
"{\n"
" public:\n"
" X()\n"
" {\n"
" m_x[0] = 0;\n"
" m_x[1] = 0;\n"
" }\n"
" int m_x[1];\n"
"};");
ASSERT_EQUALS("[test.cpp:7]: (error) Array 'm_x[1]' accessed at index 1, which is out of bounds.\n", errout_str());
}
void array_index_33() {
check("void foo(char bar[][4]) {\n"
" baz(bar[5]);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void array_index_34() { // ticket #3063
check("void foo() {\n"
" int y[2][2][2];\n"
" y[0][2][0] = 0;\n"
" y[0][0][2] = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Array 'y[2][2][2]' accessed at index y[0][2][0], which is out of bounds.\n"
"[test.cpp:4]: (error) Array 'y[2][2][2]' accessed at index y[0][0][2], which is out of bounds.\n", errout_str());
check("struct TEST\n"
"{\n"
" char a[10];\n"
" char b[10][5];\n"
"};\n"
"void foo()\n"
"{\n"
" TEST test;\n"
" test.a[10] = 3;\n"
" test.b[10][2] = 4;\n"
" test.b[0][19] = 4;\n"
" TEST *ptest;\n"
" ptest = &test;\n"
" ptest->a[10] = 3;\n"
" ptest->b[10][2] = 4;\n"
" ptest->b[0][19] = 4;\n"
"}");
ASSERT_EQUALS("[test.cpp:9]: (error) Array 'test.a[10]' accessed at index 10, which is out of bounds.\n"
"[test.cpp:10]: (error) Array 'test.b[10][5]' accessed at index test.b[10][2], which is out of bounds.\n"
"[test.cpp:11]: (error) Array 'test.b[10][5]' accessed at index test.b[0][19], which is out of bounds.\n"
"[test.cpp:14]: (error) Array 'ptest->a[10]' accessed at index 10, which is out of bounds.\n"
"[test.cpp:15]: (error) Array 'ptest->b[10][5]' accessed at index ptest->b[10][2], which is out of bounds.\n"
"[test.cpp:16]: (error) Array 'ptest->b[10][5]' accessed at index ptest->b[0][19], which is out of bounds.\n", errout_str());
check("struct TEST\n"
"{\n"
" char a[10][5];\n"
"};\n"
"void foo()\n"
"{\n"
" TEST test;\n"
" test.a[9][5] = 4;\n"
" test.a[0][50] = 4;\n"
" TEST *ptest;\n"
" ptest = &test;\n"
" ptest->a[9][5] = 4;\n"
" ptest->a[0][50] = 4;\n"
"}");
ASSERT_EQUALS("[test.cpp:8]: (error) Array 'test.a[10][5]' accessed at index test.a[9][5], which is out of bounds.\n"
"[test.cpp:9]: (error) Array 'test.a[10][5]' accessed at index test.a[0][50], which is out of bounds.\n"
"[test.cpp:12]: (error) Array 'ptest->a[10][5]' accessed at index ptest->a[9][5], which is out of bounds.\n"
"[test.cpp:13]: (error) Array 'ptest->a[10][5]' accessed at index ptest->a[0][50], which is out of bounds.\n", errout_str());
}
void array_index_35() { // ticket #2889
check("void f() {\n"
" struct Struct { unsigned m_Var[1]; } s;\n"
" s.m_Var[1] = 1;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Array 's.m_Var[1]' accessed at index 1, which is out of bounds.\n", errout_str());
check("struct Struct { unsigned m_Var[1]; };\n"
"void f() {\n"
" struct Struct s;\n"
" s.m_Var[1] = 1;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 's.m_Var[1]' accessed at index 1, which is out of bounds.\n", errout_str());
check("struct Struct { unsigned m_Var[1]; };\n"
"void f() {\n"
" struct Struct * s = calloc(40);\n"
" s->m_Var[1] = 1;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void array_index_36() { // ticket #2960
check("class Fred {\n"
" Fred(const Fred &);\n"
"private:\n"
" bool m_b[2];\n"
"};\n"
"Fred::Fred(const Fred & rhs) {\n"
" m_b[2] = rhs.m_b[2];\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (error) Array 'm_b[2]' accessed at index 2, which is out of bounds.\n"
"[test.cpp:7]: (error) Array 'rhs.m_b[2]' accessed at index 2, which is out of bounds.\n", errout_str());
}
void array_index_37() {
check("class Fred {\n"
" char x[X];\n"
" Fred() {\n"
" for (unsigned int i = 0; i < 15; i++)\n"
" i;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void array_index_38() { //ticket #3273
check("void aFunction() {\n"
" double aDoubleArray[ 10 ];\n"
" unsigned int i; i = 0;\n"
" for( i = 0; i < 6; i++ )\n"
" {\n"
" unsigned int j; j = 0;\n"
" for( j = 0; j < 5; j++ )\n"
" {\n"
" unsigned int x; x = 0;\n"
" for( x = 0; x < 4; x++ )\n"
" {\n"
" }\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void array_index_39() { // ticket 3387
check("void aFunction()\n"
"{\n"
" char a[10];\n"
" a[10] = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 'a[10]' accessed at index 10, which is out of bounds.\n", errout_str());
}
void array_index_40() {
check("void f() {\n"
" char a[10];\n"
" for (int i = 0; i < 10; ++i)\n"
" f2(&a[i + 1]);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void array_index_41() {
// Don't generate false positives when structs have the same name
check("void a() {\n"
" struct Fred { char data[6]; } fred;\n"
" fred.data[4] = 0;\n" // <- no error
"}\n"
"\n"
"void b() {\n"
" struct Fred { char data[3]; } fred;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void a() {\n"
" struct Fred { char data[6]; } fred;\n"
" fred.data[4] = 0;\n" // <- no error
"}\n"
"\n"
"void b() {\n"
" struct Fred { char data[3]; } fred;\n"
" fred.data[4] = 0;\n" // <- error
"}");
ASSERT_EQUALS("[test.cpp:8]: (error) Array 'fred.data[3]' accessed at index 4, which is out of bounds.\n", errout_str());
}
void array_index_42() { // ticket #3569
check("void f()\n"
"{\n"
" char *p; p = (char *)malloc(10);\n"
" p[10] = 7;\n"
" free(p);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 'p[10]' accessed at index 10, which is out of bounds.\n", errout_str());
check("void f()\n"
"{\n"
" float *p; p = (float *)malloc(10 * sizeof(float));\n"
" p[10] = 7;\n"
" free(p);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 'p[10]' accessed at index 10, which is out of bounds.\n", errout_str());
check("void f()\n"
"{\n"
" char *p; p = (char *)malloc(10);\n"
" p[0] = 0;\n"
" p[9] = 9;\n"
" free(p);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f()\n"
"{\n"
" char *p; p = new char[10];\n"
" p[0] = 0;\n"
" p[9] = 9;\n"
" delete [] p;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f()\n"
"{\n"
" char *p(new char[10]);\n"
" p[0] = 0;\n"
" p[9] = 9;\n"
" delete [] p;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f()\n"
"{\n"
" char *p = NULL;"
" try{\n"
" p = new char[10];\n"
" }\n"
" catch(...){\n"
" return;\n"
" }"
" p[0] = 0;\n"
" p[9] = 9;\n"
" delete [] p;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void array_index_43() { // #3838
check("int f( )\n"
"{\n"
" struct {\n"
" int arr[ 3 ];\n"
" } var[ 1 ];\n"
" int y;\n"
" var[ 0 ].arr[ 0 ] = 0;\n"
" var[ 0 ].arr[ 1 ] = 1;\n"
" var[ 0 ].arr[ 2 ] = 2;\n"
" y = var[ 0 ].arr[ 3 ];\n" // <-- array access out of bounds
" return y;\n"
"}");
ASSERT_EQUALS("[test.cpp:10]: (error) Array 'var[0].arr[3]' accessed at index 3, which is out of bounds.\n", errout_str());
check("int f( )\n"
"{\n"
" struct {\n"
" int arr[ 3 ];\n"
" } var[ 1 ];\n"
" int y=1;\n"
" var[ 0 ].arr[ 0 ] = 0;\n"
" var[ 0 ].arr[ 1 ] = 1;\n"
" var[ 0 ].arr[ 2 ] = 2;\n"
" y = var[ 0 ].arr[ 2 ];\n"
" return y;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int f( ){\n"
"struct Struct{\n"
" int arr[ 3 ];\n"
"};\n"
"int y;\n"
"Struct var;\n"
"var.arr[ 0 ] = 0;\n"
"var.arr[ 1 ] = 1;\n"
"var.arr[ 2 ] = 2;\n"
"var.arr[ 3 ] = 3;\n" // <-- array access out of bounds
"y=var.arr[ 3 ];\n" // <-- array access out of bounds
"return y;\n"
"}");
ASSERT_EQUALS("[test.cpp:10]: (error) Array 'var.arr[3]' accessed at index 3, which is out of bounds.\n"
"[test.cpp:11]: (error) Array 'var.arr[3]' accessed at index 3, which is out of bounds.\n", errout_str());
check("void f( ) {\n"
"struct S{\n"
" int var[ 3 ];\n"
"} ;\n"
"S var[2];\n"
"var[0].var[ 0 ] = 0;\n"
"var[0].var[ 1 ] = 1;\n"
"var[0].var[ 2 ] = 2;\n"
"var[0].var[ 4 ] = 4;\n" // <-- array access out of bounds
"}");
ASSERT_EQUALS("[test.cpp:9]: (error) Array 'var[0].var[3]' accessed at index 4, which is out of bounds.\n", errout_str());
check("void f( ) {\n"
"struct S{\n"
" int var[ 3 ];\n"
"} ;\n"
"S var[2];\n"
"var[0].var[ 0 ] = 0;\n"
"var[0].var[ 1 ] = 1;\n"
"var[0].var[ 2 ] = 2;\n"
"}");
ASSERT_EQUALS("", errout_str());
// avoid FPs (modified examples taken from #3838)
check("struct AB { int a[10]; int b[10]; };\n"
"int main() {\n"
" struct AB ab;\n"
" int * p = &ab.a[10];\n"
" return 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct AB { int a[10]; int b[10]; };\n"
"int main() {\n"
" struct AB ab[1];\n"
" int * p = &ab[0].a[10];\n"
" return 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct AB { int a[10]; int b[10]; };\n"
"int main() {\n"
" struct AB ab[1];\n"
" int * p = &ab[10].a[0];\n"
" return 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 'ab[1]' accessed at index 10, which is out of bounds.\n", errout_str());
}
void array_index_44() { // #3979 (false positive)
check("void f()\n"
"{\n"
" char buf[2];\n"
" int i;\n"
" for (i = 2; --i >= 0; )\n"
" {\n"
" buf[i] = 1;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f()\n"
"{\n"
" double buf[2];\n"
" for (int i = 2; i--; )\n"
" {\n"
" buf[i] = 2.;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void array_index_45() { // #4207 - handling of function with variable number of parameters / unnamed arguments
// Variable number of arguments
check("void f(const char *format, ...) {\n"
" va_args args;\n"
" va_start(args, format);\n"
"}\n"
"void test() {\n"
" CHAR buffer[1024];\n"
" f(\"%s\", buffer);\n"
"}");
ASSERT_EQUALS("", errout_str());
// Unnamed argument
check("void f(char *) {\n"
" dostuff();\n"
"}\n"
"void test() {\n"
" char buffer[1024];\n"
" f(buffer);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
// Two statement for-loop
void array_index_46() {
// #4840
check("void bufferAccessOutOfBounds2() {\n"
" char *buffer[]={\"a\",\"b\",\"c\"};\n"
" for(int i=3; i--;) {\n"
" printf(\"files(%i): %s\", 3-i, buffer[3-i]);\n"
" }\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:4]: (error) Array 'buffer[3]' accessed at index 3, which is out of bounds.\n", "", errout_str());
check("void f() {\n"
" int buffer[9];\n"
" long int i;\n"
" for(i=10; i--;) {\n"
" buffer[i] = i;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Array 'buffer[9]' accessed at index 9, which is out of bounds.\n", errout_str());
// Correct access limits -> i from 9 to 0
check("void f() {\n"
" int buffer[10];\n"
" for(unsigned long int i=10; i--;) {\n"
" buffer[i] = i;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void array_index_47() {
// #5849
check("int s[4];\n"
"void f() {\n"
" for (int i = 2; i < 0; i++)\n"
" s[i] = 5;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void array_index_48() {
// #9478
check("void test(void)\n"
"{\n"
" int array[4] = { 1,2,3,4 };\n"
" for (int i = 1; i <= 4; i++) {\n"
" printf(\" %i\", i);\n"
" array[i] = 0;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (error) Array 'array[4]' accessed at index 4, which is out of bounds.\n", errout_str());
check("void test(void)\n"
"{\n"
" int array[4] = { 1,2,3,4 };\n"
" for (int i = 1; i <= 4; i++) {\n"
" scanf(\"%i\", &i);\n"
" array[i] = 0;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void array_index_49() {
// #8653
check("void f() {\n"
" int i, k;\n"
" int arr[34] = {};\n"
" i = 1;\n"
" for (k = 0; k < 34 && i < 34; k++) {\n"
" i++;\n"
" }\n"
" arr[k];\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void array_index_50() {
check("void f(const char * str) {\n"
" int len = strlen(str);\n"
" (void)str[len - 1];\n"
"}\n"
"void g() {\n"
" f(\"12345678\");\n"
" f(\"12345\");\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void array_index_51() {
check("void f(void){\n"
" int k=0, dd, d[1U] = {1};\n"
" for (dd=d[k]; k<10; dd=d[++k]){;}\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Array 'd[1]' accessed at index 1, which is out of bounds.\n", errout_str());
}
void array_index_52() {
check("char f(void)\n"
"{\n"
" char buf[10];\n"
" for(int i = 0, j= 11; i < j; ++i)\n"
" buf[i] = 0;\n"
" return buf[0];\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Array 'buf[10]' accessed at index 10, which is out of bounds.\n", errout_str());
}
void array_index_53() {
check("double M[3][1];\n"
" \n"
"void matrix()\n"
"{\n"
" for (int i=0; i < 3; i++)\n"
" for (int j = 0; j < 3; j++)\n"
" M[i][j]=0.0;\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (error) Array 'M[3][1]' accessed at index M[*][2], which is out of bounds.\n", errout_str());
}
void array_index_54() {
check("void f() {\n"
" g(0);\n"
"}\n"
"void g(unsigned int x) {\n"
" int b[4];\n"
" for (unsigned int i = 0; i < 4; i += 2) {\n"
" b[i] = 0;\n"
" b[i+1] = 0;\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void array_index_55() {
check("void make(const char* s, size_t len) {\n"
" for (size_t i = 0; i < len; ++i)\n"
" s[i];\n"
"}\n"
"void make(const char* s) {\n"
" make(s, strlen(s));\n"
"}\n"
"void f() {\n"
" make(\"my-utf8-payload\");\n"
"}\n"
"void f2() {\n"
" make(\"false\");\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void array_index_56() {
check("struct s {\n"
" int array[1];\n"
" int index;\n"
"};\n"
"void f(struct s foo) {\n"
" foo.array[foo.index++] = 1;\n"
" if (foo.index == 1) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void array_index_57() {
check("void f(std::vector<int>& v) {\n"
" int a[3] = { 1, 2, 3 };\n"
" int i = 0;\n"
" for (auto& x : v) {\n"
" int c = a[i++];\n"
" if (i == 3)\n"
" i = 0;\n"
" x = c;\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(std::vector<int>& v) {\n"
" int a[3] = { 1, 2, 3 };\n"
" int i = 0;\n"
" for (auto& x : v) {\n"
" int c = a[i++];\n"
" if (i == 4)\n"
" i = 0;\n"
" x = c;\n"
" }\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:6] -> [test.cpp:5]: (warning) Either the condition 'i==4' is redundant or the array 'a[3]' is accessed at index 3, which is out of bounds.\n",
errout_str());
}
void array_index_58()
{
check("int f(int x, int y) {\n"
" int a[3]= {0,1,2};\n"
" if(x<2)\n"
" y = a[x] + 1;\n"
" else\n"
" y = a[x];\n"
" return y;\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:3] -> [test.cpp:6]: (warning) Either the condition 'x<2' is redundant or the array 'a[3]' is accessed at index 3, which is out of bounds.\n",
errout_str());
check("void f() {\n" // #2199
" char a[5];\n"
" for (int i = 0; i < 5; i++) {\n"
" i += 8;\n"
" a[i] = 0;\n"
" }\n"
"}\n"
"void g() {\n"
" char a[5];\n"
" for (int i = 0; i < 5; i++) {\n"
" a[i + 7] = 0;\n"
" }\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:5]: (error) Array 'a[5]' accessed at index 8, which is out of bounds.\n"
"[test.cpp:11]: (error) Array 'a[5]' accessed at index 11, which is out of bounds.\n",
errout_str());
}
void array_index_59() // #10413
{
check("long f(long b) {\n"
" const long a[] = { 0, 1, };\n"
" const long c = std::size(a);\n"
" if (b < 0 || b >= c)\n"
" return 0;\n"
" return a[b];\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(int a, int b) {\n"
" const int S[2] = {};\n"
" if (a < 0) {}\n"
" else {\n"
" if (b < 0) {}\n"
" else if (S[b] > S[a]) {}\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("int a[2] = {};\n"
"void f(int i) {\n"
" g(i < 0 ? 0 : a[i]);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void array_index_60()
{
checkP("#define CKR(B) if (!(B)) { return -1; }\n"
"int f(int i) {\n"
" const int A[3] = {};\n"
" CKR(i < 3);\n"
" if (i > 0)\n"
" i = A[i];\n"
" return i;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkP("#define ASSERT(expression, action) if (expression) {action;}\n"
"int array[5];\n"
"void func (int index) {\n"
" ASSERT(index > 5, return);\n"
" array[index]++;\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:4] -> [test.cpp:5]: (warning) Either the condition 'index>5' is redundant or the array 'array[5]' is accessed at index 5, which is out of bounds.\n",
errout_str());
}
void array_index_61()
{
check("int f(int i) {\n"
" const int M[] = { 0, 1, 2, 3 };\n"
" if (i > 4)\n"
" return -1;\n"
" if (i < 0 || i == std::size(M))\n"
" return 0; \n"
" return M[i];\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct S { enum E { e0 }; };\n"
"const S::E M[4] = { S::E:e0, S::E:e0, S::E:e0, S::E:e0 };\n"
"int f(int i) {\n"
" if (i > std::size(M) + 1)\n"
" return -1;\n"
" if (i < 0 || i >= std::size(M))\n"
" return 0;\n"
" return M[i]; \n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void array_index_62()
{
check("struct X {\n"
" static int GetSize() {return 11;}\n"
"};\n"
"char f() {\n"
" char buf[10]= {0};\n"
" for(int i = 0; i < X::GetSize(); ++i) \n"
" buf[i] = 0;\n"
" return buf[0];\n"
"}\n");
ASSERT_EQUALS("[test.cpp:7]: (error) Array 'buf[10]' accessed at index 10, which is out of bounds.\n",
errout_str());
}
void array_index_63()
{
check("int b[4];\n" // #10979
"void f(int i) {\n"
" if (i >= 0 && i < sizeof(b) / sizeof(*(b)))\n"
" b[i] = 0;\n"
" if (i >= 0 && i < sizeof(b) / sizeof((b)[0]))\n"
" b[i] = 0;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void array_index_64() // #10878
{
check("struct Array {\n"
" int x[10];\n"
" int& accessArrayRef(int a) { return x[a]; }\n"
"};\n"
"void f() {\n"
" Array array = {};\n"
" array.accessArrayRef(10);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (error) Array 'x[10]' accessed at index 10, which is out of bounds.\n", errout_str());
check("int i = 10;\n"
"struct Array {\n"
" int x[10];\n"
" int& accessArrayRef(int a) { return x[a]; }\n"
"};\n"
"void f() {\n"
" Array array = {};\n"
" array.accessArrayRef(i);\n"
"}\n");
TODO_ASSERT_EQUALS("[test.cpp:3]: (error) Array 'x[10]' accessed at index 10, which is out of bounds.\n", "", errout_str());
}
void array_index_65() // #11066
{
check("char P[] = { 2, 1 };\n"
"char f[2];\n"
"void e(char* c) {\n"
" register j;\n"
" for (j = 0; j < 2; j++)\n"
" c[j] = f[P[j] - 1];\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void array_index_66()
{
check("void foo(int j) {\n"
" int offsets[256];\n"
" while (x) {\n"
" if (j >= 256) break;\n"
" offsets[++j] = -1;\n"
" }\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:4] -> [test.cpp:5]: (warning) Either the condition 'j>=256' is redundant or the array 'offsets[256]' is accessed at index 256, which is out of bounds.\n",
errout_str());
}
void array_index_67() {
check("void func(int i) {\n" // #1596
" int types[3];\n"
" int type_cnt = 0;\n"
" if (i == 0) {\n"
" types[type_cnt] = 0;\n"
" type_cnt++;\n"
" types[type_cnt] = 0;\n"
" type_cnt++;\n"
" types[type_cnt] = 0;\n"
" type_cnt++;\n"
" } else {\n"
" types[type_cnt] = 1;\n"
" type_cnt++;\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void array_index_68() { // #6655
check("int ia[10];\n"
"void f(int len) {\n"
" for (int i = 0; i < len; i++)\n"
" ia[i] = 0;\n"
"}\n"
"int g() {\n"
" f(20);\n"
" return 0;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 'ia[10]' accessed at index 19, which is out of bounds.\n", errout_str());
}
// #6370
void array_index_69()
{
check("void f() {\n"
" const int e[] = {0,10,20,30};\n"
" int a[4];\n"
" for(int i = 0; i < 4; ++i)\n"
" a[e[i]] = 0;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5]: (error) Array 'a[4]' accessed at index 30, which is out of bounds.\n", errout_str());
}
// #11355
void array_index_70() {
check("void f() {\n"
" static const char a[] = ((\"test\"));\n"
" printf(\"%c\", a[5]);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (error) Array 'a[5]' accessed at index 5, which is out of bounds.\n", errout_str());
}
// #11461
void array_index_71()
{
check("unsigned int f(unsigned int Idx) {\n"
" if (Idx < 64)\n"
" return 0;\n"
" Idx -= 64;\n"
" int arr[64] = { 0 };\n"
" return arr[Idx];\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
// #11784
void array_index_72()
{
check("char f(int i) {\n"
" char d[4] = {};\n"
" for (; i < 3; i++) {}\n"
" for (i++; i > 0;) {\n"
" d[--i] = 1;\n"
" break;\n"
" }\n"
" return d[3];\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
// #11530
void array_index_73()
{
check("void f() {\n"
" int k = 0;\n"
" std::function<void(int)> a[1] = {};\n"
" a[k++](0);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
// #11088
void array_index_74()
{
check("void foo(const char *keys) {\n"
" const char *prefix = \"<Shift+\";\n"
" const size_t prefix_len = strlen(prefix);\n"
" if (strncmp(keys, prefix, prefix_len)) { return; }\n"
" if (keys[prefix_len] == '>') {}\n"
"}\n"
"void bar() {\n"
" foo(\"q\");\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
// #1644
void array_index_75()
{
check("void f() {\n"
" char buf[10];\n"
" int i = 10;\n"
" while (i >= 3)\n"
" buf[i--] = 0;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5]: (error) Array 'buf[10]' accessed at index 10, which is out of bounds.\n", errout_str());
}
// #12592
void array_index_76()
{
check("void cb0(void*, int i) {\n"
" const char s[] = \"\";\n"
" (void)s[i];\n"
"}\n"
"void cb1(int i, void*) {\n"
" const char s[] = \"\";\n"
" (void)s[i];\n"
"}\n"
"void f() {\n"
" cb0(nullptr, 1);\n"
" cb1(1, nullptr);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (error) Array 's[1]' accessed at index 1, which is out of bounds.\n"
"[test.cpp:7]: (error) Array 's[1]' accessed at index 1, which is out of bounds.\n",
errout_str());
}
void array_index_multidim() {
check("void f()\n"
"{\n"
" char a[2][2];\n"
" a[1][1] = 'a';\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f()\n"
"{\n"
" char a[2][2][2];\n"
" a[1][1][1] = 'a';\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f()\n"
"{\n"
" char a[2][2];\n"
" a[2][1] = 'a';\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 'a[2][2]' accessed at index a[2][1], which is out of bounds.\n", errout_str());
check("void f()\n"
"{\n"
" char a[2][2];\n"
" a[1][2] = 'a';\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 'a[2][2]' accessed at index a[1][2], which is out of bounds.\n", errout_str());
check("void f()\n"
"{\n"
" char a[2][2][2];\n"
" a[2][1][1] = 'a';\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 'a[2][2][2]' accessed at index a[2][1][1], which is out of bounds.\n", errout_str());
check("void f()\n"
"{\n"
" char a[2][2][2];\n"
" a[1][2][1] = 'a';\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 'a[2][2][2]' accessed at index a[1][2][1], which is out of bounds.\n", errout_str());
check("void f()\n"
"{\n"
" char a[2][2][2][2];\n"
" a[1][2][1][1] = 'a';\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 'a[2][2][2][2]' accessed at index a[1][2][1][1], which is out of bounds.\n", errout_str());
check("void f()\n"
"{\n"
" char a[2][2][2];\n"
" a[1][1][2] = 'a';\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 'a[2][2][2]' accessed at index a[1][1][2], which is out of bounds.\n", errout_str());
check("void f()\n"
"{\n"
" char a[10][10][10];\n"
" a[2*3][4*3][2] = 'a';\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 'a[10][10][10]' accessed at index a[6][12][2], which is out of bounds.\n", errout_str());
check("void f() {\n"
" char a[10][10][10];\n"
" a[6][40][10] = 'a';\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Array 'a[10][10][10]' accessed at index a[6][40][10], which is out of bounds.\n", errout_str());
check("void f() {\n"
" char a[1][1][1];\n"
" a[2][2][2] = 'a';\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Array 'a[1][1][1]' accessed at index a[2][2][2], which is out of bounds.\n", errout_str());
check("void f() {\n"
" char a[6][6][6];\n"
" a[6][6][2] = 'a';\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Array 'a[6][6][6]' accessed at index a[6][6][2], which is out of bounds.\n", errout_str());
check("void f() {\n"
" int a[2][2];\n"
" p = &a[2][0];\n"
"}");
ASSERT_EQUALS("", errout_str());
// unknown dim..
check("void f()\n"
"{\n"
" int a[2][countof(x)] = {{1,2},{3,4}};\n"
" a[0][0] = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void draw_quad(float z) {\n"
" int i;\n"
" float (*vertices)[2][4];\n"
" vertices[0][0][0] = z;\n"
" vertices[0][0][1] = z;\n"
" vertices[1][0][0] = z;\n"
" vertices[1][0][1] = z;\n"
" vertices[2][0][0] = z;\n"
" vertices[2][0][1] = z;\n"
" vertices[3][0][0] = z;\n"
" vertices[3][0][1] = z;\n"
" for (i = 0; i < 4; i++) {\n"
" vertices[i][0][2] = z;\n"
" vertices[i][0][3] = 1.0;\n"
" vertices[i][1][0] = 2.0;\n"
" vertices[i][1][1] = 3.0;\n"
" vertices[i][1][2] = 4.0;\n"
" vertices[i][1][3] = 5.0;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
{
check("int foo() {\n"
" const size_t A = 4;\n"
" const size_t B = 2;\n"
" extern int stuff[A][B];\n"
" return stuff[0][1];\n"
"}");
ASSERT_EQUALS("", errout_str());
// TODO: better handling of VLAs in symboldatabase. should be
// possible to use ValueFlow values.
check("int foo() {\n"
" const size_t A = 4;\n"
" const size_t B = 2;\n"
" extern int stuff[A][B];\n"
" return stuff[0][1];\n"
"}");
TODO_ASSERT_EQUALS("error", "", errout_str());
}
}
void array_index_switch_in_for() {
check("void f()\n"
"{\n"
" int ar[10];\n"
" for (int i = 0; i < 10; ++i)\n"
" {\n"
" switch(i)\n"
" {\n"
" case 9:\n"
" ar[i] = 0;\n"
" break;\n"
" default:\n"
" ar[i] = ar[i+1];\n"
" break;\n"
" };\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f()\n"
"{\n"
" int ar[10];\n"
" for (int i = 0; i < 10; ++i)\n"
" {\n"
" switch(i)\n"
" {\n"
" case 8:\n"
" ar[i] = 0;\n"
" break;\n"
" default:\n"
" ar[i] = ar[i+1];\n"
" break;\n"
" };\n"
" }\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:12]: (error) Array index out of bounds.\n", "", errout_str());
}
void array_index_for_in_for() {
check("void f() {\n"
" int a[5];\n"
" for (int i = 0; i < 10; ++i) {\n"
" for (int j = i; j < 5; ++j) {\n"
" a[i] = 0;\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void array_index_bounds() {
// #10275
check("int a[10];\n"
"void f(int i) {\n"
" if (i >= 0 && i < 10) {}\n"
" a[i] = 1;\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (warning) Either the condition 'i<10' is redundant or the array 'a[10]' is accessed at index 10, which is out of bounds.\n"
"[test.cpp:3] -> [test.cpp:4]: (warning) Either the condition 'i>=0' is redundant or the array 'a[10]' is accessed at index -1, which is out of bounds.\n",
errout_str());
}
void array_index_calculation() {
// #1193 - false negative: array out of bounds in loop when there is calculation
check("void f()\n"
"{\n"
" char data[8];\n"
" for (int i = 19; i < 36; ++i) {\n"
" data[i/2] = 0;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Array 'data[8]' accessed at index 17, which is out of bounds.\n", errout_str());
// #2199 - false negative: array out of bounds in loop when there is calculation
check("void f()\n"
"{\n"
" char arr[5];\n"
" for (int i = 0; i < 5; ++i) {\n"
" arr[i + 7] = 0;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Array 'arr[5]' accessed at index 11, which is out of bounds.\n", errout_str());
}
void array_index_negative1() {
// #948 - array index out of bound not detected 'a[-1] = 0'
check("void f()\n"
"{\n"
" char data[8];\n"
" data[-1] = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 'data[8]' accessed at index -1, which is out of bounds.\n", errout_str());
check("void f()\n"
"{\n"
" char data[8][4];\n"
" data[5][-1] = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 'data[8][4]' accessed at index data[*][-1], which is out of bounds.\n", errout_str());
// #1614 - negative index is ok for pointers
check("void foo(char *p)\n"
"{\n"
" p[-1] = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo()\n"
"{\n"
" char s[] = \"abc\";\n"
" char *p = s + strlen(s);\n"
" if (p[-1]);\n"
"}");
ASSERT_EQUALS("", errout_str());
// ticket #1850
check("int f(const std::map<int, std::map<int,int> > &m)\n"
"{\n"
" return m[0][-1];\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void array_index_negative2() { // ticket #3063
check("struct TEST { char a[10]; };\n"
"void foo() {\n"
" TEST test;\n"
" test.a[-1] = 3;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 'test.a[10]' accessed at index -1, which is out of bounds.\n", errout_str());
}
void array_index_negative3() {
check("int f(int i) {\n"
" int p[2] = {0, 0};\n"
" if(i >= 2)\n"
" return 0;\n"
" else if(i == 0)\n"
" return 0;\n"
" return p[i - 1];\n"
"}\n"
"void g(int i) {\n"
" if( i == 0 )\n"
" return f(i);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void array_index_negative4()
{
check("void f(void) {\n"
" int buf[64]={};\n"
" int i;\n"
" for(i=0; i <16; ++i){}\n"
" for(; i < 24; ++i){ buf[i] = buf[i-16];}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void array_index_negative5() // #10526
{
check("int i;\n"
"std::vector<int> v;\n"
"bool f() {\n"
" if (i != 0) {\n"
" if (v.begin() != v.end()) {\n"
" if (i < 0)\n"
" return false;\n"
" const int a[4] = { 0, 1, 2, 3 };\n"
" return a[i - 1] > 0;\n"
" }\n"
" }\n"
" return false;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
// #11349
void array_index_negative6()
{
check("void f(int i) {\n"
" int j = i;\n"
" const int a[5] = {};\n"
" const int k = j < 0 ? 0 : j;\n"
" (void)a[k];\n"
" if (i == -3) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
// #5685
void array_index_negative7()
{
check("void f() {\n"
" int i = -9;\n"
" int a[5];\n"
" for (; i < 5; i++)\n"
" a[i] = 1;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5]: (error) Array 'a[5]' accessed at index -9, which is out of bounds.\n", errout_str());
}
// #11651
void array_index_negative8()
{
check("unsigned g(char*);\n"
"void f() {\n"
" char buf[10];\n"
" unsigned u = g(buf);\n"
" for (int i = u, j = sizeof(i); --i >= 0;)\n"
" char c = buf[i];\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
// #8075
void array_index_negative9()
{
check("int g(int i) {\n"
" if (i < 10)\n"
" return -1;\n"
" return 0;\n"
"}\n"
"void f() {\n"
" int a[] = { 1, 2, 3 };\n"
" printf(\"%d\\n\", a[g(4)]);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:8]: (error) Array 'a[3]' accessed at index -1, which is out of bounds.\n", errout_str());
}
// #11844
void array_index_negative10()
{
check("struct S { int a[4]; };\n"
"void f(S* p, int k) {\n"
" int m = 3;\n"
" if (k)\n"
" m = 2;\n"
" for (int j = m + 1; j <= 4; j++)\n"
" p->a[j-1];\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void array_index_for_decr() {
check("void f()\n"
"{\n"
" char data[8];\n"
" for (int i = 10; i > 0; --i) {\n"
" data[i] = 0;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Array 'data[8]' accessed at index 10, which is out of bounds.\n", errout_str());
check("void f()\n"
"{\n"
" char val[5];\n"
" for (unsigned int i = 3; i < 5; --i) {\n"
" val[i+1] = val[i];\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f()\n"
"{\n"
" char val[5];\n"
" for (int i = 3; i < 5; --i) {\n"
" val[i+1] = val[i];\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Array 'val[5]' accessed at index -9994, which is out of bounds.\n"
"[test.cpp:5]: (error) Array 'val[5]' accessed at index -9995, which is out of bounds.\n", errout_str());
}
void array_index_varnames() {
check("struct A {\n"
" char data[4];\n"
" struct B { char data[3]; };\n"
" B b;\n"
"};\n"
"\n"
"void f()\n"
"{\n"
" A a;\n"
" a.data[3] = 0;\n"
" a.b.data[2] = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
// #1586
check("struct A {\n"
" char data[4];\n"
" struct B { char data[3]; };\n"
" B b;\n"
"};\n"
"\n"
"void f()\n"
"{\n"
" A a;\n"
" a.data[4] = 0;\n"
" a.b.data[3] = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:10]: (error) Array 'a.data[4]' accessed at index 4, which is out of bounds.\n"
"[test.cpp:11]: (error) Array 'a.b.data[3]' accessed at index 3, which is out of bounds.\n", errout_str());
}
void array_index_for_andand_oror() { // #3907 - using && or ||
// extracttests.start: volatile int y;
check("void f() {\n"
" char data[2];\n"
" int x;\n"
" for (x = 0; x < 10 && y; x++) {\n"
" data[x] = 0;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Array 'data[2]' accessed at index 9, which is out of bounds.\n", errout_str());
check("void f() {\n"
" char data[2];\n"
" int x;\n"
" for (x = 0; x < 10 || y; x++) {\n"
" data[x] = 0;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Array 'data[2]' accessed at index 9, which is out of bounds.\n", errout_str());
check("void f() {\n"
" char data[2];\n"
" int x;\n"
" for (x = 0; x <= 10 && y; x++) {\n"
" data[x] = 0;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Array 'data[2]' accessed at index 10, which is out of bounds.\n", errout_str());
check("void f() {\n"
" char data[2];\n"
" int x;\n"
" for (x = 0; y && x <= 10; x++) {\n"
" data[x] = 0;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Array 'data[2]' accessed at index 10, which is out of bounds.\n", errout_str());
check("int f() {\n" // #9126
" int i, c;\n"
" char* words[100] = {0};\n"
" g(words);\n"
" for (i = c = 0; (i < N) && (c < 1); i++) {\n"
" if (words[i][0] == '|')\n"
" c++;\n"
" }\n"
" return c;\n"
"}", false);
ASSERT_EQUALS("", errout_str());
}
void array_index_for_continue() {
// #3913
check("void f() {\n"
" int a[2];\n"
" for (int i = 0; i < 2; ++i) {\n"
" if (i == 0) {\n"
" continue;\n"
" }\n"
" a[i - 1] = 0;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// extracttests.start: int maybe();
check("void f() {\n"
" int a[2];\n"
" for (int i = 0; i < 2; ++i) {\n"
" if (maybe()) {\n"
" continue;\n"
" }\n"
" a[i - 1] = 0;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (error) Array 'a[2]' accessed at index -1, which is out of bounds.\n", errout_str());
}
void array_index_for() {
// Ticket #2370 - No false negative when there is no "break"
check("void f() {\n"
" int a[10];\n"
" for (int i = 0; i < 20; ++i) {\n"
" if (i==1) {\n"
" }\n"
" a[i] = 0;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (error) Array 'a[10]' accessed at index 19, which is out of bounds.\n", errout_str());
// Ticket #2385 - No false positive
check("void f() {\n"
" int a[10];\n"
" for (int i = 0; i < 20; ++i) {\n"
" if (i<10) {\n"
" } else {\n"
" a[i-10] = 0;\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// Ticket #3893 - start value out of bounds
// extracttests.start: int maybe(); int dostuff();
check("void f() {\n"
" int a[10];\n"
" for (int i = 10; maybe(); dostuff()) {\n"
" a[i] = 0;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 'a[10]' accessed at index 10, which is out of bounds.\n", errout_str());
// #7686
check("char f() {\n"
" char buf[10];\n"
" const bool a = true, b = true;\n"
" for (int i = 0; i < (a && b ? 11 : 10); ++i)\n"
" buf[i] = 0;\n"
" return buf[0];\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5]: (error) Array 'buf[10]' accessed at index 10, which is out of bounds.\n", errout_str());
check("void f() {\n"
" const int a[10] = {};\n"
" for (int n = 0; 1; ++n) {\n"
" if (a[n] < 1) {\n"
" switch (a[n]) {\n"
" case 0:\n"
" break;\n"
" }\n"
" }\n"
" }\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 'a[10]' accessed at index 9998, which is out of bounds.\n", errout_str());
}
void array_index_for_neq() {
// Ticket #2211 - for loop using != in the condition
check("void f() {\n"
" int a[5];\n"
" for (int i = 0; i != 10; ++i) {\n"
" a[i] = 0;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 'a[5]' accessed at index 9, which is out of bounds.\n",
errout_str());
}
void array_index_for_question() {
// Ticket #2561 - using ?: inside for loop
check("void f() {\n"
" int a[10];\n"
" for (int i = 0; i != 10; ++i) {\n"
" i == 0 ? 0 : a[i-1];\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int a[10];\n"
" for (int i = 0; i != 10; ++i) {\n"
" some_condition ? 0 : a[i-1];\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 'a[10]' accessed at index -1, which is out of bounds.\n",
errout_str());
check("void f() {\n"
" int a[10];\n"
" for (int i = 0; i != 10; ++i) {\n"
" i==0 ? 0 : a[i-1];\n"
" a[i-1] = 0;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Array 'a[10]' accessed at index -1, which is out of bounds.\n", errout_str());
}
void array_index_for_varid0() { // #4228: No varid for counter variable
check("void f() {\n"
" char a[10];\n"
" for (i=0; i<10; i++);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void array_index_vla_for() {
// #3221 - access VLA inside for
check("void f(int len) {\n"
" char a[len];\n"
" for (int i=0; i<7; ++i) {\n"
" a[0] = 0;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void array_index_extern() {
// Ticket #1684. FP when using 'extern'.
check("extern char arr[15];\n"
"char arr[15] = \"abc\";");
ASSERT_EQUALS("", errout_str());
}
void array_index_cast() {
// Ticket #2841. FP when using cast.
// Different types => no error
check("void f1(char *buf) {\n"
" buf[4] = 0;\n"
"}\n"
"void f2() {\n"
" int x[2];\n"
" f1(x);\n"
"}");
ASSERT_EQUALS("", errout_str());
// Same type => error
check("void f1(const char buf[]) {\n"
" char c = buf[4];\n"
"}\n"
"void f2() {\n"
" char x[2];\n"
" f1(x);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:6] -> [test.cpp:2]: (error) Array 'x[2]' accessed at index 4, which is out of bounds.\n",
"",
errout_str());
}
void array_index_string_literal() {
check("void f() {\n"
" const char *str = \"abc\";\n"
" bar(str[10]);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Array 'str[4]' accessed at index 10, which is out of bounds.\n", errout_str());
check("void f()\n"
"{\n"
" const char *str = \"abc\";\n"
" bar(str[4]);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 'str[4]' accessed at index 4, which is out of bounds.\n", errout_str());
check("void f()\n"
"{\n"
" const char *str = \"abc\";\n"
" bar(str[3]);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f()\n"
"{\n"
" const char *str = \"a\tc\";\n"
" bar(str[4]);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 'str[4]' accessed at index 4, which is out of bounds.\n", errout_str());
check("void f() {\n" // #6973
" const char *name = \"\";\n"
" if ( name[0] == 'U' ? name[1] : 0) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int main(int argc, char **argv) {\n"
" char str[6] = \"\\0\";\n"
" unsigned short port = 65535;\n"
" snprintf(str, sizeof(str), \"%hu\", port);\n"
"}", settings0, false);
ASSERT_EQUALS("", errout_str());
check("int f(int x) {\n" // #11020
" const char* p = (x == 0 ? \"12345\" : \"ABC\");\n"
" int s = 0;\n"
" for (int i = 0; p[i]; i++)\n"
" s += p[i];\n"
" return s;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void array_index_same_struct_and_var_name() {
// don't throw internal error
check("struct tt {\n"
" char name[21];\n"
"} ;\n"
"void doswitch(struct tt *x)\n"
"{\n"
" struct tt *tt=x;\n"
" tt->name;\n"
"}");
ASSERT_EQUALS("", errout_str());
// detect error
check("struct tt {\n"
" char name[21];\n"
"} ;\n"
"void doswitch(struct tt *x)\n"
"{\n"
" struct tt *tt=x;\n"
" tt->name[22] = 123;\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (error) Array 'tt->name[21]' accessed at index 22, which is out of bounds.\n", errout_str());
}
void array_index_valueflow() {
check("void f(int i) {\n"
" char str[3];\n"
" str[i] = 0;\n"
" if (i==10) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:3]: (warning) Either the condition 'i==10' is redundant or the array 'str[3]' is accessed at index 10, which is out of bounds.\n", errout_str());
check("void f(int i) {\n"
" char str[3];\n"
" str[i] = 0;\n"
" switch (i) {\n"
" case 10: break;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:3]: (warning) Either the switch case 'case 10' is redundant or the array 'str[3]' is accessed at index 10, which is out of bounds.\n", errout_str());
check("void f() {\n"
" char str[3];\n"
" str[((unsigned char)3) - 1] = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n" // #5416 FP
" char *str[3];\n"
" do_something(&str[0][5]);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("class X { static const int x[100]; };\n" // #6070
"const int X::x[100] = {0};");
ASSERT_EQUALS("", errout_str());
check("namespace { class X { static const int x[100]; };\n" // #6232
"const int X::x[100] = {0}; }");
ASSERT_EQUALS("", errout_str());
check("class ActorSprite { static ImageSet * targetCursorImages[2][10]; };\n"
"ImageSet *ActorSprite::targetCursorImages[2][10];");
ASSERT_EQUALS("", errout_str());
check("int f(const std::size_t s) {\n" // #10130
" const char a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };\n"
" return (s > sizeof(a)) ? 11 : (int)a[s];\n"
"}\n"
"int g() {\n"
" return f(16);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:3]: (warning) Either the condition 's>sizeof(a)' is redundant or the array 'a[16]' is accessed at index 16, which is out of bounds.\n",
errout_str());
check("void f(int fd) {\n" // #12318
" char buf[10];\n"
" int size = 0;\n"
" int pos = -1;\n"
" do {\n"
" pos++;\n"
" size = read(fd, &buf[pos], 1);\n"
" } while (size > 0);\n"
" buf[pos] = '\\0';\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void array_index_valueflow_pointer() {
check("void f() {\n"
" int a[10];\n"
" int *p = a;\n"
" p[20] = 0;\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (error) Array 'a[10]' accessed at index 20, which is out of bounds.\n", "", errout_str());
{
// address of
check("void f() {\n"
" int a[10];\n"
" int *p = a;\n"
" p[10] = 0;\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (error) Array 'a[10]' accessed at index 10, which is out of bounds.\n", "", errout_str());
check("void f() {\n"
" int a[10];\n"
" int *p = a;\n"
" dostuff(&p[10]);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
check("void f() {\n"
" int a[X];\n" // unknown size
" int *p = a;\n"
" p[20] = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int a[2];\n"
" char *p = (char *)a;\n" // cast
" p[4] = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void array_index_function_parameter() {
check("void f(char a[10]) {\n"
" a[20] = 0;\n" // <- cppcheck warn here even though it's not a definite access out of bounds
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Array 'a[10]' accessed at index 20, which is out of bounds.\n", errout_str());
check("void f(char a[10]) {\n" // #6353 - reassign 'a'
" a += 4;\n"
" a[-1] = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(char a[10]) {\n"
" a[0] = 0;\n"
" a[-1] = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Array 'a[10]' accessed at index -1, which is out of bounds.\n", errout_str());
}
void array_index_enum_array() { // #8439
check("enum E : unsigned int { e1, e2 };\n"
"void f() {\n"
" E arrE[] = { e1, e2 };\n"
" arrE[sizeof(arrE)] = e1;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 'arrE[2]' accessed at index 8, which is out of bounds.\n", errout_str());
}
void array_index_container() { // #9386
check("constexpr int blockLen = 10;\n"
"void foo(std::array<uint8_t, blockLen * 2>& a) {\n"
" a[2] = 2;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void array_index_two_for_loops() {
check("bool b();\n"
"void f()\n"
"{\n"
" int val[50];\n"
" int i, sum=0;\n"
" for (i = 1; b() && i < 50; i++)\n"
" sum += val[i];\n"
" if (i < 50)\n"
" sum -= val[i];\n"
"}");
ASSERT_EQUALS("", errout_str());
check("bool b();\n"
"void f()\n"
"{\n"
" int val[50];\n"
" int i, sum=0;\n"
" for (i = 1; b() && i < 50; i++)\n"
" sum += val[i];\n"
" for (; i < 50;) {\n"
" sum -= val[i];\n"
" break;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("bool b();\n"
"void f()\n"
"{\n"
" int val[50];\n"
" int i, sum=0;\n"
" for (i = 1; b() && i < 50; i++)\n"
" sum += val[i];\n"
" for (; i < 50; i++)\n"
" sum -= val[i];\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void array_index_new() { // #7690
check("void f() {\n"
" int* z = new int;\n"
" for (int n = 0; n < 8; ++n)\n"
" z[n] = 0;\n"
" delete[] z;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 'z[1]' accessed at index 7, which is out of bounds.\n", errout_str());
check("void f() {\n"
" int* z = new int(1);\n"
" for (int n = 0; n < 8; ++n)\n"
" z[n] = 0;\n"
" delete[] z;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 'z[1]' accessed at index 7, which is out of bounds.\n", errout_str());
check("void f() {\n"
" int* z = new int{};\n"
" for (int n = 0; n < 8; ++n)\n"
" z[n] = 0;\n"
" delete[] z;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 'z[1]' accessed at index 7, which is out of bounds.\n", errout_str());
check("void f() {\n"
" int* z = new int[5];\n"
" for (int n = 0; n < 8; ++n)\n"
" z[n] = 0;\n"
" delete[] z;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 'z[5]' accessed at index 7, which is out of bounds.\n", errout_str());
check("void g() {\n"
" int* z = new int[5]();\n"
" for (int n = 0; n < 8; ++n)\n"
" z[n] = 1;\n"
" delete[] z;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 'z[5]' accessed at index 7, which is out of bounds.\n", errout_str());
check("void h() {\n"
" int** z = new int* [5];\n"
" for (int n = 0; n < 8; ++n)\n"
" z[n] = nullptr;\n"
" delete[] z;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 'z[5]' accessed at index 7, which is out of bounds.\n", errout_str());
check("void h() {\n"
" int** z = new int* [5]();\n"
" for (int n = 0; n < 8; ++n)\n"
" z[n] = nullptr;\n"
" delete[] z;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 'z[5]' accessed at index 7, which is out of bounds.\n", errout_str());
check("void h() {\n"
" int** z = new int* [5]{};\n"
" for (int n = 0; n < 8; ++n)\n"
" z[n] = nullptr;\n"
" delete[] z;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 'z[5]' accessed at index 7, which is out of bounds.\n", errout_str());
check("void h() {\n"
" int** z = new int* [5]{ 0 };\n"
" for (int n = 0; n < 8; ++n)\n"
" z[n] = nullptr;\n"
" delete[] z;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 'z[5]' accessed at index 7, which is out of bounds.\n", errout_str());
}
void buffer_overrun_2_struct() {
check("struct ABC\n"
"{\n"
" char str[5];\n"
"};\n"
"\n"
"static void f(struct ABC *abc)\n"
"{\n"
" strcpy( abc->str, \"abcdef\" );\n"
"}");
ASSERT_EQUALS("[test.cpp:8]: (error) Buffer is accessed out of bounds: abc->str\n", errout_str());
check("struct ABC\n"
"{\n"
" char str[5];\n"
"};\n"
"\n"
"static void f()\n"
"{\n"
" struct ABC abc;\n"
" strcpy( abc.str, \"abcdef\" );\n"
"}");
ASSERT_EQUALS("[test.cpp:9]: (error) Buffer is accessed out of bounds: abc.str\n", errout_str());
check("struct ABC\n"
"{\n"
" char str[5];\n"
"};\n"
"\n"
"static void f(struct ABC &abc)\n"
"{\n"
" strcpy( abc.str, \"abcdef\" );\n"
"}");
ASSERT_EQUALS("[test.cpp:8]: (error) Buffer is accessed out of bounds: abc.str\n", errout_str());
check("static void f()\n"
"{\n"
" struct ABC\n"
" {\n"
" char str[5];\n"
" } abc;\n"
" strcpy( abc.str, \"abcdef\" );\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (error) Buffer is accessed out of bounds: abc.str\n", errout_str());
check("static void f()\n"
"{\n"
" struct ABC\n"
" {\n"
" char str[5];\n"
" };\n"
" struct ABC *abc = malloc(sizeof(struct ABC));\n"
" strcpy( abc->str, \"abcdef\" );\n"
" free(abc);\n"
"}");
ASSERT_EQUALS("[test.cpp:8]: (error) Buffer is accessed out of bounds: abc->str\n", errout_str());
}
void buffer_overrun_3() {
check("int a[10];\n"
"\n"
"void foo()\n"
"{\n"
" int i;\n"
" for (i = 0; i <= 10; ++i)\n"
" a[i] = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (error) Array 'a[10]' accessed at index 10, which is out of bounds.\n", errout_str());
check("struct S { int b; } static e[1];\n" // #11052
"int f() { return e[1].b; }\n");
ASSERT_EQUALS("[test.cpp:2]: (error) Array 'e[1]' accessed at index 1, which is out of bounds.\n", errout_str());
}
void buffer_overrun_4() {
check("void foo()\n"
"{\n"
" const char *p[2];\n"
" for (int i = 0; i < 8; ++i)\n"
" p[i] = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Array 'p[2]' accessed at index 7, which is out of bounds.\n", errout_str());
// No false positive
check("void foo(int x, int y)\n"
"{\n"
" const char *p[2];\n"
" const char *s = y + p[1];\n"
" p[1] = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
// There is no error here
check("void f1(char *s,int size)\n"
"{\n"
" if( size > 10 ) strcpy(s,\"abc\");\n"
"}\n"
"void f2()\n"
"{\n"
" char s[3];\n"
" f1(s,20);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:8] -> [test.cpp:3]: (error) Buffer is accessed out of bounds.\n", "", errout_str());
check("void f1(char *s,int size)\n"
"{\n"
" if( size > 10 ) strcpy(s,\"abc\");\n"
"}\n"
"void f2()\n"
"{\n"
" char s[3];\n"
" f1(s,3);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void buffer_overrun_5() {
check("void f()\n"
"{\n"
" char n[5];\n"
" sprintf(n, \"d\");\n"
" printf(\"hello!\");\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void buffer_overrun_6() {
check("void f()\n"
"{\n"
" char n[5];\n"
" strcat(n, \"abc\");\n"
" strcat(n, \"def\");\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:5]: (error) Buffer is accessed out of bounds: n\n", "", errout_str());
}
void buffer_overrun_7() {
// ticket #731
check("void f()\n"
"{\n"
" char a[2];\n"
" strcpy(a, \"a\\0\");\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void buffer_overrun_8() {
// ticket #714
check("void f()\n"
"{\n"
" char a[5];\n"
" for (int i = 0; i < 20; i = i + 100)\n"
" {\n"
" a[i] = 0;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f()\n"
"{\n"
" char a[5];\n"
" for (int i = 0; i < 20; i = 100 + i)\n"
" {\n"
" a[i] = 0;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void buffer_overrun_9() {
// ticket #738
check("void f()\n"
"{\n"
" char a[5];\n"
" for (int i = 0; i < 20; )\n"
" {\n"
" a[i] = 0;\n"
" i += 100;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void buffer_overrun_10() {
// ticket #740
check("void f()\n"
"{\n"
" char a[4];\n"
" for (int i = 0; i < 4; i++)\n"
" {\n"
" char b = a[i];\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void buffer_overrun_11() {
check("void f()\n"
"{\n"
" char a[4];\n"
" for (float i=0; i<10.0;i=i+0.1)\n"
" {\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f()\n"
"{\n"
" char a[4];\n"
" for (float i=0; i<10.0;i=0.1+i)\n"
" {\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void buffer_overrun_15() { // ticket #1787
check("class A : public B {\n"
" char val[2];\n"
" void f(int i, int ii);\n"
"};\n"
"void A::f(int i, int ii)\n"
"{\n"
" strcpy(val, \"ab\") ;\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (error) Buffer is accessed out of bounds: val\n", errout_str());
}
void buffer_overrun_16() {
// unknown types
check("void f() {\n"
" struct Foo foo[5];\n"
" memset(foo, 0, sizeof(foo));\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n" // ticket #2093
" gchar x[3];\n"
" strcpy(x, \"12\");\n"
"}");
ASSERT_EQUALS("", errout_str());
check("extern char a[10];\n"
"void f() {\n"
" char b[25] = {0};\n"
" std::memcpy(b, a, 10);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void buffer_overrun_18() { // ticket #2576
check("class A {\n"
" void foo();\n"
" bool b[7];\n"
"};\n"
"\n"
"void A::foo() {\n"
" for (int i=0; i<6; i++) {\n"
" b[i] = b[i+1];\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("class A {\n"
" void foo();\n"
" bool b[7];\n"
"};\n"
"\n"
"void A::foo() {\n"
" for (int i=0; i<7; i++) {\n"
" b[i] = b[i+1];\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:8]: (error) Array 'b[7]' accessed at index 7, which is out of bounds.\n", errout_str());
}
void buffer_overrun_19() { // #2597 - class member with unknown type
check("class A {\n"
"public:\n"
" u8 buf[10];\n"
" A();"
"};\n"
"\n"
"A::A() {\n"
" memset(buf, 0, 10);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void buffer_overrun_21() {
check("void foo()\n"
"{ { {\n"
" char dst[4];\n"
" const char *src = \"AAAAAAAAAAAAAAAAAAAAA\";\n"
" for (size_t i = 0; i <= 4; i++)\n"
" dst[i] = src[i];\n"
"} } }");
ASSERT_EQUALS("[test.cpp:6]: (error) Array 'dst[4]' accessed at index 4, which is out of bounds.\n", errout_str());
}
void buffer_overrun_24() { // index variable is changed in for-loop
// ticket #4106
check("void main() {\n"
" int array[] = {1,2};\n"
" int x = 0;\n"
" for( int i = 0; i<6; ) {\n"
" x += array[i];\n"
" i++; }\n"
"}");
TODO_ASSERT_EQUALS("error", "", errout_str());
// ticket #4096
check("void main() {\n"
" int array[] = {1,2};\n"
" int x = 0;\n"
" for( int i = 0; i<6; ) {\n"
" x += array[i++];\n"
" }\n"
"}");
TODO_ASSERT_EQUALS("error", "", errout_str());
}
void buffer_overrun_26() { // ticket #4432 (segmentation fault)
check("extern int split();\n"
"void regress() {\n"
" char inbuf[1000];\n"
" char *f[10];\n"
" split(inbuf, f, 10, \"\t\t\");\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void buffer_overrun_27() { // ticket #4444 (segmentation fault)
check("void abc(struct foobar[5]);\n"
"void main() {\n"
"struct foobar x[5];\n"
"abc(x);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
// #7083: false positive: typedef and initialization with strings
void buffer_overrun_29() {
check("typedef char testChar[10];\n"
"int main(){\n"
" testChar tc1 = \"\";\n"
" tc1[5]='a';\n"
"}");
ASSERT_EQUALS("", errout_str());
}
// #6367
void buffer_overrun_30() {
check("struct S { int m[9]; };\n"
"int f(S * s) {\n"
" return s->m[sizeof(s->m)];\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Array 's->m[9]' accessed at index 36, which is out of bounds.\n", errout_str());
}
void buffer_overrun_31() {
check("void f(WhereInfo *pWInfo, int *aiCur) {\n"
" memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void buffer_overrun_32() {
// destination size is too small
check("void f(void) {\n"
" const char src[3] = \"abc\";\n"
" char dest[1] = \"a\";\n"
" (void)strxfrm(dest,src,1);\n"
" (void)strxfrm(dest,src,2);\n"// <<
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Buffer is accessed out of bounds: dest\n", errout_str());
// destination size is too small
check("void f(void) {\n"
" const char src[3] = \"abc\";\n"
" char dest[2] = \"ab\";\n"
" (void)strxfrm(dest,src,1);\n"
" (void)strxfrm(dest,src,2);\n"
" (void)strxfrm(dest,src,3);\n" // <<
"}");
ASSERT_EQUALS("[test.cpp:6]: (error) Buffer is accessed out of bounds: dest\n", errout_str());
// source size is too small
check("void f(void) {\n"
" const char src[2] = \"ab\";\n"
" char dest[3] = \"abc\";\n"
" (void)strxfrm(dest,src,1);\n"
" (void)strxfrm(dest,src,2);\n"
" (void)strxfrm(dest,src,3);\n" // <<
"}");
ASSERT_EQUALS("[test.cpp:6]: (error) Buffer is accessed out of bounds: src\n", errout_str());
// source size is too small
check("void f(void) {\n"
" const char src[1] = \"a\";\n"
" char dest[3] = \"abc\";\n"
" (void)strxfrm(dest,src,1);\n"
" (void)strxfrm(dest,src,2);\n" // <<
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Buffer is accessed out of bounds: src\n", errout_str());
}
void buffer_overrun_33() { // #2019
check("int f() {\n"
" int z[16];\n"
" for (int i=0; i<20; i++)\n"
" for (int j=0; j<20; j++)\n"
" z[i] = 0;\n"
" return z[0];\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Array 'z[16]' accessed at index 19, which is out of bounds.\n", errout_str());
}
void buffer_overrun_34() { // #11035
check("struct S {\n"
" std::vector<int> v;\n"
" int a[15] = {};\n"
" int g() const { return v.size(); }\n"
" int f(int i) const {\n"
" if (i < 0 || i >= g())\n"
" return 0;\n"
" return a[i];\n"
" }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
}
void buffer_overrun_35() { // #2304
check("void f() {\n"
" char* q = \"0123456789\";\n"
" char* p = (char*)malloc(sizeof(q) + 1);\n"
" strcpy(p, q);\n"
" free(p);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (error) Buffer is accessed out of bounds: p\n", errout_str());
check("void f() {\n"
" char* q = \"0123456789\";\n"
" char* p = (char*)malloc(1);\n"
" strcpy(p, q);\n"
" free(p);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (error) Buffer is accessed out of bounds: p\n", errout_str());
check("typedef struct { char buf[1]; } S;\n"
"S* f() {\n"
" S* s = NULL;\n"
" s = (S*)malloc(sizeof(S) + 10);\n"
" sprintf((char*)s->buf, \"abc\");\n"
" return s;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void buffer_overrun_36() { // #11708
check("void f(double d) {\n"
" char a[80];\n"
" sprintf(a, \"%2.1f\", d);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void buffer_overrun_errorpath() {
setMultiline();
const Settings settingsOld = settings0;
settings0.templateLocation = "{file}:{line}:note:{info}";
check("void f() {\n"
" char *p = malloc(10);\n"
" memset(p, 0, 20);\n"
"}");
ASSERT_EQUALS("test.cpp:3:error:Buffer is accessed out of bounds: p\n"
"test.cpp:2:note:Assign p, buffer with size 10\n"
"test.cpp:3:note:Buffer overrun\n", errout_str());
settings0 = settingsOld;
}
void buffer_overrun_bailoutIfSwitch() {
// No false positive
check("void f1(char *s) {\n"
" if (x) s[100] = 0;\n"
"}\n"
"\n"
"void f2() {\n"
" char a[10];\n"
" f1(a);"
"}");
ASSERT_EQUALS("", errout_str());
// No false positive
check("void f1(char *s) {\n"
" if (x) return;\n"
" s[100] = 0;\n"
"}\n"
"\n"
"void f2() {\n"
" char a[10];\n"
" f1(a);"
"}");
ASSERT_EQUALS("", errout_str());
// No false negative
check("void f1(char *s) {\n"
" if (x) { }\n"
" s[100] = 0;\n"
"}\n"
"\n"
"void f2() {\n"
" char a[10];\n"
" f1(a);"
"}");
TODO_ASSERT_EQUALS("[test.cpp:8] -> [test.cpp:3]: (error) Array 'a[10]' accessed at index 100, which is out of bounds.\n", "", errout_str());
}
void buffer_overrun_function_array_argument() {
setMultiline();
check("void f(char a[10]);\n"
"void g() {\n"
" char a[2];\n"
" f(a);\n"
"}");
ASSERT_EQUALS("test.cpp:4:warning:Buffer 'a' is too small, the function 'f' expects a bigger buffer in 1st argument\n"
"test.cpp:4:note:Function 'f' is called\n"
"test.cpp:1:note:Declaration of 1st function argument.\n"
"test.cpp:3:note:Passing buffer 'a' to function that is declared here\n"
"test.cpp:4:note:Buffer 'a' is too small, the function 'f' expects a bigger buffer in 1st argument\n", errout_str());
check("void f(float a[10][3]);\n"
"void g() {\n"
" float a[2][3];\n"
" f(a);\n"
"}");
ASSERT_EQUALS("test.cpp:4:warning:Buffer 'a' is too small, the function 'f' expects a bigger buffer in 1st argument\n"
"test.cpp:4:note:Function 'f' is called\n"
"test.cpp:1:note:Declaration of 1st function argument.\n"
"test.cpp:3:note:Passing buffer 'a' to function that is declared here\n"
"test.cpp:4:note:Buffer 'a' is too small, the function 'f' expects a bigger buffer in 1st argument\n", errout_str());
check("void f(int a[20]);\n"
"void g() {\n"
" int a[2];\n"
" f(a);\n"
"}");
ASSERT_EQUALS("test.cpp:4:warning:Buffer 'a' is too small, the function 'f' expects a bigger buffer in 1st argument\n"
"test.cpp:4:note:Function 'f' is called\n"
"test.cpp:1:note:Declaration of 1st function argument.\n"
"test.cpp:3:note:Passing buffer 'a' to function that is declared here\n"
"test.cpp:4:note:Buffer 'a' is too small, the function 'f' expects a bigger buffer in 1st argument\n", errout_str());
check("void f(int a[]) {\n"
" switch (2) {\n"
" case 1:\n"
" a[1] = 1;\n"
" }\n"
"}\n"
"int a[1];\n"
"f(a);\n"
"");
ASSERT_EQUALS("", errout_str());
check("void CreateLeafTex(unsigned char buf[256][2048][4]);\n"
"void foo() {\n"
" unsigned char(* tree)[2048][4] = new unsigned char[256][2048][4];\n"
" CreateLeafTex(tree);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int a[10]) {\n" // #10069
" int i = 0;\n"
" for (i = 0; i < 10; i++)\n"
" a[i] = i * 2;\n"
"}\n"
"void g() {\n"
" int b[5];\n"
" f(b);\n"
" return 0;\n"
"}\n");
ASSERT_EQUALS("test.cpp:8:warning:Buffer 'b' is too small, the function 'f' expects a bigger buffer in 1st argument\n"
"test.cpp:8:note:Function 'f' is called\n"
"test.cpp:1:note:Declaration of 1st function argument.\n"
"test.cpp:7:note:Passing buffer 'b' to function that is declared here\n"
"test.cpp:8:note:Buffer 'b' is too small, the function 'f' expects a bigger buffer in 1st argument\n",
errout_str());
}
void possible_buffer_overrun_1() { // #3035
check("void foo() {\n"
" char * data = (char *)alloca(50);\n"
" char src[100];\n"
" memset(src, 'C', 99);\n"
" src[99] = '\\0';\n"
" strcat(data, src);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:6]: (warning) Possible buffer overflow if strlen(src) is larger than sizeof(data)-strlen(data).\n", "", errout_str());
check("void foo() {\n"
" char * data = (char *)alloca(100);\n"
" char src[100];\n"
" memset(src, 'C', 99);\n"
" src[99] = '\\0';\n"
" strcat(data, src);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(char src[100]) {\n"
" char * data = (char *)alloca(50);\n"
" strcat(data, src);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:3]: (warning) Possible buffer overflow if strlen(src) is larger than sizeof(data)-strlen(data).\n", "", errout_str());
check("void foo(char src[100]) {\n"
" char * data = (char *)alloca(100);\n"
" strcat(data, src);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" char * data = (char *)alloca(50);\n"
" char src[100];\n"
" memset(src, 'C', 99);\n"
" src[99] = '\\0';\n"
" strcpy(data, src);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:6]: (warning) Possible buffer overflow if strlen(src) is larger than or equal to sizeof(data).\n", "", errout_str());
check("void foo() {\n"
" char * data = (char *)alloca(100);\n"
" char src[100];\n"
" memset(src, 'C', 99);\n"
" src[99] = '\\0';\n"
" strcpy(data, src);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(char src[100]) {\n"
" char * data = (char *)alloca(50);\n"
" strcpy(data, src);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:3]: (warning) Possible buffer overflow if strlen(src) is larger than or equal to sizeof(data).\n", "", errout_str());
check("void foo(char src[100]) {\n"
" char * data = (char *)alloca(100);\n"
" strcpy(data, src);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void buffer_overrun_readSizeFromCfg() {
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <podtype name=\"u8\" sign=\"u\" size=\"1\"/>\n"
" <function name=\"mystrcpy\">\n"
" <noreturn>false</noreturn>\n"
" <arg nr=\"1\">\n"
" <minsize type=\"strlen\" arg=\"2\"/>\n"
" </arg>\n"
" <arg nr=\"2\"/>\n"
" </function>\n"
"</def>";
const Settings settings = settingsBuilder().libraryxml(xmldata, sizeof(xmldata)).build();
// Attempt to get size from Cfg files, no false positives if size is not specified
check("void f() {\n"
" u8 str[256];\n"
" mystrcpy(str, \"abcd\");\n"
"}", settings);
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" u8 str[2];\n"
" mystrcpy(str, \"abcd\");\n"
"}", settings);
ASSERT_EQUALS("[test.cpp:3]: (error) Buffer is accessed out of bounds: str\n", errout_str());
// The same for structs, where the message comes from a different check
check("void f() {\n"
" struct { u8 str[256]; } ms;\n"
" mystrcpy(ms.str, \"abcd\");\n"
"}", settings);
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" struct { u8 str[2]; } ms;\n"
" mystrcpy(ms.str, \"abcd\");\n"
"}", settings);
ASSERT_EQUALS("[test.cpp:3]: (error) Buffer is accessed out of bounds: ms.str\n", errout_str());
}
void valueflow_string() { // using ValueFlow string values in checking
check("char f() {\n"
" const char *x = s;\n"
" if (cond) x = \"abcde\";\n"
" return x[20];\n" // <- array index out of bounds when x is "abcde"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 'x[6]' accessed at index 20, which is out of bounds.\n", errout_str());
}
void pointer_out_of_bounds_1() {
// extracttests.start: void dostuff(char *);
check("void f() {\n"
" char a[10];\n"
" char *p = a + 100;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (portability) Undefined behaviour, pointer arithmetic 'a+100' is out of bounds.\n", errout_str());
check("char *f() {\n"
" char a[10];\n"
" return a + 100;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (portability) Undefined behaviour, pointer arithmetic 'a+100' is out of bounds.\n", errout_str());
check("void f(int i) {\n"
" char x[10];\n"
" if (i == 123) {}\n"
" dostuff(x+i);\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (portability) Undefined behaviour, when 'i' is 123 the pointer arithmetic 'x+i' is out of bounds.\n", errout_str());
check("void f(int i) {\n"
" char x[10];\n"
" if (i == -1) {}\n"
" dostuff(x+i);\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (portability) Undefined behaviour, when 'i' is -1 the pointer arithmetic 'x+i' is out of bounds.\n", errout_str());
check("void f() {\n" // #6350 - fp when there is cast of buffer
" wchar_t buf[64];\n"
" p = (unsigned char *) buf + sizeof (buf);\n"
"}", false);
ASSERT_EQUALS("", errout_str());
check("int f() {\n"
" const char d[] = \"0123456789\";\n"
" char *cp = d + 3;\n"
" return cp - d;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void pointer_out_of_bounds_2() {
check("void f() {\n"
" char *p = malloc(10);\n"
" p += 100;\n"
" free(p);"
"}");
TODO_ASSERT_EQUALS("[test.cpp:3]: (portability) Undefined behaviour, pointer arithmetic 'p+100' is out of bounds.\n", "", errout_str());
check("void f() {\n"
" char *p = malloc(10);\n"
" p += 10;\n"
" *p = 0;\n"
" free(p);"
"}");
TODO_ASSERT_EQUALS("[test.cpp:4]: (error) p is out of bounds.\n", "", errout_str());
check("void f() {\n"
" char *p = malloc(10);\n"
" p += 10;\n"
" p -= 10;\n"
" *p = 0;\n"
" free(p);"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" char *p = malloc(10);\n"
" p += 10;\n"
" p = p - 1;\n"
" *p = 0;\n"
" free(p);"
"}");
ASSERT_EQUALS("", errout_str());
}
void pointer_out_of_bounds_3() {
check("struct S { int a[10]; };\n"
"void f(struct S *s) {\n"
" int *p = s->a + 100;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (portability) Undefined behaviour, pointer arithmetic 's->a+100' is out of bounds.\n", errout_str());
check("template <class T> class Vector\n"
"{\n"
"public:\n"
" void test() const;\n"
" T* data();\n"
"};\n"
"template <class T>\n"
"void Vector<T>::test() const\n"
"{\n"
" const T* PDat = data();\n"
" const T* P2 = PDat + 1;\n"
" const T* P1 = P2 - 1;\n"
"}\n"
"Vector<std::array<long, 2>> Foo;\n");
ASSERT_EQUALS("", errout_str());
}
void pointer_out_of_bounds_4() {
check("const char* f() {\n"
" g(\"Hello\" + 6);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("const char* f() {\n"
" g(\"Hello\" + 7);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (portability) Undefined behaviour, pointer arithmetic '\"Hello\"+7' is out of bounds.\n", errout_str());
check("const char16_t* f() {\n"
" g(u\"Hello\" + 6);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("const char16_t* f() {\n"
" g(u\"Hello\" + 7);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (portability) Undefined behaviour, pointer arithmetic 'u\"Hello\"+7' is out of bounds.\n", errout_str());
check("void f() {\n" // #4647
" int val = 5;\n"
" std::string hi = \"hi\" + val;\n"
" std::cout << hi << std::endl;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (portability) Undefined behaviour, pointer arithmetic '\"hi\"+val' is out of bounds.\n", errout_str());
check("void f(const char* s, int len) {\n" // #11026
" const char* end = s + len;\n"
" printf(\"%s, %d\\n\", s, *end);\n"
"}\n"
"void g() {\n"
" f(\"a\", 1);\n"
" f(\"bbb\", 3);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(int i, const char* a) {\n" // #11140
" (void)a[i];\n"
"}\n"
"void g() {\n"
" for (int i = 0; \"01234\"[i]; ++i)\n"
" f(i, \"56789\");\n"
"}\n"
"void h() {\n"
" for (int i = 0; \"012\"[i]; ++i)\n"
" f(i, \"345\");\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void pointer_out_of_bounds_5() { // #10227
check("int foo(char str[6]) {\n"
" return !((0 && *(\"STRING\" + 14) == 0) || memcmp(str, \"STRING\", 6) == 0);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void pointer_out_of_bounds_sub() {
// extracttests.start: void dostuff(char *);
check("char *f() {\n"
" char x[10];\n"
" return x-1;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (portability) Undefined behaviour, pointer arithmetic 'x-1' is out of bounds.\n", errout_str());
check("void f(int i) {\n"
" char x[10];\n"
" if (i == 123) {}\n"
" dostuff(x-i);\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (portability) Undefined behaviour, when 'i' is 123 the pointer arithmetic 'x-i' is out of bounds.\n", errout_str());
check("void f(int i) {\n"
" char x[10];\n"
" if (i == -20) {}\n"
" dostuff(x-i);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:4]: (portability) Undefined behaviour, when 'i' is -20 the pointer arithmetic 'x-i' is out of bounds.\n", "", errout_str());
check("void f(const char *x[10]) {\n"
" return x-4;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void strcat1() {
check("struct Foo { char a[4]; };\n"
"void f() {\n"
" struct Foo x = {0};\n"
" strcat(x.a, \"aa\");\n"
" strcat(x.a, \"aa\");\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:5]: (error) Buffer is accessed out of bounds.\n", "", errout_str());
}
void varid1() {
check("void foo()\n"
"{\n"
" char str[10];\n"
" if (str[0])\n"
" {\n"
" char str[50];\n"
" str[30] = 0;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void varid2() { // #4764
check("struct foo {\n"
" void bar() { return; }\n"
" type<> member[1];\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void assign1() {
check("char str[3] = {'a', 'b', 'c'};\n"
"\n"
"void foo()\n"
"{\n"
" str[3] = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Array 'str[3]' accessed at index 3, which is out of bounds.\n", errout_str());
}
void alloc_new() {
check("void foo()\n"
"{\n"
" char *s; s = new char[10];\n"
" s[10] = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 's[10]' accessed at index 10, which is out of bounds.\n", errout_str());
// ticket #1670 - false negative when using return
check("char f()\n"
"{\n"
" int *s; s = new int[10];\n"
" return s[10];\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 's[10]' accessed at index 10, which is out of bounds.\n", errout_str());
check("struct Fred { char c[10]; };\n"
"char f()\n"
"{\n"
" Fred *f; f = new Fred;\n"
" return f->c[10];\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Array 'f->c[10]' accessed at index 10, which is out of bounds.\n", errout_str());
check("static const size_t MAX_SIZE = UNAVAILABLE_TO_CPPCHECK;\n"
"struct Thing { char data[MAX_SIZE]; };\n"
"char f4(const Thing& t) { return !t.data[0]; }");
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" char * buf; buf = new char[8];\n"
" buf[7] = 0;\n"
" delete [] buf;\n"
" buf = new char[9];\n"
" buf[8] = 0;\n"
" delete [] buf;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" char * buf; buf = new char[8];\n"
" buf[7] = 0;\n"
" delete [] buf;\n"
" buf = new char[9];\n"
" buf[9] = 0;\n"
" delete [] buf;\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (error) Array 'buf[9]' accessed at index 9, which is out of bounds.\n", errout_str());
check("void foo()\n"
"{\n"
" enum E { Size = 10 };\n"
" char *s; s = new char[Size];\n"
" s[Size] = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Array 's[10]' accessed at index 10, which is out of bounds.\n", errout_str());
check("void foo()\n"
"{\n"
" enum E { ZERO };\n"
" E *e; e = new E[10];\n"
" e[10] = ZERO;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Array 'e[10]' accessed at index 10, which is out of bounds.\n", errout_str());
}
// data is allocated with malloc
void alloc_malloc() {
check("void foo()\n"
"{\n"
" char *s; s = (char *)malloc(10);\n"
" s[10] = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 's[10]' accessed at index 10, which is out of bounds.\n", errout_str());
// ticket #842
check("void f() {\n"
" int *tab4 = (int *)malloc(20 * sizeof(int));\n"
" tab4[20] = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Array 'tab4[20]' accessed at index 20, which is out of bounds.\n", errout_str());
// ticket #1478
check("void foo() {\n"
" char *p = (char *)malloc(10);\n"
" free(p);\n"
" p = (char *)malloc(10);\n"
" p[10] = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Array 'p[10]' accessed at index 10, which is out of bounds.\n", errout_str());
// ticket #1134
check("void f() {\n"
" int *x, i;\n"
" x = (int *)malloc(10 * sizeof(int));\n"
" x[10] = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 'x[10]' accessed at index 10, which is out of bounds.\n", errout_str());
check("void f() {\n"
" int *tab4; tab4 = malloc(20 * sizeof(int));\n"
" tab4[19] = 0;\n"
" free(tab4);\n"
" tab4 = malloc(21 * sizeof(int));\n"
" tab4[20] = 0;\n"
" free(tab4);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int *tab4 = malloc(20 * sizeof(int));\n"
" tab4[19] = 0;\n"
" tab4 = realloc(tab4,21 * sizeof(int));\n"
" tab4[20] = 0;\n"
" free(tab4);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" enum E { Size = 20 };\n"
" E *tab4 = (E *)malloc(Size * 4);\n"
" tab4[Size] = Size;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 'tab4[20]' accessed at index 20, which is out of bounds.\n", errout_str());
check("void f() {\n"
" enum E { Size = 20 };\n"
" E *tab4 = (E *)malloc(4 * Size);\n"
" tab4[Size] = Size;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 'tab4[20]' accessed at index 20, which is out of bounds.\n", errout_str());
check("void f() {\n"
" enum E { ZERO };\n"
" E *tab4 = (E *)malloc(20 * sizeof(E));\n"
" tab4[20] = ZERO;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 'tab4[20]' accessed at index 20, which is out of bounds.\n", errout_str());
check("void f() {\n" // #8721
" unsigned char **cache = malloc(32);\n"
" cache[i] = malloc(65536);\n"
" cache[i][0xFFFF] = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int **a = malloc(2 * sizeof(int*));\n"
" for (int i = 0; i < 3; i++)\n"
" a[i] = NULL;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 'a[2]' accessed at index 2, which is out of bounds.\n", errout_str());
check("void f() {\n"
" int **a = new int*[2];\n"
" for (int i = 0; i < 3; i++)\n"
" a[i] = NULL;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 'a[2]' accessed at index 2, which is out of bounds.\n", errout_str());
}
// statically allocated buffer
void alloc_string() {
check("void foo()\n"
"{\n"
" const char *s = \"123\";\n"
" s[10] = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 's[4]' accessed at index 10, which is out of bounds.\n", errout_str());
check("void foo()\n"
"{\n"
" char *s; s = \"\";\n"
" s[10] = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 's[1]' accessed at index 10, which is out of bounds.\n", errout_str());
check("void foo() {\n"
" const char *s = \"\";\n"
" s = y();\n"
" s[10] = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo()\n" // #7718
"{\n"
" std::string s = \"123\";\n"
" s.resize(100);\n"
" s[10] = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
// data is allocated with alloca
void alloc_alloca() {
check("void foo()\n"
"{\n"
" char *s = (char *)alloca(10);\n"
" s[10] = 0;\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:4]: (error) Array 's[10]' accessed at index 10, which is out of bounds.\n", "", errout_str());
}
/*
void countSprintfLength() const {
std::list<const Token*> unknownParameter(1, nullptr);
ASSERT_EQUALS(6, CheckBufferOverrun::countSprintfLength("Hello", unknownParameter));
ASSERT_EQUALS(2, CheckBufferOverrun::countSprintfLength("s", unknownParameter));
ASSERT_EQUALS(2, CheckBufferOverrun::countSprintfLength("i", unknownParameter));
ASSERT_EQUALS(2, CheckBufferOverrun::countSprintfLength("%d", unknownParameter));
ASSERT_EQUALS(2, CheckBufferOverrun::countSprintfLength("%1d", unknownParameter));
ASSERT_EQUALS(3, CheckBufferOverrun::countSprintfLength("%2.2d", unknownParameter));
ASSERT_EQUALS(1, CheckBufferOverrun::countSprintfLength("%s", unknownParameter));
ASSERT_EQUALS(2, CheckBufferOverrun::countSprintfLength("f%s", unknownParameter));
ASSERT_EQUALS(1, CheckBufferOverrun::countSprintfLength("%-s", unknownParameter));
ASSERT_EQUALS(6, CheckBufferOverrun::countSprintfLength("%-5s", unknownParameter));
ASSERT_EQUALS(2, CheckBufferOverrun::countSprintfLength("\\\"", unknownParameter));
ASSERT_EQUALS(7, CheckBufferOverrun::countSprintfLength("Hello \\0Text", unknownParameter));
ASSERT_EQUALS(1, CheckBufferOverrun::countSprintfLength("\\0", unknownParameter));
ASSERT_EQUALS(2, CheckBufferOverrun::countSprintfLength("%%", unknownParameter));
ASSERT_EQUALS(3, CheckBufferOverrun::countSprintfLength("%d%d", unknownParameter));
ASSERT_EQUALS(3, CheckBufferOverrun::countSprintfLength("\\\\a%s\\0a", unknownParameter));
ASSERT_EQUALS(10, CheckBufferOverrun::countSprintfLength("\\\\\\\\Hello%d \\0Text\\\\\\\\", unknownParameter));
ASSERT_EQUALS(4, CheckBufferOverrun::countSprintfLength("%%%%%d", unknownParameter));
Token strTok;
std::list<const Token*> stringAsParameter(1, &strTok);
strTok.str("\"\"");
ASSERT_EQUALS(4, CheckBufferOverrun::countSprintfLength("str%s", stringAsParameter));
strTok.str("\"12345\"");
ASSERT_EQUALS(9, CheckBufferOverrun::countSprintfLength("str%s", stringAsParameter));
ASSERT_EQUALS(6, CheckBufferOverrun::countSprintfLength("%-4s", stringAsParameter));
ASSERT_EQUALS(6, CheckBufferOverrun::countSprintfLength("%-5s", stringAsParameter));
ASSERT_EQUALS(7, CheckBufferOverrun::countSprintfLength("%-6s", stringAsParameter));
ASSERT_EQUALS(5, CheckBufferOverrun::countSprintfLength("%.4s", stringAsParameter));
ASSERT_EQUALS(6, CheckBufferOverrun::countSprintfLength("%.5s", stringAsParameter));
ASSERT_EQUALS(6, CheckBufferOverrun::countSprintfLength("%.6s", stringAsParameter));
ASSERT_EQUALS(6, CheckBufferOverrun::countSprintfLength("%5.6s", stringAsParameter));
ASSERT_EQUALS(7, CheckBufferOverrun::countSprintfLength("%6.6s", stringAsParameter));
Token numTok;
numTok.str("12345");
std::list<const Token*> intAsParameter(1, &numTok);
ASSERT_EQUALS(6, CheckBufferOverrun::countSprintfLength("%02ld", intAsParameter));
ASSERT_EQUALS(9, CheckBufferOverrun::countSprintfLength("%08ld", intAsParameter));
ASSERT_EQUALS(6, CheckBufferOverrun::countSprintfLength("%.2d", intAsParameter));
ASSERT_EQUALS(9, CheckBufferOverrun::countSprintfLength("%08.2d", intAsParameter));
TODO_ASSERT_EQUALS(5, 2, CheckBufferOverrun::countSprintfLength("%x", intAsParameter));
ASSERT_EQUALS(5, CheckBufferOverrun::countSprintfLength("%4x", intAsParameter));
ASSERT_EQUALS(6, CheckBufferOverrun::countSprintfLength("%5x", intAsParameter));
ASSERT_EQUALS(5, CheckBufferOverrun::countSprintfLength("%.4x", intAsParameter));
ASSERT_EQUALS(6, CheckBufferOverrun::countSprintfLength("%.5x", intAsParameter));
ASSERT_EQUALS(6, CheckBufferOverrun::countSprintfLength("%1.5x", intAsParameter));
ASSERT_EQUALS(6, CheckBufferOverrun::countSprintfLength("%5.1x", intAsParameter));
Token floatTok;
floatTok.str("1.12345f");
std::list<const Token*> floatAsParameter(1, &floatTok);
TODO_ASSERT_EQUALS(5, 3, CheckBufferOverrun::countSprintfLength("%.2f", floatAsParameter));
ASSERT_EQUALS(9, CheckBufferOverrun::countSprintfLength("%8.2f", floatAsParameter));
TODO_ASSERT_EQUALS(5, 3, CheckBufferOverrun::countSprintfLength("%2.2f", floatAsParameter));
Token floatTok2;
floatTok2.str("100.12345f");
std::list<const Token*> floatAsParameter2(1, &floatTok2);
TODO_ASSERT_EQUALS(7, 3, CheckBufferOverrun::countSprintfLength("%2.2f", floatAsParameter2));
TODO_ASSERT_EQUALS(7, 3, CheckBufferOverrun::countSprintfLength("%.2f", floatAsParameter));
TODO_ASSERT_EQUALS(7, 5, CheckBufferOverrun::countSprintfLength("%4.2f", floatAsParameter));
std::list<const Token*> multipleParams = { &strTok, nullptr, &numTok };
ASSERT_EQUALS(15, CheckBufferOverrun::countSprintfLength("str%s%d%d", multipleParams));
ASSERT_EQUALS(26, CheckBufferOverrun::countSprintfLength("str%-6s%08ld%08ld", multipleParams));
}
*/
// extracttests.disable
void minsize_argvalue() {
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <function name=\"mymemset\">\n"
" <noreturn>false</noreturn>\n"
" <arg nr=\"1\">\n"
" <minsize type=\"argvalue\" arg=\"3\"/>\n"
" </arg>\n"
" <arg nr=\"2\"/>\n"
" <arg nr=\"3\"/>\n"
" </function>\n"
"</def>";
/*const*/ Settings settings = settingsBuilder().libraryxml(xmldata, sizeof(xmldata)).severity(Severity::warning).build();
settings.platform.sizeof_wchar_t = 4;
check("void f() {\n"
" char c[10];\n"
" mymemset(c, 0, 10);\n"
"}", settings);
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" char c[10];\n"
" mymemset(c, 0, 11);\n"
"}", settings);
ASSERT_EQUALS("[test.cpp:3]: (error) Buffer is accessed out of bounds: c\n", errout_str());
check("struct S {\n"
" char a[5];\n"
"};\n"
"void f() {\n"
" S s;\n"
" mymemset(s.a, 0, 10);\n"
"}", settings);
ASSERT_EQUALS("[test.cpp:6]: (error) Buffer is accessed out of bounds: s.a\n", errout_str());
check("void foo() {\n"
" char s[10];\n"
" mymemset(s, 0, '*');\n"
"}", settings);
TODO_ASSERT_EQUALS("[test.cpp:3]: (warning) The size argument is given as a char constant.\n"
"[test.cpp:3]: (error) Buffer is accessed out of bounds: s\n", "[test.cpp:3]: (error) Buffer is accessed out of bounds: s\n", errout_str());
// ticket #836
check("void f(void) {\n"
" char a[10];\n"
" mymemset(a+5, 0, 10);\n"
"}", settings);
TODO_ASSERT_EQUALS("[test.cpp:3]: (error) Buffer is accessed out of bounds: a\n", "", errout_str());
// Ticket #909
check("void f(void) {\n"
" char str[] = \"abcd\";\n"
" mymemset(str, 0, 6);\n"
"}", settings);
ASSERT_EQUALS("[test.cpp:3]: (error) Buffer is accessed out of bounds: str\n", errout_str());
check("void f(void) {\n"
" char str[] = \"abcd\";\n"
" mymemset(str, 0, 5);\n"
"}", settings);
ASSERT_EQUALS("", errout_str());
check("void f(void) {\n"
" wchar_t str[] = L\"abcd\";\n"
" mymemset(str, 0, 21);\n"
"}", settings);
ASSERT_EQUALS("[test.cpp:3]: (error) Buffer is accessed out of bounds: str\n", errout_str());
check("void f(void) {\n"
" wchar_t str[] = L\"abcd\";\n"
" mymemset(str, 0, 20);\n"
"}", settings);
ASSERT_EQUALS("", errout_str());
// ticket #1659 - overflowing variable when using memcpy
check("void f(void) {\n"
" char c;\n"
" mymemset(&c, 0, 4);\n"
"}", settings);
TODO_ASSERT_EQUALS("[test.cpp:3]: (error) Buffer is accessed out of bounds: c\n", "", errout_str());
// ticket #2121 - buffer access out of bounds when using uint32_t
check("void f(void) {\n"
" unknown_type_t buf[4];\n"
" mymemset(buf, 0, 100);\n"
"}", settings);
ASSERT_EQUALS("", errout_str());
// #3124 - multidimensional array
check("int main() {\n"
" char b[5][6];\n"
" mymemset(b, 0, 5 * 6);\n"
"}", settings);
ASSERT_EQUALS("", errout_str());
check("int main() {\n"
" char b[5][6];\n"
" mymemset(b, 0, 6 * 6);\n"
"}", settings);
ASSERT_EQUALS("[test.cpp:3]: (error) Buffer is accessed out of bounds: b\n", errout_str());
check("int main() {\n"
" char b[5][6];\n"
" mymemset(b, 0, 31);\n"
"}", settings);
ASSERT_EQUALS("[test.cpp:3]: (error) Buffer is accessed out of bounds: b\n", errout_str());
// #4968 - not standard function
check("void f() {\n"
" char str[3];\n"
" foo.mymemset(str, 0, 100);\n"
" foo::mymemset(str, 0, 100);\n"
" std::mymemset(str, 0, 100);\n"
"}", settings);
TODO_ASSERT_EQUALS("[test.cpp:5]: (error) Buffer is accessed out of bounds: str\n", "", errout_str());
// #5257 - check strings
check("void f() {\n"
" mymemset(\"abc\", 0, 20);\n"
"}", settings);
TODO_ASSERT_EQUALS("[test.cpp:2]: (error) Buffer is accessed out of bounds.\n",
"",
errout_str());
check("void f() {\n"
" mymemset(temp, \"abc\", 4);\n"
"}", settings);
ASSERT_EQUALS("", errout_str());
check("void f() {\n" // #6816 - fp when array has known string value
" char c[10] = \"c\";\n"
" mymemset(c, 0, 10);\n"
"}", settings);
ASSERT_EQUALS("", errout_str());
}
void minsize_sizeof() {
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <function name=\"mystrncpy\">\n"
" <noreturn>false</noreturn>\n"
" <arg nr=\"1\">\n"
" <minsize type=\"strlen\" arg=\"2\"/>\n"
" <minsize type=\"argvalue\" arg=\"3\"/>\n"
" </arg>\n"
" <arg nr=\"2\"/>\n"
" <arg nr=\"3\"/>\n"
" </function>\n"
"</def>";
const Settings settings = settingsBuilder().libraryxml(xmldata, sizeof(xmldata)).build();
check("void f() {\n"
" char c[7];\n"
" mystrncpy(c, \"hello\", 7);\n"
"}", settings);
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" char c[6];\n"
" mystrncpy(c,\"hello\",6);\n"
"}", settings);
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" char c[5];\n"
" mystrncpy(c,\"hello\",6);\n"
"}", settings);
ASSERT_EQUALS("[test.cpp:3]: (error) Buffer is accessed out of bounds: c\n", errout_str());
check("void f() {\n"
" char c[6];\n"
" mystrncpy(c,\"hello!\",7);\n"
"}", settings);
ASSERT_EQUALS("[test.cpp:3]: (error) Buffer is accessed out of bounds: c\n", errout_str());
check("void f(unsigned int addr) {\n"
" memset((void *)addr, 0, 1000);\n"
"}", settings0);
ASSERT_EQUALS("", errout_str());
check("struct AB { char a[10]; };\n"
"void foo(AB *ab) {\n"
" mystrncpy(x, ab->a, 100);\n"
"}", settings);
ASSERT_EQUALS("", errout_str());
check("void a(char *p) { mystrncpy(p,\"hello world!\",10); }\n" // #3168
"void b() {\n"
" char buf[5];\n"
" a(buf);"
"}", settings);
TODO_ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:1]: (error) Buffer is accessed out of bounds: buf\n",
"",
errout_str());
}
void minsize_strlen() {
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <function name=\"mysprintf\">\n"
" <noreturn>false</noreturn>\n"
" <formatstr/>\n"
" <arg nr=\"1\">\n"
" <minsize type=\"strlen\" arg=\"2\"/>\n"
" </arg>\n"
" <arg nr=\"2\">\n"
" <formatstr/>\n"
" </arg>\n"
" </function>\n"
"</def>";
const Settings settings = settingsBuilder().libraryxml(xmldata, sizeof(xmldata)).build();
// formatstr..
check("void f() {\n"
" char str[3];\n"
" mysprintf(str, \"test\");\n"
"}", settings);
ASSERT_EQUALS("[test.cpp:3]: (error) Buffer is accessed out of bounds: str\n", errout_str());
check("void f() {\n"
" char str[5];\n"
" mysprintf(str, \"%s\", \"abcde\");\n"
"}", settings);
ASSERT_EQUALS("[test.cpp:3]: (error) Buffer is accessed out of bounds: str\n", errout_str());
check("int getnumber();\n"
"void f()\n"
"{\n"
" char str[5];\n"
" mysprintf(str, \"%d: %s\", getnumber(), \"abcde\");\n"
"}", settings);
ASSERT_EQUALS("[test.cpp:5]: (error) Buffer is accessed out of bounds: str\n", errout_str());
check("void f() {\n"
" char str[5];\n"
" mysprintf(str, \"test%s\", \"\");\n"
"}", settings);
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" char *str = new char[5];\n"
" mysprintf(str, \"abcde\");\n"
"}", settings);
ASSERT_EQUALS("[test.cpp:3]: (error) Buffer is accessed out of bounds: str\n", errout_str());
check("void f(int condition) {\n"
" char str[5];\n"
" mysprintf(str, \"test%s\", condition ? \"12\" : \"34\");\n"
"}", settings);
ASSERT_EQUALS("", errout_str());
check("void f(int condition) {\n"
" char str[5];\n"
" mysprintf(str, \"test%s\", condition ? \"12\" : \"345\");\n"
"}", settings);
TODO_ASSERT_EQUALS("error", "", errout_str());
check("struct Foo { char a[1]; };\n"
"void f() {\n"
" struct Foo x;\n"
" mysprintf(x.a, \"aa\");\n"
"}", settings);
ASSERT_EQUALS("[test.cpp:4]: (error) Buffer is accessed out of bounds: x.a\n", errout_str());
// ticket #900
check("void f() {\n"
" char *a = new char(30);\n"
" mysprintf(a, \"a\");\n"
"}", settings);
ASSERT_EQUALS("[test.cpp:3]: (error) Buffer is accessed out of bounds: a\n", errout_str());
check("void f(char value) {\n"
" char *a = new char(value);\n"
" mysprintf(a, \"a\");\n"
"}", settings);
ASSERT_EQUALS("[test.cpp:3]: (error) Buffer is accessed out of bounds: a\n", errout_str());
// This is out of bounds if 'sizeof(ABC)' is 1 (No padding)
check("struct Foo { char a[1]; };\n"
"void f() {\n"
" struct Foo *x = malloc(sizeof(Foo));\n"
" mysprintf(x->a, \"aa\");\n"
"}", settings);
TODO_ASSERT_EQUALS("[test.cpp:4]: (error, inconclusive) Buffer is accessed out of bounds: x.a\n", "", errout_str());
check("struct Foo { char a[1]; };\n"
"void f() {\n"
" struct Foo *x = malloc(sizeof(Foo) + 10);\n"
" mysprintf(x->a, \"aa\");\n"
"}", settings);
ASSERT_EQUALS("", errout_str());
check("struct Foo { char a[1]; };\n"
"void f() {\n"
" struct Foo x;\n"
" mysprintf(x.a, \"aa\");\n"
"}", settings);
ASSERT_EQUALS("[test.cpp:4]: (error) Buffer is accessed out of bounds: x.a\n", errout_str());
check("struct Foo {\n" // #6668 - unknown size
" char a[LEN];\n"
" void f();\n"
"};"
"void Foo::f() {\n"
" mysprintf(a, \"abcd\");\n"
"}", settings);
ASSERT_EQUALS("", errout_str());
}
void minsize_mul() {
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <function name=\"myfread\">\n"
" <arg nr=\"1\">\n"
" <minsize type=\"mul\" arg=\"2\" arg2=\"3\"/>\n"
" </arg>\n"
" <arg nr=\"2\"/>\n"
" <arg nr=\"3\"/>\n"
" <arg nr=\"4\"/>\n"
" </function>\n"
"</def>";
const Settings settings = settingsBuilder().libraryxml(xmldata, sizeof(xmldata)).build();
check("void f() {\n"
" char c[5];\n"
" myfread(c, 1, 5, stdin);\n"
"}", settings);
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" char c[5];\n"
" myfread(c, 1, 6, stdin);\n"
"}", settings);
ASSERT_EQUALS("[test.cpp:3]: (error) Buffer is accessed out of bounds: c\n", errout_str());
}
// extracttests.enable
void unknownType() {
check("void f()\n"
"{\n"
" UnknownType *a = malloc(4);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
// extracttests.disable
void terminateStrncpy1() {
check("void foo ( char *bar ) {\n"
" char baz[100];\n"
" strncpy(baz, bar, 100);\n"
" strncpy(baz, bar, 100);\n"
" baz[99] = 0;\n"
" strncpy(baz, bar, 100);\n"
" baz[99] = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo ( char *bar ) {\n"
" char baz[100];\n"
" strncpy(baz, bar, 100);\n"
" baz[99] = '\\0';\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo ( char *bar ) {\n"
" char baz[100];\n"
" strncpy(baz, bar, 100);\n"
" baz[x+1] = '\\0';\n"
"}");
ASSERT_EQUALS("", errout_str());
// Test with invalid code that there is no segfault
check("char baz[100];\n"
"strncpy(baz, \"var\", 100)");
ASSERT_EQUALS("", errout_str());
// Test that there are no duplicate error messages
check("void foo ( char *bar ) {\n"
" char baz[100];\n"
" strncpy(baz, bar, 100);\n"
" foo(baz);\n"
" foo(baz);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning, inconclusive) The buffer 'baz' may not be null-terminated after the call to strncpy().\n", errout_str());
}
void terminateStrncpy2() {
check("char *foo ( char *bar ) {\n"
" char baz[100];\n"
" strncpy(baz, bar, 100);\n"
" bar[99] = 0;\n"
" return strdup(baz);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning, inconclusive) The buffer 'baz' may not be null-terminated after the call to strncpy().\n", errout_str());
}
void terminateStrncpy3() {
// Ticket #2170 - false positive
// The function bar is risky. But it might work that way intentionally.
check("char str[100];\n"
"\n"
"void foo(char *a) {\n"
" strncpy(str, a, 100);\n"
"}\n"
"\n"
"void bar(char *p) {\n"
" strncpy(p, str, 100);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (warning, inconclusive) The buffer 'str' may not be null-terminated after the call to strncpy().\n", errout_str());
}
void terminateStrncpy4() {
check("void bar() {\n"
" char buf[4];\n"
" strncpy(buf, \"ab\", 4);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void bar() {\n"
" char buf[4];\n"
" strncpy(buf, \"abcde\", 4);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning, inconclusive) The buffer 'buf' may not be null-terminated after the call to strncpy().\n", errout_str());
}
void terminateStrncpy5() { // #9944
check("void f(const std::string& buf) {\n"
" char v[255];\n"
" if (buf.size() >= sizeof(v))\n"
" return;\n"
" strncpy(v, buf.c_str(), sizeof(v));\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(const std::string& buf) {\n"
" char v[255];\n"
" if (buf.size() >= sizeof(v))\n"
" strncpy(v, buf.c_str(), sizeof(v));\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (warning, inconclusive) The buffer 'v' may not be null-terminated after the call to strncpy().\n", errout_str());
}
// extracttests.enable
void recursive_long_time() {
// Just test that recursive check doesn't take long time
check("char *f2 ( char *b )\n"
"{\n"
" f2( b );\n"
" f2( b );\n"
" f2( b );\n"
" f2( b );\n"
" f2( b );\n"
" f2( b );\n"
" f2( b );\n"
" f2( b );\n"
" f2( b );\n"
" f2( b );\n"
" f2( b );\n"
" f2( b );\n"
" f2( b );\n"
" f2( b );\n"
" f2( b );\n"
"}\n"
"void f()\n"
"{\n"
" char a[10];\n"
" f2(a);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
// Ticket #1587 - crash
void crash1() {
check("struct struct A\n"
"{\n"
" int alloclen;\n"
"};\n"
"\n"
"void foo()\n"
"{\n"
" struct A *str;\n"
" str = malloc(4);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void crash2() {
check("void a(char *p) {\n"
" f( { if(finally_arg); } );\n"
"}\n"
"\n"
"void b() {\n"
" char arr[64];\n"
" a(arr);\n"
"}");
}
void crash3() {
check("struct b { unknown v[0]; };\n"
"void d() { struct b *f; f = malloc(108); }");
}
void crash4() { // #8679
check("__thread void *thread_local_var; "
"int main() { "
" thread_local_var = malloc(1337); "
" return 0; "
"}");
check("thread_local void *thread_local_var; "
"int main() { "
" thread_local_var = malloc(1337); "
" return 0; "
"}");
}
void crash5() { // 8644 - token has varId() but variable() is null
check("int a() {\n"
" void b(char **dst) {\n"
" *dst = malloc(50);\n"
" }\n"
"}");
}
void crash6() {
check("void start(char* name) {\n"
"char snapname[64] = { 0 };\n"
"strncpy(snapname, \"snapshot\", arrayLength(snapname));\n"
"}");
}
void crash7() { // 9073 - [ has no astParent
check("char x[10];\n"
"void f() { x[10]; }");
}
void insecureCmdLineArgs() {
check("int main(int argc, char *argv[])\n"
"{\n"
" if(argc>1)\n"
" {\n"
" char buf[2];\n"
" char *p = strdup(argv[1]);\n"
" strcpy(buf,p);\n"
" free(p);\n"
" }\n"
" return 0;\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:7]: (error) Buffer overrun possible for long command line arguments.\n", "", errout_str());
check("int main(int argc, char *argv[])\n"
"{\n"
" if(argc>1)\n"
" {\n"
" char buf[2] = {'\\0','\\0'};\n"
" char *p = strdup(argv[1]);\n"
" strcat(buf,p);\n"
" free(p);\n"
" }\n"
" return 0;\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:7]: (error) Buffer overrun possible for long command line arguments.\n", "", errout_str());
check("int main(const int argc, char* argv[])\n"
"{\n"
" char prog[10];\n"
" strcpy(prog, argv[0]);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:4]: (error) Buffer overrun possible for long command line arguments.\n", "", errout_str());
check("int main(int argc, const char* argv[])\n"
"{\n"
" char prog[10];\n"
" strcpy(prog, argv[0]);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:4]: (error) Buffer overrun possible for long command line arguments.\n", "", errout_str());
check("int main(const int argc, const char* argv[])\n"
"{\n"
" char prog[10];\n"
" strcpy(prog, argv[0]);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:4]: (error) Buffer overrun possible for long command line arguments.\n", "", errout_str());
check("int main(int argc, char* argv[])\n"
"{\n"
" char prog[10] = {'\\0'};\n"
" strcat(prog, argv[0]);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:4]: (error) Buffer overrun possible for long command line arguments.\n", "", errout_str());
check("int main(int argc, char **argv, char **envp)\n"
"{\n"
" char prog[10];\n"
" strcpy(prog, argv[0]);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:4]: (error) Buffer overrun possible for long command line arguments.\n", "", errout_str());
check("int main(int argc, const char *const *const argv, char **envp)\n"
"{\n"
" char prog[10];\n"
" strcpy(prog, argv[0]);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:4]: (error) Buffer overrun possible for long command line arguments.\n", "", errout_str());
check("int main(const int argc, const char *const *const argv, const char *const *const envp)\n"
"{\n"
" char prog[10];\n"
" strcpy(prog, argv[0]);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:4]: (error) Buffer overrun possible for long command line arguments.\n", "", errout_str());
check("int main(int argc, char **argv, char **envp)\n"
"{\n"
" char prog[10] = {'\\0'};\n"
" strcat(prog, argv[0]);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:4]: (error) Buffer overrun possible for long command line arguments.\n", "", errout_str());
check("int main(const int argc, const char **argv, char **envp)\n"
"{\n"
" char prog[10] = {'\\0'};\n"
" strcat(prog, argv[0]);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:4]: (error) Buffer overrun possible for long command line arguments.\n", "", errout_str());
check("int main(int argc, const char **argv, char **envp)\n"
"{\n"
" char prog[10] = {'\\0'};\n"
" strcat(prog, argv[0]);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:4]: (error) Buffer overrun possible for long command line arguments.\n", "", errout_str());
check("int main(const int argc, char **argv, char **envp)\n"
"{\n"
" char prog[10] = {'\\0'};\n"
" strcat(prog, argv[0]);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:4]: (error) Buffer overrun possible for long command line arguments.\n", "", errout_str());
check("int main(int argc, char **options)\n"
"{\n"
" char prog[10];\n"
" strcpy(prog, options[0]);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:4]: (error) Buffer overrun possible for long command line arguments.\n", "", errout_str());
check("int main(int argc, char **options)\n"
"{\n"
" char prog[10] = {'\\0'};\n"
" strcat(prog, options[0]);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:4]: (error) Buffer overrun possible for long command line arguments.\n", "", errout_str());
check("int main(int argc, char **options)\n"
"{\n"
" char prog[10];\n"
" strcpy(prog, *options);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:4]: (error) Buffer overrun possible for long command line arguments.\n", "", errout_str());
check("int main(int argc, char **options)\n"
"{\n"
" char prog[10];\n"
" strcpy(prog+3, *options);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:4]: (error) Buffer overrun possible for long command line arguments.\n", "", errout_str());
check("int main(int argc, char **argv, char **envp)\n"
"{\n"
" char prog[10];\n"
" if (strlen(argv[0]) < 10)\n"
" strcpy(prog, argv[0]);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int main(int argc, char **argv, char **envp)\n"
"{\n"
" char prog[10] = {'\\0'};\n"
" if (10 > strlen(argv[0]))\n"
" strcat(prog, argv[0]);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int main(int argc, char **argv, char **envp)\n"
"{\n"
" char prog[10];\n"
" argv[0][0] = '\\0';\n"
" strcpy(prog, argv[0]);\n"
"}");
ASSERT_EQUALS("", errout_str());
// #5835
check("int main(int argc, char* argv[]) {\n"
" char prog[10];\n"
" strcpy(prog, argv[0]);\n"
" strcpy(prog, argv[0]);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:3]: (error) Buffer overrun possible for long command line arguments.\n"
"[test.cpp:4]: (error) Buffer overrun possible for long command line arguments.\n", "", errout_str());
// #7964
check("int main(int argc, char *argv[]) {\n"
" char *strcpy();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int main(int argc, char *argv[]) {\n"
" char *strcat();\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void checkBufferAllocatedWithStrlen() {
check("void f(char *a) {\n"
" char *b = new char[strlen(a)];\n"
" strcpy(b, a);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:3]: (error) Buffer is accessed out of bounds.\n", "", errout_str());
check("void f(char *a) {\n"
" char *b = new char[strlen(a) + 1];\n"
" strcpy(b, a);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(char *a) {\n"
" char *b = new char[strlen(a)];\n"
" a[0] = '\\0';\n"
" strcpy(b, a);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(char *a) {\n"
" char *b = (char *)malloc(strlen(a));\n"
" b = realloc(b, 10000);\n"
" strcpy(b, a);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(char *a) {\n"
" char *b = (char *)malloc(strlen(a));\n"
" strcpy(b, a);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:3]: (error) Buffer is accessed out of bounds.\n", "", errout_str());
check("void f(char *a) {\n"
" char *b = (char *)malloc(strlen(a));\n"
" {\n"
" strcpy(b, a);\n"
" }\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:4]: (error) Buffer is accessed out of bounds.\n", "", errout_str());
check("void f(char *a) {\n"
" char *b = (char *)malloc(strlen(a) + 1);\n"
" strcpy(b, a);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(char *a, char *c) {\n"
" char *b = (char *)realloc(c, strlen(a));\n"
" strcpy(b, a);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:3]: (error) Buffer is accessed out of bounds.\n", "", errout_str());
check("void f(char *a, char *c) {\n"
" char *b = (char *)realloc(c, strlen(a) + 1);\n"
" strcpy(b, a);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(char *a) {\n"
" char *b = (char *)malloc(strlen(a));\n"
" strcpy(b, a);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:3]: (error) Buffer is accessed out of bounds.\n", "", errout_str());
}
void scope() {
check("class A {\n"
"private:\n"
" struct X { char buf[10]; };\n"
"};\n"
"\n"
"void f()\n"
"{\n"
" X x;\n"
" x.buf[10] = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("class A {\n"
"public:\n"
" struct X { char buf[10]; };\n"
"};\n"
"\n"
"void f()\n"
"{\n"
" A::X x;\n"
" x.buf[10] = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:9]: (error) Array 'x.buf[10]' accessed at index 10, which is out of bounds.\n", errout_str());
}
void getErrorMessages() {
// Ticket #2292: segmentation fault when using --errorlist
const Check& c = getCheck<CheckBufferOverrun>();
c.getErrorMessages(this, nullptr);
// we are not interested in the output - just consume it
ignore_errout();
}
void arrayIndexThenCheck() {
// extracttests.start: volatile int y;
check("void f(const char s[]) {\n"
" if (s[i] == 'x' && i < y) {\n"
" }"
"}");
ASSERT_EQUALS("", errout_str()); // No message because i is unknown and thus gets no varid. Avoid an internalError here.
check("void f(const char s[], int i) {\n"
" if (s[i] == 'x' && i < y) {\n"
" }"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Array index 'i' is used before limits check.\n", errout_str());
check("void f(const char s[]) {\n"
" for (int i = 0; s[i] == 'x' && i < y; ++i) {\n"
" }"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Array index 'i' is used before limits check.\n", errout_str());
check("void f(const int a[], unsigned i) {\n"
" if((a[i] < 2) && (i <= 42)) {\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Array index 'i' is used before limits check.\n", errout_str());
check("void f(const int a[], unsigned i) {\n"
" if((a[i] < 2) && (42 >= i)) {\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Array index 'i' is used before limits check.\n", errout_str());
// extracttests.start: int elen;
check("void f(char* e, int y) {\n"
" if (e[y] == '/' && elen > y + 1 && e[y + 1] == '?') {\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// extracttests.start: int foo(int); int func(int);
check("void f(const int a[], unsigned i) {\n"
" if(a[i] < func(i) && i <= 42) {\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Array index 'i' is used before limits check.\n", errout_str());
check("void f(const int a[], unsigned i) {\n"
" if (i <= 42 && a[i] < func(i)) {\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(const int a[], unsigned i) {\n"
" if (foo(a[i] + 3) < func(i) && i <= 42) {\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Array index 'i' is used before limits check.\n", errout_str());
check("void f(int i) {\n" // sizeof
" sizeof(a)/sizeof(a[i]) && i < 10;\n"
"}");
ASSERT_EQUALS("", errout_str());
// extracttests.start: extern int buf[];
check("void f(int i) {\n" // ?:
" if ((i < 10 ? buf[i] : 1) && (i < 5 ? buf[i] : 5)){}\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void arrayIndexEarlyReturn() { // #6884
check("extern const char *Names[2];\n"
"const char* getName(int value) {\n"
" if ((value < 0) || (value > 1))\n"
" return \"???\";\n"
" const char* name = Names[value]; \n"
" switch (value) {\n"
" case 2:\n"
" break; \n"
" }\n"
" return name;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void bufferNotZeroTerminated() {
check("void f() {\n"
" char c[6];\n"
" strncpy(c,\"hello!\",6);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning, inconclusive) The buffer 'c' may not be null-terminated after the call to strncpy().\n", errout_str());
check("void f() {\n"
" char c[6];\n"
" memcpy(c,\"hello!\",6);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:3]: (warning, inconclusive) The buffer 'c' may not be null-terminated after the call to memcpy().\n", "", errout_str());
check("void f() {\n"
" char c[6];\n"
" memmove(c,\"hello!\",6);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:3]: (warning, inconclusive) The buffer 'c' may not be null-terminated after the call to memmove().\n", "", errout_str());
}
void negativeMemoryAllocationSizeError() { // #389
check("void f()\n"
"{\n"
" int *a;\n"
" a = new int[-1];\n"
" delete [] a;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Memory allocation size is negative.\n", errout_str());
check("void f()\n"
"{\n"
" int *a;\n"
" a = (int *)malloc( -10 );\n"
" free(a);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:4]: (error) Memory allocation size is negative.\n", "", errout_str());
check("void f()\n"
"{\n"
" int *a;\n"
" a = (int *)malloc( -10);\n"
" free(a);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:4]: (error) Memory allocation size is negative.\n", "", errout_str());
check("void f()\n"
"{\n"
" int *a;\n"
" a = (int *)alloca( -10 );\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:4]: (error) Memory allocation size is negative.\n", "", errout_str());
check("int* f(int n) {\n" // #11145
" int d = -1;\n"
" for (int i = 0; i < n; ++i)\n"
" d = std::max(i, d);\n"
" int* p = new int[d];\n"
" return p;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5]: (warning, inconclusive) Memory allocation size is negative.\n", errout_str());
}
void negativeArraySize() {
check("void f(int sz) {\n" // #1760 - VLA
" int a[sz];\n"
"}\n"
"void x() { f(-100); }");
ASSERT_EQUALS("[test.cpp:2]: (error) Declaration of array 'a' with negative size is undefined behaviour\n", errout_str());
// don't warn for constant sizes -> this is a compiler error so this is used for static assertions for instance
check("int x, y;\n"
"int a[-1];\n"
"int b[x?1:-1];\n"
"int c[x?y:-1];");
ASSERT_EQUALS("", errout_str());
}
void pointerAddition1() {
check("void f() {\n"
" char arr[10];\n"
" char *p = arr + 20;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (portability) Undefined behaviour, pointer arithmetic 'arr+20' is out of bounds.\n", errout_str());
check("char(*g())[1];\n" // #7950
"void f() {\n"
" int a[2];\n"
" int* b = a + sizeof(*g());\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
#define ctu(code) ctu_(code, __FILE__, __LINE__)
template<size_t size>
void ctu_(const char (&code)[size], const char* file, int line) {
// Tokenize..
SimpleTokenizer tokenizer(settings0, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
CTU::FileInfo *ctu = CTU::getFileInfo(tokenizer);
// Check code..
std::list<Check::FileInfo*> fileInfo;
Check& c = getCheck<CheckBufferOverrun>();
fileInfo.push_back(c.getFileInfo(tokenizer, settings0));
c.analyseWholeProgram(ctu, fileInfo, settings0, *this); // TODO: check result
while (!fileInfo.empty()) {
delete fileInfo.back();
fileInfo.pop_back();
}
delete ctu;
}
void ctu_malloc() {
ctu("void dostuff(char *p) {\n"
" p[-3] = 0;\n"
"}\n"
"\n"
"int main() {\n"
" char *s = malloc(4);\n"
" dostuff(s);\n"
"}");
ASSERT_EQUALS("[test.cpp:6] -> [test.cpp:7] -> [test.cpp:2]: (error) Array index out of bounds; buffer 'p' is accessed at offset -3.\n", errout_str());
ctu("void dostuff(char *p) {\n"
" p[4] = 0;\n"
"}\n"
"\n"
"int main() {\n"
" char *s = malloc(4);\n"
" dostuff(s);\n"
"}");
ASSERT_EQUALS("[test.cpp:6] -> [test.cpp:7] -> [test.cpp:2]: (error) Array index out of bounds; 'p' buffer size is 4 and it is accessed at offset 4.\n", errout_str());
ctu("void f(int* p) {\n" // #10415
" int b[1];\n"
" b[0] = p[5];\n"
" std::cout << b[0];\n"
"}\n"
"void g() {\n"
" int* a = new int[1];\n"
" a[0] = 5;\n"
" f(a);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:7] -> [test.cpp:9] -> [test.cpp:3]: (error) Array index out of bounds; 'p' buffer size is 4 and it is accessed at offset 20.\n", errout_str());
}
void ctu_array() {
ctu("void dostuff(char *p) {\n"
" p[10] = 0;\n"
"}\n"
"int main() {\n"
" char str[4];\n"
" dostuff(str);\n"
"}");
ASSERT_EQUALS("[test.cpp:6] -> [test.cpp:2]: (error) Array index out of bounds; 'p' buffer size is 4 and it is accessed at offset 10.\n", errout_str());
ctu("static void memclr( char *data )\n"
"{\n"
" data[10] = 0;\n"
"}\n"
"\n"
"static void f()\n"
"{\n"
" char str[5];\n"
" memclr( str );\n"
"}");
ASSERT_EQUALS("[test.cpp:9] -> [test.cpp:3]: (error) Array index out of bounds; 'data' buffer size is 5 and it is accessed at offset 10.\n", errout_str());
ctu("static void memclr( int i, char *data )\n"
"{\n"
" data[10] = 0;\n"
"}\n"
"\n"
"static void f()\n"
"{\n"
" char str[5];\n"
" memclr( 0, str );\n"
"}");
ASSERT_EQUALS("[test.cpp:9] -> [test.cpp:3]: (error) Array index out of bounds; 'data' buffer size is 5 and it is accessed at offset 10.\n", errout_str());
ctu("static void memclr( int i, char *data )\n"
"{\n"
" data[i] = 0;\n"
"}\n"
"\n"
"static void f()\n"
"{\n"
" char str[5];\n"
" memclr( 10, str );\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:9] -> [test.cpp:3]: (possible error) Array index out of bounds.\n",
"", errout_str());
// This is not an error
ctu("static void memclr( char *data, int size )\n"
"{\n"
" if( size > 10 )"
" data[10] = 0;\n"
"}\n"
"\n"
"static void f()\n"
"{\n"
" char str[5];\n"
" memclr( str, 5 );\n"
"}");
ASSERT_EQUALS("", errout_str());
// #2097
ctu("void foo(int *p)\n"
"{\n"
" --p;\n"
" p[2] = 0;\n"
"}\n"
"\n"
"void bar()\n"
"{\n"
" int p[3];\n"
" foo(p+1);\n"
"}");
ASSERT_EQUALS("", errout_str());
// #9112
ctu("static void get_mac_address(const u8 *strbuf)\n"
"{\n"
" (strbuf[2]);\n"
"}\n"
"\n"
"static void program_mac_address(u32 mem_base)\n"
"{\n"
" u8 macstrbuf[17] = { 0 };\n"
" get_mac_address(macstrbuf);\n"
"}");
ASSERT_EQUALS("", errout_str());
// #9788
ctu("void f1(char *s) { s[2] = 'B'; }\n"
"void f2(char s[]) { s[2] = 'B'; }\n"
"void g() {\n"
" char str[2];\n"
" f1(str);\n"
" f2(str);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:1]: (error) Array index out of bounds; 's' buffer size is 2 and it is accessed at offset 2.\n"
"[test.cpp:6] -> [test.cpp:2]: (error) Array index out of bounds; 's' buffer size is 2 and it is accessed at offset 2.\n",
errout_str());
// #5140
ctu("void g(const char* argv[]) { std::cout << \"argv: \" << argv[4] << std::endl; }\n"
"void f() {\n"
" const char* argv[] = { \"test\" };\n"
" g(argv);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:1]: (error) Array index out of bounds; 'argv' buffer size is 1 and it is accessed at offset 4.\n",
errout_str());
ctu("void g(const char* argv[]) { std::cout << \"argv: \" << argv[5] << std::endl; }\n"
"void f() {\n"
" const char* argv[1] = { \"test\" };\n"
" g(argv);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:1]: (error) Array index out of bounds; 'argv' buffer size is 1 and it is accessed at offset 5.\n",
errout_str());
ctu("void g(int *b) { b[0] = 0; }\n"
"void f() {\n"
" GLint a[1];\n"
" g(a);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
ctu("const int a[1] = { 1 };\n" // #11042
"void g(const int* d) {\n"
" (void)d[2];\n"
"}\n"
"void f() {\n"
" g(a);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:6] -> [test.cpp:3]: (error) Array index out of bounds; 'd' buffer size is 4 and it is accessed at offset 8.\n",
errout_str());
}
void ctu_variable() {
ctu("void dostuff(int *p) {\n"
" p[10] = 0;\n"
"}\n"
"int main() {\n"
" int x = 4;\n"
" dostuff(&x);\n"
"}");
ASSERT_EQUALS("[test.cpp:6] -> [test.cpp:2]: (error) Array index out of bounds; 'p' buffer size is 4 and it is accessed at offset 40.\n", errout_str());
}
void ctu_arithmetic() {
ctu("void dostuff(int *p) { x = p + 10; }\n"
"int main() {\n"
" int x[3];\n"
" dostuff(x);\n"
"}");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:1]: (error) Pointer arithmetic overflow; 'p' buffer size is 12\n", errout_str());
ctu("void f(const char *p) {\n" // #11361
" const char* c = p + 1;\n"
"}\n"
"void g() {\n"
" const char s[N] = \"ab\";\n"
" f(s);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void objectIndex() {
check("int f() {\n"
" int i;\n"
" return (&i)[1];\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3] -> [test.cpp:3]: (error) The address of variable 'i' is accessed at non-zero index.\n",
errout_str());
check("int f(int j) {\n"
" int i;\n"
" return (&i)[j];\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3] -> [test.cpp:3]: (warning) The address of variable 'i' might be accessed at non-zero index.\n",
errout_str());
check("int f() {\n"
" int i;\n"
" return (&i)[0];\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int f(int * i) {\n"
" return i[1];\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int f(std::vector<int> i) {\n"
" return i[1];\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int f(std::vector<int> i) {\n"
" return i.data()[1];\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int* f(std::vector<int>& i) {\n"
" return &(i[1]);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct A { int i; int j; };\n"
"int f() {\n"
" A x;\n"
" return (&x.i)[0];\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct A { int i; int j; };\n"
"int f() {\n"
" A x;\n"
" int * i = &x.i;\n"
" return i[0];\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int x = 0;\n"
" std::map<int, int*> m;\n"
" m[0] = &x;\n"
" m[1] = &x;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int f() {\n"
" int x = 0;\n"
" std::map<int, int*> m;\n"
" m[0] = &x;\n"
" return m[0][1];\n"
"}");
ASSERT_EQUALS(
"[test.cpp:4] -> [test.cpp:5]: (error) The address of variable 'x' is accessed at non-zero index.\n",
errout_str());
check("int x = 0;\n"
"int f() {\n"
" std::map<int, int*> m;\n"
" m[0] = &x;\n"
" return m[0][1];\n"
"}");
ASSERT_EQUALS(
"[test.cpp:4] -> [test.cpp:5]: (error) The address of variable 'x' is accessed at non-zero index.\n",
errout_str());
check("int f(int * y) {\n"
" int x = 0;\n"
" std::map<int, int*> m;\n"
" m[0] = &x;\n"
" m[1] = y;\n"
" return m[1][1];\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void print(char** test);\n"
"int main(){\n"
" char* test = \"abcdef\";\n"
" print(&test);\n"
" return 0;\n"
"}\n"
"void print(char** test){\n"
" for(int i=0;i<strlen(*test);i++)\n"
" printf(\"%c\",*test[i]);\n"
"}\n");
TODO_ASSERT_EQUALS(
"[test.cpp:4] -> [test.cpp:4] -> [test.cpp:9]: (warning) The address of local variable 'test' might be accessed at non-zero index.\n",
"",
errout_str());
check("void Bar(uint8_t data);\n"
"void Foo(const uint8_t * const data, const uint8_t length) {\n"
" for(uint8_t index = 0U; index < length ; ++index)\n"
" Bar(data[index]);\n"
"}\n"
"void test() {\n"
" const uint8_t data = 0U;\n"
" Foo(&data,1U);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("int foo(int n, int* p) {\n"
" int res = 0;\n"
" for(int i = 0; i < n; i++ )\n"
" res += p[i];\n"
" return res;\n"
"}\n"
"int bar() {\n"
" int single_value = 0;\n"
" return foo(1, &single_value);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(const char* app, size_t applen) {\n" // #10137
" char* tmp_de = NULL;\n"
" char** str = &tmp_de;\n"
" char* tmp = (char*)realloc(*str, applen + 1);\n"
" if (tmp) {\n"
" *str = tmp;\n"
" memcpy(*str, app, applen);\n"
" (*str)[applen] = '\\0';\n"
" }\n"
" free(*str);\n"
"}\n", false);
ASSERT_EQUALS("", errout_str());
check("template <typename T, unsigned N>\n"
"using vector = Eigen::Matrix<T, N, 1>;\n"
"template <typename V>\n"
"void scharr(image2d<vector<V, 2>>& out) {\n"
" vector<V, 2>* out_row = &out(r, 0);\n"
" out_row[c] = vector<V, 2>(1,2);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(const uint8_t* d, const uint8_t L) {\n" // #10092
" for (uint8_t i = 0U; i < L; ++i)\n"
" g(d[i]);\n"
"}\n"
"void h() {\n"
" const uint8_t u = 4;\n"
" f(&u, N);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("uint32_t f(uint32_t u) {\n" // #10154
" return ((uint8_t*)&u)[3];\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("uint32_t f(uint32_t u) {\n"
" return ((uint8_t*)&u)[4];\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:2]: (error) The address of variable 'u' is accessed at non-zero index.\n", errout_str());
check("uint32_t f(uint32_t u) {\n"
" return reinterpret_cast<unsigned char*>(&u)[3];\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("uint32_t f(uint32_t u) {\n"
" return reinterpret_cast<unsigned char*>(&u)[4];\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:2]: (error) The address of variable 'u' is accessed at non-zero index.\n", errout_str());
check("uint32_t f(uint32_t u) {\n"
" uint8_t* p = (uint8_t*)&u;\n"
" return p[3];\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("uint32_t f(uint32_t u) {\n"
" uint8_t* p = (uint8_t*)&u;\n"
" return p[4];\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (error) The address of variable 'u' is accessed at non-zero index.\n", errout_str());
check("uint32_t f(uint32_t* pu) {\n"
" uint8_t* p = (uint8_t*)pu;\n"
" return p[4];\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct S { uint8_t padding[500]; };\n" // #10133
"S s = { 0 };\n"
"uint8_t f() {\n"
" uint8_t* p = (uint8_t*)&s;\n"
" return p[10];\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct X {\n" // #2654
" int a;\n"
" char b;\n"
"};\n"
"void f() {\n"
" const X s;\n"
" const int* y = &s.a;\n"
" (void)y[0];\n"
" (void)y[1];\n"
" (void)y[2];\n"
"}\n");
TODO_ASSERT_EQUALS("error", "", errout_str());
}
void checkPipeParameterSize() { // #3521
const Settings settings = settingsBuilder().library("posix.cfg").build();
check("void f(){\n"
"int pipefd[1];\n" // <-- array of two integers is needed
"if (pipe(pipefd) == -1) {\n"
" return;\n"
" }\n"
"}", settings);
ASSERT_EQUALS("[test.cpp:3]: (error) Buffer is accessed out of bounds: pipefd\n", errout_str());
check("void f(){\n"
"int pipefd[2];\n"
"if (pipe(pipefd) == -1) {\n"
" return;\n"
" }\n"
"}", settings);
ASSERT_EQUALS("", errout_str());
check("void f(){\n"
"char pipefd[2];\n"
"if (pipe((int*)pipefd) == -1) {\n"
" return;\n"
" }\n"
"}", settings);
ASSERT_EQUALS("[test.cpp:3]: (error) Buffer is accessed out of bounds: (int*)pipefd\n", errout_str());
check("void f(){\n"
"char pipefd[20];\n" // Strange, but large enough
"if (pipe((int*)pipefd) == -1) {\n"
" return;\n"
" }\n"
"}", settings);
ASSERT_EQUALS("", errout_str());
}
};
REGISTER_TEST(TestBufferOverrun)
| null |
1,008 | cpp | cppcheck | precompiled.h | test/precompiled.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#pragma once
// IWYU pragma: begin_keep
#include "check.h"
#include "config.h"
#include "importproject.h"
#include "library.h"
#include "mathlib.h"
#include "settings.h"
#include "timer.h"
#include "token.h"
#include "tokenlist.h"
#include "tokenize.h"
// IWYU pragma: end_keep
| null |
1,009 | cpp | cppcheck | testsimplifytypedef.cpp | test/testsimplifytypedef.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#include "errortypes.h"
#include "fixture.h"
#include "helpers.h"
#include "platform.h"
#include "settings.h"
#include "standards.h"
#include "token.h"
#include "tokenize.h"
#include "tokenlist.h"
#include <cstddef>
#include <sstream>
#include <string>
#include <vector>
class TestSimplifyTypedef : public TestFixture {
public:
TestSimplifyTypedef() : TestFixture("TestSimplifyTypedef") {}
private:
const Settings settings0 = settingsBuilder().severity(Severity::style).build();
const Settings settings1 = settingsBuilder().severity(Severity::portability).build();
void run() override {
TEST_CASE(c1);
TEST_CASE(c2);
TEST_CASE(canreplace1);
TEST_CASE(canreplace2);
TEST_CASE(canreplace3);
TEST_CASE(canreplace4);
TEST_CASE(cconst);
TEST_CASE(cstruct1);
TEST_CASE(cstruct2);
TEST_CASE(cstruct3);
TEST_CASE(cstruct3);
TEST_CASE(cstruct4);
TEST_CASE(cenum1);
TEST_CASE(cfunction1);
TEST_CASE(cfunction2);
TEST_CASE(cfunction3);
TEST_CASE(cfunction4);
TEST_CASE(cfp1);
TEST_CASE(cfp2);
TEST_CASE(cfp4);
TEST_CASE(cfp5);
TEST_CASE(cfp6);
TEST_CASE(cfp7);
TEST_CASE(carray1);
TEST_CASE(carray2);
TEST_CASE(carray3);
TEST_CASE(carray4);
TEST_CASE(cdonotreplace1);
TEST_CASE(cppfp1);
TEST_CASE(Generic1);
TEST_CASE(simplifyTypedef1);
TEST_CASE(simplifyTypedef2);
TEST_CASE(simplifyTypedef3);
TEST_CASE(simplifyTypedef4);
TEST_CASE(simplifyTypedef5);
TEST_CASE(simplifyTypedef6);
TEST_CASE(simplifyTypedef7);
TEST_CASE(simplifyTypedef8);
TEST_CASE(simplifyTypedef9);
TEST_CASE(simplifyTypedef10);
TEST_CASE(simplifyTypedef11);
TEST_CASE(simplifyTypedef12);
TEST_CASE(simplifyTypedef13);
TEST_CASE(simplifyTypedef14);
TEST_CASE(simplifyTypedef15);
TEST_CASE(simplifyTypedef16);
TEST_CASE(simplifyTypedef17);
TEST_CASE(simplifyTypedef18); // typedef vector<int[4]> a;
TEST_CASE(simplifyTypedef19);
TEST_CASE(simplifyTypedef20);
TEST_CASE(simplifyTypedef21);
TEST_CASE(simplifyTypedef22);
TEST_CASE(simplifyTypedef23);
TEST_CASE(simplifyTypedef24);
TEST_CASE(simplifyTypedef25);
TEST_CASE(simplifyTypedef26);
TEST_CASE(simplifyTypedef27);
TEST_CASE(simplifyTypedef28);
TEST_CASE(simplifyTypedef29);
TEST_CASE(simplifyTypedef30);
TEST_CASE(simplifyTypedef31);
TEST_CASE(simplifyTypedef32);
TEST_CASE(simplifyTypedef33);
TEST_CASE(simplifyTypedef34); // ticket #1411
TEST_CASE(simplifyTypedef35);
TEST_CASE(simplifyTypedef36); // ticket #1434
TEST_CASE(simplifyTypedef37); // ticket #1449
TEST_CASE(simplifyTypedef38);
TEST_CASE(simplifyTypedef43); // ticket #1588
TEST_CASE(simplifyTypedef44);
TEST_CASE(simplifyTypedef45); // ticket #1613
TEST_CASE(simplifyTypedef46);
TEST_CASE(simplifyTypedef47);
TEST_CASE(simplifyTypedef48); // ticket #1673
TEST_CASE(simplifyTypedef49); // ticket #1691
TEST_CASE(simplifyTypedef50);
TEST_CASE(simplifyTypedef51);
TEST_CASE(simplifyTypedef52); // ticket #1782
TEST_CASE(simplifyTypedef54); // ticket #1814
TEST_CASE(simplifyTypedef55);
TEST_CASE(simplifyTypedef56); // ticket #1829
TEST_CASE(simplifyTypedef57); // ticket #1846
TEST_CASE(simplifyTypedef58); // ticket #1963
TEST_CASE(simplifyTypedef59); // ticket #2011
TEST_CASE(simplifyTypedef60); // ticket #2035
TEST_CASE(simplifyTypedef61); // ticket #2074 and 2075
TEST_CASE(simplifyTypedef62); // ticket #2082
TEST_CASE(simplifyTypedef63); // ticket #2175 'typedef float x[3];'
TEST_CASE(simplifyTypedef64);
TEST_CASE(simplifyTypedef65); // ticket #2314
TEST_CASE(simplifyTypedef66); // ticket #2341
TEST_CASE(simplifyTypedef67); // ticket #2354
TEST_CASE(simplifyTypedef68); // ticket #2355
TEST_CASE(simplifyTypedef69); // ticket #2348
TEST_CASE(simplifyTypedef70); // ticket #2348
TEST_CASE(simplifyTypedef71); // ticket #2348
TEST_CASE(simplifyTypedef72); // ticket #2375
TEST_CASE(simplifyTypedef73); // ticket #2412
TEST_CASE(simplifyTypedef74); // ticket #2414
TEST_CASE(simplifyTypedef75); // ticket #2426
TEST_CASE(simplifyTypedef76); // ticket #2453
TEST_CASE(simplifyTypedef77); // ticket #2554
TEST_CASE(simplifyTypedef78); // ticket #2568
TEST_CASE(simplifyTypedef79); // ticket #2348
TEST_CASE(simplifyTypedef80); // ticket #2587
TEST_CASE(simplifyTypedef81); // ticket #2603
TEST_CASE(simplifyTypedef82); // ticket #2403
TEST_CASE(simplifyTypedef83); // ticket #2620
TEST_CASE(simplifyTypedef84); // ticket #2630
TEST_CASE(simplifyTypedef85); // ticket #2651
TEST_CASE(simplifyTypedef86); // ticket #2581
TEST_CASE(simplifyTypedef87); // ticket #2651
TEST_CASE(simplifyTypedef88); // ticket #2675
TEST_CASE(simplifyTypedef89); // ticket #2717
TEST_CASE(simplifyTypedef90); // ticket #2718
TEST_CASE(simplifyTypedef91); // ticket #2716
TEST_CASE(simplifyTypedef92); // ticket #2736
TEST_CASE(simplifyTypedef93); // ticket #2738
TEST_CASE(simplifyTypedef94); // ticket #1982
TEST_CASE(simplifyTypedef95); // ticket #2844
TEST_CASE(simplifyTypedef96); // ticket #2886
TEST_CASE(simplifyTypedef97); // ticket #2983 (segmentation fault)
TEST_CASE(simplifyTypedef99); // ticket #2999
TEST_CASE(simplifyTypedef100); // ticket #3000
TEST_CASE(simplifyTypedef101); // ticket #3003 (segmentation fault)
TEST_CASE(simplifyTypedef102); // ticket #3004
TEST_CASE(simplifyTypedef103); // ticket #3007
TEST_CASE(simplifyTypedef104); // ticket #3070
TEST_CASE(simplifyTypedef105); // ticket #3616
TEST_CASE(simplifyTypedef106); // ticket #3619
TEST_CASE(simplifyTypedef107); // ticket #3963 - bad code => segmentation fault
TEST_CASE(simplifyTypedef108); // ticket #4777
TEST_CASE(simplifyTypedef109); // ticket #1823 - rvalue reference
TEST_CASE(simplifyTypedef110); // ticket #6268
TEST_CASE(simplifyTypedef111); // ticket #6345
TEST_CASE(simplifyTypedef112); // ticket #6048
TEST_CASE(simplifyTypedef113); // ticket #7030
TEST_CASE(simplifyTypedef114); // ticket #7058 - skip "struct", AB::..
TEST_CASE(simplifyTypedef115); // ticket #6998
TEST_CASE(simplifyTypedef116); // ticket #5624
TEST_CASE(simplifyTypedef117); // ticket #6507
TEST_CASE(simplifyTypedef118); // ticket #5749
TEST_CASE(simplifyTypedef119); // ticket #7541
TEST_CASE(simplifyTypedef120); // ticket #8357
TEST_CASE(simplifyTypedef121); // ticket #5766
TEST_CASE(simplifyTypedef122); // segmentation fault
TEST_CASE(simplifyTypedef123); // ticket #7406
TEST_CASE(simplifyTypedef124); // ticket #7792
TEST_CASE(simplifyTypedef125); // #8749 - typedef char A[10]; p = new A[1];
TEST_CASE(simplifyTypedef126); // ticket #5953
TEST_CASE(simplifyTypedef127); // ticket #8878
TEST_CASE(simplifyTypedef128); // ticket #9053
TEST_CASE(simplifyTypedef129);
TEST_CASE(simplifyTypedef130); // ticket #9446
TEST_CASE(simplifyTypedef131); // ticket #9446
TEST_CASE(simplifyTypedef132); // ticket #9739 - using
TEST_CASE(simplifyTypedef133); // ticket #9812 - using
TEST_CASE(simplifyTypedef134);
TEST_CASE(simplifyTypedef135); // ticket #10068
TEST_CASE(simplifyTypedef136);
TEST_CASE(simplifyTypedef137);
TEST_CASE(simplifyTypedef138);
TEST_CASE(simplifyTypedef139);
TEST_CASE(simplifyTypedef140); // #10798
TEST_CASE(simplifyTypedef141); // #10144
TEST_CASE(simplifyTypedef142); // T() when T is a pointer type
TEST_CASE(simplifyTypedef143); // #11506
TEST_CASE(simplifyTypedef144); // #9353
TEST_CASE(simplifyTypedef145); // #9353
TEST_CASE(simplifyTypedef146);
TEST_CASE(simplifyTypedef147);
TEST_CASE(simplifyTypedef148);
TEST_CASE(simplifyTypedef149);
TEST_CASE(simplifyTypedef150);
TEST_CASE(simplifyTypedef151);
TEST_CASE(simplifyTypedef152);
TEST_CASE(simplifyTypedef153);
TEST_CASE(simplifyTypedef154);
TEST_CASE(simplifyTypedef155);
TEST_CASE(simplifyTypedef156);
TEST_CASE(simplifyTypedef157);
TEST_CASE(simplifyTypedefFunction1);
TEST_CASE(simplifyTypedefFunction2); // ticket #1685
TEST_CASE(simplifyTypedefFunction3);
TEST_CASE(simplifyTypedefFunction4);
TEST_CASE(simplifyTypedefFunction5);
TEST_CASE(simplifyTypedefFunction6);
TEST_CASE(simplifyTypedefFunction7);
TEST_CASE(simplifyTypedefFunction8);
TEST_CASE(simplifyTypedefFunction9);
TEST_CASE(simplifyTypedefFunction10); // #5191
TEST_CASE(simplifyTypedefFunction11);
TEST_CASE(simplifyTypedefStruct); // #12081 - volatile struct
TEST_CASE(simplifyTypedefShadow); // #4445 - shadow variable
TEST_CASE(simplifyTypedefMacro);
TEST_CASE(simplifyTypedefOriginalName);
TEST_CASE(simplifyTypedefTokenColumn1);
TEST_CASE(simplifyTypedefTokenColumn2);
TEST_CASE(simplifyTypedefTokenColumn3);
TEST_CASE(typedefInfo1);
TEST_CASE(typedefInfo2);
}
#define tok(...) tok_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
std::string tok_(const char* file, int line, const char (&code)[size], bool simplify = true, Platform::Type type = Platform::Type::Native, bool debugwarnings = true) {
// show warnings about unhandled typedef
const Settings settings = settingsBuilder(settings0).certainty(Certainty::inconclusive).debugwarnings(debugwarnings).platform(type).build();
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
return tokenizer.tokens()->stringifyList(nullptr, !simplify);
}
std::string simplifyTypedef(const char code[]) {
Tokenizer tokenizer(settings1, *this);
std::istringstream istr(code);
if (!tokenizer.list.createTokens(istr, Standards::Language::CPP))
return "";
tokenizer.createLinks();
tokenizer.simplifyTypedef();
return tokenizer.tokens()->stringifyList(nullptr, false);
}
std::string simplifyTypedefP(const char code[]) {
std::vector<std::string> files(1, "test.cpp");
Tokenizer tokenizer(settings0, *this);
PreprocessorHelper::preprocess(code, files, tokenizer, *this);
// Tokenize..
tokenizer.createLinks();
tokenizer.simplifyTypedef();
return tokenizer.tokens()->stringifyList(nullptr, false);
}
#define checkSimplifyTypedef(code) checkSimplifyTypedef_(code, __FILE__, __LINE__)
template<size_t size>
void checkSimplifyTypedef_(const char (&code)[size], const char* file, int line) {
// Tokenize..
// show warnings about unhandled typedef
const Settings settings = settingsBuilder(settings0).certainty(Certainty::inconclusive).debugwarnings().build();
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
}
std::string simplifyTypedefC(const char code[]) {
Tokenizer tokenizer(settings1, *this);
std::istringstream istr(code);
if (!tokenizer.list.createTokens(istr, "file.c"))
return "";
tokenizer.createLinks();
tokenizer.simplifyTypedef();
try {
tokenizer.validate();
} catch (const InternalError&) {
return "";
}
return tokenizer.tokens()->stringifyList(nullptr, false);
}
std::string dumpTypedefInfo(const char code[]) {
Tokenizer tokenizer(settings1, *this);
std::istringstream istr(code);
if (!tokenizer.list.createTokens(istr, "file.c"))
return {};
tokenizer.createLinks();
tokenizer.simplifyTypedef();
try {
tokenizer.validate();
} catch (const InternalError&) {
return {};
}
return tokenizer.dumpTypedefInfo();
}
void c1() {
const char code[] = "typedef int t;\n"
"t x;";
ASSERT_EQUALS("int x ;", simplifyTypedefC(code));
}
void c2() {
const char code[] = "void f1() { typedef int t; t x; }\n"
"void f2() { typedef float t; t x; }\n";
ASSERT_EQUALS("void f1 ( ) { int x ; } void f2 ( ) { float x ; }", simplifyTypedefC(code));
}
void canreplace1() {
const char code[] = "typedef unsigned char u8;\n"
"void f(uint8_t u8) { x = u8 & y; }\n";
ASSERT_EQUALS("void f ( uint8_t u8 ) { x = u8 & y ; }", simplifyTypedefC(code));
}
void canreplace2() {
const char code1[] = "typedef char* entry;\n"
"void f(Y* entry) { for (entry=x->y; entry; entry = entry->next) {} }\n";
ASSERT_EQUALS("void f ( Y * entry ) { for ( entry = x -> y ; entry ; entry = entry -> next ) { } }", simplifyTypedefC(code1));
const char code2[] = "typedef char* entry;\n"
"void f() { dostuff(entry * 2); }\n";
ASSERT_EQUALS("void f ( ) { dostuff ( entry * 2 ) ; }", simplifyTypedefC(code2));
const char code3[] = "typedef char* entry;\n"
"void f() { dostuff(entry * y < z); }\n";
ASSERT_EQUALS("void f ( ) { dostuff ( entry * y < z ) ; }", simplifyTypedefC(code3));
}
void canreplace3() {
const char code1[] = "typedef char* c_str;\n" // #11640
"struct S {\n"
" const char* g() const {\n"
" return s.c_str();\n"
" }\n"
" std::string s;\n"
"};\n";
ASSERT_EQUALS("struct S { const char * g ( ) const { return s . c_str ( ) ; } std :: string s ; } ;", simplifyTypedefC(code1));
}
void canreplace4() {
const char code1[] = "typedef std::vector<int> X;\n" // #12026
"struct S {\n"
" enum E { X };\n"
"};\n";
ASSERT_EQUALS("struct S { enum E { X } ; } ;", simplifyTypedef(code1));
}
void cconst() {
const char code1[] = "typedef void* HWND;\n"
"const HWND x;";
ASSERT_EQUALS("void * const x ;", simplifyTypedef(code1));
const char code2[] = "typedef void (*fp)();\n"
"const fp x;";
ASSERT_EQUALS("void ( * const x ) ( ) ;", simplifyTypedef(code2));
}
void cstruct1() {
const char code[] = "typedef struct { int a; int b; } t;\n"
"t x;";
ASSERT_EQUALS("struct t { int a ; int b ; } ; struct t x ;", simplifyTypedef(code));
ASSERT_EQUALS("struct t { int a ; int b ; } ; struct t x ;", simplifyTypedefC(code));
}
void cstruct2() {
const char code[] = "typedef enum { A, B } t;\n"
"t x;";
ASSERT_EQUALS("enum t { A , B } ; enum t x ;", simplifyTypedef(code));
ASSERT_EQUALS("enum t { A , B } ; enum t x ;", simplifyTypedefC(code));
}
void cstruct3() {
const char code[] = "typedef struct s { int a; int b; } t;\n"
"t x;";
ASSERT_EQUALS("struct s { int a ; int b ; } ; struct s x ;", simplifyTypedefC(code));
}
void cstruct4() {
const char code[] = "typedef struct s { int a; int b; } t;\n"
"struct t x{};";
ASSERT_EQUALS("struct s { int a ; int b ; } ; struct s x { } ;", simplifyTypedefC(code));
}
void cenum1() {
const char code[] = "typedef enum { a, b } E;\n"
"E e;";
ASSERT_EQUALS("enum E { a , b } ; enum E e ;", simplifyTypedefC(code));
}
void cfunction1() {
const char code[] = "typedef int callback(int);\n"
"callback* cb;";
ASSERT_EQUALS("int ( * cb ) ( int ) ;", simplifyTypedefC(code));
}
void cfunction2() {
const char code[] = "typedef int callback(int);\n"
"typedef callback* callbackPtr;\n"
"callbackPtr cb;";
ASSERT_EQUALS("int ( * cb ) ( int ) ;", simplifyTypedefC(code));
}
void cfunction3() {
const char code[] = "typedef int f(int);\n"
"typedef const f cf;\n";
(void)simplifyTypedefC(code);
ASSERT_EQUALS("[file.c:2]: (portability) It is unspecified behavior to const qualify a function type.\n", errout_str());
}
void cfunction4() {
const char code[] = "typedef int (func_t) (int);\n" // #12625
"int f(int*, func_t*, int);\n";
ASSERT_EQUALS("int f ( int * , int ( * ) ( int ) , int ) ;", simplifyTypedefC(code));
}
void cfp1() {
const char code[] = "typedef void (*fp)(void * p);\n"
"fp x;";
ASSERT_EQUALS("void ( * x ) ( void * p ) ;", simplifyTypedefC(code));
}
void cfp2() {
const char code[] = "typedef void (*const fp)(void * p);\n"
"fp x;";
ASSERT_EQUALS("void ( * const x ) ( void * p ) ;", simplifyTypedefC(code));
}
void cfp4() {
const char code[] = "typedef struct S Stype ;\n"
"typedef void ( * F ) ( Stype * ) ;\n"
"F func;";
ASSERT_EQUALS("void ( * func ) ( struct S * ) ;", simplifyTypedefC(code));
}
void cfp5() {
const char code[] = "typedef void (*fp)(void);\n"
"typedef fp t;\n"
"void foo(t p);";
ASSERT_EQUALS("void foo ( void ( * p ) ( void ) ) ;", simplifyTypedef(code));
}
void cfp6() {
const char code[] = "typedef void (*fp)(void);\n"
"fp a[10];";
ASSERT_EQUALS("void ( * a [ 10 ] ) ( void ) ;", simplifyTypedef(code));
}
void cfp7() {
const char code[] = "typedef uint32_t ((*fp)(uint32_t n));\n" // #11725
"uint32_t g();\n"
"fp f;\n";
ASSERT_EQUALS("uint32_t g ( ) ; uint32_t ( * f ) ( uint32_t n ) ;", simplifyTypedef(code));
}
void carray1() {
const char code[] = "typedef int t[20];\n"
"t x;";
ASSERT_EQUALS("int x [ 20 ] ;", simplifyTypedefC(code));
}
void carray2() {
const char code[] = "typedef double t[4];\n"
"t x[10];";
ASSERT_EQUALS("double x [ 10 ] [ 4 ] ;", simplifyTypedef(code));
}
void carray3() {
const char* code{};
code = "typedef int a[256];\n" // #11689
"typedef a b[256];\n"
"b* p;\n";
ASSERT_EQUALS("int ( * p ) [ 256 ] [ 256 ] ;", simplifyTypedef(code));
code = "typedef int a[1];\n"
"typedef a b[2];\n"
"typedef b c[3];\n"
"c* p;\n";
ASSERT_EQUALS("int ( * p ) [ 3 ] [ 2 ] [ 1 ] ;", simplifyTypedef(code));
}
void carray4() {
const char code[] = "typedef int arr[12];\n" // #12019
"void foo() { arr temp = {0}; }\n";
ASSERT_EQUALS("void foo ( ) { int temp [ 12 ] = { 0 } ; }", tok(code));
}
void cdonotreplace1() {
const char code[] = "typedef int t;\n"
"int* t;";
ASSERT_EQUALS("int * t ;", simplifyTypedefC(code));
}
void cppfp1() {
const char code[] = "typedef void (*fp)(void);\n"
"typedef fp t;\n"
"void foo(t p);";
ASSERT_EQUALS("void foo ( void ( * p ) ( void ) ) ;", tok(code));
}
void Generic1() {
const char code[] = "typedef void func(void);\n"
"_Generic((x), func: 1, default: 2);";
ASSERT_EQUALS("_Generic ( x , void ( ) : 1 , default : 2 ) ;", tok(code));
}
void simplifyTypedef1() {
const char code[] = "class A\n"
"{\n"
"public:\n"
" typedef wchar_t duplicate;\n"
" void foo() {}\n"
"};\n"
"typedef A duplicate;\n"
"int main()\n"
"{\n"
" duplicate a;\n"
" a.foo();\n"
" A::duplicate c = 0;\n"
"}";
const char expected[] =
"class A "
"{ "
"public: "
""
"void foo ( ) { } "
"} ; "
"int main ( ) "
"{ "
"A a ; "
"a . foo ( ) ; "
"wchar_t c ; c = 0 ; "
"}";
ASSERT_EQUALS(expected, tok(code, false));
}
void simplifyTypedef2() {
const char code[] = "class A;\n"
"typedef A duplicate;\n"
"class A\n"
"{\n"
"public:\n"
"typedef wchar_t duplicate;\n"
"duplicate foo() { wchar_t b; return b; }\n"
"};";
const char expected[] =
"class A ; "
"class A "
"{ "
"public: "
""
"wchar_t foo ( ) { wchar_t b ; return b ; } "
"} ;";
ASSERT_EQUALS(expected, tok(code));
}
void simplifyTypedef3() {
const char code[] = "class A {};\n"
"typedef A duplicate;\n"
"wchar_t foo()\n"
"{\n"
"typedef wchar_t duplicate;\n"
"duplicate b;\n"
"return b;\n"
"}\n"
"int main()\n"
"{\n"
"duplicate b;\n"
"}";
const char expected[] =
"class A { } ; "
"wchar_t foo ( ) "
"{ "
""
"wchar_t b ; "
"return b ; "
"} "
"int main ( ) "
"{ "
"A b ; "
"}";
ASSERT_EQUALS(expected, tok(code));
}
void simplifyTypedef4() {
const char code[] = "typedef int s32;\n"
"typedef unsigned int u32;\n"
"void f()\n"
"{\n"
" s32 ivar = -2;\n"
" u32 uvar = 2;\n"
" return uvar / ivar;\n"
"}";
const char expected[] =
"void f ( ) "
"{ "
"int ivar ; ivar = -2 ; "
"unsigned int uvar ; uvar = 2 ; "
"return uvar / ivar ; "
"}";
ASSERT_EQUALS(expected, tok(code, false));
}
void simplifyTypedef5() {
// ticket #780
const char code[] =
"typedef struct yy_buffer_state *YY_BUFFER_STATE;\n"
"void f()\n"
"{\n"
" YY_BUFFER_STATE state;\n"
"}";
const char expected[] =
"void f ( ) "
"{ "
"struct yy_buffer_state * state ; "
"}";
ASSERT_EQUALS(expected, tok(code, false));
}
void simplifyTypedef6() {
// ticket #983
const char code[] =
"namespace VL {\n"
" typedef float float_t ;\n"
" inline VL::float_t fast_atan2(VL::float_t y, VL::float_t x){}\n"
"}";
const char expected[] =
"namespace VL { "
""
"float fast_atan2 ( float y , float x ) { } "
"}";
ASSERT_EQUALS(expected, tok(code, false));
// ticket #11373
const char code1[] =
"typedef int foo;\n"
"inline foo f();\n";
const char expected1[] = "int f ( ) ;";
ASSERT_EQUALS(expected1, tok(code1, false));
}
void simplifyTypedef7() {
const char code[] = "typedef int abc ; "
"Fred :: abc f ;";
const char expected[] = "Fred :: abc f ;";
ASSERT_EQUALS(expected, tok(code, false));
}
void simplifyTypedef8() {
const char code[] = "typedef int INT;\n"
"typedef unsigned int UINT;\n"
"typedef int * PINT;\n"
"typedef unsigned int * PUINT;\n"
"typedef int & RINT;\n"
"typedef unsigned int & RUINT;\n"
"typedef const int & RCINT;\n"
"typedef const unsigned int & RCUINT;\n"
"INT ti;\n"
"UINT tui;\n"
"PINT tpi;\n"
"PUINT tpui;\n"
"RINT tri;\n"
"RUINT trui;\n"
"RCINT trci;\n"
"RCUINT trcui;";
const char expected[] =
"int ti ; "
"unsigned int tui ; "
"int * tpi ; "
"unsigned int * tpui ; "
"int & tri ; "
"unsigned int & trui ; "
"const int & trci ; "
"const unsigned int & trcui ;";
ASSERT_EQUALS(expected, tok(code, false));
}
void simplifyTypedef9() {
const char code[] = "typedef struct s S, * PS;\n"
"typedef struct t { int a; } T, *TP;\n"
"typedef struct { int a; } U;\n"
"typedef struct { int a; } * V;\n"
"S s;\n"
"PS ps;\n"
"T t;\n"
"TP tp;\n"
"U u;\n"
"V v;";
const char expected[] =
"struct t { int a ; } ; "
"struct U { int a ; } ; "
"struct V { int a ; } ; "
"struct s s ; "
"struct s * ps ; "
"struct t t ; "
"struct t * tp ; "
"struct U u ; "
"struct V * v ;";
ASSERT_EQUALS(expected, tok(code, false));
}
void simplifyTypedef10() {
const char code[] = "typedef union s S, * PS;\n"
"typedef union t { int a; float b ; } T, *TP;\n"
"typedef union { int a; float b; } U;\n"
"typedef union { int a; float b; } * V;\n"
"S s;\n"
"PS ps;\n"
"T t;\n"
"TP tp;\n"
"U u;\n"
"V v;";
const char expected[] =
"union t { int a ; float b ; } ; "
"union U { int a ; float b ; } ; "
"union V { int a ; float b ; } ; "
"union s s ; "
"union s * ps ; "
"union t t ; "
"union t * tp ; "
"union U u ; "
"union V * v ;";
ASSERT_EQUALS(expected, tok(code, false));
}
void simplifyTypedef11() {
const char code[] = "typedef enum { a = 0 , b = 1 , c = 2 } abc;\n"
"typedef enum xyz { x = 0 , y = 1 , z = 2 } XYZ;\n"
"abc e1;\n"
"XYZ e2;";
const char expected[] = "enum abc { a = 0 , b = 1 , c = 2 } ; "
"enum xyz { x = 0 , y = 1 , z = 2 } ; "
"enum abc e1 ; "
"enum xyz e2 ;";
ASSERT_EQUALS(expected, tok(code, false));
}
void simplifyTypedef12() {
const char code[] = "typedef vector<int> V1;\n"
"typedef std::vector<int> V2;\n"
"typedef std::vector<std::vector<int> > V3;\n"
"typedef std::list<int>::iterator IntListIterator;\n"
"V1 v1;\n"
"V2 v2;\n"
"V3 v3;\n"
"IntListIterator iter;";
const char expected[] =
"vector < int > v1 ; "
"std :: vector < int > v2 ; "
"std :: vector < std :: vector < int > > v3 ; "
"std :: list < int > :: iterator iter ;";
ASSERT_EQUALS(expected, tok(code, false));
}
void simplifyTypedef13() {
// ticket # 1167 (InternalError)
const char code[] = "typedef std::pair<int(*)(void*), void*> Func;"
"typedef std::vector<Func> CallQueue;"
"int main() {}";
// Tokenize and check output..
ASSERT_NO_THROW(tok(code));
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef14() {
// ticket # 1232
const char code[] = "template <typename F, unsigned int N> struct E"
"{"
" typedef E<F,(N>0)?(N-1):0> v;"
" typedef typename add<v,v>::val val;"
" FP_M(val);"
"};"
"template <typename F> struct E <F,0>"
"{"
" typedef typename D<1>::val val;"
" FP_M(val);"
"};";
// Tokenize and check output..
TODO_ASSERT_THROW(tok(code, true, Platform::Type::Native, false), InternalError); // TODO: Do not throw exception
//ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef15() {
{
const char code[] = "typedef char frame[10];\n"
"frame f;";
const char expected[] = "char f [ 10 ] ;";
ASSERT_EQUALS(expected, tok(code, false));
}
{
const char code[] = "typedef unsigned char frame[10];\n"
"frame f;";
const char expected[] = "unsigned char f [ 10 ] ;";
ASSERT_EQUALS(expected, tok(code, false));
}
}
void simplifyTypedef16() {
// ticket # 1252 (InternalError)
const char code[] = "typedef char MOT8;\n"
"typedef MOT8 CHFOO[4096];\n"
"typedef struct {\n"
" CHFOO freem;\n"
"} STRFOO;";
// Tokenize and check output..
ASSERT_NO_THROW(tok(code));
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef17() {
const char code[] = "typedef char * PCHAR, CHAR;\n"
"PCHAR pc;\n"
"CHAR c;";
const char expected[] =
"char * pc ; "
"char c ;";
ASSERT_EQUALS(expected, tok(code, false));
}
void simplifyTypedef18() {
const char code[] = "typedef vector<int[4]> a;\n"
"a b;";
ASSERT_EQUALS("vector < int [ 4 ] > b ;", tok(code));
}
void simplifyTypedef19() {
{
// ticket #1275
const char code[] = "typedef struct {} A, *B, **C;\n"
"A a;\n"
"B b;\n"
"C c;";
const char expected[] =
"struct A { } ; "
"struct A a ; "
"struct A * b ; "
"struct A * * c ;";
ASSERT_EQUALS(expected, tok(code, false));
}
{
const char code[] = "typedef struct {} A, *********B;\n"
"A a;\n"
"B b;";
const char expected[] =
"struct A { } ; "
"struct A a ; "
"struct A * * * * * * * * * b ;";
ASSERT_EQUALS(expected, tok(code, false));
}
{
const char code[] = "typedef struct {} **********A, *B, C;\n"
"A a;\n"
"B b;\n"
"C c;";
const char expected[] =
"struct Unnamed0 { } ; "
"struct Unnamed0 * * * * * * * * * * a ; "
"struct Unnamed0 * b ; "
"struct Unnamed0 c ;";
ASSERT_EQUALS(expected, tok(code, false));
}
}
void simplifyTypedef20() {
// ticket #1284
const char code[] = "typedef jobject invoke_t (jobject, Proxy *, Method *, JArray< jobject > *);";
ASSERT_EQUALS(";", tok(code));
}
void simplifyTypedef21() {
const char code[] = "typedef void (* PF)();\n"
"typedef void * (* PFV)(void *);\n"
"PF pf;\n"
"PFV pfv;";
const char expected[] =
""
""
"void ( * pf ) ( ) ; "
"void * ( * pfv ) ( void * ) ;";
ASSERT_EQUALS(expected, simplifyTypedef(code));
}
void simplifyTypedef22() {
{
const char code[] = "class Fred {\n"
" typedef void (*testfp)();\n"
" testfp get() { return test; }\n"
" static void test() { }\n"
"};";
const char expected[] =
"class Fred { "
""
"void * get ( ) { return test ; } "
"static void test ( ) { } "
"} ;";
ASSERT_EQUALS(expected, tok(code, false));
}
{
const char code[] = "class Fred {\n"
" typedef void * (*testfp)(void *);\n"
" testfp get() { return test; }\n"
" static void * test(void * p) { return p; }\n"
"};";
const char expected[] =
"class Fred { "
""
"void * * get ( ) { return test ; } "
"static void * test ( void * p ) { return p ; } "
"} ;";
ASSERT_EQUALS(expected, tok(code, false));
}
{
const char code[] = "class Fred {\n"
" typedef unsigned int * (*testfp)(unsigned int *);\n"
" testfp get() { return test; }\n"
" static unsigned int * test(unsigned int * p) { return p; }\n"
"};";
const char expected[] =
"class Fred { "
""
"unsigned int * * get ( ) { return test ; } "
"static unsigned int * test ( unsigned int * p ) { return p ; } "
"} ;";
ASSERT_EQUALS(expected, tok(code, false));
}
{
const char code[] = "class Fred {\n"
" typedef const unsigned int * (*testfp)(const unsigned int *);\n"
" testfp get() { return test; }\n"
" static const unsigned int * test(const unsigned int * p) { return p; }\n"
"};";
// static const gets changed to const static
const char expected[] =
"class Fred { "
""
"const unsigned int * * get ( ) { return test ; } "
"static const unsigned int * test ( const unsigned int * p ) { return p ; } "
"} ;";
ASSERT_EQUALS(expected, tok(code, false));
}
{
const char code[] = "class Fred {\n"
" typedef void * (*testfp)(void *);\n"
" testfp get(int i) { return test; }\n"
" static void * test(void * p) { return p; }\n"
"};";
const char expected[] =
"class Fred { "
""
"void * * get ( int i ) { return test ; } "
"static void * test ( void * p ) { return p ; } "
"} ;";
ASSERT_EQUALS(expected, tok(code, false));
}
}
void simplifyTypedef23() {
const char code[] = "typedef bool (*Callback) (int i);\n"
"void addCallback(Callback callback) { }\n"
"void addCallback1(Callback callback, int j) { }";
const char expected[] =
"void addCallback ( bool ( * callback ) ( int ) ) { } "
"void addCallback1 ( bool ( * callback ) ( int ) , int j ) { }";
ASSERT_EQUALS(expected, tok(code, false));
}
void simplifyTypedef24() {
{
const char code[] = "typedef int (*fp)();\n"
"void g( fp f )\n"
"{\n"
" fp f2 = (fp)f;\n"
"}";
const char expected[] =
"void g ( int ( * f ) ( ) ) "
"{ "
"int ( * f2 ) ( ) ; f2 = ( int * ) f ; "
"}";
ASSERT_EQUALS(expected, tok(code, false));
}
{
const char code[] = "typedef int (*fp)();\n"
"void g( fp f )\n"
"{\n"
" fp f2 = static_cast<fp>(f);\n"
"}";
const char expected[] =
"void g ( int ( * f ) ( ) ) "
"{ "
"int ( * f2 ) ( ) ; f2 = static_cast < int * > ( f ) ; "
"}";
ASSERT_EQUALS(expected, tok(code, false));
}
}
void simplifyTypedef25() {
{
// ticket #1298
const char code[] = "typedef void (*fill_names_f) (const char *);\n"
"struct vfs_class {\n"
" void (*fill_names) (struct vfs_class *me, fill_names_f);\n"
"}";
const char expected[] =
"struct vfs_class { "
"void ( * fill_names ) ( struct vfs_class * me , void ( * ) ( const char * ) ) ; "
"}";
ASSERT_EQUALS(expected, simplifyTypedef(code));
}
{
const char code[] = "typedef void (*fill_names_f) (const char *);\n"
"struct vfs_class {\n"
" void (*fill_names) (fill_names_f, struct vfs_class *me);\n"
"}";
const char expected[] =
"struct vfs_class { "
"void ( * fill_names ) ( void ( * ) ( const char * ) , struct vfs_class * me ) ; "
"}";
ASSERT_EQUALS(expected, simplifyTypedef(code));
}
}
void simplifyTypedef26() {
{
const char code[] = "typedef void (*Callback) ();\n"
"void addCallback(Callback (*callback)());";
const char expected[] = "void addCallback ( void ( * ( * callback ) ( ) ) ( ) ) ;";
ASSERT_EQUALS(expected, tok(code, false));
}
{
// ticket # 1307
const char code[] = "typedef void (*pc_video_update_proc)(bitmap_t *bitmap,\n"
"struct mscrtc6845 *crtc);\n"
"\n"
"struct mscrtc6845 *pc_video_start(pc_video_update_proc (*choosevideomode)(running_machine *machine, int *width, int *height, struct mscrtc6845 *crtc));";
const char expected[] = "struct mscrtc6845 * pc_video_start ( void ( * ( * choosevideomode ) ( running_machine * machine , int * width , int * height , struct mscrtc6845 * crtc ) ) ( bitmap_t * bitmap , struct mscrtc6845 * crtc ) ) ;";
ASSERT_EQUALS(expected, tok(code, false));
}
}
void simplifyTypedef27() {
// ticket #1316
const char code[] = "int main()\n"
"{\n"
" typedef int (*func_ptr)(float, double);\n"
" VERIFY((is_same<result_of<func_ptr(char, float)>::type, int>::value));\n"
"}";
const char expected[] =
"int main ( ) "
"{ "
""
"VERIFY ( ( is_same < result_of < int ( * ( char , float ) ) ( float , double ) > :: type , int > :: value ) ) ; "
"}";
ASSERT_EQUALS(expected, tok(code, false));
ASSERT_EQUALS(
"[test.cpp:4]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable value\n",
errout_str());
}
void simplifyTypedef28() {
const char code[] = "typedef std::pair<double, double> (*F)(double);\n"
"F f;";
const char expected[] = "std :: pair < double , double > ( * f ) ( double ) ;";
ASSERT_EQUALS(expected, tok(code, false));
}
void simplifyTypedef29() {
const char code[] = "typedef int array [ice_or<is_int<int>::value, is_int<UDT>::value>::value ? 1 : -1];\n"
"typedef int array1 [N];\n"
"typedef int array2 [N][M];\n"
"typedef int int_t, int_array[N];\n"
"array a;\n"
"array1 a1;\n"
"array2 a2;\n"
"int_t t;\n"
"int_array ia;";
const char expected[] =
"int a [ ice_or < is_int < int > :: value , is_int < UDT > :: value > :: value ? 1 : -1 ] ; "
"int a1 [ N ] ; "
"int a2 [ N ] [ M ] ; "
"int t ; "
"int ia [ N ] ;";
ASSERT_EQUALS(expected, tok(code, false));
}
void simplifyTypedef30() {
const char code[] = "typedef ::std::list<int> int_list;\n"
"typedef ::std::list<int>::iterator int_list_iterator;\n"
"typedef ::std::list<int> int_list_array[10];\n"
"int_list il;\n"
"int_list_iterator ili;\n"
"int_list_array ila;";
const char expected[] =
":: std :: list < int > il ; "
":: std :: list < int > :: iterator ili ; "
":: std :: list < int > ila [ 10 ] ;";
ASSERT_EQUALS(expected, tok(code, false));
}
void simplifyTypedef31() {
{
const char code[] = "class A {\n"
"public:\n"
" typedef int INT;\n"
" INT get() const;\n"
" void put(INT x) { a = x; }\n"
" INT a;\n"
"};\n"
"A::INT A::get() const { return a; }\n"
"A::INT i = A::a;";
const char expected[] = "class A { "
"public: "
""
"int get ( ) const ; "
"void put ( int x ) { a = x ; } "
"int a ; "
"} ; "
"int A :: get ( ) const { return a ; } "
"int i ; i = A :: a ;";
ASSERT_EQUALS(expected, tok(code, false));
}
{
const char code[] = "struct A {\n"
" typedef int INT;\n"
" INT get() const;\n"
" void put(INT x) { a = x; }\n"
" INT a;\n"
"};\n"
"A::INT A::get() const { return a; }\n"
"A::INT i = A::a;";
const char expected[] = "struct A { "
""
"int get ( ) const ; "
"void put ( int x ) { a = x ; } "
"int a ; "
"} ; "
"int A :: get ( ) const { return a ; } "
"int i ; i = A :: a ;";
ASSERT_EQUALS(expected, tok(code, false));
}
}
void simplifyTypedef32() {
const char code[] = "typedef char CHAR;\n"
"typedef CHAR * LPSTR;\n"
"typedef const CHAR * LPCSTR;\n"
"CHAR c;\n"
"LPSTR cp;\n"
"LPCSTR ccp;";
const char expected[] =
"; char c ; "
"char * cp ; "
"const char * ccp ;";
ASSERT_EQUALS(expected, tok(code, false));
}
void simplifyTypedef33() {
const char code[] = "class A {\n"
"public:\n"
" typedef char CHAR_A;\n"
" CHAR_A funA();\n"
" class B {\n"
" public:\n"
" typedef short SHRT_B;\n"
" SHRT_B funB();\n"
" class C {\n"
" public:\n"
" typedef int INT_C;\n"
" INT_C funC();\n"
" struct D {\n"
" typedef long LONG_D;\n"
" LONG_D funD();\n"
" LONG_D d;\n"
" };\n"
" INT_C c;\n"
" };\n"
" SHRT_B b;\n"
" };\n"
" CHAR_A a;\n"
"};\n"
"A::CHAR_A A::funA() { return a; }\n"
"A::B::SHRT_B A::B::funB() { return b; }\n"
"A::B::C::INT_C A::B::C::funC() { return c; }"
"A::B::C::D::LONG_D A::B::C::D::funD() { return d; }";
const char codeFullSpecified[] = "class A {\n"
"public:\n"
" typedef char CHAR_A;\n"
" A::CHAR_A funA();\n"
" class B {\n"
" public:\n"
" typedef short SHRT_B;\n"
" A::B::SHRT_B funB();\n"
" class C {\n"
" public:\n"
" typedef int INT_C;\n"
" A::B::C::INT_C funC();\n"
" struct D {\n"
" typedef long LONG_D;\n"
" A::B::C::D::LONG_D funD();\n"
" A::B::C::D::LONG_D d;\n"
" };\n"
" A::B::C::INT_C c;\n"
" };\n"
" A::B::SHRT_B b;\n"
" };\n"
" A::CHAR_A a;\n"
"};\n"
"A::CHAR_A A::funA() { return a; }\n"
"A::B::SHRT_B A::B::funB() { return b; }\n"
"A::B::C::INT_C A::B::C::funC() { return c; }"
"A::B::C::D::LONG_D A::B::C::D::funD() { return d; }";
const char codePartialSpecified[] = "class A {\n"
"public:\n"
" typedef char CHAR_A;\n"
" CHAR_A funA();\n"
" class B {\n"
" public:\n"
" typedef short SHRT_B;\n"
" B::SHRT_B funB();\n"
" class C {\n"
" public:\n"
" typedef int INT_C;\n"
" C::INT_C funC();\n"
" struct D {\n"
" typedef long LONG_D;\n"
" D::LONG_D funD();\n"
" C::D::LONG_D d;\n"
" };\n"
" B::C::INT_C c;\n"
" };\n"
" B::SHRT_B b;\n"
" };\n"
" CHAR_A a;\n"
"};\n"
"A::CHAR_A A::funA() { return a; }\n"
"A::B::SHRT_B A::B::funB() { return b; }\n"
"A::B::C::INT_C A::B::C::funC() { return c; }"
"A::B::C::D::LONG_D A::B::C::D::funD() { return d; }";
const char expected[] =
"class A { "
"public: "
""
"char funA ( ) ; "
"class B { "
"public: "
""
"short funB ( ) ; "
"class C { "
"public: "
""
"int funC ( ) ; "
"struct D { "
""
"long funD ( ) ; "
"long d ; "
"} ; "
"int c ; "
"} ; "
"short b ; "
"} ; "
"char a ; "
"} ; "
"char A :: funA ( ) { return a ; } "
"short A :: B :: funB ( ) { return b ; } "
"int A :: B :: C :: funC ( ) { return c ; } "
"long A :: B :: C :: D :: funD ( ) { return d ; }";
ASSERT_EQUALS(expected, tok(code, false));
ASSERT_EQUALS(expected, tok(codePartialSpecified, false));
ASSERT_EQUALS(expected, tok(codeFullSpecified, false));
}
void simplifyTypedef34() {
// ticket #1411
const char code[] = "class X { };\n"
"typedef X (*foofunc)(const X&);\n"
"int main()\n"
"{\n"
" foofunc *Foo = new foofunc[2];\n"
"}";
const char expected[] =
"class X { } ; "
"int main ( ) "
"{ "
"X ( * * Foo ) ( const X & ) ; Foo = new X ( * [ 2 ] ) ( const X & ) ; "
"}";
// TODO: Ideally some parentheses should be added. This code is compilable:
// int (**Foo)(int);
// Foo = new (int(*[2])(int)) ;
ASSERT_EQUALS(expected, tok(code, false));
}
void simplifyTypedef35() {
const char code[] = "typedef int A;\n"
"class S\n"
"{\n"
"public:\n"
" typedef float A;\n"
" A a;\n"
" virtual void fun(A x);\n"
"};\n"
"void S::fun(S::A) { };\n"
"class S1 : public S\n"
"{\n"
"public:\n"
" void fun(S::A) { }\n"
"};\n"
"struct T\n"
"{\n"
" typedef A B;\n"
" B b;\n"
"};\n"
"float fun1(float A) { return A; }\n"
"float fun2(float a) { float A = a++; return A; }\n"
"float fun3(int a)\n"
"{\n"
" typedef struct { int a; } A;\n"
" A s; s.a = a;\n"
" return s.a;\n"
"}\n"
"int main()\n"
"{\n"
" A a = 0;\n"
" S::A s = fun1(a) + fun2(a) - fun3(a);\n"
" return a + s;\n"
"}";
const char expected[] = "class S "
"{ "
"public: "
""
"float a ; "
"virtual void fun ( float x ) ; "
"} ; "
"void S :: fun ( float ) { } ; "
"class S1 : public S "
"{ "
"public: "
"void fun ( float ) { } "
"} ; "
"struct T "
"{ "
""
"int b ; "
"} ; "
"float fun1 ( float A ) { return A ; } "
"float fun2 ( float a ) { float A ; A = a ++ ; return A ; } "
"float fun3 ( int a ) "
"{ "
"struct A { int a ; } ; "
"struct A s ; s . a = a ; "
"return s . a ; "
"} "
"int main ( ) "
"{ "
"int a ; a = 0 ; "
"float s ; s = fun1 ( a ) + fun2 ( a ) - fun3 ( a ) ; "
"return a + s ; "
"}";
ASSERT_EQUALS(expected, tok(code, false));
ASSERT_EQUALS_WITHOUT_LINENUMBERS("", errout_str());
}
void simplifyTypedef36() {
// ticket #1434
const char code[] = "typedef void (*TIFFFaxFillFunc)();\n"
"void f(va_list ap)\n"
"{\n"
" *va_arg(ap, TIFFFaxFillFunc*) = 0;\n"
"}";
const char expected[] = "void f ( va_list ap ) "
"{ "
"* va_arg ( ap , void ( * * ) ( ) ) = 0 ; "
"}";
ASSERT_EQUALS(expected, tok(code, false));
}
void simplifyTypedef37() {
const char code[] = "typedef int INT;\n"
"void f()\n"
"{\n"
" INT i; { }\n"
"}";
const char expected[] = "void f ( ) "
"{ "
"int i ; { } "
"}";
ASSERT_EQUALS(expected, tok(code, false));
}
void simplifyTypedef38() {
const char code[] = "typedef C A;\n"
"struct AB : public A, public B { };";
const char expected[] = "struct AB : public C , public B { } ;";
ASSERT_EQUALS(expected, tok(code, false));
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef43() {
// ticket #1588
{
const char code[] = "typedef struct foo A;\n"
"struct A\n"
"{\n"
" int alloclen;\n"
"};";
// The expected result..
const char expected[] = "struct A "
"{ "
"int alloclen ; "
"} ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "typedef union foo A;\n"
"union A\n"
"{\n"
" int alloclen;\n"
"};";
// The expected result..
const char expected[] = "union A "
"{ "
"int alloclen ; "
"} ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "typedef class foo A;\n"
"class A\n"
"{\n"
" int alloclen;\n"
"};";
// The expected result..
const char expected[] = "class A "
"{ "
"int alloclen ; "
"} ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
}
void simplifyTypedef44() {
{
const char code[] = "typedef std::map<std::string, int> Map;\n"
"class MyMap : public Map\n"
"{\n"
"};";
// The expected result..
const char expected[] = "class MyMap : public std :: map < std :: string , int > "
"{ "
"} ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "typedef std::map<std::string, int> Map;\n"
"class MyMap : protected Map\n"
"{\n"
"};";
// The expected result..
const char expected[] = "class MyMap : protected std :: map < std :: string , int > "
"{ "
"} ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "typedef std::map<std::string, int> Map;\n"
"class MyMap : private Map\n"
"{\n"
"};";
// The expected result..
const char expected[] = "class MyMap : private std :: map < std :: string , int > "
"{ "
"} ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "typedef struct foo { } A;\n"
"struct MyA : public A\n"
"{\n"
"};";
// The expected result..
const char expected[] = "struct foo { } ; "
"struct MyA : public foo "
"{ "
"} ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "typedef class foo { } A;\n"
"class MyA : public A\n"
"{\n"
"};";
// The expected result..
const char expected[] = "class foo { } ; "
"class MyA : public foo "
"{ "
"} ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "struct B {};\n" // #12141
"typedef struct B B;\n"
"namespace N {\n"
" struct D : public B {};\n"
"}\n";
const char expected[] = "struct B { } ; namespace N { struct D : public B { } ; }";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "struct B {};\n"
"typedef const struct B CB;\n"
"namespace N {\n"
" struct D : public CB {};\n"
"}\n"
"CB cb;\n";
const char expected[] = "struct B { } ; namespace N { struct D : public B { } ; } const struct B cb ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
}
void simplifyTypedef45() {
// ticket # 1613
const char code[] = "void fn() {\n"
" typedef foo<> bar;\n"
" while (0 > bar(1)) {}\n"
"}";
checkSimplifyTypedef(code);
ASSERT_EQUALS_WITHOUT_LINENUMBERS(
"[test.cpp:3]: (debug) valueflow.cpp:6541:(valueFlow) bailout: valueFlowAfterCondition: bailing in conditional block\n"
"[test.cpp:3]: (debug) valueflow.cpp:6541:(valueFlow) bailout: valueFlowAfterCondition: bailing in conditional block\n", // duplicate
errout_str());
}
void simplifyTypedef46() {
const char code[] = "typedef const struct A { int a; } * AP;\n"
"AP ap;";
// The expected result..
const char expected[] = "struct A { int a ; } ; "
"const struct A * ap ;";
ASSERT_EQUALS(expected, tok(code));
}
void simplifyTypedef47() {
{
const char code[] = "typedef std::pair<int, int> const I;\n"
"I i;";
// The expected result..
const char expected[] = "const std :: pair < int , int > i ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "typedef void (X:: *F)();\n"
"F f;";
// The expected result..
const char expected[] = "void ( * f ) ( ) ;";
ASSERT_EQUALS(expected, tok(code));
}
}
void simplifyTypedef48() { // ticket #1673
const char code[] = "typedef struct string { } string;\n"
"void foo (LIST *module_name)\n"
"{\n"
" bar(module_name ? module_name->string : 0);\n"
"}";
// The expected result..
const char expected[] = "struct string { } ; "
"void foo ( LIST * module_name ) "
"{ "
"bar ( module_name ? module_name . string : 0 ) ; "
"}";
ASSERT_EQUALS(expected, tok(code));
}
void simplifyTypedef49() { // ticket #1691
const char code[] = "class Class2 {\n"
"typedef const Class & Const_Reference;\n"
"void some_method (Const_Reference x) const {}\n"
"void another_method (Const_Reference x) const {}\n"
"};";
// The expected result..
const char expected[] = "class Class2 { "
""
"void some_method ( const Class & x ) const { } "
"void another_method ( const Class & x ) const { } "
"} ;";
ASSERT_EQUALS(expected, tok(code));
}
void simplifyTypedef50() {
const char code[] = "typedef char (* type1)[10];\n"
"typedef char (& type2)[10];\n"
"typedef char (& type3)[x];\n"
"typedef char (& type4)[x + 2];\n"
"type1 t1;\n"
"type1 (*tp1)[2];\n"
"type2 t2;\n"
"type3 t3;\n"
"type4 t4;";
// The expected result..
const char expected[] = "char ( * t1 ) [ 10 ] ; "
"char ( * ( * tp1 ) [ 2 ] ) [ 10 ] ; "
"char ( & t2 ) [ 10 ] ; "
"char ( & t3 ) [ x ] ; "
"char ( & t4 ) [ x + 2 ] ;";
ASSERT_EQUALS(expected, tok(code));
}
void simplifyTypedef51() {
const char code[] = "class A { public: int i; };\n"
"typedef const char (A :: * type1);\n"
"type1 t1 = &A::i;";
// The expected result..
const char expected[] = "class A { public: int i ; } ; "
"const char ( A :: * t1 ) ; t1 = & A :: i ;";
ASSERT_EQUALS(expected, tok(code));
}
void simplifyTypedef52() { // ticket #1782
{
const char code[] = "typedef char (* type1)[10];\n"
"type1 foo() { }";
// The expected result..
const char expected[] = "char ( * foo ( ) ) [ 10 ] { }";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "typedef char (* type1)[10];\n"
"LOCAL(type1) foo() { }";
// this is invalid C, assert that an "unknown macro" warning is written
ASSERT_THROW_INTERNAL(checkSimplifyTypedef(code), UNKNOWN_MACRO);
}
}
void simplifyTypedef54() { // ticket #1814
const char code[] = "void foo()\n"
"{\n"
" typedef std::basic_string<char, traits_type, allocator_type> string_type;\n"
" try\n"
" {\n"
" throw string_type(\"leak\");\n"
" }\n"
" catch (const string_type&)\n"
" {\n"
" pthread_exit (0);\n"
" }\n"
"}";
checkSimplifyTypedef(code);
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef55() {
const char code[] = "typedef volatile unsigned long * const hwreg_t ;\n"
"typedef void *const t1[2];\n"
"typedef int*const *_Iterator;\n"
"hwreg_t v1;\n"
"t1 v2;\n"
"_Iterator v3;";
// The expected result..
const char expected[] = "volatile long * const v1 ; "
"void * const v2 [ 2 ] ; "
"int * const * v3 ;";
ASSERT_EQUALS(expected, tok(code));
// Check for output..
checkSimplifyTypedef(code);
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef56() { // ticket #1829
const char code[] = "struct C {\n"
" typedef void (*fptr)();\n"
" const fptr pr;\n"
" operator const fptr& () { return pr; }\n"
"};";
// The expected result..
const char expected[] = "struct C { "
""
"const void ( * pr ) ( ) ; "
"operatorconstvoid(*)()& ( ) { return pr ; } "
"} ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef57() { // ticket #1846
const char code[] = "void foo() {\n"
" typedef int A;\n"
" A a = A(1) * A(2);\n"
"};";
// The expected result..
const char expected[] = "void foo ( ) { "
""
"int a ; a = int ( 1 ) * int ( 2 ) ; "
"} ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef58() { // ticket #1963
{
const char code[] = "typedef int vec2_t[2];\n"
"vec2_t coords[4] = {1,2,3,4,5,6,7,8};";
// The expected result..
const char expected[] = "int coords [ 4 ] [ 2 ] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 } ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "typedef int vec2_t[2];\n"
"vec2_t coords[4][5][6+1] = {1,2,3,4,5,6,7,8};";
// The expected result..
const char expected[] = "int coords [ 4 ] [ 5 ] [ 6 + 1 ] [ 2 ] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 } ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
}
void simplifyTypedef59() { // ticket #2011
const char code[] = "template<typename DISPATCHER> class SomeTemplateClass {\n"
" typedef void (SomeTemplateClass<DISPATCHER>::*MessageDispatcherFunc)(SerialInputMessage&);\n"
"};";
// The expected result..
const char expected[] = "template < typename DISPATCHER > class SomeTemplateClass { } ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef60() { // ticket #2035
const char code[] = "typedef enum {qfalse, qtrue} qboolean;\n"
"typedef qboolean (*localEntitiyAddFunc_t) (struct le_s * le, entity_t * ent);\n"
"void f()\n"
"{\n"
" qboolean b;\n"
" localEntitiyAddFunc_t f;\n"
"}";
// The expected result..
const char expected[] = "enum qboolean { qfalse , qtrue } ; void f ( ) { enum qboolean b ; enum qboolean ( * f ) ( struct le_s * , entity_t * ) ; }";
ASSERT_EQUALS(expected, tok(code, false));
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef61() { // ticket #2074 and 2075
const char code1[] = "typedef unsigned char (*Mf_GetIndexByte_Func) (void);\n"
"typedef const unsigned char * (*Mf_GetPointerToCurrentPos_Func)(void);";
// Check for output..
checkSimplifyTypedef(code1);
ASSERT_EQUALS("", errout_str());
const char code2[] = "typedef unsigned long uint32_t;\n"
"typedef uint32_t (*write_type_t) (uint32_t);";
// Check for output..
checkSimplifyTypedef(code2);
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef62() { // ticket #2082
const char code1[] = "typedef char TString[256];\n"
"void f()\n"
"{\n"
" TString a, b;\n"
"}";
// The expected tokens..
const char expected1[] = "void f ( ) { char a [ 256 ] ; char b [ 256 ] ; }";
ASSERT_EQUALS(expected1, tok(code1, false));
ASSERT_EQUALS("", errout_str());
const char code2[] = "typedef char TString[256];\n"
"void f()\n"
"{\n"
" TString a = { 0 }, b = { 0 };\n"
"}";
// The expected tokens..
const char expected2[] = "void f ( ) { char a [ 256 ] = { 0 } ; char b [ 256 ] = { 0 } ; }";
ASSERT_EQUALS(expected2, tok(code2, false, Platform::Type::Native, false));
ASSERT_EQUALS("", errout_str());
const char code3[] = "typedef char TString[256];\n"
"void f()\n"
"{\n"
" TString a = \"\", b = \"\";\n"
"}";
// The expected tokens..
const char expected3[] = "void f ( ) { char a [ 256 ] ; a = \"\" ; char b [ 256 ] ; b = \"\" ; }";
ASSERT_EQUALS(expected3, tok(code3, false, Platform::Type::Native, false));
ASSERT_EQUALS("", errout_str());
const char code4[] = "typedef char TString[256];\n"
"void f()\n"
"{\n"
" TString a = \"1234\", b = \"5678\";\n"
"}";
// The expected tokens..
const char expected4[] = "void f ( ) { char a [ 256 ] ; a = \"1234\" ; char b [ 256 ] ; b = \"5678\" ; }";
ASSERT_EQUALS(expected4, tok(code4, false, Platform::Type::Native, false));
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef63() { // ticket #2175 'typedef float x[3];'
const char code[] = "typedef float x[3];\n"
"x a,b,c;";
const std::string actual(tok(code));
ASSERT_EQUALS("float a [ 3 ] ; float b [ 3 ] ; float c [ 3 ] ;", actual);
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef64() {
const char code[] = "typedef typeof(__type1() + __type2()) __type;"
"__type t;";
const std::string actual(tok(code));
ASSERT_EQUALS("typeof ( __type1 ( ) + __type2 ( ) ) t ;", actual);
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef65() { // ticket #2314
const char code[] = "typedef BAR<int> Foo;\n"
"int main() {\n"
" Foo b(0);\n"
" return b > Foo(10);\n"
"}";
const std::string actual(tok(code, true, Platform::Type::Native, false));
ASSERT_EQUALS("int main ( ) { BAR < int > b ( 0 ) ; return b > BAR < int > ( 10 ) ; }", actual);
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef66() { // ticket #2341
const char code[] = "typedef long* GEN;\n"
"extern GEN (*foo)(long);";
(void)tok(code);
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef67() { // ticket #2354
const char code[] = "typedef int ( * Function ) ( ) ;\n"
"void f ( ) {\n"
" ((Function * (*) (char *, char *, int, int)) global[6]) ( \"assoc\", \"eggdrop\", 106, 0);\n"
"}";
// TODO should it be simplified as below instead?
// "( ( int ( * * ( * ) ( char * , char * , int , int ) ) ( ) ) global [ 6 ] ) ( \"assoc\" , \"eggdrop\" , 106 , 0 ) ; "
const char expected[] = "void f ( ) { "
"( ( int * * * ) global [ 6 ] ) ( \"assoc\" , \"eggdrop\" , 106 , 0 ) ; "
"}";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS(
"[test.cpp:3]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable global\n",
errout_str());
}
void simplifyTypedef68() { // ticket #2355
const char code[] = "typedef FMAC1 void (* a) ();\n"
"void *(*b) ();";
const std::string actual(tok(code));
ASSERT_EQUALS("void * ( * b ) ( ) ;", actual);
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef69() { // ticket #2348
const char code[] = "typedef int (*CompilerHook)();\n"
"typedef struct VirtualMachine\n"
"{\n"
" CompilerHook *(*compilerHookVector)(void);\n"
"}VirtualMachine;";
const char expected[] = "struct VirtualMachine "
"{ "
"int ( * * ( * compilerHookVector ) ( void ) ) ( ) ; "
"} ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef70() { // ticket #2348
const char code[] = "typedef int pread_f ( int ) ;\n"
"pread_f *(*test_func)(char *filename);";
const char expected[] = "int ( * ( * test_func ) ( char * filename ) ) ( int ) ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef71() { // ticket #2348
{
const char code[] = "typedef int RexxFunctionHandler();\n"
"RexxFunctionHandler *(efuncs[1]);";
const char expected[] = "int ( * ( efuncs [ 1 ] ) ) ( ) ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "typedef int RexxFunctionHandler();\n"
"RexxFunctionHandler *(efuncs[]) = { NULL, NULL };";
const char expected[] = "int ( * ( efuncs [ ] ) ) ( ) = { NULL , NULL } ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
}
void simplifyTypedef72() { // ticket #2374
// inline operator
{
const char code[] = "class Fred {\n"
" typedef int* (Fred::*F);\n"
" operator F() const { }\n"
"};";
const char expected[] = "class Fred { "
""
"operatorint** ( ) const { } "
"} ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
// inline local variable
{
const char code[] = "class Fred {\n"
" typedef int INT;\n"
" void f1() const { INT i; }\n"
"};";
const char expected[] = "class Fred { "
""
"void f1 ( ) const { int i ; } "
"} ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
// out of line member variable
{
const char code[] = "class Fred {\n"
" typedef int INT;\n"
" void f1() const;\n"
"};\n"
"void Fred::f1() const { INT i; f(i); }";
const char expected[] = "class Fred { "
""
"void f1 ( ) const ; "
"} ; "
"void Fred :: f1 ( ) const { int i ; f ( i ) ; }";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
// out of line operator
{
const char code[] = "class Fred {\n"
" typedef int* (Fred::*F);\n"
" operator F() const;\n"
"};\n"
"Fred::operator F() const { }";
const char expected[] = "class Fred { "
""
"operatorint** ( ) const ; "
"} ; "
"Fred :: operatorint** ( ) const { }";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
}
void simplifyTypedef73() { // ticket #2412
const char code[] = "struct B {};\n"
"typedef struct A : public B {\n"
" void f();\n"
"} a, *aPtr;";
const char expected[] = "struct B { } ; "
"struct A : public B { "
"void f ( ) ; "
"} ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef74() { // ticket #2414
const char code[] = "typedef long (*state_func_t)(void);\n"
"typedef state_func_t (*state_t)(void);\n"
"state_t current_state = death;\n"
"static char get_runlevel(const state_t);";
const char expected[] = "long ( * ( * current_state ) ( void ) ) ( void ) ; current_state = death ; "
"static char get_runlevel ( long ( * ( * const ) ( void ) ) ( void ) ) ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef75() { // ticket #2426
const char code[] = "typedef _Packed struct S { long l; };";
ASSERT_EQUALS(";", tok(code, true, Platform::Type::Native, false));
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef76() { // ticket #2453 segmentation fault
ASSERT_THROW_INTERNAL(checkSimplifyTypedef("void f1(typedef int x) {}"), SYNTAX);
}
void simplifyTypedef77() { // ticket #2554
const char code[] = "typedef char Str[10]; int x = sizeof(Str);";
const char expected[] = "int x ; x = sizeof ( char [ 10 ] ) ;";
ASSERT_EQUALS(expected, tok(code));
}
void simplifyTypedef78() { // ticket #2568
const char code[] = "typedef struct A A_t;\n"
"A_t a;\n"
"typedef struct A { } A_t;\n"
"A_t a1;";
const char expected[] = "struct A a ; struct A { } ; struct A a1 ;";
ASSERT_EQUALS(expected, tok(code));
}
void simplifyTypedef79() { // ticket #2348
const char code[] = "typedef int (Tcl_ObjCmdProc) (int x);\n"
"typedef struct LangVtab\n"
"{\n"
" Tcl_ObjCmdProc * (*V_LangOptionCommand);\n"
"} LangVtab;";
const char expected[] = "struct LangVtab "
"{ "
"int ( * ( * V_LangOptionCommand ) ) ( int x ) ; "
"} ;";
ASSERT_EQUALS(expected, tok(code));
}
void simplifyTypedef80() { // ticket #2587
const char code[] = "typedef struct s { };\n"
"void f() {\n"
" sizeof(struct s);\n"
"};";
const char expected[] = "struct s { } ; "
"void f ( ) { "
"sizeof ( struct s ) ; "
"} ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef81() { // ticket #2603 segmentation fault
ASSERT_THROW_INTERNAL(checkSimplifyTypedef("typedef\n"), SYNTAX);
ASSERT_THROW_INTERNAL(checkSimplifyTypedef("typedef constexpr\n"), SYNTAX);
}
void simplifyTypedef82() { // ticket #2403
checkSimplifyTypedef("class A {\n"
"public:\n"
" typedef int F(int idx);\n"
"};\n"
"class B {\n"
"public:\n"
" A::F ** f;\n"
"};\n"
"int main()\n"
"{\n"
" B * b = new B;\n"
" b->f = new A::F * [ 10 ];\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef83() { // ticket #2620
const char code[] = "typedef char Str[10];\n"
"void f(Str &cl) { }";
// The expected result..
const char expected[] = "void f ( char ( & cl ) [ 10 ] ) { }";
ASSERT_EQUALS(expected, tok(code));
}
void simplifyTypedef84() { // ticket #2630 (segmentation fault)
const char code1[] = "typedef y x () x";
ASSERT_THROW_INTERNAL(checkSimplifyTypedef(code1), SYNTAX);
const char code2[] = "typedef struct template <>";
ASSERT_THROW_INTERNAL(checkSimplifyTypedef(code2), SYNTAX);
const char code3[] = "typedef ::<>";
ASSERT_THROW_INTERNAL(checkSimplifyTypedef(code3), SYNTAX);
}
void simplifyTypedef85() { // ticket #2651
const char code[] = "typedef FOO ((BAR)(void, int, const int, int*));";
const char expected[] = ";";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef86() { // ticket #2581
const char code[] = "class relational {\n"
" typedef void (safe_bool_helper::*safe_bool)();\n"
"public:\n"
" operator safe_bool() const;\n"
" safe_bool operator!() const;\n"
"};";
const char expected[] = "class relational { "
""
"public: "
"operatorsafe_bool ( ) const ; "
"safe_bool operator! ( ) const ; "
"} ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef87() { // ticket #2651
const char code[] = "typedef FOO (*(*BAR)(void, int, const int, int*));";
const char expected[] = ";";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef88() { // ticket #2675
const char code[] = "typedef short int (*x)(...);";
const char expected[] = ";";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef89() { // ticket #2717
const char code[] = "class Fred {\n"
" typedef void f(int) const;\n"
" f func;\n"
"};";
const char expected[] = "class Fred { void func ( int ) const ; } ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef90() { // ticket #2718
const char code[] = "typedef int IA[2];\n"
"void f(const IA&) {};";
const char expected[] = "void f ( const int ( & ) [ 2 ] ) { } ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef91() { // ticket #2716
const char code1[] = "namespace NS {\n"
" typedef int (*T)();\n"
" class A {\n"
" T f();\n"
" };\n"
"}\n"
"namespace NS {\n"
" T A::f() {}\n"
"}";
const char expected1[] = "namespace NS { "
""
"class A { "
"int * f ( ) ; "
"} ; "
"} "
"namespace NS { "
"int * A :: f ( ) { } "
"}";
ASSERT_EQUALS(expected1, tok(code1));
ASSERT_EQUALS("", errout_str());
const char code2[] = "namespace NS {\n"
" typedef int (*T)();\n"
" class A {\n"
" T f();\n"
" };\n"
"}\n"
"NS::T NS::A::f() {}";
const char expected2[] = "namespace NS { "
""
"class A { "
"int * f ( ) ; "
"} ; "
"} "
"int * NS :: A :: f ( ) { }";
ASSERT_EQUALS(expected2, tok(code2));
ASSERT_EQUALS("", errout_str());
const char code3[] = "namespace NS1 {\n"
" namespace NS2 {\n"
" typedef int (*T)();\n"
" class A {\n"
" T f();\n"
" };\n"
" }\n"
"}\n"
"namespace NS1 {\n"
" namespace NS2 {\n"
" T A::f() {}\n"
" }\n"
"}";
const char expected3[] = "namespace NS1 { "
"namespace NS2 { "
""
"class A { "
"int * f ( ) ; "
"} ; "
"} "
"} "
"namespace NS1 { "
"namespace NS2 { "
"int * A :: f ( ) { } "
"} "
"}";
ASSERT_EQUALS(expected3, tok(code3));
ASSERT_EQUALS("", errout_str());
const char code4[] = "namespace NS1 {\n"
" namespace NS2 {\n"
" typedef int (*T)();\n"
" class A {\n"
" T f();\n"
" };\n"
" }\n"
"}\n"
"namespace NS1 {\n"
" NS2::T NS2::A::f() {}\n"
"}";
const char expected4[] = "namespace NS1 { "
"namespace NS2 { "
""
"class A { "
"int * f ( ) ; "
"} ; "
"} "
"} "
"namespace NS1 { "
"int * NS2 :: A :: f ( ) { } "
"}";
ASSERT_EQUALS(expected4, tok(code4));
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef92() { // ticket #2736 (segmentation fault)
const char code[] = "typedef long Long;\n"
"namespace NS {\n"
"}";
ASSERT_EQUALS(";", tok(code));
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef93() { // ticket #2738 (syntax error)
const char code[] = "struct s { double x; };\n"
"typedef struct s (*binop) (struct s, struct s);";
const char expected[] = "struct s { double x ; } ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef94() { // ticket #1982
const char code1[] = "class A {\n"
"public:\n"
" typedef struct {\n"
" int a[4];\n"
" } data;\n"
"};\n"
"A::data d;";
const char expected1[] = "class A { "
"public: "
"struct data { "
"int a [ 4 ] ; "
"} ; "
"} ; "
"struct A :: data d ;";
ASSERT_EQUALS(expected1, tok(code1));
ASSERT_EQUALS("", errout_str());
const char code2[] = "class A {\n"
"public:\n"
" typedef struct {\n"
" int a[4];\n"
" } data;\n"
"};\n"
"::A::data d;";
const char expected2[] = "class A { "
"public: "
"struct data { "
"int a [ 4 ] ; "
"} ; "
"} ; "
"struct :: A :: data d ;";
ASSERT_EQUALS(expected2, tok(code2));
ASSERT_EQUALS("", errout_str());
const char code3[] = "class A {\n"
"public:\n"
" typedef struct {\n"
" int a[4];\n"
" } data;\n"
"};\n"
"class B : public ::A::data { };";
const char expected3[] = "class A { "
"public: "
"struct data { "
"int a [ 4 ] ; "
"} ; "
"} ; "
"class B : public :: A :: data { } ;";
ASSERT_EQUALS(expected3, tok(code3));
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef95() { // ticket #2844
const char code[] = "class symbol_table {\n"
"public:\n"
" typedef expression_error::error_code (*valid_func)(void *cbparam, const char *name, expression_space space);\n"
" valid_func f;\n"
"};";
const char expected[] = "class symbol_table { "
"public: "
"expression_error :: error_code ( * f ) ( void * , const char * , expression_space ) ; "
"} ;";
ASSERT_EQUALS(expected, tok(code, true, Platform::Type::Native, false));
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef96() { // ticket #2886 (segmentation fault)
const char code[] = "typedef struct x { }";
ASSERT_THROW_INTERNAL(tok(code), SYNTAX);
}
void simplifyTypedef97() { // ticket #2983 (segmentation fault)
const char code[] = "typedef x y\n"
"(A); y";
(void)tok(code);
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef99() { // ticket #2999
const char code[] = "typedef struct Fred Fred;\n"
"struct Fred { };";
(void)tok(code);
ASSERT_EQUALS("", errout_str());
const char code1[] = "struct Fred { };\n"
"typedef struct Fred Fred;";
(void)tok(code1);
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef100() { // ticket #3000
const char code[] = "typedef struct Fred { } Fred;\n"
"Fred * foo() {\n"
" Fred *fred;\n"
" fred = se_alloc(sizeof(struct Fred));\n"
" return fred;\n"
"}";
(void)tok(code);
ASSERT_EQUALS_WITHOUT_LINENUMBERS("", errout_str());
}
void simplifyTypedef101() { // ticket #3003 (segmentation fault)
const char code[] = "typedef a x[];\n"
"y = x";
ASSERT_EQUALS("y = x", tok(code));
}
void simplifyTypedef102() { // ticket #3004
const char code[] = "typedef struct { } Fred;\n"
"void foo()\n"
"{\n"
" Fred * Fred;\n"
"}";
(void)tok(code);
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef103() { // ticket #3007
const char code[] = "typedef struct { } Fred;\n"
"void foo()\n"
"{\n"
" Fred Fred;\n"
"}";
(void)tok(code);
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef104() { // ticket #3070
const char code[] = "typedef int (*in_func) (void FAR *, unsigned char FAR * FAR *);";
ASSERT_EQUALS(";", tok(code));
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef105() { // ticket #3616 (segmentation fault)
const char code[] = "( int typedef char x; ){}";
ASSERT_THROW_INTERNAL(tok(code), SYNTAX);
}
void simplifyTypedef106() { // ticket #3619 (segmentation fault)
const char code[] = "typedef void f ();\ntypedef { f }";
ASSERT_THROW_INTERNAL_EQUALS(tok(code), INTERNAL, "Internal error. AST cyclic dependency.");
}
void simplifyTypedef107() { // ticket #3963 (bad code => segmentation fault)
const char code[] = "typedef int x[]; int main() { return x }";
ASSERT_EQUALS("int main ( ) { return x }", tok(code));
ignore_errout(); // we do not care about the output
}
void simplifyTypedef108() { // ticket #4777
const char code[] = "typedef long* GEN;\n"
"void sort_factor(GEN *y, long n) {\n"
" GEN a, b;\n"
" foo(a, b);\n"
"}";
const char expected[] = "void sort_factor ( long * * y , long n ) { "
"long * a ; long * b ; "
"foo ( a , b ) ; "
"}";
ASSERT_EQUALS(expected, tok(code));
}
void simplifyTypedef109() {
const char code[] = "typedef int&& rref;\n"
"rref var = 0;";
const char expected[] = "int && var = 0 ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef110() {
const char code[] = "namespace A {\n"
" namespace B {\n"
" namespace D {\n"
" typedef int DKIPtr;\n"
" }\n"
" struct ZClass {\n"
" void set1(const A::B::D::DKIPtr& p) {\n"
" membervariable1 = p;\n"
" }\n"
" void set2(const ::A::B::D::DKIPtr& p) {\n"
" membervariable2 = p;\n"
" }\n"
" void set3(const B::D::DKIPtr& p) {\n"
" membervariable3 = p;\n"
" }\n"
" void set4(const ::B::D::DKIPtr& p) {\n"
" membervariable4 = p;\n"
" }\n"
" void set5(const C::D::DKIPtr& p) {\n"
" membervariable5 = p;\n"
" }\n"
" A::B::D::DKIPtr membervariable1;\n"
" ::A::B::D::DKIPtr membervariable2;\n"
" B::D::DKIPtr membervariable3;\n"
" ::B::D::DKIPtr membervariable4;\n"
" C::D::DKIPtr membervariable5;\n"
" };\n"
" }\n"
"}";
const char expected[] = "namespace A { "
"namespace B { "
"struct ZClass { "
"void set1 ( const int & p ) { "
"membervariable1 = p ; "
"} "
"void set2 ( const int & p ) { "
"membervariable2 = p ; "
"} "
"void set3 ( const int & p ) { "
"membervariable3 = p ; "
"} "
"void set4 ( const :: B :: D :: DKIPtr & p ) { "
"membervariable4 = p ; "
"} "
"void set5 ( const C :: D :: DKIPtr & p ) { "
"membervariable5 = p ; "
"} "
"int membervariable1 ; "
"int membervariable2 ; "
"int membervariable3 ; "
":: B :: D :: DKIPtr membervariable4 ; "
"C :: D :: DKIPtr membervariable5 ; "
"} ; "
"} "
"}";
ASSERT_EQUALS(expected, tok(code, true, Platform::Type::Native, false));
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef111() { // ticket #6345
const char code1[] = "typedef typename A B;\n"
"typedef typename B C;\n"
"typename C c;\n";
const char expected1[] = "A c ;";
ASSERT_EQUALS(expected1, tok(code1));
const char code2[] = "typedef typename A B;\n"
"typedef typename B C;\n"
"C c;\n";
const char expected2[] = "A c ;";
ASSERT_EQUALS(expected2, tok(code2));
const char code3[] = "typedef typename A B;\n"
"typedef B C;\n"
"C c;\n";
const char expected3[] = "A c ;";
ASSERT_EQUALS(expected3, tok(code3));
const char code4[] = "typedef A B;\n"
"typedef typename B C;\n"
"C c;\n";
const char expected4[] = "A c ;";
ASSERT_EQUALS(expected4, tok(code4));
const char code5[] = "typedef A B;\n"
"typedef B C;\n"
"C c;\n";
const char expected5[] = "A c ;";
ASSERT_EQUALS(expected5, tok(code5));
// #5614
const char code5614[] = "typedef typename T::U V;\n"
"typedef typename T::W (V::*Fn)();\n";
const char expected5614[] = ";";
ASSERT_EQUALS(expected5614, tok(code5614));
}
void simplifyTypedef112() { // ticket #6048
const char code[] = "template<\n"
"typename DataType,\n"
"typename SpaceType,\n"
"typename TrafoConfig>\n"
"class AsmTraits1 {\n"
" typedef typename SpaceType::TrafoType TrafoType;\n"
" typedef typename TrafoType::ShapeType ShapeType;\n"
" typedef typename TrafoType::template Evaluator<ShapeType, DataType>::Type TrafoEvaluator;\n"
" enum {\n"
" domain_dim = TrafoEvaluator::domain_dim,\n"
" };\n"
"};";
const char expected[] = "template < "
"typename DataType , "
"typename SpaceType , "
"typename TrafoConfig > "
"class AsmTraits1 { "
"enum Anonymous0 { "
"domain_dim = SpaceType :: TrafoType :: Evaluator < SpaceType :: TrafoType :: ShapeType , DataType > :: Type :: domain_dim , "
"} ; } ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef113() { // ticket #7030
const char code[] = "typedef int T;\n"
"void f() { T:; }";
const char expected[] = "void f ( ) { T : ; }";
ASSERT_EQUALS(expected, tok(code));
}
void simplifyTypedef114() { // ticket #7058
const char code[] = "typedef struct { enum {A,B}; } AB;\n"
"x=AB::B;";
const char expected[] = "struct AB { enum Anonymous0 { A , B } ; } ; x = AB :: B ;";
ASSERT_EQUALS(expected, tok(code));
}
void simplifyTypedef115() { // ticket #6998
const char code[] = "typedef unsigned unsignedTypedef;\n"
"unsignedTypedef t1 ;\n"
"unsigned t2 ;";
const char expected[] = "unsigned int t1 ; "
"unsigned int t2 ;";
ASSERT_EQUALS(expected, tok(code, false));
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef116() { // #5624
const char code[] = "void fn() {\n"
" typedef std::vector<CharacterConversion> CharacterToConversion;\n"
" CharacterToConversion c2c;\n"
" for (CharacterToConversion::iterator it = c2c.begin(); it != c2c.end(); ++it) {}\n"
" CharacterToConversion().swap(c2c);\n"
"}";
const char expected[] = "void fn ( ) { "
"std :: vector < CharacterConversion > c2c ; "
"for ( std :: vector < CharacterConversion > :: iterator it = c2c . begin ( ) ; it != c2c . end ( ) ; ++ it ) { } "
"std :: vector < CharacterConversion > ( ) . swap ( c2c ) ; "
"}";
ASSERT_EQUALS(expected, tok(code, false));
ASSERT_EQUALS_WITHOUT_LINENUMBERS("", errout_str());
}
void simplifyTypedef117() { // #6507
const char code[] = "typedef struct bstr {} bstr;\n"
"struct bstr bstr0(const char *s) {\n"
" return (struct bstr) { (unsigned char *)s, s ? strlen(s) : 0 };\n"
"}";
const char expected[] = "struct bstr { } ; "
"struct bstr bstr0 ( const char * s ) { "
"return ( struct bstr ) { ( unsigned char * ) s , s ? strlen ( s ) : 0 } ; "
"}";
ASSERT_EQUALS(expected, tok(code, false));
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef118() { // #5749
const char code[] = "struct ClassyClass {\n"
"int id;\n"
"typedef int (ClassyClass::*funky_type);\n"
"operator funky_type() {\n"
"return &ClassyClass::id;\n"
"}}";
const char expected[] = "struct ClassyClass { "
"int id ; "
"operatorintClassyClass::* ( ) { "
"return & ClassyClass :: id ; "
"} }";
ASSERT_EQUALS(expected, tok(code, false));
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef119() { // #7541
const char code[] = "namespace Baz {\n"
" typedef char* T1;\n"
" typedef T1 XX;\n"
"}\n"
"namespace Baz { }\n"
"enum Bar { XX = 1 };";
const char exp[] = "enum Bar { XX = 1 } ;";
ASSERT_EQUALS(exp, tok(code, false));
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef120() { // #8357
const char code[] = "typedef char test_utf8_char[5];\n"
"static test_utf8_char const bad_chars[] = { };\n"
"static void report_good(bool passed, test_utf8_char const c) { };";
const char exp[] = "static const char bad_chars [ ] [ 5 ] = { } ; "
"static void report_good ( bool passed , const char c [ 5 ] ) { } ;";
ASSERT_EQUALS(exp, tok(code, false));
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef121() { // #5766
const char code[] = "typedef float vec3[3];\n"
"typedef float mat3x3[3][3];\n"
"vec3 v3;\n"
"mat3x3 m3x3;\n"
"const vec3 &gv() { return v3; }\n"
"const mat3x3 &gm() { return m3x3; }\n"
"class Fred {\n"
"public:\n"
" vec3 &v();\n"
" mat3x3 &m();\n"
" const vec3 &vc() const;\n"
" const mat3x3 &mc() const;\n"
"};\n"
"vec3 & Fred::v() { return v3; }\n"
"mat3x3 & Fred::m() { return m3x3; }\n"
"const vec3 & Fred::vc() const { return v3; }\n"
"const mat3x3 & Fred::mc() const { return m3x3; }";
const char exp[] = "float v3 [ 3 ] ; "
"float m3x3 [ 3 ] [ 3 ] ; "
"const float * & gv ( ) { return v3 ; } "
"const float * * & gm ( ) { return m3x3 ; } "
"class Fred { "
"public: "
"float * & v ( ) ; "
"float * * & m ( ) ; "
"const float * & vc ( ) const ; "
"const float * * & mc ( ) const ; "
"} ; "
"float * & Fred :: v ( ) { return v3 ; } "
"float * * & Fred :: m ( ) { return m3x3 ; } "
"const float * & Fred :: vc ( ) const { return v3 ; } "
"const float * * & Fred :: mc ( ) const { return m3x3 ; }";
ASSERT_EQUALS(exp, tok(code, false));
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef122() { // segmentation fault
const char code[] = "int result = [] { return git_run_cmd(\"update-index\",\"update-index -q --refresh\"); }();";
(void)tok(code);
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef123() { // ticket #7406
const char code[] = "typedef int intvec[1];\n"
"Dummy<intvec> y;";
const char exp[] = "Dummy < int [ 1 ] > y ;";
ASSERT_EQUALS(exp, tok(code, false));
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef124() { // ticket #7792
const char code[] = "typedef long unsigned int size_t;\n"
"typedef size_t (my_func)(char *, size_t, size_t, void *);"
"size_t f(size_t s);";
const char exp[] = "long f ( long s ) ;";
ASSERT_EQUALS(exp, tok(code, /*simplify*/ true));
ASSERT_EQUALS("", errout_str());
const char code1[] = "typedef long unsigned int uint32_t;\n"
"typedef uint32_t (my_func)(char *, uint32_t, uint32_t, void *);";
// Check for output..
checkSimplifyTypedef(code1);
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedef125() { // #8749
const char code[] = "typedef char A[3];\n"
"char (*p)[3] = new A[4];";
const char exp[] = "char ( * p ) [ 3 ] = new char [ 4 ] [ 3 ] ;";
ASSERT_EQUALS(exp, tok(code, false));
}
void simplifyTypedef126() { // #5953
const char code[] = "typedef char automap_data_t[100];\n"
"void write_array(automap_data_t *data) {}";
const char exp[] = "void write_array ( char ( * data ) [ 100 ] ) { }";
ASSERT_EQUALS(exp, tok(code, false));
}
void simplifyTypedef127() { // #8878
const char code[] = "class a; typedef int (a::*b); "
"template <long, class> struct c; "
"template <int g> struct d { enum { e = c<g, b>::f }; };";
const char exp[] = "class a ; "
"template < long , class > struct c ; "
"template < int g > struct d { enum Anonymous0 { e = c < g , int ( a :: * ) > :: f } ; } ;";
ASSERT_EQUALS(exp, tok(code, false));
}
void simplifyTypedef128() { // #9053
const char code[] = "typedef int d[4];\n"
"void f() {\n"
" dostuff((const d){1,2,3,4});\n"
"}";
const char exp[] = "void f ( ) { "
"dostuff ( ( const int [ 4 ] ) { 1 , 2 , 3 , 4 } ) ; "
"}";
ASSERT_EQUALS(exp, tok(code, false));
}
void simplifyTypedef129() {
{
const char code[] = "class c {\n"
" typedef char foo[4];\n"
" foo &f ;\n"
"};";
const char exp[] = "class c { char ( & f ) [ 4 ] ; } ;";
ASSERT_EQUALS(exp, tok(code, false));
}
{
const char code[] = "class c {\n"
" typedef char foo[4];\n"
" const foo &f;\n"
"};";
const char exp[] = "class c { const char ( & f ) [ 4 ] ; } ;";
ASSERT_EQUALS(exp, tok(code, false));
}
{
const char code[] = "class c {\n"
" typedef char foo[4];\n"
" foo _a;\n"
" constexpr const foo &c_str() const noexcept { return _a; }\n"
"};";
const char exp[] = "class c { char _a [ 4 ] ; const constexpr char ( & c_str ( ) const noexcept ( true ) ) [ 4 ] { return _a ; } } ;";
ASSERT_EQUALS(exp, tok(code, false));
}
{
const char code[] = "class c {\n"
" typedef char foo[4];\n"
" foo _a;\n"
" constexpr operator foo &() noexcept { return _a; }\n"
"};";
const char actual[] = "class c { char _a [ 4 ] ; constexpr char ( & operatorchar ( ) noexcept ( true ) ) [ 4 ] { return _a ; } } ;";
const char exp[] = "class c { char _a [ 4 ] ; char ( & operatorchar ( ) noexcept ( true ) ) [ 4 ] { return _a ; } } ;";
TODO_ASSERT_EQUALS(exp, actual, tok(code, false));
}
{
const char code[] = "class c {\n"
" typedef char foo[4];\n"
" foo _a;\n"
" constexpr operator const foo &() const noexcept { return _a; }\n"
"};";
const char actual[] = "class c { char _a [ 4 ] ; constexpr const char ( & operatorconstchar ( ) const noexcept ( true ) ) [ 4 ] { return _a ; } } ;";
const char exp[] = "class c { char _a [ 4 ] ; const char ( & operatorconstchar ( ) const noexcept ( true ) ) [ 4 ] { return _a ; } } ;";
TODO_ASSERT_EQUALS(exp, actual, tok(code, false));
}
}
void simplifyTypedef130() { // #9446
const char code[] = "template <class, class> void a() {\n"
" typedef int(*b)[10];\n"
" a<b, b>();\n"
"}";
const char exp[] = "template < class , class > void a ( ) { "
"a < int ( * ) [ 10 ] , int ( * ) [ 10 ] > ( ) ; "
"}";
ASSERT_EQUALS(exp, tok(code, false));
}
void simplifyTypedef131() {
const char code[] = "typedef unsigned char a4[4];\n"
"a4 a4obj;\n"
"a4 && a4_rref = std::move(a4obj);\n"
"a4* a4p = &(a4obj);\n"
"a4*&& a4p_rref = std::move(a4p);";
const char exp[] = "unsigned char a4obj [ 4 ] ; "
"unsigned char ( && a4_rref ) [ 4 ] = std :: move ( a4obj ) ; "
"unsigned char ( * a4p ) [ 4 ] ; "
"a4p = & ( a4obj ) ; "
"unsigned char ( * && a4p_rref ) [ 4 ] = std :: move ( a4p ) ;";
ASSERT_EQUALS(exp, tok(code, false));
}
void simplifyTypedef132() {
const char code[] = "namespace NamespaceA {\n"
" typedef int MySpecialType;\n"
"}\n"
"\n"
"class A {\n"
" void DoSomething( NamespaceA::MySpecialType special );\n"
"};\n"
"\n"
"using NamespaceA::MySpecialType;\n"
"\n"
"void A::DoSomething( MySpecialType wrongName ) {}";
const char exp[] = "class A { "
"void DoSomething ( int special ) ; "
"} ; "
"void A :: DoSomething ( int wrongName ) { }";
ASSERT_EQUALS(exp, tok(code, false));
}
void simplifyTypedef133() { // #9812
const char code[] = "typedef unsigned char array_t[16];\n"
"using array_p = const array_t *;\n"
"array_p x;\n";
ASSERT_EQUALS("using array_p = const unsigned char ( * ) [ 16 ] ; array_p x ;", tok(code, false));
ASSERT_EQUALS("[test.cpp:2]: (debug) Failed to parse 'using array_p = const unsigned char ( * ) [ 16 ] ;'. The checking continues anyway.\n", errout_str());
}
void simplifyTypedef134() {
const char code[] = "namespace foo { typedef long long int64; }\n"
"typedef int int32;\n"
"namespace foo { int64 i; }\n"
"int32 j;";
ASSERT_EQUALS("; namespace foo { long long i ; } int j ;", tok(code, false));
}
void simplifyTypedef135() {
const char code[] = "namespace clangimport {\n"
" class AstNode;\n"
" typedef std::shared_ptr<AstNode> AstNodePtr;\n"
" class AstNode {\n"
" public:\n"
" AstNode() {}\n"
" private:\n"
" void createTokens();\n"
" void createScope(const std::vector<AstNodePtr> &children);\n"
" };\n"
"}\n"
"void clangimport::AstNode::createTokens() {\n"
" AstNodePtr range;\n"
" range->createTokens();\n"
"}\n"
"void clangimport::AstNode::createScope(const std::vector<AstNodePtr> & children2) { }";
const char expected[] = "namespace clangimport { "
"class AstNode ; "
"class AstNode { "
"public: "
"AstNode ( ) "
"{ } "
"private: "
"void createTokens ( ) ; "
"void createScope ( const std :: vector < std :: shared_ptr < AstNode > > & children ) ; "
"} ; "
"} "
"void clangimport :: AstNode :: createTokens ( ) { "
"std :: shared_ptr < AstNode > range ; "
"range . createTokens ( ) ; "
"} "
"void clangimport :: AstNode :: createScope ( const std :: vector < std :: shared_ptr < AstNode > > & children2 ) { }";
ASSERT_EQUALS(expected, tok(code));
}
void simplifyTypedef136() {
const char code[] = "class C1 {};\n"
"typedef class S1 {} S1;\n"
"typedef class S2 : public C1 {} S2;\n"
"typedef class {} S3;\n"
"typedef class : public C1 {} S4;\n"
"S1 s1;\n"
"S2 s2;\n"
"S3 s3;\n"
"S4 s4;";
const char expected[] = "class C1 { } ; "
"class S1 { } ; "
"class S2 : public C1 { } ; "
"class S3 { } ; "
"class S4 : public C1 { } ; "
"class S1 s1 ; "
"class S2 s2 ; "
"class S3 s3 ; "
"class S4 s4 ;";
ASSERT_EQUALS(expected, tok(code, false));
}
void simplifyTypedef137() { // #10054 debug: Executable scope 'x' with unknown function.
{
// original example: using "namespace external::ns1;" but redundant qualification
const char code[] = "namespace external {\n"
" namespace ns1 {\n"
" template <int size> struct B { };\n"
" typedef B<sizeof(bool)> V;\n"
" }\n"
"}\n"
"namespace ns {\n"
" struct A {\n"
" void f(external::ns1::V);\n"
" };\n"
"}\n"
"using namespace external::ns1;\n"
"namespace ns {\n"
" void A::f(external::ns1::V) {}\n"
"}";
const char exp[] = "namespace external { "
"namespace ns1 { "
"struct B<1> ; "
"} "
"} "
"namespace ns { "
"struct A { "
"void f ( external :: ns1 :: B<1> ) ; "
"} ; "
"} "
"using namespace external :: ns1 ; "
"namespace ns { "
"void A :: f ( external :: ns1 :: B<1> ) { } "
"} "
"struct external :: ns1 :: B<1> { } ;";
ASSERT_EQUALS(exp, tok(code, true, Platform::Type::Native, true));
ASSERT_EQUALS("", errout_str());
}
{
// no using "namespace external::ns1;"
const char code[] = "namespace external {\n"
" namespace ns1 {\n"
" template <int size> struct B { };\n"
" typedef B<sizeof(bool)> V;\n"
" }\n"
"}\n"
"namespace ns {\n"
" struct A {\n"
" void f(external::ns1::V);\n"
" };\n"
"}\n"
"namespace ns {\n"
" void A::f(external::ns1::V) {}\n"
"}";
const char exp[] = "namespace external { "
"namespace ns1 { "
"struct B<1> ; "
"} "
"} "
"namespace ns { "
"struct A { "
"void f ( external :: ns1 :: B<1> ) ; "
"} ; "
"} "
"namespace ns { "
"void A :: f ( external :: ns1 :: B<1> ) { } "
"} "
"struct external :: ns1 :: B<1> { } ;";
ASSERT_EQUALS(exp, tok(code, true, Platform::Type::Native, true));
ASSERT_EQUALS("", errout_str());
}
{
// using "namespace external::ns1;" without redundant qualification
const char code[] = "namespace external {\n"
" namespace ns1 {\n"
" template <int size> struct B { };\n"
" typedef B<sizeof(bool)> V;\n"
" }\n"
"}\n"
"namespace ns {\n"
" struct A {\n"
" void f(external::ns1::V);\n"
" };\n"
"}\n"
"using namespace external::ns1;\n"
"namespace ns {\n"
" void A::f(V) {}\n"
"}";
const char exp[] = "namespace external { "
"namespace ns1 { "
"struct B<1> ; "
"} "
"} "
"namespace ns { "
"struct A { "
"void f ( external :: ns1 :: B<1> ) ; "
"} ; "
"} "
"using namespace external :: ns1 ; "
"namespace ns { "
"void A :: f ( external :: ns1 :: B<1> ) { } "
"} "
"struct external :: ns1 :: B<1> { } ;";
const char act[] = "namespace external { "
"namespace ns1 { "
"struct B<1> ; "
"} "
"} "
"namespace ns { "
"struct A { "
"void f ( external :: ns1 :: B<1> ) ; "
"} ; "
"} "
"using namespace external :: ns1 ; "
"namespace ns { "
"void A :: f ( V ) { } "
"} "
"struct external :: ns1 :: B<1> { } ;";
TODO_ASSERT_EQUALS(exp, act, tok(code, true, Platform::Type::Native, true));
TODO_ASSERT_EQUALS("", "[test.cpp:14]: (debug) Executable scope 'f' with unknown function.\n", errout_str());
}
{
// using "namespace external::ns1;" without redundant qualification on declaration and definition
const char code[] = "namespace external {\n"
" namespace ns1 {\n"
" template <int size> struct B { };\n"
" typedef B<sizeof(bool)> V;\n"
" }\n"
"}\n"
"using namespace external::ns1;\n"
"namespace ns {\n"
" struct A {\n"
" void f(V);\n"
" };\n"
"}\n"
"namespace ns {\n"
" void A::f(V) {}\n"
"}";
const char exp[] = "namespace external { "
"namespace ns1 { "
"struct B<1> ; "
"} "
"} "
"using namespace external :: ns1 ; "
"namespace ns { "
"struct A { "
"void f ( external :: ns1 :: B<1> ) ; "
"} ; "
"} "
"namespace ns { "
"void A :: f ( external :: ns1 :: B<1> ) { } "
"} "
"struct external :: ns1 :: B<1> { } ;";
const char act[] = "namespace external { "
"namespace ns1 { "
"template < int size > struct B { } ; "
"} "
"} "
"using namespace external :: ns1 ; "
"namespace ns { "
"struct A { "
"void f ( V ) ; "
"} ; "
"} "
"namespace ns { "
"void A :: f ( V ) { } "
"}";
TODO_ASSERT_EQUALS(exp, act, tok(code, true, Platform::Type::Native, true));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "namespace external {\n"
" template <int size> struct B { };\n"
" namespace ns1 {\n"
" typedef B<sizeof(bool)> V;\n"
" }\n"
"}\n"
"namespace ns {\n"
" struct A {\n"
" void f(external::ns1::V);\n"
" };\n"
"}\n"
"namespace ns {\n"
" void A::f(external::ns1::V) {}\n"
"}";
const char exp[] = "namespace external { "
"struct B<1> ; "
"} "
"namespace ns { "
"struct A { "
"void f ( external :: B<1> ) ; "
"} ; "
"} "
"namespace ns { "
"void A :: f ( external :: B<1> ) { } "
"} "
"struct external :: B<1> { } ;";
ASSERT_EQUALS(exp, tok(code, true, Platform::Type::Native, true));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "template <int size> struct B { };\n"
"namespace external {\n"
" namespace ns1 {\n"
" typedef B<sizeof(bool)> V;\n"
" }\n"
"}\n"
"namespace ns {\n"
" struct A {\n"
" void f(external::ns1::V);\n"
" };\n"
"}\n"
"namespace ns {\n"
" void A::f(external::ns1::V) {}\n"
"}";
const char exp[] = "struct B<1> ; "
"namespace ns { "
"struct A { "
"void f ( B<1> ) ; "
"} ; "
"} "
"namespace ns { "
"void A :: f ( B<1> ) { } "
"} "
"struct B<1> { } ;";
ASSERT_EQUALS(exp, tok(code, true, Platform::Type::Native, true));
ASSERT_EQUALS("", errout_str());
}
}
void simplifyTypedef138() {
const char code[] = "namespace foo { class Bar; }\n"
"class Baz;\n"
"typedef foo::Bar C;\n"
"namespace bar {\n"
"class C : Baz {};\n"
"}\n";
ASSERT_EQUALS("namespace foo { class Bar ; } class Baz ; namespace bar { class C : Baz { } ; }", tok(code));
}
void simplifyTypedef139()
{
const char code[] = "typedef struct c a;\n"
"struct {\n"
" a *b;\n"
"} * d;\n"
"void e(a *a) {\n"
" if (a < d[0].b) {}\n"
"}\n";
ASSERT_EQUALS(
"struct Anonymous0 { struct c * b ; } ; struct Anonymous0 * d ; void e ( struct c * a ) { if ( a < d [ 0 ] . b ) { } }",
tok(code));
ASSERT_EQUALS_WITHOUT_LINENUMBERS(
"[test.cpp:6]: (debug) valueflow.cpp:6730:(valueFlow) bailout: valueFlowAfterCondition: bailing in conditional block\n"
"[test.cpp:6]: (debug) valueflow.cpp:6730:(valueFlow) bailout: valueFlowAfterCondition: bailing in conditional block\n", // duplicate
errout_str());
}
void simplifyTypedef140() {
{ // #10798
const char code[] = "typedef void (*b)();\n"
"enum class E { a, b, c };\n";
ASSERT_EQUALS("enum class E { a , b , c } ;", tok(code));
}
{
const char code[] = "typedef int A;\n"
"enum class E { A };\n";
ASSERT_EQUALS("enum class E { A } ;", tok(code));
}
{
const char code[] = "namespace N {\n"
" struct S { enum E { E0 }; };\n"
"}\n"
"typedef N::S T;\n"
"enum class E { a = T::E0 };\n";
ASSERT_EQUALS("namespace N { struct S { enum E { E0 } ; } ; } enum class E { a = N :: S :: E0 } ;", tok(code));
}
{ // #11494
const char code[] = "typedef struct S {} KEY;\n"
"class C { enum E { KEY }; };\n";
ASSERT_EQUALS("struct S { } ; class C { enum E { KEY } ; } ;", tok(code));
}
}
void simplifyTypedef141() { // #10144
const char code[] = "class C {\n"
" struct I {\n"
" using vt = const std::string;\n"
" using ptr = vt*;\n"
" };\n"
"};\n";
ASSERT_EQUALS("class C { struct I { } ; } ;", tok(code));
}
void simplifyTypedef142() { // T() when T is a pointer type
// #11232
const char code1[] = "typedef int* T;\n"
"a = T();\n";
ASSERT_EQUALS("a = ( int * ) 0 ;", tok(code1));
// #9479
const char code2[] = "typedef int* T;\n"
"void f(T = T()){}\n";
ASSERT_EQUALS("void f ( int * = ( int * ) 0 ) { }", tok(code2));
// #11430
const char code3[] = "typedef char* T;\n"
"T f() { return T(\"abc\"); }\n";
ASSERT_EQUALS("char * f ( ) { return ( ( char * ) ( \"abc\" ) ) ; }", tok(code3));
const char code4[] = "typedef struct _a *A;\n" // #13104
"typedef struct _b* B;\n"
"typedef A(get_t)(B);\n"
"extern get_t* get;\n"
"A f() {\n"
" return get(0);\n"
"}\n";
ASSERT_EQUALS("extern struct _a * ( * get ) ( struct _b * ) ; "
"struct _a * f ( ) { return get ( 0 ) ; }",
tok(code4));
const char code5[] = "struct S { int x; };\n" // #13182
"typedef S* PS;\n"
"void f(void* a[], int i) {\n"
" PS(a[i])->x = i;\n"
"}\n";
ASSERT_EQUALS("struct S { int x ; } ; "
"void f ( void * a [ ] , int i ) { "
"( ( S * ) ( a [ i ] ) ) . x = i ; "
"}",
tok(code5));
}
void simplifyTypedef143() { // #11506
const char code[] = "typedef struct { int i; } B;\n"
"void f() {\n"
" struct D : B {\n"
" char c;\n"
" };\n"
"}\n";
ASSERT_EQUALS("struct B { int i ; } ; void f ( ) { struct D : B { char c ; } ; }", tok(code));
}
void simplifyTypedef144() { // #9353
const char code[] = "typedef struct {} X;\n"
"std::vector<X> v;\n";
ASSERT_EQUALS("struct X { } ; std :: vector < X > v ;", tok(code));
}
void simplifyTypedef145() {
{ // #11634
const char code[] = "int typedef i;\n"
"i main() {}\n";
ASSERT_EQUALS("int main ( ) { }", tok(code));
}
{
const char code[] = "struct {} typedef S;\n"
"void f() {\n"
" S();\n"
"}\n";
ASSERT_EQUALS("struct S { } ; void f ( ) { struct S ( ) ; }", tok(code));
}
{
const char code[] = "struct {} typedef S;\n" // don't crash
"S();\n";
ASSERT_EQUALS("struct S { } ; struct S ( ) ;", tok(code));
}
{ // #11693
const char code[] = "typedef unsigned char unsigned char;\n" // don't hang
"void f(char);\n";
ASSERT_EQUALS("void f ( char ) ;", tok(code));
}
{ // #10796
const char code[] = "typedef unsigned a[7];\n"
"void f(unsigned N) {\n"
" a** p = new a * [N];\n"
"}\n";
TODO_ASSERT_EQUALS("does not compile", "void f ( int N ) { int ( * * p ) [ 7 ] ; p = new int ( * ) [ N ] [ 7 ] ; }", tok(code));
}
{ // #11772
const char code[] = "typedef t;\n" // don't crash on implicit int
"void g() {\n"
" sizeof(t);\n"
"}\n";
ASSERT_EQUALS("void g ( ) { sizeof ( t ) ; }", tok(code)); // TODO: handle implicit int
ignore_errout(); // we do not care about the output
}
{
const char code[] = "typedef t[3];\n"
"void g() {\n"
" sizeof(t);\n"
"}\n";
ASSERT_EQUALS("void g ( ) { sizeof ( t ) ; }", tok(code)); // TODO: handle implicit int
ignore_errout(); // we do not care about the output
}
}
void simplifyTypedef146() {
{
const char code[] = "namespace N {\n" // #11978
" typedef int T;\n"
" struct C {\n"
" C(T*);\n"
" void* p;\n"
" };\n"
"}\n"
"N::C::C(T*) : p(nullptr) {}\n";
ASSERT_EQUALS("namespace N { struct C { C ( int * ) ; void * p ; } ; } N :: C :: C ( int * ) : p ( nullptr ) { }", tok(code));
}
{
const char code[] = "namespace N {\n" // #11986
" typedef char U;\n"
" typedef int V;\n"
" struct S {};\n"
" struct T { void f(V*); };\n"
"}\n"
"void N::T::f(V*) {}\n"
"namespace N {}\n";
ASSERT_EQUALS("namespace N { struct S { } ; struct T { void f ( int * ) ; } ; } void N :: T :: f ( int * ) { }", tok(code));
}
{
const char code[] = "namespace N {\n" // #12008
" typedef char U;\n"
" typedef int V;\n"
" struct S {\n"
" S(V* v);\n"
" };\n"
"}\n"
"void f() {}\n"
"N::S::S(V* v) {}\n"
"namespace N {}\n";
ASSERT_EQUALS("namespace N { struct S { S ( int * v ) ; } ; } void f ( ) { } N :: S :: S ( int * v ) { }", tok(code));
}
}
void simplifyTypedef147() {
const char code[] = "namespace N {\n" // #12014
" template<typename T>\n"
" struct S {};\n"
"}\n"
"typedef N::S<int> S;\n"
"namespace N {\n"
" template<typename T>\n"
" struct U {\n"
" S<T> operator()() {\n"
" return {};\n"
" }\n"
" };\n"
"}\n";
ASSERT_EQUALS("namespace N { template < typename T > struct S { } ; } namespace N { template < typename T > struct U { S < T > operator() ( ) { return { } ; } } ; }",
tok(code));
}
void simplifyTypedef148() {
const char code[] = "typedef int& R;\n" // #12166
"R r = i;\n";
ASSERT_EQUALS("int & r = i ;", tok(code));
}
void simplifyTypedef149() { // #12218
{
const char code[] = "namespace N {\n"
" typedef struct S {} S;\n"
"}\n"
"void g(int);\n"
"void f() {\n"
" g(sizeof(struct N::S));\n"
"}\n";
ASSERT_EQUALS("namespace N { struct S { } ; } void g ( int ) ; void f ( ) { g ( sizeof ( struct N :: S ) ) ; }", tok(code));
}
{
const char code[] = "namespace N {\n"
" typedef class C {} C;\n"
"}\n"
"void g(int);\n"
"void f() {\n"
" g(sizeof(class N::C));\n"
"}\n";
ASSERT_EQUALS("namespace N { class C { } ; } void g ( int ) ; void f ( ) { g ( sizeof ( class N :: C ) ) ; }", tok(code));
}
{
const char code[] = "namespace N {\n"
" typedef union U {} U;\n"
"}\n"
"void g(int);\n"
"void f() {\n"
" g(sizeof(union N::U));\n"
"}\n";
ASSERT_EQUALS("namespace N { union U { } ; } void g ( int ) ; void f ( ) { g ( sizeof ( union N :: U ) ) ; }", tok(code));
}
{
const char code[] = "namespace N {\n"
" typedef enum E {} E;\n"
"}\n"
"void g(int);\n"
"void f() {\n"
" g(sizeof(enum N::E));\n"
"}\n";
ASSERT_EQUALS("namespace N { enum E { } ; } void g ( int ) ; void f ( ) { g ( sizeof ( enum N :: E ) ) ; }", tok(code));
}
}
void simplifyTypedef150() { // #12475
const char *exp{};
const char code[] = "struct S {\n"
" std::vector<int> const& h(int);\n"
"};\n"
"typedef std::vector<int> const& (S::* func_t)(int);\n"
"void g(func_t, int);\n"
"void f() {\n"
" g(func_t(&S::h), 5);\n"
"}\n";
exp = "struct S { "
"const std :: vector < int > & h ( int ) ; "
"} ; "
"void g ( const std :: vector < int > & ( S :: * ) ( int ) , int ) ; "
"void f ( ) { "
"g ( const std :: vector < int > & ( S :: * ( & S :: h ) ) ( int ) , 5 ) ; " // TODO: don't generate invalid code
"}";
ASSERT_EQUALS(exp, tok(code));
}
void simplifyTypedef151() {
const char *exp{};
const char code[] = "namespace N {\n" // #12597
" typedef int T[10];\n"
" const T* f() { return static_cast<const T*>(nullptr); }\n"
"}\n";
exp = "namespace N { "
"const int ( * f ( ) ) [ 10 ] { return static_cast < const int ( * ) [ 10 ] > ( nullptr ) ; } "
"}";
ASSERT_EQUALS(exp, tok(code));
}
void simplifyTypedef152() {
const char *exp{};
const char code[] = "namespace O { struct T {}; }\n"
"typedef O::T S;\n"
"namespace M {\n"
" enum E { E0, S = 1 };\n"
" enum class F : ::std::int8_t { F0, S = 1 };\n"
"}\n"
"namespace N { enum { G0, S = 1 }; }\n";
exp = "namespace O { struct T { } ; } "
"namespace M { "
"enum E { E0 , S = 1 } ; "
"enum class F : :: std :: int8_t { F0 , S = 1 } ; "
"}"
" namespace N { enum Anonymous0 { G0 , S = 1 } ; "
"}";
ASSERT_EQUALS(exp, tok(code));
}
void simplifyTypedef153() {
const char *exp{}; // #12647
const char code[] = "typedef unsigned long X;\n"
"typedef unsigned long X;\n"
"typedef X Y;\n"
"typedef X* Yp;\n"
"typedef X Ya[3];\n"
"Y y;\n"
"Yp yp;\n"
"Ya ya;\n";
exp = "long y ; long * yp ; long ya [ 3 ] ;";
ASSERT_EQUALS(exp, tok(code));
}
void simplifyTypedef154() {
const char code[] = "typedef int T;\n"
"typedef T T;\n"
"T t = 0;\n";
const char exp[] = "int t ; t = 0 ;";
ASSERT_EQUALS(exp, tok(code));
}
void simplifyTypedef155() {
const char code[] = "typedef struct S T;\n" // #12808
"typedef struct S { int i; } T;\n"
"extern \"C\" void f(T* t);\n";
const char exp[] = "struct S { int i ; } ; "
"void f ( struct S * t ) ;";
ASSERT_EQUALS(exp, tok(code));
}
void simplifyTypedef156() {
const char code[] = "typedef struct S_t {\n" // #12930
" enum E { E0 };\n"
" E e;\n"
"} S;\n"
"void f(S s) {\n"
" switch (s.e) {\n"
" case S::E0:\n"
" break;\n"
" }\n"
"}\n";
const char exp[] = "struct S_t { "
"enum E { E0 } ; "
"E e ; "
"} ; "
"void f ( struct S_t s ) { "
"switch ( s . e ) { "
"case S_t :: E0 : ; "
"break ; "
"} "
"}";
ASSERT_EQUALS(exp, tok(code));
const char code2[] = "typedef enum E_t { E0 } E;\n"
"void f(E e) {\n"
" switch (e) {\n"
" case E::E0:\n"
" break;\n"
" }\n"
"}\n";
const char exp2[] = "enum E_t { E0 } ; "
"void f ( enum E_t e ) { "
"switch ( e ) { "
"case E_t :: E0 : ; "
"break ; "
"} "
"}";
ASSERT_EQUALS(exp2, tok(code2));
const char code3[] = "typedef union U_t {\n"
" int i;\n"
" enum { E0 } e;\n"
"} U;\n"
"void f(U u) {\n"
" switch (u.e) {\n"
" case U::E0:\n"
" break;\n"
" }\n"
"}\n";
const char exp3[] = "union U_t { "
"int i ; "
"enum Anonymous0 { E0 } ; "
"enum Anonymous0 e ; "
"} ; "
"void f ( union U_t u ) { "
"switch ( u . e ) { "
"case U_t :: E0 : ; "
"break ; "
"} "
"}";
ASSERT_EQUALS(exp3, tok(code3));
const char code4[] = "struct A { static const int i = 1; };\n" // #12947
"typedef A B;\n"
"int f() {\n"
" return B::i;\n"
"}\n";
const char exp4[] = "struct A { "
"static const int i = 1 ; "
"} ; "
"int f ( ) { "
"return A :: i ; "
"}";
ASSERT_EQUALS(exp4, tok(code4));
}
void simplifyTypedef157() {
const char code[] = "namespace NS1 {\n" // #13451
" typedef NS2::Bar Bar;\n"
" using NS2::MyType;\n"
"}\n"
"enum E : unsigned int {\n"
" zero = 0,\n"
" MyType = 1\n"
"};\n"
"namespace NS1 {}\n";
const char exp[] = "enum E : int { zero = 0 , MyType = 1 } ;";
ASSERT_EQUALS(exp, tok(code));
}
void simplifyTypedefFunction1() {
{
const char code[] = "typedef void (*my_func)();\n"
"std::queue<my_func> func_queue;";
// The expected result..
const char expected[] = "std :: queue < void ( * ) ( ) > func_queue ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "typedef void (*my_func)(void);\n"
"std::queue<my_func> func_queue;";
// The expected result..
const char expected[] = "std :: queue < void ( * ) ( void ) > func_queue ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "typedef void (*my_func)(int);\n"
"std::queue<my_func> func_queue;";
// The expected result..
const char expected[] = "std :: queue < void ( * ) ( int ) > func_queue ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "typedef void (*my_func)(int*);\n"
"std::queue<my_func> func_queue;";
// The expected result..
const char expected[] = "std :: queue < void ( * ) ( int * ) > func_queue ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
{
// ticket # 1615
const char code[] = "typedef void (*my_func)(arg_class*);\n"
"std::queue<my_func> func_queue;";
// The expected result..
const char expected[] = "std :: queue < void ( * ) ( arg_class * ) > func_queue ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "typedef void (my_func)();\n"
"std::queue<my_func *> func_queue;";
// The expected result..
const char expected[] = "std :: queue < void ( * ) ( ) > func_queue ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "typedef void (my_func)(void);\n"
"std::queue<my_func *> func_queue;";
// The expected result..
const char expected[] = "std :: queue < void ( * ) ( void ) > func_queue ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "typedef void (my_func)(int);\n"
"std::queue<my_func *> func_queue;";
// The expected result..
const char expected[] = "std :: queue < void ( * ) ( int ) > func_queue ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "typedef void (my_func)(int*);\n"
"std::queue<my_func *> func_queue;";
// The expected result..
const char expected[] = "std :: queue < void ( * ) ( int * ) > func_queue ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "typedef void (my_func)(arg_class*);\n"
"std::queue<my_func *> func_queue;";
// The expected result..
const char expected[] = "std :: queue < void ( * ) ( arg_class * ) > func_queue ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "typedef void my_func();\n"
"std::queue<my_func *> func_queue;";
// The expected result..
const char expected[] = "std :: queue < void ( * ) ( ) > func_queue ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "typedef void my_func(void);\n"
"std::queue<my_func *> func_queue;";
// The expected result..
const char expected[] = "std :: queue < void ( * ) ( void ) > func_queue ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "typedef void my_func(int);\n"
"std::queue<my_func *> func_queue;";
// The expected result..
const char expected[] = "std :: queue < void ( * ) ( int ) > func_queue ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "typedef void my_func(int*);\n"
"std::queue<my_func *> func_queue;";
// The expected result..
const char expected[] = "std :: queue < void ( * ) ( int * ) > func_queue ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "typedef void my_func(arg_class*);\n"
"std::queue<my_func *> func_queue;";
// The expected result..
const char expected[] = "std :: queue < void ( * ) ( arg_class * ) > func_queue ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "typedef void (my_func());\n"
"std::queue<my_func *> func_queue;";
// The expected result..
const char expected[] = "std :: queue < void ( * ) ( ) > func_queue ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "typedef void (my_func(void));\n"
"std::queue<my_func *> func_queue;";
// The expected result..
const char expected[] = "std :: queue < void ( * ) ( void ) > func_queue ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "typedef void (my_func(int));\n"
"std::queue<my_func *> func_queue;";
// The expected result..
const char expected[] = "std :: queue < void ( * ) ( int ) > func_queue ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "typedef void (my_func(int*));\n"
"std::queue<my_func *> func_queue;";
// The expected result..
const char expected[] = "std :: queue < void ( * ) ( int * ) > func_queue ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "typedef void (my_func(arg_class*));\n"
"std::queue<my_func *> func_queue;";
// The expected result..
const char expected[] = "std :: queue < void ( * ) ( arg_class * ) > func_queue ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
}
void simplifyTypedefFunction2() { // ticket #1685
const char code[] = "typedef void voidfn (int);\n"
"voidfn xxx;";
// The expected result..
const char expected[] = "void xxx ( int ) ;";
ASSERT_EQUALS(expected, tok(code));
}
void simplifyTypedefFunction3() {
{
const char code[] = "typedef C func1();\n"
"typedef C (* func2)();\n"
"typedef C (& func3)();\n"
"typedef C (C::* func4)();\n"
"typedef C (C::* func5)() const;\n"
"typedef C (C::* func6)() volatile;\n"
"typedef C (C::* func7)() const volatile;\n"
"func1 f1;\n"
"func2 f2;\n"
"func3 f3;\n"
"func4 f4;\n"
"func5 f5;\n"
"func6 f6;\n"
"func7 f7;";
// The expected result..
const char expected[] = "C f1 ( ) ; "
"C ( * f2 ) ( ) ; "
"C ( & f3 ) ( ) ; "
"C ( * f4 ) ( ) ; "
"C ( * f5 ) ( ) ; "
"C ( * f6 ) ( ) ; "
"C ( * f7 ) ( ) ;";
ASSERT_EQUALS(expected, tok(code, true, Platform::Type::Native, false));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "typedef C const func1();\n"
"typedef C const (* func2)();\n"
"typedef C const (& func3)();\n"
"typedef C const (C::* func4)();\n"
"typedef C const (C::* func5)() const;\n"
"typedef C const (C::* func6)() volatile;\n"
"typedef C const (C::* func7)() const volatile;\n"
"func1 f1;\n"
"func2 f2;\n"
"func3 f3;\n"
"func4 f4;\n"
"func5 f5;\n"
"func6 f6;\n"
"func7 f7;";
// The expected result..
// C const -> const C
const char expected[] = "const C f1 ( ) ; "
"const C ( * f2 ) ( ) ; "
"const C ( & f3 ) ( ) ; "
"const C ( * f4 ) ( ) ; "
"const C ( * f5 ) ( ) ; "
"const C ( * f6 ) ( ) ; "
"const C ( * f7 ) ( ) ;";
ASSERT_EQUALS(expected, tok(code, true, Platform::Type::Native, false));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "typedef const C func1();\n"
"typedef const C (* func2)();\n"
"typedef const C (& func3)();\n"
"typedef const C (C::* func4)();\n"
"typedef const C (C::* func5)() const;\n"
"typedef const C (C::* func6)() volatile;\n"
"typedef const C (C::* func7)() const volatile;\n"
"func1 f1;\n"
"func2 f2;\n"
"func3 f3;\n"
"func4 f4;\n"
"func5 f5;\n"
"func6 f6;\n"
"func7 f7;";
// The expected result..
const char expected[] = "const C f1 ( ) ; "
"const C ( * f2 ) ( ) ; "
"const C ( & f3 ) ( ) ; "
"const C ( * f4 ) ( ) ; "
"const C ( * f5 ) ( ) ; "
"const C ( * f6 ) ( ) ; "
"const C ( * f7 ) ( ) ;";
ASSERT_EQUALS(expected, tok(code, true, Platform::Type::Native, false));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "typedef C * func1();\n"
"typedef C * (* func2)();\n"
"typedef C * (& func3)();\n"
"typedef C * (C::* func4)();\n"
"typedef C * (C::* func5)() const;\n"
"typedef C * (C::* func6)() volatile;\n"
"typedef C * (C::* func7)() const volatile;\n"
"func1 f1;\n"
"func2 f2;\n"
"func3 f3;\n"
"func4 f4;\n"
"func5 f5;\n"
"func6 f6;\n"
"func7 f7;";
// The expected result..
const char expected[] = "C * f1 ( ) ; "
"C * ( * f2 ) ( ) ; "
"C * ( & f3 ) ( ) ; "
"C * ( * f4 ) ( ) ; "
"C * ( * f5 ) ( ) ; "
"C * ( * f6 ) ( ) ; "
"C * ( * f7 ) ( ) ;";
ASSERT_EQUALS(expected, tok(code, true, Platform::Type::Native, false));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "typedef const C * func1();\n"
"typedef const C * (* func2)();\n"
"typedef const C * (& func3)();\n"
"typedef const C * (C::* func4)();\n"
"typedef const C * (C::* func5)() const;\n"
"typedef const C * (C::* func6)() volatile;\n"
"typedef const C * (C::* func7)() const volatile;\n"
"func1 f1;\n"
"func2 f2;\n"
"func3 f3;\n"
"func4 f4;\n"
"func5 f5;\n"
"func6 f6;\n"
"func7 f7;";
// The expected result..
const char expected[] = "const C * f1 ( ) ; "
"const C * ( * f2 ) ( ) ; "
"const C * ( & f3 ) ( ) ; "
"const C * ( * f4 ) ( ) ; "
"const C * ( * f5 ) ( ) ; "
"const C * ( * f6 ) ( ) ; "
"const C * ( * f7 ) ( ) ;";
ASSERT_EQUALS(expected, tok(code, true, Platform::Type::Native, false));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "typedef C const * func1();\n"
"typedef C const * (* func2)();\n"
"typedef C const * (& func3)();\n"
"typedef C const * (C::* func4)();\n"
"typedef C const * (C::* func5)() const;\n"
"typedef C const * (C::* func6)() volatile;\n"
"typedef C const * (C::* func7)() const volatile;\n"
"func1 f1;\n"
"func2 f2;\n"
"func3 f3;\n"
"func4 f4;\n"
"func5 f5;\n"
"func6 f6;\n"
"func7 f7;";
// The expected result..
// C const -> const C
const char expected[] = "const C * f1 ( ) ; "
"const C * ( * f2 ) ( ) ; "
"const C * ( & f3 ) ( ) ; "
"const C * ( * f4 ) ( ) ; "
"const C * ( * f5 ) ( ) ; "
"const C * ( * f6 ) ( ) ; "
"const C * ( * f7 ) ( ) ;";
ASSERT_EQUALS(expected, tok(code, true, Platform::Type::Native, false));
ASSERT_EQUALS("", errout_str());
}
}
void simplifyTypedefFunction4() {
const char code[] = "typedef int ( * ( * type1 ) ( bool ) ) ( int , int ) ;\n"
"typedef int ( * ( type2 ) ( bool ) ) ( int , int ) ;\n"
"typedef int ( * type3 ( bool ) ) ( int , int ) ;\n"
"type1 t1;\n"
"type2 t2;\n"
"type3 t3;";
// The expected result..
const char expected[] = "int ( * ( * t1 ) ( bool ) ) ( int , int ) ; "
"int * t2 ( bool ) ; "
"int * t3 ( bool ) ;";
ASSERT_EQUALS(expected, tok(code, false));
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedefFunction5() {
const char code[] = "typedef int ( * type1 ) ( float ) ;\n"
"typedef int ( * const type2 ) ( float ) ;\n"
"typedef int ( * volatile type3 ) ( float ) ;\n"
"typedef int ( * const volatile type4 ) ( float ) ;\n"
"typedef int ( C :: * type5 ) ( float ) ;\n"
"typedef int ( C :: * const type6 ) ( float ) ;\n"
"typedef int ( C :: * volatile type7 ) ( float ) ;\n"
"typedef int ( C :: * const volatile type8 ) ( float ) ;\n"
"typedef int ( :: C :: * type9 ) ( float ) ;\n"
"typedef int ( :: C :: * const type10 ) ( float ) ;\n"
"typedef int ( :: C :: * volatile type11 ) ( float ) ;\n"
"typedef int ( :: C :: * const volatile type12 ) ( float ) ;\n"
"type1 t1;\n"
"type2 t2;\n"
"type3 t3;\n"
"type4 t4;\n"
"type5 t5;\n"
"type6 t6;\n"
"type7 t7;\n"
"type8 t8;\n"
"type9 t9;\n"
"type10 t10;\n"
"type11 t11;\n"
"type12 t12;";
// The expected result..
const char expected[] = "int ( * t1 ) ( float ) ; "
"int ( * const t2 ) ( float ) ; "
"int ( * volatile t3 ) ( float ) ; "
"int ( * const volatile t4 ) ( float ) ; "
"int ( * t5 ) ( float ) ; "
"int ( * const t6 ) ( float ) ; "
"int ( * volatile t7 ) ( float ) ; "
"int ( * const volatile t8 ) ( float ) ; "
"int ( :: C :: * t9 ) ( float ) ; "
"int ( :: C :: * const t10 ) ( float ) ; "
"int ( :: C :: * volatile t11 ) ( float ) ; "
"int ( :: C :: * const volatile t12 ) ( float ) ;";
ASSERT_EQUALS(expected, tok(code, false));
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedefFunction6() {
const char code[] = "typedef void (*testfp)();\n"
"struct Fred\n"
"{\n"
" testfp get1() { return 0; }\n"
" void ( * get2 ( ) ) ( ) { return 0 ; }\n"
" testfp get3();\n"
" void ( * get4 ( ) ) ( );\n"
"};\n"
"testfp Fred::get3() { return 0; }\n"
"void ( * Fred::get4 ( ) ) ( ) { return 0 ; }";
// The expected result..
const char expected[] = "struct Fred "
"{ "
"void * get1 ( ) { return 0 ; } "
"void * get2 ( ) { return 0 ; } "
"void * get3 ( ) ; "
"void * get4 ( ) ; "
"} ; "
"void * Fred :: get3 ( ) { return 0 ; } "
"void * Fred :: get4 ( ) { return 0 ; }";
ASSERT_EQUALS(expected, tok(code, false));
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedefFunction7() {
const char code[] = "typedef void ( __gnu_cxx :: _SGIAssignableConcept < _Tp > :: * _func_Tp_SGIAssignableConcept ) () ;"
"_func_Tp_SGIAssignableConcept X;";
// The expected result..
const char expected[] = "void ( __gnu_cxx :: _SGIAssignableConcept < _Tp > :: * X ) ( ) ;";
ASSERT_EQUALS(expected, tok(code, false));
ASSERT_EQUALS("", errout_str());
}
void simplifyTypedefFunction8() {
// #2376 - internal error
const char code[] = "typedef int f_expand(const nrv_byte *);\n"
"void f(f_expand *(*get_fexp(int))){}";
checkSimplifyTypedef(code);
TODO_ASSERT_EQUALS("", "[test.cpp:2]: (debug) Function::addArguments found argument 'int' with varid 0.\n", errout_str()); // make sure that there is no internal error
}
void simplifyTypedefFunction9() {
{
const char code[] = "typedef ::C (::C::* func1)();\n"
"typedef ::C (::C::* func2)() const;\n"
"typedef ::C (::C::* func3)() volatile;\n"
"typedef ::C (::C::* func4)() const volatile;\n"
"func1 f1;\n"
"func2 f2;\n"
"func3 f3;\n"
"func4 f4;";
// The expected result..
const char expected[] = ":: C ( :: C :: * f1 ) ( ) ; "
":: C ( :: C :: * f2 ) ( ) const ; "
":: C ( :: C :: * f3 ) ( ) volatile ; "
":: C ( :: C :: * f4 ) ( ) const volatile ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "typedef B::C (B::C::* func1)();\n"
"typedef B::C (B::C::* func2)() const;\n"
"typedef B::C (B::C::* func3)() volatile;\n"
"typedef B::C (B::C::* func4)() const volatile;\n"
"func1 f1;\n"
"func2 f2;\n"
"func3 f3;\n"
"func4 f4;";
// The expected result..
const char expected[] = "B :: C ( * f1 ) ( ) ; "
"B :: C ( * f2 ) ( ) ; "
"B :: C ( * f3 ) ( ) ; "
"B :: C ( * f4 ) ( ) ;";
ASSERT_EQUALS(expected, tok(code, true, Platform::Type::Native, false));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "typedef ::B::C (::B::C::* func1)();\n"
"typedef ::B::C (::B::C::* func2)() const;\n"
"typedef ::B::C (::B::C::* func3)() volatile;\n"
"typedef ::B::C (::B::C::* func4)() const volatile;\n"
"func1 f1;\n"
"func2 f2;\n"
"func3 f3;\n"
"func4 f4;";
// The expected result..
const char expected[] = ":: B :: C ( :: B :: C :: * f1 ) ( ) ; "
":: B :: C ( :: B :: C :: * f2 ) ( ) const ; "
":: B :: C ( :: B :: C :: * f3 ) ( ) volatile ; "
":: B :: C ( :: B :: C :: * f4 ) ( ) const volatile ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "typedef A::B::C (A::B::C::* func1)();\n"
"typedef A::B::C (A::B::C::* func2)() const;\n"
"typedef A::B::C (A::B::C::* func3)() volatile;\n"
"typedef A::B::C (A::B::C::* func4)() const volatile;\n"
"func1 f1;\n"
"func2 f2;\n"
"func3 f3;\n"
"func4 f4;";
// The expected result..
const char expected[] = "A :: B :: C ( * f1 ) ( ) ; "
"A :: B :: C ( * f2 ) ( ) ; "
"A :: B :: C ( * f3 ) ( ) ; "
"A :: B :: C ( * f4 ) ( ) ;";
ASSERT_EQUALS(expected, tok(code, true, Platform::Type::Native, false));
ASSERT_EQUALS("", errout_str());
}
}
void simplifyTypedefFunction10() {
const char code[] = "enum Format_E1 { FORMAT11, FORMAT12 } Format_T1;\n"
"namespace MySpace {\n"
" enum Format_E2 { FORMAT21, FORMAT22 } Format_T2;\n"
"}\n"
"typedef Format_E1 (**PtrToFunPtr_Type1)();\n"
"typedef MySpace::Format_E2 (**PtrToFunPtr_Type2)();\n"
"PtrToFunPtr_Type1 t1;\n"
"PtrToFunPtr_Type2 t2;";
ASSERT_EQUALS("enum Format_E1 { FORMAT11 , FORMAT12 } ; enum Format_E1 Format_T1 ; "
"namespace MySpace { "
"enum Format_E2 { FORMAT21 , FORMAT22 } ; enum Format_E2 Format_T2 ; "
"} "
"Format_E1 ( * * t1 ) ( ) ; "
"MySpace :: Format_E2 ( * * t2 ) ( ) ;",
tok(code,false));
}
void simplifyTypedefFunction11() {
const char code[] = "typedef void (*func_t) (int);\n"
"void g(int);\n"
"void f(void* p) {\n"
" if (g != func_t(p)) {}\n"
" if (g != (func_t)p) {}\n"
"}\n";
TODO_ASSERT_EQUALS("void g ( int ) ; "
"void f ( void * p ) { "
"if ( g != ( void ( * ) ( int ) ) ( p ) ) { } "
"if ( g != ( void ( * ) ( int ) ) p ) { } "
"}",
"void g ( int ) ; "
"void f ( void * p ) { "
"if ( g != void * ( p ) ) { } "
"if ( g != ( void * ) p ) { } "
"}",
tok(code,false));
ignore_errout(); // we are not interested in the output
}
void simplifyTypedefStruct() {
const char code1[] = "typedef struct S { int x; } xyz;\n"
"xyz var;";
ASSERT_EQUALS("struct S { int x ; } ; struct S var ;", tok(code1,false));
const char code2[] = "typedef const struct S { int x; } xyz;\n"
"xyz var;";
ASSERT_EQUALS("struct S { int x ; } ; const struct S var ;", tok(code2,false));
const char code3[] = "typedef volatile struct S { int x; } xyz;\n"
"xyz var;";
ASSERT_EQUALS("struct S { int x ; } ; volatile struct S var ;", tok(code3,false));
}
void simplifyTypedefShadow() { // shadow variable (#4445)
const char code[] = "typedef struct { int x; } xyz;;\n"
"void f(){\n"
" int abc, xyz;\n" // <- shadow variable
"}";
ASSERT_EQUALS("struct xyz { int x ; } ; void f ( ) { int abc ; int xyz ; }",
tok(code,false));
}
void simplifyTypedefMacro() {
const char code[] = "typedef uint32_t index_t;\n"
"\n"
"#define NO_SEGMENT ((index_t)12)\n"
"\n"
"void foo(index_t prev_segment) {\n"
" if(prev_segment==NO_SEGMENT) {}\n" // <- test that index_t is replaced with uint32_t in the expanded tokens
"}";
ASSERT_EQUALS("void foo ( uint32_t prev_segment ) { if ( prev_segment == ( ( uint32_t ) 12 ) ) { } }",
simplifyTypedefP(code));
}
void simplifyTypedefOriginalName() {
const char code[] = "typedef unsigned char uint8_t;"
"typedef float (*rFunctionPointer_fp)(uint8_t, uint8_t);"
"typedef enum eEnumDef {"
" ABC = 0,"
"}eEnum_t;"
"typedef enum {"
" ABC = 0,"
"}eEnum2_t;"
"typedef short int16_t;"
"typedef struct stStructDef {"
" int16_t swA;"
"}stStruct_t;"
"double endOfTypeDef;"
"eEnum2_t enum2Type;"
"stStruct_t structType;"
"eEnum_t enumType;"
"uint8_t t;"
"void test(rFunctionPointer_fp functionPointer);";
Tokenizer tokenizer(settings1, *this);
std::istringstream istr(code);
ASSERT(tokenizer.list.createTokens(istr, "file.c"));
tokenizer.createLinks();
tokenizer.simplifyTypedef();
try {
tokenizer.validate();
}
catch (const InternalError&) {
ASSERT_EQUALS_MSG(false, true, "Validation of Tokenizer failed");
}
const Token* token;
// Get the Token which is at the end of all the Typedef's in this case i placed a variable
const Token* endOfTypeDef = Token::findsimplematch(tokenizer.list.front(), "endOfTypeDef", tokenizer.list.back());
// Search for the simplified char token and check its original Name
token = Token::findsimplematch(endOfTypeDef, "char", tokenizer.list.back());
ASSERT_EQUALS("uint8_t", token->originalName());
// Search for the simplified eEnumDef token and check its original Name
token = Token::findsimplematch(endOfTypeDef, "eEnumDef", tokenizer.list.back());
ASSERT_EQUALS("eEnum_t", token->originalName());
// Search for the eEnum2_t token as it does not have a name it should be the direct type name
token = Token::findsimplematch(endOfTypeDef, "eEnum2_t", tokenizer.list.back());
ASSERT_EQUALS("eEnum2_t", token->str());
// Search for the simplified stStructDef token and check its original Name
token = Token::findsimplematch(endOfTypeDef, "stStructDef", tokenizer.list.back());
ASSERT_EQUALS("stStruct_t", token->originalName());
// Search for the simplified short token and check its original Name, start from front to get the variable in the struct
token = Token::findsimplematch(tokenizer.list.front(), "short", tokenizer.list.back());
ASSERT_EQUALS("int16_t", token->originalName());
// Search for the simplified * token -> function pointer gets "(*" tokens infront of it
token = Token::findsimplematch(endOfTypeDef, "*", tokenizer.list.back());
ASSERT_EQUALS("rFunctionPointer_fp", token->originalName());
}
void simplifyTypedefTokenColumn1() { // #13155
const char code[] = "void foo(void) {\n"
" typedef signed int MY_INT;\n"
" MY_INT x = 0;\n"
"}";
Tokenizer tokenizer(settings1, *this);
std::istringstream istr(code);
ASSERT(tokenizer.list.createTokens(istr, "file.c"));
tokenizer.createLinks();
tokenizer.simplifyTypedef();
const Token* x = Token::findsimplematch(tokenizer.list.front(), "x");
const Token* type = x->previous();
ASSERT_EQUALS("int", type->str());
ASSERT_EQUALS(5, type->column());
}
void simplifyTypedefTokenColumn2() {
const char code[] = "void foo(void) {\n"
" typedef signed int (*F)(int);\n"
" F x = 0;\n"
"}";
Tokenizer tokenizer(settings1, *this);
std::istringstream istr(code);
ASSERT(tokenizer.list.createTokens(istr, "file.c"));
tokenizer.createLinks();
tokenizer.simplifyTypedef();
const Token* x = Token::findsimplematch(tokenizer.list.front(), "x");
const Token* type = x->previous();
ASSERT_EQUALS("*", type->str());
ASSERT_EQUALS(5, type->column());
}
void simplifyTypedefTokenColumn3() { // #13368
const char code[] = "typedef struct S_ {} S;\n"
"typedef S* P;\n"
"void f(const P p);\n";
ASSERT_EQUALS("struct S_ { } ; void f ( struct S_ * const p ) ;", // don't crash
tok(code));
const char code2[] = "struct S;\n"
"typedef S& (S::* P)(const S&);\n"
"void f(const P);\n";
ASSERT_EQUALS("struct S ; void f ( const S & ( S :: * ) ( const S & ) ) ;", // don't crash
tok(code2));
}
void typedefInfo1() {
const std::string xml = dumpTypedefInfo("typedef int A;\nA x;");
ASSERT_EQUALS(" <typedef-info>\n"
" <info name=\"A\" file=\"file.c\" line=\"1\" column=\"1\" used=\"1\" isFunctionPointer=\"0\"/>\n"
" </typedef-info>\n",
xml);
}
void typedefInfo2() {
const std::string xml = dumpTypedefInfo("typedef signed short int16_t;\n"
"typedef void ( *fp16 )( int16_t n );\n"
"void R_11_1 ( void ){\n"
" typedef fp16 ( *pfp16 ) ( void );\n"
"}\n");
ASSERT_EQUALS(" <typedef-info>\n"
" <info name=\"fp16\" file=\"file.c\" line=\"2\" column=\"1\" used=\"1\" isFunctionPointer=\"1\"/>\n"
" <info name=\"int16_t\" file=\"file.c\" line=\"1\" column=\"1\" used=\"1\" isFunctionPointer=\"0\"/>\n"
" <info name=\"pfp16\" file=\"file.c\" line=\"4\" column=\"20\" used=\"0\" isFunctionPointer=\"1\"/>\n"
" </typedef-info>\n",xml);
}
};
REGISTER_TEST(TestSimplifyTypedef)
| null |
1,010 | cpp | cppcheck | testcolor.cpp | test/testcolor.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2023 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/>.
*/
#include "color.h"
#include "fixture.h"
class TestColor : public TestFixture {
public:
TestColor() : TestFixture("TestColor") {}
private:
void run() override {
TEST_CASE(toString);
}
void toString() const {
// TODO: color conversion is dependent on stdout/stderr being a TTY
ASSERT_EQUALS("", ::toString(Color::FgRed));
}
};
REGISTER_TEST(TestColor)
| null |
1,011 | cpp | cppcheck | testastutils.cpp | test/testastutils.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#include "astutils.h"
#include "fixture.h"
#include "helpers.h"
#include "settings.h"
#include "symboldatabase.h"
#include "token.h"
#include "tokenlist.h"
#include <cstdint>
#include <cstring>
class TestAstUtils : public TestFixture {
public:
TestAstUtils() : TestFixture("TestAstUtils") {}
private:
// TODO: test with C code
void run() override {
TEST_CASE(findLambdaEndTokenTest);
TEST_CASE(findLambdaStartTokenTest);
TEST_CASE(isNullOperandTest);
TEST_CASE(isReturnScopeTest);
TEST_CASE(isSameExpressionCpp);
TEST_CASE(isSameExpressionC);
TEST_CASE(isVariableChangedTest);
TEST_CASE(isVariableChangedByFunctionCallTest);
TEST_CASE(isExpressionChangedTest);
TEST_CASE(nextAfterAstRightmostLeafTest);
TEST_CASE(isUsedAsBool);
}
#define findLambdaEndToken(...) findLambdaEndToken_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
bool findLambdaEndToken_(const char* file, int line, const char (&code)[size], const char pattern[] = nullptr, bool checkNext = true) {
const Settings settings;
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
const Token* const tokStart = pattern ? Token::findsimplematch(tokenizer.tokens(), pattern, strlen(pattern)) : tokenizer.tokens();
const Token * const tokEnd = (::findLambdaEndToken)(tokStart);
return tokEnd && (!checkNext || tokEnd->next() == nullptr);
}
void findLambdaEndTokenTest() {
const Token* nullTok = nullptr;
ASSERT(nullptr == (::findLambdaEndToken)(nullTok));
ASSERT_EQUALS(false, findLambdaEndToken("void f() { }"));
ASSERT_EQUALS(true, findLambdaEndToken("[]{ }"));
ASSERT_EQUALS(true, findLambdaEndToken("[]{ return 0; }"));
ASSERT_EQUALS(true, findLambdaEndToken("[](){ }"));
ASSERT_EQUALS(true, findLambdaEndToken("[&](){ }"));
ASSERT_EQUALS(true, findLambdaEndToken("[&, i](){ }"));
ASSERT_EQUALS(true, findLambdaEndToken("[](void) { return -1; }"));
ASSERT_EQUALS(true, findLambdaEndToken("[](int a, int b) { return a + b; }"));
ASSERT_EQUALS(true, findLambdaEndToken("[](int a, int b) mutable { return a + b; }"));
ASSERT_EQUALS(true, findLambdaEndToken("[](int a, int b) constexpr { return a + b; }"));
ASSERT_EQUALS(true, findLambdaEndToken("[](void) -> int { return -1; }"));
ASSERT_EQUALS(true, findLambdaEndToken("[](void) mutable -> int { return -1; }"));
ASSERT_EQUALS(false, findLambdaEndToken("[](void) foo -> int { return -1; }"));
ASSERT_EQUALS(true, findLambdaEndToken("[](void) constexpr -> int { return -1; }"));
ASSERT_EQUALS(true, findLambdaEndToken("[](void) constexpr -> int* { return x; }"));
ASSERT_EQUALS(true, findLambdaEndToken("[](void) constexpr -> const * int { return x; }"));
ASSERT_EQUALS(true, findLambdaEndToken("[](void) mutable -> const * int { return x; }"));
ASSERT_EQUALS(true, findLambdaEndToken("[](void) constexpr -> const ** int { return x; }"));
ASSERT_EQUALS(true, findLambdaEndToken("[](void) constexpr -> const * const* int { return x; }"));
ASSERT_EQUALS(false, findLambdaEndToken("int** a[] { new int*[2] { new int, new int} }", "[ ]"));
ASSERT_EQUALS(false, findLambdaEndToken("int** a[] { new int*[2] { new int, new int} }", "[ 2"));
ASSERT_EQUALS(false, findLambdaEndToken("shared_ptr<Type *[]> sp{ new Type *[2] {new Type, new Type}, Deleter<Type>{ 2 } };", "[ 2"));
ASSERT_EQUALS(true, findLambdaEndToken("int i = 5 * []{ return 7; }();", "[", /*checkNext*/ false));
}
#define findLambdaStartToken(code) findLambdaStartToken_(code, __FILE__, __LINE__)
template<size_t size>
bool findLambdaStartToken_(const char (&code)[size], const char* file, int line) {
SimpleTokenizer tokenizer(settingsDefault, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
const Token * const tokStart = (::findLambdaStartToken)(tokenizer.list.back());
return tokStart && tokStart == tokenizer.list.front();
}
void findLambdaStartTokenTest() {
ASSERT(nullptr == (::findLambdaStartToken)(nullptr));
ASSERT_EQUALS(false, findLambdaStartToken("void f() { }"));
ASSERT_EQUALS(true, findLambdaStartToken("[]{ }"));
ASSERT_EQUALS(true, findLambdaStartToken("[]{ return 0; }"));
ASSERT_EQUALS(true, findLambdaStartToken("[](){ }"));
ASSERT_EQUALS(true, findLambdaStartToken("[&](){ }"));
ASSERT_EQUALS(true, findLambdaStartToken("[&, i](){ }"));
ASSERT_EQUALS(true, findLambdaStartToken("[](void) { return -1; }"));
ASSERT_EQUALS(true, findLambdaStartToken("[](int a, int b) { return a + b; }"));
ASSERT_EQUALS(true, findLambdaStartToken("[](int a, int b) mutable { return a + b; }"));
ASSERT_EQUALS(true, findLambdaStartToken("[](int a, int b) constexpr { return a + b; }"));
ASSERT_EQUALS(true, findLambdaStartToken("[](void) -> int { return -1; }"));
ASSERT_EQUALS(true, findLambdaStartToken("[](void) mutable -> int { return -1; }"));
ASSERT_EQUALS(false, findLambdaStartToken("[](void) foo -> int { return -1; }"));
ASSERT_EQUALS(true, findLambdaStartToken("[](void) constexpr -> int { return -1; }"));
ASSERT_EQUALS(true, findLambdaStartToken("[](void) constexpr -> int* { return x; }"));
ASSERT_EQUALS(true, findLambdaStartToken("[](void) constexpr -> const * int { return x; }"));
ASSERT_EQUALS(true, findLambdaStartToken("[](void) mutable -> const * int { return x; }"));
ASSERT_EQUALS(true, findLambdaStartToken("[](void) constexpr -> const ** int { return x; }"));
ASSERT_EQUALS(true, findLambdaStartToken("[](void) constexpr -> const * const* int { return x; }"));
}
#define isNullOperand(code) isNullOperand_(code, __FILE__, __LINE__)
template<size_t size>
bool isNullOperand_(const char (&code)[size], const char* file, int line) {
SimpleTokenizer tokenizer(settingsDefault, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
return (::isNullOperand)(tokenizer.tokens());
}
void isNullOperandTest() {
ASSERT_EQUALS(true, isNullOperand("(void*)0;"));
ASSERT_EQUALS(true, isNullOperand("(void*)0U;"));
ASSERT_EQUALS(true, isNullOperand("(void*)0x0LL;"));
ASSERT_EQUALS(true, isNullOperand("NULL;"));
ASSERT_EQUALS(true, isNullOperand("nullptr;"));
ASSERT_EQUALS(true, isNullOperand("(void*)NULL;"));
ASSERT_EQUALS(true, isNullOperand("static_cast<int*>(0);"));
ASSERT_EQUALS(false, isNullOperand("0;"));
ASSERT_EQUALS(false, isNullOperand("(void*)0.0;"));
ASSERT_EQUALS(false, isNullOperand("(void*)1;"));
}
#define isReturnScope(code, offset) isReturnScope_(code, offset, __FILE__, __LINE__)
template<size_t size>
bool isReturnScope_(const char (&code)[size], int offset, const char* file, int line) {
SimpleTokenizer tokenizer(settingsDefault, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
const Token * const tok = (offset < 0)
? tokenizer.list.back()->tokAt(1+offset)
: tokenizer.tokens()->tokAt(offset);
return (isReturnScope)(tok, settingsDefault.library);
}
void isReturnScopeTest() {
ASSERT_EQUALS(true, isReturnScope("void f() { if (a) { return; } }", -2));
ASSERT_EQUALS(true, isReturnScope("int f() { if (a) { return {}; } }", -2)); // #8891
ASSERT_EQUALS(true, isReturnScope("std::string f() { if (a) { return std::string{}; } }", -2)); // #8891
ASSERT_EQUALS(true, isReturnScope("std::string f() { if (a) { return std::string{\"\"}; } }", -2)); // #8891
ASSERT_EQUALS(true, isReturnScope("void f() { if (a) { return (ab){0}; } }", -2)); // #7103
ASSERT_EQUALS(false, isReturnScope("void f() { if (a) { return (ab){0}; } }", -4)); // #7103
ASSERT_EQUALS(true, isReturnScope("void f() { if (a) { {throw new string(x);}; } }", -4)); // #7144
ASSERT_EQUALS(true, isReturnScope("void f() { if (a) { {throw new string(x);}; } }", -2)); // #7144
ASSERT_EQUALS(false, isReturnScope("void f() { [=]() { return data; }; }", -1));
ASSERT_EQUALS(true, isReturnScope("auto f() { return [=]() { return data; }; }", -1));
ASSERT_EQUALS(true, isReturnScope("auto f() { return [=]() { return data; }(); }", -1));
ASSERT_EQUALS(false, isReturnScope("auto f() { [=]() { return data; }(); }", -1));
ASSERT_EQUALS(true, isReturnScope("void negativeTokenOffset() { return; }", -1));
ASSERT_EQUALS(false, isReturnScope("void zeroTokenOffset() { return; }", 0));
ASSERT_EQUALS(true, isReturnScope("void positiveTokenOffset() { return; }", 7));
}
#define isSameExpression(...) isSameExpression_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
bool isSameExpression_(const char* file, int line, const char (&code)[size], const char tokStr1[], const char tokStr2[], bool cpp) {
SimpleTokenizer tokenizer(settingsDefault, *this);
ASSERT_LOC(tokenizer.tokenize(code, cpp), file, line);
const Token * const tok1 = Token::findsimplematch(tokenizer.tokens(), tokStr1, strlen(tokStr1));
const Token * const tok2 = Token::findsimplematch(tok1->next(), tokStr2, strlen(tokStr2));
return (isSameExpression)(false, tok1, tok2, settingsDefault, false, true);
}
void isSameExpressionTestInternal(bool cpp) {
ASSERT_EQUALS(true, isSameExpression("x = 1 + 1;", "1", "1", cpp));
ASSERT_EQUALS(false, isSameExpression("x = 1 + 1u;", "1", "1u", cpp));
ASSERT_EQUALS(true, isSameExpression("x = 1.0 + 1.0;", "1.0", "1.0", cpp));
ASSERT_EQUALS(false, isSameExpression("x = 1.0f + 1.0;", "1.0f", "1.0", cpp));
ASSERT_EQUALS(false, isSameExpression("x = 1L + 1;", "1L", "1", cpp));
ASSERT_EQUALS(true, isSameExpression("x = 0.0f + 0x0p+0f;", "0.0f", "0x0p+0f", cpp));
ASSERT_EQUALS(true, isSameExpression("x < x;", "x", "x", cpp));
ASSERT_EQUALS(false, isSameExpression("x < y;", "x", "y", cpp));
ASSERT_EQUALS(true, isSameExpression("(x + 1) < (x + 1);", "+", "+", cpp));
ASSERT_EQUALS(false, isSameExpression("(x + 1) < (x + 1L);", "+", "+", cpp));
ASSERT_EQUALS(!cpp, isSameExpression("(1 + x) < (x + 1);", "+", "+", cpp));
ASSERT_EQUALS(false, isSameExpression("(1.0l + x) < (1.0 + x);", "+", "+", cpp));
ASSERT_EQUALS(!cpp, isSameExpression("(0.0 + x) < (x + 0x0p+0);", "+", "+", cpp));
ASSERT_EQUALS(true, isSameExpression("void f() {double y = 1e1; (x + y) < (x + 10.0); } ", "+", "+", cpp));
ASSERT_EQUALS(!cpp, isSameExpression("void f() {double y = 1e1; (x + 10.0) < (y + x); } ", "+", "+", cpp));
ASSERT_EQUALS(true, isSameExpression("void f() {double y = 1e1; double z = 10.0; (x + y) < (x + z); } ", "+", "+", cpp));
ASSERT_EQUALS(true, isSameExpression("A + A", "A", "A", cpp));
// the remaining test cases are not valid C code
if (!cpp)
return;
//https://trac.cppcheck.net/ticket/9700
ASSERT_EQUALS(true, isSameExpression("A::B + A::B;", "::", "::", cpp));
ASSERT_EQUALS(false, isSameExpression("A::B + A::C;", "::", "::", cpp));
ASSERT_EQUALS(true, isSameExpression("A::B* get() { if(x) return new A::B(true); else return new A::B(true); }", "new", "new", cpp));
ASSERT_EQUALS(false, isSameExpression("A::B* get() { if(x) return new A::B(true); else return new A::C(true); }", "new", "new", cpp));
}
void isSameExpressionCpp() {
isSameExpressionTestInternal(true);
}
void isSameExpressionC() {
isSameExpressionTestInternal(false);
}
#define isVariableChanged(code, startPattern, endPattern) isVariableChanged_(code, startPattern, endPattern, __FILE__, __LINE__)
template<size_t size>
bool isVariableChanged_(const char (&code)[size], const char startPattern[], const char endPattern[], const char* file, int line) {
SimpleTokenizer tokenizer(settingsDefault, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
const Token * const tok1 = Token::findsimplematch(tokenizer.tokens(), startPattern, strlen(startPattern));
const Token * const tok2 = Token::findsimplematch(tokenizer.tokens(), endPattern, strlen(endPattern));
return (isVariableChanged)(tok1, tok2, 1, false, settingsDefault);
}
void isVariableChangedTest() {
// #8211 - no lhs for >> , do not crash
(void)isVariableChanged("void f() {\n"
" int b;\n"
" if (b) { (int)((INTOF(8))result >> b); }\n"
"}", "if", "}");
// #9235
ASSERT_EQUALS(false,
isVariableChanged("void f() {\n"
" int &a = a;\n"
"}\n",
"= a",
"}"));
ASSERT_EQUALS(false, isVariableChanged("void f(const A& a) { a.f(); }", "{", "}"));
ASSERT_EQUALS(true,
isVariableChanged("void g(int*);\n"
"void f(int x) { g(&x); }\n",
"{",
"}"));
ASSERT_EQUALS(false, isVariableChanged("const int A[] = { 1, 2, 3 };", "[", "]"));
}
#define isVariableChangedByFunctionCall(code, pattern, inconclusive) isVariableChangedByFunctionCall_(code, pattern, inconclusive, __FILE__, __LINE__)
template<size_t size>
bool isVariableChangedByFunctionCall_(const char (&code)[size], const char pattern[], bool *inconclusive, const char* file, int line) {
SimpleTokenizer tokenizer(settingsDefault, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
const Token * const argtok = Token::findmatch(tokenizer.tokens(), pattern);
ASSERT_LOC(argtok, file, line);
int indirect = (argtok->variable() && argtok->variable()->isArray());
return (isVariableChangedByFunctionCall)(argtok, indirect, settingsDefault, inconclusive);
}
void isVariableChangedByFunctionCallTest() {
{ // #8271 - template method
const char code[] = "void f(int x) {\n"
" a<int>(x);\n"
"}";
bool inconclusive = false;
ASSERT_EQUALS(false, isVariableChangedByFunctionCall(code, "x ) ;", &inconclusive));
ASSERT_EQUALS(true, inconclusive);
}
{
const char code[] = "int f(int x) {\n"
"return int(x);\n"
"}\n";
bool inconclusive = false;
ASSERT_EQUALS(false, isVariableChangedByFunctionCall(code, "x ) ;", &inconclusive));
ASSERT_EQUALS(false, inconclusive);
}
{
const char code[] = "void g(int* p);\n"
"void f(int x) {\n"
" return g(&x);\n"
"}\n";
bool inconclusive = false;
ASSERT_EQUALS(true, isVariableChangedByFunctionCall(code, "x ) ;", &inconclusive));
ASSERT_EQUALS(false, inconclusive);
}
{
const char code[] = "void g(const int* p);\n"
"void f(int x) {\n"
" return g(&x);\n"
"}\n";
bool inconclusive = false;
ASSERT_EQUALS(false, isVariableChangedByFunctionCall(code, "x ) ;", &inconclusive));
ASSERT_EQUALS(false, inconclusive);
}
{
const char code[] = "void g(int** pp);\n"
"void f(int* p) {\n"
" return g(&p);\n"
"}\n";
bool inconclusive = false;
ASSERT_EQUALS(true, isVariableChangedByFunctionCall(code, "p ) ;", &inconclusive));
ASSERT_EQUALS(false, inconclusive);
}
{
const char code[] = "void g(int* const* pp);\n"
"void f(int* p) {\n"
" return g(&p);\n"
"}\n";
bool inconclusive = false;
ASSERT_EQUALS(false, isVariableChangedByFunctionCall(code, "p ) ;", &inconclusive));
ASSERT_EQUALS(false, inconclusive);
}
{
const char code[] = "void g(int a[2]);\n"
"void f() {\n"
" int b[2] = {};\n"
" return g(b);\n"
"}\n";
bool inconclusive = false;
ASSERT_EQUALS(true, isVariableChangedByFunctionCall(code, "b ) ;", &inconclusive));
ASSERT_EQUALS(false, inconclusive);
}
{
const char code[] = "void g(const int a[2]);\n"
"void f() {\n"
" int b[2] = {};\n"
" return g(b);\n"
"}\n";
bool inconclusive = false;
TODO_ASSERT_EQUALS(false, true, isVariableChangedByFunctionCall(code, "b ) ;", &inconclusive));
ASSERT_EQUALS(false, inconclusive);
}
{
const char code[] = "void g(std::array<int, 2> a);\n"
"void f() {\n"
" std::array<int, 2> b = {};\n"
" return g(b);\n"
"}\n";
bool inconclusive = false;
ASSERT_EQUALS(false, isVariableChangedByFunctionCall(code, "b ) ;", &inconclusive));
ASSERT_EQUALS(false, inconclusive);
}
{
const char code[] = "void g(std::array<int, 2>& a);\n"
"void f() {\n"
" std::array<int, 2> b = {};\n"
" return g(b);\n"
"}\n";
bool inconclusive = false;
ASSERT_EQUALS(true, isVariableChangedByFunctionCall(code, "b ) ;", &inconclusive));
ASSERT_EQUALS(false, inconclusive);
}
{
const char code[] = "void g(const std::array<int, 2>& a);\n"
"void f() {\n"
" std::array<int, 2> b = {};\n"
" return g(b);\n"
"}\n";
bool inconclusive = false;
ASSERT_EQUALS(false, isVariableChangedByFunctionCall(code, "b ) ;", &inconclusive));
ASSERT_EQUALS(false, inconclusive);
}
{
const char code[] = "void g(std::array<int, 2>* p);\n"
"void f() {\n"
" std::array<int, 2> b = {};\n"
" return g(&b);\n"
"}\n";
bool inconclusive = false;
ASSERT_EQUALS(true, isVariableChangedByFunctionCall(code, "b ) ;", &inconclusive));
ASSERT_EQUALS(false, inconclusive);
}
{
const char code[] = "struct S {};\n"
"void g(S);\n"
"void f(S* s) {\n"
" g(*s);\n"
"}\n";
bool inconclusive = false;
ASSERT_EQUALS(false, isVariableChangedByFunctionCall(code, "s ) ;", &inconclusive));
ASSERT_EQUALS(false, inconclusive);
}
{
const char code[] = "struct S {};\n"
"void g(const S&);\n"
"void f(S* s) {\n"
" g(*s);\n"
"}\n";
bool inconclusive = false;
ASSERT_EQUALS(false, isVariableChangedByFunctionCall(code, "s ) ;", &inconclusive));
ASSERT_EQUALS(false, inconclusive);
}
}
#define isExpressionChanged(code, var, startPattern, endPattern) \
isExpressionChanged_(code, var, startPattern, endPattern, __FILE__, __LINE__)
template<size_t size>
bool isExpressionChanged_(const char (&code)[size],
const char var[],
const char startPattern[],
const char endPattern[],
const char* file,
int line)
{
const Settings settings = settingsBuilder().library("std.cfg").build();
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
const Token* const start = Token::findsimplematch(tokenizer.tokens(), startPattern, strlen(startPattern));
const Token* const end = Token::findsimplematch(start, endPattern, strlen(endPattern));
const Token* const expr = Token::findsimplematch(tokenizer.tokens(), var, strlen(var));
return (findExpressionChanged)(expr, start, end, settings);
}
void isExpressionChangedTest()
{
ASSERT_EQUALS(true, isExpressionChanged("void f(std::map<int, int>& m) { m[0]; }", "m [", "{", "}"));
ASSERT_EQUALS(false, isExpressionChanged("void f(const A& a) { a.f(); }", "a .", "{", "}"));
ASSERT_EQUALS(true,
isExpressionChanged("void g(int*);\n"
"void f(int x) { g(&x); }\n",
"x",
") {",
"}"));
ASSERT_EQUALS(true,
isExpressionChanged("struct S { void f(); int i; };\n"
"void call_f(S& s) { (s.*(&S::f))(); }\n",
"s .",
"{ (",
"}"));
}
#define nextAfterAstRightmostLeaf(code, parentPattern, rightPattern) nextAfterAstRightmostLeaf_(code, parentPattern, rightPattern, __FILE__, __LINE__)
template<size_t size>
bool nextAfterAstRightmostLeaf_(const char (&code)[size], const char parentPattern[], const char rightPattern[], const char* file, int line) {
SimpleTokenizer tokenizer(settingsDefault, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
const Token * tok = Token::findsimplematch(tokenizer.tokens(), parentPattern, strlen(parentPattern));
return Token::simpleMatch((::nextAfterAstRightmostLeaf)(tok), rightPattern, strlen(rightPattern));
}
void nextAfterAstRightmostLeafTest() {
ASSERT_EQUALS(true, nextAfterAstRightmostLeaf("void f(int a, int b) { int x = a + b; }", "=", "; }"));
ASSERT_EQUALS(true, nextAfterAstRightmostLeaf("int * g(int); void f(int a, int b) { int x = g(a); }", "=", "; }"));
ASSERT_EQUALS(true, nextAfterAstRightmostLeaf("int * g(int); void f(int a, int b) { int x = g(a)[b]; }", "=", "; }"));
ASSERT_EQUALS(true, nextAfterAstRightmostLeaf("int * g(int); void f(int a, int b) { int x = g(g(a)[b]); }", "=", "; }"));
ASSERT_EQUALS(true, nextAfterAstRightmostLeaf("int * g(int); void f(int a, int b) { int x = g(g(a)[b] + a); }", "=", "; }"));
ASSERT_EQUALS(true, nextAfterAstRightmostLeaf("int * g(int); void f(int a, int b) { int x = g(a)[b + 1]; }", "=", "; }"));
ASSERT_EQUALS(true, nextAfterAstRightmostLeaf("void f() { int a; int b; int x = [](int a){}; }", "=", "; }"));
ASSERT_EQUALS(true, nextAfterAstRightmostLeaf("int * g(int); void f(int a, int b) { int x = a + b; }", "+", "; }"));
ASSERT_EQUALS(true, nextAfterAstRightmostLeaf("int * g(int); void f(int a, int b) { int x = g(a)[b + 1]; }", "+", "] ; }"));
ASSERT_EQUALS(true, nextAfterAstRightmostLeaf("int * g(int); void f(int a, int b) { int x = g(a + 1)[b]; }", "+", ") ["));
}
enum class Result : std::uint8_t {False, True, Fail};
template<size_t size>
Result isUsedAsBool(const char (&code)[size], const char pattern[]) {
SimpleTokenizer tokenizer(settingsDefault, *this);
if (!tokenizer.tokenize(code))
return Result::Fail;
const Token * const argtok = Token::findmatch(tokenizer.tokens(), pattern);
if (!argtok)
return Result::Fail;
return ::isUsedAsBool(argtok, settingsDefault) ? Result::True : Result::False;
}
void isUsedAsBool() {
ASSERT(Result::True == isUsedAsBool("void f() { bool b = true; }", "b"));
ASSERT(Result::False ==isUsedAsBool("void f() { int i = true; }", "i"));
ASSERT(Result::True == isUsedAsBool("void f() { int i; if (i) {} }", "i )"));
ASSERT(Result::True == isUsedAsBool("void f() { int i; while (i) {} }", "i )"));
ASSERT(Result::True == isUsedAsBool("void f() { int i; for (;i;) {} }", "i ; )"));
ASSERT(Result::False == isUsedAsBool("void f() { int i; for (;;i) {} }", "i )"));
ASSERT(Result::False == isUsedAsBool("void f() { int i; for (i;;) {} }", "i ; ; )"));
ASSERT(Result::True == isUsedAsBool("void f() { int i; for (int j=0; i; ++j) {} }", "i ; ++"));
ASSERT(Result::False == isUsedAsBool("void f() { int i; if (i == 2) {} }", "i =="));
ASSERT(Result::False == isUsedAsBool("void f() { int i; if (i == true) {} }", "i =="));
ASSERT(Result::False == isUsedAsBool("void f() { int i,j; if (i == (j&&f())) {} }", "i =="));
ASSERT(Result::True == isUsedAsBool("void f() { int i; if (!i == 0) {} }", "i =="));
ASSERT(Result::True == isUsedAsBool("void f() { int i; if (!i) {} }", "i )"));
ASSERT(Result::True == isUsedAsBool("void f() { int i; if (!!i) {} }", "i )"));
ASSERT(Result::True == isUsedAsBool("void f() { int i; if (i && f()) {} }", "i &&"));
ASSERT(Result::True == isUsedAsBool("void f() { int i; int j = i && f(); }", "i &&"));
ASSERT(Result::False == isUsedAsBool("void f() { int i; if (i & f()) {} }", "i &"));
ASSERT(Result::True == isUsedAsBool("void f() { int i; if (static_cast<bool>(i)) {} }", "i )"));
ASSERT(Result::True == isUsedAsBool("void f() { int i; if ((bool)i) {} }", "i )"));
ASSERT(Result::True == isUsedAsBool("void f() { int i; if (1+static_cast<bool>(i)) {} }", "i )"));
ASSERT(Result::True == isUsedAsBool("void f() { int i; if (1+(bool)i) {} }", "i )"));
ASSERT(Result::False == isUsedAsBool("void f() { int i; if (1+static_cast<int>(i)) {} }", "i )"));
ASSERT(Result::True == isUsedAsBool("void f() { int i; if (1+!static_cast<int>(i)) {} }", "i )"));
ASSERT(Result::False == isUsedAsBool("void f() { int i; if (1+(int)i) {} }", "i )"));
ASSERT(Result::False == isUsedAsBool("void f() { int i; if (i + 2) {} }", "i +"));
ASSERT(Result::True == isUsedAsBool("void f() { int i; bool b = i; }", "i ; }"));
ASSERT(Result::True == isUsedAsBool("void f(bool b); void f() { int i; f(i); }","i )"));
ASSERT(Result::False == isUsedAsBool("void f() { int *i; if (*i) {} }", "i )"));
ASSERT(Result::True == isUsedAsBool("void f() { int *i; if (*i) {} }", "* i )"));
ASSERT(Result::True == isUsedAsBool("int g(); void h(bool); void f() { h(g()); }", "( ) )"));
ASSERT(Result::True == isUsedAsBool("int g(int); void h(bool); void f() { h(g(0)); }", "( 0 ) )"));
}
};
REGISTER_TEST(TestAstUtils)
| null |
1,012 | cpp | cppcheck | helpers.h | test/helpers.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#ifndef helpersH
#define helpersH
#include "config.h"
#include "library.h"
#include "preprocessor.h"
#include "settings.h"
#include "standards.h"
#include "tokenize.h"
#include "tokenlist.h"
#include <cstddef>
#include <map>
#include <set>
#include <stdexcept>
#include <sstream>
#include <string>
#include <vector>
class Token;
class SuppressionList;
class ErrorLogger;
namespace simplecpp {
struct DUI;
}
namespace tinyxml2 {
class XMLDocument;
}
// TODO: make Tokenizer private
class SimpleTokenizer : public Tokenizer {
public:
template<size_t size>
SimpleTokenizer(ErrorLogger& errorlogger, const char (&code)[size], bool cpp = true)
: Tokenizer{s_settings, errorlogger}
{
if (!tokenize(code, cpp))
throw std::runtime_error("creating tokens failed");
}
SimpleTokenizer(const Settings& settings, ErrorLogger& errorlogger)
: Tokenizer{settings, errorlogger}
{}
/*
Token* tokens() {
return Tokenizer::tokens();
}
const Token* tokens() const {
return Tokenizer::tokens();
}
*/
/**
* Tokenize code
* @param code The code
* @param cpp Indicates if the code is C++
* @param configuration E.g. "A" for code where "#ifdef A" is true
* @return false if source code contains syntax errors
*/
template<size_t size>
bool tokenize(const char (&code)[size],
bool cpp = true,
const std::string &configuration = emptyString)
{
std::istringstream istr(code);
if (!list.createTokens(istr, cpp ? "test.cpp" : "test.c"))
return false;
return simplifyTokens1(configuration);
}
// TODO: get rid of this
bool tokenize(const std::string& code,
bool cpp = true,
const std::string &configuration = emptyString)
{
std::istringstream istr(code);
if (!list.createTokens(istr, cpp ? "test.cpp" : "test.c"))
return false;
return simplifyTokens1(configuration);
}
private:
// TODO. find a better solution
static const Settings s_settings;
};
class SimpleTokenList
{
public:
template<size_t size>
explicit SimpleTokenList(const char (&code)[size], Standards::Language lang = Standards::Language::CPP)
{
std::istringstream iss(code);
if (!list.createTokens(iss, lang))
throw std::runtime_error("creating tokens failed");
}
Token* front() {
return list.front();
}
const Token* front() const {
return list.front();
}
private:
const Settings settings;
TokenList list{&settings};
};
class ScopedFile {
public:
ScopedFile(std::string name, const std::string &content, std::string path = "");
~ScopedFile();
const std::string& path() const
{
return mFullPath;
}
const std::string& name() const {
return mName;
}
ScopedFile(const ScopedFile&) = delete;
ScopedFile(ScopedFile&&) = delete;
ScopedFile& operator=(const ScopedFile&) = delete;
ScopedFile& operator=(ScopedFile&&) = delete;
private:
const std::string mName;
const std::string mPath;
const std::string mFullPath;
};
class PreprocessorHelper
{
public:
/**
* Get preprocessed code for a given configuration
*
* Note: for testing only.
*
* @param filedata file data including preprocessing 'if', 'define', etc
* @param cfg configuration to read out
* @param filename name of source file
* @param inlineSuppression the inline suppressions
*/
static std::string getcode(const Settings& settings, ErrorLogger& errorlogger, const std::string &filedata, const std::string &cfg, const std::string &filename, SuppressionList *inlineSuppression = nullptr);
static std::map<std::string, std::string> getcode(const Settings& settings, ErrorLogger& errorlogger, const char code[], const std::string &filename = "file.c", SuppressionList *inlineSuppression = nullptr);
static void preprocess(const char code[], std::vector<std::string> &files, Tokenizer& tokenizer, ErrorLogger& errorlogger);
static void preprocess(const char code[], std::vector<std::string> &files, Tokenizer& tokenizer, ErrorLogger& errorlogger, const simplecpp::DUI& dui);
/** get remark comments */
static std::vector<RemarkComment> getRemarkComments(const char code[], ErrorLogger& errorLogger);
private:
static std::map<std::string, std::string> getcode(const Settings& settings, ErrorLogger& errorlogger, const char code[], std::set<std::string> cfgs, const std::string &filename = "file.c", SuppressionList *inlineSuppression = nullptr);
};
namespace cppcheck {
template<typename T>
std::size_t count_all_of(const std::string& str, T sub) {
std::size_t n = 0;
std::string::size_type pos = 0;
while ((pos = str.find(sub, pos)) != std::string::npos) {
++pos;
++n;
}
return n;
}
}
/* designated initialization helper
Usage:
struct S
{
int i;
};
const auto s = dinit(S,
$.i = 1
);
*/
#define dinit(T, ...) \
([&] { T ${}; __VA_ARGS__; return $; }())
// Default construct object to avoid bug in clang
// error: default member initializer for 'y' needed within definition of enclosing class 'X' outside of member functions
// see https://stackoverflow.com/questions/53408962
struct make_default_obj
{
template<class T>
operator T() const // NOLINT
{
return T{};
}
};
inline std::string filter_valueflow(const std::string& s) {
bool filtered = false;
std::istringstream istr(s);
std::string ostr;
std::string errline;
while (std::getline(istr, errline)) {
if (errline.find("valueflow.cpp") != std::string::npos)
{
filtered = true;
continue;
}
ostr += errline;
ostr += '\n'; // TODO: last line might not contain a newline
}
if (!filtered)
throw std::runtime_error("no valueflow.cpp messages were filtered");
return ostr;
}
struct LibraryHelper
{
static bool loadxmldata(Library &lib, const char xmldata[], std::size_t len);
static bool loadxmldata(Library &lib, Library::Error& liberr, const char xmldata[], std::size_t len);
static Library::Error loadxmldoc(Library &lib, const tinyxml2::XMLDocument& doc);
};
#endif // helpersH
| null |
1,013 | cpp | cppcheck | main.cpp | test/main.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2023 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/>.
*/
#include "color.h"
#include "options.h"
#include "preprocessor.h"
#include "fixture.h"
#include <cstdlib>
int main(int argc, char *argv[])
{
// MS Visual C++ memory leak debug tracing
#if defined(_MSC_VER) && defined(_DEBUG)
_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
#endif
Preprocessor::macroChar = '$'; // While macroChar is char(1) per default outside test suite, we require it to be a human-readable character here.
gDisableColors = true;
options args(argc, argv);
if (args.help()) {
TestFixture::printHelp();
return EXIT_SUCCESS;
}
const std::size_t failedTestsCount = TestFixture::runTests(args);
return (failedTestsCount == 0) ? EXIT_SUCCESS : EXIT_FAILURE;
}
| null |
1,014 | cpp | cppcheck | testutils.cpp | test/testutils.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#include "fixture.h"
#include "utils.h"
#include <cstddef>
#include <cstdint>
#include <limits>
#include <stdexcept>
#include <string>
class TestUtils : public TestFixture {
public:
TestUtils() : TestFixture("TestUtils") {}
private:
void run() override {
TEST_CASE(isValidGlobPattern);
TEST_CASE(matchglob);
TEST_CASE(isStringLiteral);
TEST_CASE(isCharLiteral);
TEST_CASE(strToInt);
TEST_CASE(id_string);
TEST_CASE(startsWith);
TEST_CASE(trim);
TEST_CASE(findAndReplace);
TEST_CASE(replaceEscapeSequences);
TEST_CASE(splitString);
TEST_CASE(as_const);
}
void isValidGlobPattern() const {
ASSERT_EQUALS(true, ::isValidGlobPattern("*"));
ASSERT_EQUALS(true, ::isValidGlobPattern("*x"));
ASSERT_EQUALS(true, ::isValidGlobPattern("x*"));
ASSERT_EQUALS(true, ::isValidGlobPattern("*/x/*"));
ASSERT_EQUALS(true, ::isValidGlobPattern("x/*/z"));
ASSERT_EQUALS(false, ::isValidGlobPattern("**"));
ASSERT_EQUALS(false, ::isValidGlobPattern("**x"));
ASSERT_EQUALS(false, ::isValidGlobPattern("x**"));
ASSERT_EQUALS(true, ::isValidGlobPattern("?"));
ASSERT_EQUALS(true, ::isValidGlobPattern("?x"));
ASSERT_EQUALS(true, ::isValidGlobPattern("x?"));
ASSERT_EQUALS(true, ::isValidGlobPattern("?/x/?"));
ASSERT_EQUALS(true, ::isValidGlobPattern("x/?/z"));
ASSERT_EQUALS(false, ::isValidGlobPattern("??"));
ASSERT_EQUALS(false, ::isValidGlobPattern("??x"));
ASSERT_EQUALS(false, ::isValidGlobPattern("x??"));
}
void matchglob() const {
ASSERT_EQUALS(true, ::matchglob("*", "xyz"));
ASSERT_EQUALS(true, ::matchglob("x*", "xyz"));
ASSERT_EQUALS(true, ::matchglob("*z", "xyz"));
ASSERT_EQUALS(true, ::matchglob("*y*", "xyz"));
ASSERT_EQUALS(true, ::matchglob("*y*", "yz"));
ASSERT_EQUALS(false, ::matchglob("*y*", "abc"));
ASSERT_EQUALS(true, ::matchglob("*", "x/y/z"));
ASSERT_EQUALS(true, ::matchglob("*/y/z", "x/y/z"));
ASSERT_EQUALS(false, ::matchglob("?", "xyz"));
ASSERT_EQUALS(false, ::matchglob("x?", "xyz"));
ASSERT_EQUALS(false, ::matchglob("?z", "xyz"));
ASSERT_EQUALS(true, ::matchglob("?y?", "xyz"));
ASSERT_EQUALS(true, ::matchglob("?/?/?", "x/y/z"));
}
void isStringLiteral() const {
// empty
ASSERT_EQUALS(false, ::isStringLiteral(""));
// no literals
ASSERT_EQUALS(false, ::isStringLiteral("u8"));
ASSERT_EQUALS(false, ::isStringLiteral("u"));
ASSERT_EQUALS(false, ::isStringLiteral("U"));
ASSERT_EQUALS(false, ::isStringLiteral("L"));
// incomplete string literals
ASSERT_EQUALS(false, ::isStringLiteral("\""));
ASSERT_EQUALS(false, ::isStringLiteral("u8\""));
ASSERT_EQUALS(false, ::isStringLiteral("u\""));
ASSERT_EQUALS(false, ::isStringLiteral("U\""));
ASSERT_EQUALS(false, ::isStringLiteral("L\""));
// valid string literals
ASSERT_EQUALS(true, ::isStringLiteral("\"\""));
ASSERT_EQUALS(true, ::isStringLiteral("u8\"\""));
ASSERT_EQUALS(true, ::isStringLiteral("u\"\""));
ASSERT_EQUALS(true, ::isStringLiteral("U\"\""));
ASSERT_EQUALS(true, ::isStringLiteral("L\"\""));
ASSERT_EQUALS(true, ::isStringLiteral("\"t\""));
ASSERT_EQUALS(true, ::isStringLiteral("u8\"t\""));
ASSERT_EQUALS(true, ::isStringLiteral("u\"t\""));
ASSERT_EQUALS(true, ::isStringLiteral("U\"t\""));
ASSERT_EQUALS(true, ::isStringLiteral("L\"t\""));
ASSERT_EQUALS(true, ::isStringLiteral("\"test\""));
ASSERT_EQUALS(true, ::isStringLiteral("u8\"test\""));
ASSERT_EQUALS(true, ::isStringLiteral("u\"test\""));
ASSERT_EQUALS(true, ::isStringLiteral("U\"test\""));
ASSERT_EQUALS(true, ::isStringLiteral("L\"test\""));
// incomplete char literals
ASSERT_EQUALS(false, ::isStringLiteral("'"));
ASSERT_EQUALS(false, ::isStringLiteral("u8'"));
ASSERT_EQUALS(false, ::isStringLiteral("u'"));
ASSERT_EQUALS(false, ::isStringLiteral("U'"));
ASSERT_EQUALS(false, ::isStringLiteral("L'"));
// valid char literals
ASSERT_EQUALS(false, ::isStringLiteral("'t'"));
ASSERT_EQUALS(false, ::isStringLiteral("u8't'"));
ASSERT_EQUALS(false, ::isStringLiteral("u't'"));
ASSERT_EQUALS(false, ::isStringLiteral("U't'"));
ASSERT_EQUALS(false, ::isStringLiteral("L't'"));
ASSERT_EQUALS(false, ::isStringLiteral("'test'"));
ASSERT_EQUALS(false, ::isStringLiteral("u8'test'"));
ASSERT_EQUALS(false, ::isStringLiteral("u'test'"));
ASSERT_EQUALS(false, ::isStringLiteral("U'test'"));
ASSERT_EQUALS(false, ::isStringLiteral("L'test'"));
}
void isCharLiteral() const {
// empty
ASSERT_EQUALS(false, ::isCharLiteral(""));
// no literals
ASSERT_EQUALS(false, ::isCharLiteral("u8"));
ASSERT_EQUALS(false, ::isCharLiteral("u"));
ASSERT_EQUALS(false, ::isCharLiteral("U"));
ASSERT_EQUALS(false, ::isCharLiteral("L"));
// incomplete string literals
ASSERT_EQUALS(false, ::isCharLiteral("\""));
ASSERT_EQUALS(false, ::isCharLiteral("u8\""));
ASSERT_EQUALS(false, ::isCharLiteral("u\""));
ASSERT_EQUALS(false, ::isCharLiteral("U\""));
ASSERT_EQUALS(false, ::isCharLiteral("L\""));
// valid string literals
ASSERT_EQUALS(false, ::isCharLiteral("\"\""));
ASSERT_EQUALS(false, ::isCharLiteral("u8\"\""));
ASSERT_EQUALS(false, ::isCharLiteral("u\"\""));
ASSERT_EQUALS(false, ::isCharLiteral("U\"\""));
ASSERT_EQUALS(false, ::isCharLiteral("L\"\""));
ASSERT_EQUALS(false, ::isCharLiteral("\"t\""));
ASSERT_EQUALS(false, ::isCharLiteral("u8\"t\""));
ASSERT_EQUALS(false, ::isCharLiteral("u\"t\""));
ASSERT_EQUALS(false, ::isCharLiteral("U\"t\""));
ASSERT_EQUALS(false, ::isCharLiteral("L\"t\""));
ASSERT_EQUALS(false, ::isCharLiteral("\"test\""));
ASSERT_EQUALS(false, ::isCharLiteral("u8\"test\""));
ASSERT_EQUALS(false, ::isCharLiteral("u\"test\""));
ASSERT_EQUALS(false, ::isCharLiteral("U\"test\""));
ASSERT_EQUALS(false, ::isCharLiteral("L\"test\""));
// incomplete char literals
ASSERT_EQUALS(false, ::isCharLiteral("'"));
ASSERT_EQUALS(false, ::isCharLiteral("u8'"));
ASSERT_EQUALS(false, ::isCharLiteral("u'"));
ASSERT_EQUALS(false, ::isCharLiteral("U'"));
ASSERT_EQUALS(false, ::isCharLiteral("L'"));
// valid char literals
ASSERT_EQUALS(true, ::isCharLiteral("'t'"));
ASSERT_EQUALS(true, ::isCharLiteral("u8't'"));
ASSERT_EQUALS(true, ::isCharLiteral("u't'"));
ASSERT_EQUALS(true, ::isCharLiteral("U't'"));
ASSERT_EQUALS(true, ::isCharLiteral("L't'"));
ASSERT_EQUALS(true, ::isCharLiteral("'test'"));
ASSERT_EQUALS(true, ::isCharLiteral("u8'test'"));
ASSERT_EQUALS(true, ::isCharLiteral("u'test'"));
ASSERT_EQUALS(true, ::isCharLiteral("U'test'"));
ASSERT_EQUALS(true, ::isCharLiteral("L'test'"));
}
void strToInt() {
ASSERT_EQUALS(1, ::strToInt<int>("1"));
ASSERT_EQUALS(-1, ::strToInt<int>("-1"));
ASSERT_EQUALS(1, ::strToInt<std::size_t>("1"));
ASSERT_THROW_EQUALS_2(::strToInt<int>(""), std::runtime_error, "converting '' to integer failed - not an integer");
ASSERT_THROW_EQUALS_2(::strToInt<std::size_t>(""), std::runtime_error, "converting '' to integer failed - not an integer");
ASSERT_THROW_EQUALS_2(::strToInt<int>(" "), std::runtime_error, "converting ' ' to integer failed - not an integer");
ASSERT_THROW_EQUALS_2(::strToInt<std::size_t>(" "), std::runtime_error, "converting ' ' to integer failed - not an integer");
ASSERT_THROW_EQUALS_2(::strToInt<unsigned int>("-1"), std::runtime_error, "converting '-1' to integer failed - needs to be positive");
ASSERT_THROW_EQUALS_2(::strToInt<int>("1ms"), std::runtime_error, "converting '1ms' to integer failed - not an integer");
ASSERT_THROW_EQUALS_2(::strToInt<int>("1.0"), std::runtime_error, "converting '1.0' to integer failed - not an integer");
ASSERT_THROW_EQUALS_2(::strToInt<int>("one"), std::runtime_error, "converting 'one' to integer failed - not an integer");
ASSERT_THROW_EQUALS_2(::strToInt<unsigned int>("1ms"), std::runtime_error, "converting '1ms' to integer failed - not an integer");
ASSERT_THROW_EQUALS_2(::strToInt<unsigned int>("1.0"), std::runtime_error, "converting '1.0' to integer failed - not an integer");
ASSERT_THROW_EQUALS_2(::strToInt<unsigned int>("one"), std::runtime_error, "converting 'one' to integer failed - not an integer");
ASSERT_THROW_EQUALS_2(::strToInt<int>(std::to_string(static_cast<int64_t>(std::numeric_limits<int>::max()) + 1)), std::runtime_error, "converting '2147483648' to integer failed - out of range (limits)");
ASSERT_THROW_EQUALS_2(::strToInt<int>(std::to_string(static_cast<int64_t>(std::numeric_limits<int>::min()) - 1)), std::runtime_error, "converting '-2147483649' to integer failed - out of range (limits)");
ASSERT_THROW_EQUALS_2(::strToInt<int8_t>(std::to_string(static_cast<int64_t>(std::numeric_limits<int8_t>::max()) + 1)), std::runtime_error, "converting '128' to integer failed - out of range (limits)");
ASSERT_THROW_EQUALS_2(::strToInt<int8_t>(std::to_string(static_cast<int64_t>(std::numeric_limits<int8_t>::min()) - 1)), std::runtime_error, "converting '-129' to integer failed - out of range (limits)");
ASSERT_THROW_EQUALS_2(::strToInt<unsigned int>(std::to_string(static_cast<uint64_t>(std::numeric_limits<unsigned int>::max()) + 1)), std::runtime_error, "converting '4294967296' to integer failed - out of range (limits)");
ASSERT_THROW_EQUALS_2(::strToInt<int>("9223372036854775808"), std::runtime_error, "converting '9223372036854775808' to integer failed - out of range (stoll)"); // LLONG_MAX + 1
ASSERT_THROW_EQUALS_2(::strToInt<std::size_t>("18446744073709551616"), std::runtime_error, "converting '18446744073709551616' to integer failed - out of range (stoull)"); // ULLONG_MAX + 1
{
long tmp;
ASSERT(::strToInt("1", tmp));
ASSERT_EQUALS(1, tmp);
}
{
long tmp;
ASSERT(::strToInt("-1", tmp));
ASSERT_EQUALS(-1, tmp);
}
{
std::size_t tmp;
ASSERT(::strToInt("1", tmp));
}
{
std::size_t tmp;
ASSERT(!::strToInt("-1", tmp));
}
{
long tmp;
ASSERT(!::strToInt("1ms", tmp));
}
{
unsigned long tmp;
ASSERT(!::strToInt("1ms", tmp));
}
{
long tmp;
ASSERT(!::strToInt("", tmp));
}
{
unsigned long tmp;
ASSERT(!::strToInt("", tmp));
}
{
long tmp;
ASSERT(!::strToInt(" ", tmp));
}
{
unsigned long tmp;
ASSERT(!::strToInt(" ", tmp));
}
{
long tmp;
std::string err;
ASSERT(::strToInt("1", tmp, &err));
ASSERT_EQUALS(1, tmp);
ASSERT_EQUALS("", err);
}
{
std::size_t tmp;
std::string err;
ASSERT(::strToInt("1", tmp, &err));
ASSERT_EQUALS(1, tmp);
ASSERT_EQUALS("", err);
}
{
unsigned long tmp;
std::string err;
ASSERT(!::strToInt("-1", tmp, &err));
ASSERT_EQUALS("needs to be positive", err);
}
{
long tmp;
std::string err;
ASSERT(!::strToInt("1ms", tmp, &err));
ASSERT_EQUALS("not an integer", err);
}
{
long tmp;
std::string err;
ASSERT(!::strToInt("1.0", tmp, &err));
ASSERT_EQUALS("not an integer", err);
}
{
long tmp;
std::string err;
ASSERT(!::strToInt("one", tmp, &err));
ASSERT_EQUALS("not an integer", err);
}
{
std::size_t tmp;
std::string err;
ASSERT(!::strToInt("1ms", tmp, &err));
ASSERT_EQUALS("not an integer", err);
}
{
long tmp;
std::string err;
ASSERT(!::strToInt("9223372036854775808", tmp, &err)); // LLONG_MAX + 1
ASSERT_EQUALS("out of range (stoll)", err);
}
{
int tmp;
std::string err;
ASSERT(!::strToInt(std::to_string(static_cast<int64_t>(std::numeric_limits<int>::max()) + 1), tmp, &err));
ASSERT_EQUALS("out of range (limits)", err);
}
{
int tmp;
std::string err;
ASSERT(!::strToInt(std::to_string(static_cast<int64_t>(std::numeric_limits<int>::min()) - 1), tmp, &err));
ASSERT_EQUALS("out of range (limits)", err);
}
{
int8_t tmp;
std::string err;
ASSERT(!::strToInt(std::to_string(static_cast<int64_t>(std::numeric_limits<int8_t>::max()) + 1), tmp, &err));
ASSERT_EQUALS("out of range (limits)", err);
}
{
int8_t tmp;
std::string err;
ASSERT(!::strToInt(std::to_string(static_cast<int64_t>(std::numeric_limits<int8_t>::min()) - 1), tmp, &err));
ASSERT_EQUALS("out of range (limits)", err);
}
{
std::size_t tmp;
std::string err;
ASSERT(!::strToInt("18446744073709551616", tmp, &err)); // ULLONG_MAX + 1
ASSERT_EQUALS("out of range (stoull)", err);
}
}
void id_string() const
{
ASSERT_EQUALS("0", id_string_i(0));
ASSERT_EQUALS("f1", id_string_i(0xF1));
ASSERT_EQUALS("123", id_string_i(0x123));
ASSERT_EQUALS("1230", id_string_i(0x1230));
ASSERT_EQUALS(std::string(8,'f'), id_string_i(0xffffffffU));
if (sizeof(void*) == 8) {
ASSERT_EQUALS(std::string(16,'f'), id_string_i(~0ULL));
}
}
void startsWith() const
{
ASSERT(::startsWith("test", "test"));
ASSERT(::startsWith("test2", "test"));
ASSERT(::startsWith("test test", "test"));
ASSERT(::startsWith("test", "t"));
ASSERT(!::startsWith("2test", "test"));
ASSERT(!::startsWith("", "test"));
ASSERT(!::startsWith("tes", "test"));
ASSERT(!::startsWith("2test", "t"));
ASSERT(!::startsWith("t", "test"));
}
void trim() const
{
ASSERT_EQUALS("test", ::trim("test"));
ASSERT_EQUALS("test", ::trim(" test"));
ASSERT_EQUALS("test", ::trim("test "));
ASSERT_EQUALS("test", ::trim(" test "));
ASSERT_EQUALS("test", ::trim(" test"));
ASSERT_EQUALS("test", ::trim("test "));
ASSERT_EQUALS("test", ::trim(" test "));
ASSERT_EQUALS("test", ::trim("\ttest"));
ASSERT_EQUALS("test", ::trim("test\t"));
ASSERT_EQUALS("test", ::trim("\ttest\t"));
ASSERT_EQUALS("test", ::trim("\t\ttest"));
ASSERT_EQUALS("test", ::trim("test\t\t"));
ASSERT_EQUALS("test", ::trim("\t\ttest\t\t"));
ASSERT_EQUALS("test", ::trim(" \ttest"));
ASSERT_EQUALS("test", ::trim("test\t "));
ASSERT_EQUALS("test", ::trim(" \ttest\t"));
ASSERT_EQUALS("test", ::trim("\t \ttest"));
ASSERT_EQUALS("test", ::trim("test\t \t"));
ASSERT_EQUALS("test", ::trim("\t \ttest\t \t"));
ASSERT_EQUALS("test test", ::trim("test test"));
ASSERT_EQUALS("test test", ::trim(" test test"));
ASSERT_EQUALS("test test", ::trim("test test "));
ASSERT_EQUALS("test test", ::trim(" test test "));
ASSERT_EQUALS("test\ttest", ::trim(" test\ttest"));
ASSERT_EQUALS("test\ttest", ::trim("test\ttest "));
ASSERT_EQUALS("test\ttest", ::trim(" test\ttest "));
ASSERT_EQUALS("test", ::trim("\ntest", "\n"));
ASSERT_EQUALS("test", ::trim("test\n", "\n"));
ASSERT_EQUALS("test", ::trim("\ntest\n", "\n"));
}
void findAndReplace() const {
{
std::string s{"test"};
::findAndReplace(s, "test", "tset");
ASSERT_EQUALS("tset", s);
}
{
std::string s{"testtest"};
::findAndReplace(s, "test", "tset");
ASSERT_EQUALS("tsettset", s);
}
{
std::string s{"1test1test1"};
::findAndReplace(s, "test", "tset");
ASSERT_EQUALS("1tset1tset1", s);
}
{
std::string s{"1test1test1"};
::findAndReplace(s, "test", "");
ASSERT_EQUALS("111", s);
}
{
std::string s{"111"};
::findAndReplace(s, "test", "tset");
ASSERT_EQUALS("111", s);
}
{
std::string s;
::findAndReplace(s, "test", "tset");
ASSERT_EQUALS("", s);
}
}
void replaceEscapeSequences() const {
ASSERT_EQUALS("\x30", ::replaceEscapeSequences("\\x30"));
ASSERT_EQUALS("\030", ::replaceEscapeSequences("\\030"));
ASSERT_EQUALS("\r", ::replaceEscapeSequences("\\r"));
ASSERT_EQUALS("\n", ::replaceEscapeSequences("\\n"));
ASSERT_EQUALS("\t", ::replaceEscapeSequences("\\t"));
ASSERT_EQUALS("\\", ::replaceEscapeSequences("\\\\"));
ASSERT_EQUALS("\"", ::replaceEscapeSequences("\\\""));
}
void splitString() const {
{
const auto l = ::splitString("test", ',');
ASSERT_EQUALS(1, l.size());
ASSERT_EQUALS("test", *l.cbegin());
}
{
const auto l = ::splitString("test,test", ';');
ASSERT_EQUALS(1, l.size());
ASSERT_EQUALS("test,test", *l.cbegin());
}
{
const auto l = ::splitString("test,test", ',');
ASSERT_EQUALS(2, l.size());
auto it = l.cbegin();
ASSERT_EQUALS("test", *it++);
ASSERT_EQUALS("test", *it);
}
{
const auto l = ::splitString("test,test,", ',');
ASSERT_EQUALS(3, l.size());
auto it = l.cbegin();
ASSERT_EQUALS("test", *it++);
ASSERT_EQUALS("test", *it++);
ASSERT_EQUALS("", *it);
}
{
const auto l = ::splitString("test,,test", ',');
ASSERT_EQUALS(3, l.size());
auto it = l.cbegin();
ASSERT_EQUALS("test", *it++);
ASSERT_EQUALS("", *it++);
ASSERT_EQUALS("test", *it);
}
{
const auto l = ::splitString(",test,test", ',');
ASSERT_EQUALS(3, l.size());
auto it = l.cbegin();
ASSERT_EQUALS("", *it++);
ASSERT_EQUALS("test", *it++);
ASSERT_EQUALS("test", *it);
}
}
void as_const() const {
struct C {
bool written = false;
void f() {
written = true;
}
// cppcheck-suppress functionStatic - needs to be const
void f() const {}
};
{
C c;
c.f();
ASSERT(c.written);
}
{
C c;
utils::as_const(c).f();
ASSERT(!c.written);
}
{
C c;
C* cp = &c;
cp->f();
ASSERT(c.written);
}
{
C c;
C* cp = &c;
utils::as_const(cp)->f(); // (correctly) calls non-const version
ASSERT(c.written);
}
}
};
REGISTER_TEST(TestUtils)
| null |
1,015 | cpp | cppcheck | testsettings.cpp | test/testsettings.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#include "errortypes.h"
#include "settings.h"
#include "fixture.h"
#include "helpers.h"
#include "suppressions.h"
class TestSettings : public TestFixture {
public:
TestSettings() : TestFixture("TestSettings") {}
private:
void run() override {
TEST_CASE(simpleEnableGroup);
TEST_CASE(loadCppcheckCfg);
TEST_CASE(loadCppcheckCfgSafety);
TEST_CASE(getNameAndVersion);
TEST_CASE(ruleTexts);
TEST_CASE(checkLevelDefault);
}
void simpleEnableGroup() const {
SimpleEnableGroup<Checks> group;
ASSERT_EQUALS(0, group.intValue());
ASSERT_EQUALS(false, group.isEnabled(Checks::unusedFunction));
ASSERT_EQUALS(false, group.isEnabled(Checks::missingInclude));
ASSERT_EQUALS(false, group.isEnabled(Checks::internalCheck));
group.fill();
ASSERT_EQUALS(4294967295, group.intValue());
ASSERT_EQUALS(true, group.isEnabled(Checks::unusedFunction));
ASSERT_EQUALS(true, group.isEnabled(Checks::missingInclude));
ASSERT_EQUALS(true, group.isEnabled(Checks::internalCheck));
group.clear();
ASSERT_EQUALS(0, group.intValue());
ASSERT_EQUALS(false, group.isEnabled(Checks::unusedFunction));
ASSERT_EQUALS(false, group.isEnabled(Checks::missingInclude));
ASSERT_EQUALS(false, group.isEnabled(Checks::internalCheck));
group.enable(Checks::unusedFunction);
group.setEnabled(Checks::missingInclude, true);
ASSERT_EQUALS(3, group.intValue());
ASSERT_EQUALS(true, group.isEnabled(Checks::unusedFunction));
ASSERT_EQUALS(true, group.isEnabled(Checks::missingInclude));
ASSERT_EQUALS(false, group.isEnabled(Checks::internalCheck));
group.disable(Checks::unusedFunction);
group.setEnabled(Checks::missingInclude, false);
ASSERT_EQUALS(0, group.intValue());
ASSERT_EQUALS(false, group.isEnabled(Checks::unusedFunction));
ASSERT_EQUALS(false, group.isEnabled(Checks::missingInclude));
ASSERT_EQUALS(false, group.isEnabled(Checks::internalCheck));
SimpleEnableGroup<Checks> newGroup;
newGroup.enable(Checks::missingInclude);
group.enable(newGroup);
ASSERT_EQUALS(2, group.intValue());
ASSERT_EQUALS(false, group.isEnabled(Checks::unusedFunction));
ASSERT_EQUALS(true, group.isEnabled(Checks::missingInclude));
ASSERT_EQUALS(false, group.isEnabled(Checks::internalCheck));
group.disable(newGroup);
ASSERT_EQUALS(0, group.intValue());
ASSERT_EQUALS(false, group.isEnabled(Checks::unusedFunction));
ASSERT_EQUALS(false, group.isEnabled(Checks::missingInclude));
ASSERT_EQUALS(false, group.isEnabled(Checks::internalCheck));
}
void loadCppcheckCfg()
{
{
Settings s;
ASSERT_EQUALS("", Settings::loadCppcheckCfg(s, s.supprs));
}
{
Settings s;
ScopedFile file("cppcheck.cfg",
"{}\n");
ASSERT_EQUALS("", Settings::loadCppcheckCfg(s, s.supprs));
}
{
Settings s;
ScopedFile file("cppcheck.cfg",
"{\n");
ASSERT_EQUALS("not a valid JSON - syntax error at line 2 near: ", Settings::loadCppcheckCfg(s, s.supprs));
}
{
Settings s;
ScopedFile file("cppcheck.cfg",
R"({"productName": ""}\n)");
ASSERT_EQUALS("", Settings::loadCppcheckCfg(s, s.supprs));
ASSERT_EQUALS("", s.cppcheckCfgProductName);
}
{
Settings s;
ScopedFile file("cppcheck.cfg",
R"({"productName": "product"}\n)");
ASSERT_EQUALS("", Settings::loadCppcheckCfg(s, s.supprs));
ASSERT_EQUALS("product", s.cppcheckCfgProductName);
}
{
Settings s;
ScopedFile file("cppcheck.cfg",
R"({"productName": 1}\n)");
ASSERT_EQUALS("'productName' is not a string", Settings::loadCppcheckCfg(s, s.supprs));
}
{
Settings s;
ScopedFile file("cppcheck.cfg",
R"({"about": ""}\n)");
ASSERT_EQUALS("", Settings::loadCppcheckCfg(s, s.supprs));
ASSERT_EQUALS("", s.cppcheckCfgAbout);
}
{
Settings s;
ScopedFile file("cppcheck.cfg",
R"({"about": "about"}\n)");
ASSERT_EQUALS("", Settings::loadCppcheckCfg(s, s.supprs));
ASSERT_EQUALS("about", s.cppcheckCfgAbout);
}
{
Settings s;
ScopedFile file("cppcheck.cfg",
R"({"about": 1}\n)");
ASSERT_EQUALS("'about' is not a string", Settings::loadCppcheckCfg(s, s.supprs));
}
{
Settings s;
ScopedFile file("cppcheck.cfg",
R"({"addons": []}\n)");
ASSERT_EQUALS("", Settings::loadCppcheckCfg(s, s.supprs));
ASSERT_EQUALS(0, s.addons.size());
}
{
Settings s;
ScopedFile file("cppcheck.cfg",
R"({"addons": 1}\n)");
ASSERT_EQUALS("'addons' is not an array", Settings::loadCppcheckCfg(s, s.supprs));
}
{
Settings s;
ScopedFile file("cppcheck.cfg",
R"({"addons": ["addon"]}\n)");
ASSERT_EQUALS("", Settings::loadCppcheckCfg(s, s.supprs));
ASSERT_EQUALS(1, s.addons.size());
ASSERT_EQUALS("addon", *s.addons.cbegin());
}
{
Settings s;
ScopedFile file("cppcheck.cfg",
R"({"addons": [1]}\n)");
ASSERT_EQUALS("'addons' array entry is not a string", Settings::loadCppcheckCfg(s, s.supprs));
}
{
Settings s;
ScopedFile file("cppcheck.cfg",
R"({"addons": []}\n)");
ASSERT_EQUALS("", Settings::loadCppcheckCfg(s, s.supprs));
ASSERT_EQUALS(0, s.addons.size());
}
{
Settings s;
ScopedFile file("cppcheck.cfg",
R"({"suppressions": 1}\n)");
ASSERT_EQUALS("'suppressions' is not an array", Settings::loadCppcheckCfg(s, s.supprs));
}
{
Settings s;
ScopedFile file("cppcheck.cfg",
R"({"suppressions": ["id"]}\n)");
ASSERT_EQUALS("", Settings::loadCppcheckCfg(s, s.supprs));
ASSERT_EQUALS(1, s.supprs.nomsg.getSuppressions().size());
ASSERT_EQUALS("id", s.supprs.nomsg.getSuppressions().cbegin()->errorId);
}
{
Settings s;
ScopedFile file("cppcheck.cfg",
R"({"suppressions": [""]}\n)");
ASSERT_EQUALS("could not parse suppression '' - Failed to add suppression. No id.", Settings::loadCppcheckCfg(s, s.supprs));
}
{
Settings s;
ScopedFile file("cppcheck.cfg",
R"({"suppressions": [1]}\n)");
ASSERT_EQUALS("'suppressions' array entry is not a string", Settings::loadCppcheckCfg(s, s.supprs));
}
// TODO: test with FILESDIR
}
void loadCppcheckCfgSafety() const
{
// Test the "safety" flag
{
Settings s;
s.safety = false;
ScopedFile file("cppcheck.cfg", "{}");
ASSERT_EQUALS("", Settings::loadCppcheckCfg(s, s.supprs));
ASSERT_EQUALS(false, s.safety);
}
{
Settings s;
s.safety = true;
ScopedFile file("cppcheck.cfg", "{\"safety\": false}");
ASSERT_EQUALS("", Settings::loadCppcheckCfg(s, s.supprs));
ASSERT_EQUALS(true, s.safety);
}
{
Settings s;
s.safety = false;
ScopedFile file("cppcheck.cfg", "{\"safety\": true}");
ASSERT_EQUALS("", Settings::loadCppcheckCfg(s, s.supprs));
ASSERT_EQUALS(true, s.safety);
}
}
void getNameAndVersion() const
{
{
const auto nameVersion = Settings::getNameAndVersion("Cppcheck Premium 12.3.4");
ASSERT_EQUALS("Cppcheck Premium", nameVersion.first);
ASSERT_EQUALS("12.3.4", nameVersion.second);
}
{
const auto nameVersion = Settings::getNameAndVersion("Cppcheck Premium 12.3.4s");
ASSERT_EQUALS("Cppcheck Premium", nameVersion.first);
ASSERT_EQUALS("12.3.4s", nameVersion.second);
}
}
void ruleTexts() const
{
Settings s;
s.setMisraRuleTexts("1.1 text 1\n1.2 text 2\n1.3 text 3\r\n");
ASSERT_EQUALS("text 1", s.getMisraRuleText("misra-c2012-1.1", "---"));
ASSERT_EQUALS("text 2", s.getMisraRuleText("misra-c2012-1.2", "---"));
ASSERT_EQUALS("text 3", s.getMisraRuleText("misra-c2012-1.3", "---"));
}
void checkLevelDefault() const
{
Settings s;
ASSERT_EQUALS_ENUM(s.checkLevel, Settings::CheckLevel::exhaustive);
ASSERT_EQUALS(s.vfOptions.maxIfCount, -1);
ASSERT_EQUALS(s.vfOptions.maxSubFunctionArgs, 256);
ASSERT_EQUALS(true, s.vfOptions.doConditionExpressionAnalysis);
ASSERT_EQUALS(-1, s.vfOptions.maxForwardBranches);
}
};
REGISTER_TEST(TestSettings)
| null |
1,016 | cpp | cppcheck | testautovariables.cpp | test/testautovariables.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#include "checkautovariables.h"
#include "errortypes.h"
#include "fixture.h"
#include "helpers.h"
#include "settings.h"
#include <cstddef>
class TestAutoVariables : public TestFixture {
public:
TestAutoVariables() : TestFixture("TestAutoVariables") {}
private:
const Settings settings = settingsBuilder().severity(Severity::warning).severity(Severity::style).library("std.cfg").library("qt.cfg").build();
#define check(...) check_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
void check_(const char* file, int line, const char (&code)[size], bool inconclusive = true, bool cpp = true) {
const Settings settings1 = settingsBuilder(settings).certainty(Certainty::inconclusive, inconclusive).build();
// Tokenize..
SimpleTokenizer tokenizer(settings1, *this);
ASSERT_LOC(tokenizer.tokenize(code, cpp), file, line);
runChecks<CheckAutoVariables>(tokenizer, this);
}
void run() override {
TEST_CASE(testautovar1);
TEST_CASE(testautovar2);
TEST_CASE(testautovar3); // ticket #2925
TEST_CASE(testautovar4); // ticket #2928
TEST_CASE(testautovar5); // ticket #2926
TEST_CASE(testautovar6); // ticket #2931
TEST_CASE(testautovar7); // ticket #3066
TEST_CASE(testautovar8);
TEST_CASE(testautovar9);
TEST_CASE(testautovar10); // ticket #2930 - void f(char *p) { p = '\0'; }
TEST_CASE(testautovar11); // ticket #4641 - fp, assign local struct member address to function parameter
TEST_CASE(testautovar12); // ticket #5024 - crash
TEST_CASE(testautovar13); // ticket #5537 - crash
TEST_CASE(testautovar14); // ticket #4776 - assignment of function parameter, goto
TEST_CASE(testautovar15); // ticket #6538
TEST_CASE(testautovar16); // ticket #8114
TEST_CASE(testautovar_array1);
TEST_CASE(testautovar_array2);
TEST_CASE(testautovar_array3);
TEST_CASE(testautovar_normal); // "normal" token list that does not remove casts etc
TEST_CASE(testautovar_ptrptr); // ticket #6956
TEST_CASE(testautovar_return1);
TEST_CASE(testautovar_return2);
TEST_CASE(testautovar_return3);
TEST_CASE(testautovar_return4);
TEST_CASE(testautovar_return5);
TEST_CASE(testautovar_extern);
TEST_CASE(testautovar_reassigned);
TEST_CASE(testinvaliddealloc);
TEST_CASE(testinvaliddealloc_input); // Ticket #10600
TEST_CASE(testinvaliddealloc_string);
TEST_CASE(testinvaliddealloc_C);
TEST_CASE(testassign1); // Ticket #1819
TEST_CASE(testassign2); // Ticket #2765
TEST_CASE(assignAddressOfLocalArrayToGlobalPointer);
TEST_CASE(assignAddressOfLocalVariableToGlobalPointer);
TEST_CASE(assignAddressOfLocalVariableToMemberVariable);
TEST_CASE(returnLocalVariable1);
TEST_CASE(returnLocalVariable2);
TEST_CASE(returnLocalVariable3); // &x[0]
TEST_CASE(returnLocalVariable4); // x+y
TEST_CASE(returnLocalVariable5); // cast
TEST_CASE(returnLocalVariable6); // valueflow
// return reference..
TEST_CASE(returnReference1);
TEST_CASE(returnReference2);
TEST_CASE(returnReference3);
TEST_CASE(returnReference4);
TEST_CASE(returnReference5);
TEST_CASE(returnReference6);
TEST_CASE(returnReference7);
TEST_CASE(returnReference8);
TEST_CASE(returnReference9);
TEST_CASE(returnReference10);
TEST_CASE(returnReference11);
TEST_CASE(returnReference12);
TEST_CASE(returnReference13);
TEST_CASE(returnReference14);
TEST_CASE(returnReference15); // #9432
TEST_CASE(returnReference16); // #9433
TEST_CASE(returnReference16); // #9433
TEST_CASE(returnReference17); // #9461
TEST_CASE(returnReference18); // #9482
TEST_CASE(returnReference19); // #9597
TEST_CASE(returnReference20); // #9536
TEST_CASE(returnReference21); // #9530
TEST_CASE(returnReference22);
TEST_CASE(returnReference23);
TEST_CASE(returnReference24); // #10098
TEST_CASE(returnReference25); // #10983
TEST_CASE(returnReference26);
TEST_CASE(returnReference27);
TEST_CASE(returnReference28);
TEST_CASE(returnReferenceFunction);
TEST_CASE(returnReferenceContainer);
TEST_CASE(returnReferenceLiteral);
TEST_CASE(returnReferenceCalculation);
TEST_CASE(returnReferenceLambda);
TEST_CASE(returnReferenceInnerScope);
TEST_CASE(returnReferenceRecursive);
TEST_CASE(extendedLifetime);
TEST_CASE(danglingReference);
TEST_CASE(danglingTempReference);
// global namespace
TEST_CASE(testglobalnamespace);
TEST_CASE(returnParameterAddress);
TEST_CASE(testconstructor); // ticket #5478 - crash
TEST_CASE(variableIsUsedInScope); // ticket #5599 crash in variableIsUsedInScope()
TEST_CASE(danglingLifetimeLambda);
TEST_CASE(danglingLifetimeContainer);
TEST_CASE(danglingLifetimeContainerView);
TEST_CASE(danglingLifetimeUniquePtr);
TEST_CASE(danglingLifetime);
TEST_CASE(danglingLifetimeFunction);
TEST_CASE(danglingLifetimeUserConstructor);
TEST_CASE(danglingLifetimeAggegrateConstructor);
TEST_CASE(danglingLifetimeInitList);
TEST_CASE(danglingLifetimeImplicitConversion);
TEST_CASE(danglingTemporaryLifetime);
TEST_CASE(danglingLifetimeBorrowedMembers);
TEST_CASE(danglingLifetimeClassMemberFunctions);
TEST_CASE(invalidLifetime);
TEST_CASE(deadPointer);
TEST_CASE(splitNamespaceAuto); // crash #10473
}
void testautovar1() {
check("void func1(int **res)\n"
"{\n"
" int num = 2;\n"
" *res = #\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Address of local auto-variable assigned to a function parameter.\n", errout_str());
check("void func1(int **res)\n"
"{\n"
" int num = 2;\n"
" res = #\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (warning) Assignment of function parameter has no effect outside the function. Did you forget dereferencing it?\n", errout_str());
check("void func1(int **res)\n"
"{\n"
" int num = 2;\n"
" foo.res = #\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void testautovar2() {
check("class Fred {\n"
" void func1(int **res);\n"
"}\n"
"void Fred::func1(int **res)\n"
"{\n"
" int num = 2;\n"
" *res = #\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (error) Address of local auto-variable assigned to a function parameter.\n", errout_str());
check("class Fred {\n"
" void func1(int **res);\n"
"}\n"
"void Fred::func1(int **res)\n"
"{\n"
" int num = 2;\n"
" res = #\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (warning) Assignment of function parameter has no effect outside the function. Did you forget dereferencing it?\n", errout_str());
check("class Fred {\n"
" void func1(int **res);\n"
"}\n"
"void Fred::func1(int **res)\n"
"{\n"
" int num = 2;\n"
" foo.res = #\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void testautovar3() { // ticket #2925
check("void foo(int **p)\n"
"{\n"
" int x[100];\n"
" *p = x;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Address of local auto-variable assigned to a function parameter.\n", errout_str());
}
void testautovar4() { // ticket #2928
check("void foo(int **p)\n"
"{\n"
" static int x[100];\n"
" *p = x;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void testautovar5() { // ticket #2926
check("void foo(struct AB *ab)\n"
"{\n"
" char a;\n"
" ab->a = &a;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error, inconclusive) Address of local auto-variable assigned to a function parameter.\n", errout_str());
}
void testautovar6() { // ticket #2931
check("void foo(struct X *x)\n"
"{\n"
" char a[10];\n"
" x->str = a;\n"
"}", false);
ASSERT_EQUALS("", errout_str());
check("void foo(struct X *x)\n"
"{\n"
" char a[10];\n"
" x->str = a;\n"
"}", true);
ASSERT_EQUALS("[test.cpp:4]: (error, inconclusive) Address of local auto-variable assigned to a function parameter.\n", errout_str());
}
void testautovar7() { // ticket #3066
check("struct txt_scrollpane_s * TXT_NewScrollPane(struct txt_widget_s * target)\n"
"{\n"
" struct txt_scrollpane_s * scrollpane;\n"
" target->parent = &scrollpane->widget;\n"
" return scrollpane;\n"
"}", false);
ASSERT_EQUALS("", errout_str());
}
void testautovar8() {
check("void foo(int*& p) {\n"
" int i = 0;\n"
" p = &i;\n"
"}", false);
ASSERT_EQUALS("[test.cpp:3]: (error) Address of local auto-variable assigned to a function parameter.\n", errout_str());
check("void foo(std::string& s) {\n"
" s = foo;\n"
"}", false);
ASSERT_EQUALS("", errout_str());
}
void testautovar9() {
check("struct FN {int i;};\n"
"struct FP {FN* f};\n"
"void foo(int*& p, FN* p_fp) {\n"
" FN fn;\n"
" FP fp;\n"
" p = &fn.i;\n"
"}", false);
ASSERT_EQUALS("[test.cpp:6]: (error) Address of local auto-variable assigned to a function parameter.\n", errout_str());
check("struct FN {int i;};\n"
"struct FP {FN* f};\n"
"void foo(int*& p, FN* p_fp) {\n"
" FN fn;\n"
" FP fp;\n"
" p = &p_fp->i;\n"
"}", false);
ASSERT_EQUALS("", errout_str());
check("struct FN {int i;};\n"
"struct FP {FN* f};\n"
"void foo(int*& p, FN* p_fp) {\n"
" FN fn;\n"
" FP fp;\n"
" p = &fp.f->i;\n"
"}", false);
ASSERT_EQUALS("", errout_str());
}
void testautovar10() { // #2930 - assignment of function parameter
check("void foo(char* p) {\n"
" p = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Assignment of function parameter has no effect outside the function. Did you forget dereferencing it?\n", errout_str());
check("void foo(int b) {\n"
" b = foo(b);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Assignment of function parameter has no effect outside the function.\n", errout_str());
check("void foo(int b) {\n"
" b += 1;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Assignment of function parameter has no effect outside the function.\n", errout_str());
check("void foo(std::string s) {\n"
" s = foo(b);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Assignment of function parameter has no effect outside the function.\n", errout_str());
check("void foo(char* p) {\n" // don't warn for self assignment, there is another warning for this
" p = p;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(char* p) {\n"
" if (!p) p = buf;\n"
" *p = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(char* p) {\n"
" if (!p) p = buf;\n"
" do_something(p);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(char* p) {\n"
" while (!p) p = buf;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(char* p) {\n"
" p = 0;\n"
" asm(\"somecmd\");\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(Foo* p) {\n"
" p = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Assignment of function parameter has no effect outside the function. Did you forget dereferencing it?\n", errout_str());
check("class Foo {};\n"
"void foo(Foo p) {\n"
" p = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Assignment of function parameter has no effect outside the function.\n", errout_str());
check("void foo(Foo p) {\n"
" p = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(int& p) {\n"
" p = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("double foo(double d) {\n" // #5005
" int i = d;\n"
" d = i;\n"
" return d;"
"}",false);
ASSERT_EQUALS("", errout_str());
check("void foo(int* ptr) {\n" // #4793
" ptr++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Assignment of function parameter has no effect outside the function. Did you forget dereferencing it?\n", errout_str());
check("void foo(int* ptr) {\n" // #3177
" --ptr;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Assignment of function parameter has no effect outside the function. Did you forget dereferencing it?\n", errout_str());
check("void foo(struct S* const x) {\n" // #7839
" ++x->n;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void testautovar11() { // #4641 - fp, assign local struct member address to function parameter
check("struct A {\n"
" char (*data)[10];\n"
"};\n"
"void foo(char** p) {\n"
" struct A a = bar();\n"
" *p = &(*a.data)[0];\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct A {\n"
" char data[10];\n"
"};\n"
"void foo(char** p) {\n"
" struct A a = bar();\n"
" *p = &a.data[0];\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (error) Address of local auto-variable assigned to a function parameter.\n", errout_str());
check("void f(char **out) {\n"
" struct S *p = glob;\n"
" *out = &p->data;\n"
"}");
ASSERT_EQUALS("", errout_str());
// #4998
check("void f(s8**out) {\n"
" s8 *p;\n" // <- p is pointer => no error
" *out = &p[1];\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(s8**out) {\n"
" s8 p[10];\n" // <- p is array => error
" *out = &p[1];\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Address of local auto-variable assigned to a function parameter.\n", errout_str());
}
void testautovar12() { // Ticket #5024, #5050 - Crash on invalid input
ASSERT_THROW_INTERNAL(check("void f(int* a) { a = }"), SYNTAX);
check("struct custom_type { custom_type(int) {} };\n"
"void func(int) {}\n"
"int var;\n"
"void init() { func(var); }\n"
"UNKNOWN_MACRO_EXPANDING_TO_SIGNATURE { custom_type a(var); }");
}
void testautovar13() { // Ticket #5537
check("class FileManager {\n"
" FileManager() : UniqueRealDirs(*new UniqueDirContainer())\n"
" {}\n"
" ~FileManager() {\n"
" delete &UniqueRealDirs;\n"
" }\n"
"};");
}
void testautovar14() { // Ticket #4776
check("void f(int x) {\n"
"label:"
" if (x>0) {\n"
" x = x >> 1;\n"
" goto label;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void testautovar15() { // Ticket #6538
check("static const float4 darkOutline(0.05f, 0.05f, 0.05f, 0.95f);\n"
"static const float darkLuminosity = 0.05 +\n"
" 0.0722f * math::powf(darkOutline[2], 2.2);\n"
"const float4* ChooseOutlineColor(const float4& textColor) {\n"
" const float lumdiff = something;\n"
" if (lumdiff > 5.0f)\n"
" return &darkOutline;\n"
" return 0;\n"
"}", false);
ASSERT_EQUALS("", errout_str());
}
void testautovar16() { // Ticket #8114
check("void f(const void* ptr, bool* result) {\n"
" int dummy;\n"
" *result = (&dummy < ptr);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void testautovar_array1() {
check("void func1(int* arr[2])\n"
"{\n"
" int num=2;"
" arr[0]=#\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Address of local auto-variable assigned to a function parameter.\n", errout_str());
}
void testautovar_array2() {
check("class Fred {\n"
" void func1(int* arr[2]);\n"
"}\n"
"void Fred::func1(int* arr[2])\n"
"{\n"
" int num=2;"
" arr[0]=#\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (error) Address of local auto-variable assigned to a function parameter.\n", errout_str());
}
void testautovar_array3() {
check("int main(int argc, char* argv[]) {\n" // #11732
" std::string a = \"abc\";\n"
" argv[0] = &a[0];\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(char* c[]) {\n"
" char a[] = \"abc\";\n"
" c[0] = a;\n"
"}\n"
"void g(char* c[]) {\n"
" std::string a = \"abc\";\n"
" c[0] = a.data();\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (error) Address of local auto-variable assigned to a function parameter.\n"
"[test.cpp:7]: (error) Address of local auto-variable assigned to a function parameter.\n",
errout_str());
check("struct String {\n"
" String& operator=(const char* c) { m = c; return *this; }\n"
" std::string m;\n"
"};\n"
"struct T { String s; };\n"
"void f(T* t) {\n"
" char a[] = \"abc\";\n"
" t->s = &a[0];\n"
"}\n"
"void g(std::string* s) {\n"
" char a[] = \"abc\";\n"
" *s = &a[0];\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void testautovar_normal() {
check("void f(XmDestinationCallbackStruct *ds)\n"
"{\n"
" XPoint DropPoint;\n"
" ds->location_data = (XtPointer *)&DropPoint;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error, inconclusive) Address of local auto-variable assigned to a function parameter.\n", errout_str());
}
void testautovar_ptrptr() { // #6596
check("void remove_duplicate_matches (char **matches) {\n"
" char dead_slot;\n"
" matches[0] = (char *)&dead_slot;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Address of local auto-variable assigned to a function parameter.\n", errout_str());
}
void testautovar_return1() {
check("int* func1()\n"
"{\n"
" int num=2;"
" return #"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:3] -> [test.cpp:3]: (error) Returning pointer to local variable 'num' that will be invalid when returning.\n", errout_str());
}
void testautovar_return2() {
check("class Fred {\n"
" int* func1();\n"
"}\n"
"int* Fred::func1()\n"
"{\n"
" int num=2;"
" return #"
"}");
ASSERT_EQUALS("[test.cpp:6] -> [test.cpp:6] -> [test.cpp:6]: (error) Returning pointer to local variable 'num' that will be invalid when returning.\n", errout_str());
}
void testautovar_return3() {
// #2975 - FP
check("void** f()\n"
"{\n"
" void *&value = tls[id];"
" return &value;"
"}");
ASSERT_EQUALS("", errout_str());
}
void testautovar_return4() {
// #8058 - FP ignore return in lambda
check("void foo() {\n"
" int cond2;\n"
" dostuff([&cond2]() { return &cond2; });\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void testautovar_return5() { // #11465
check("struct S {};\n"
"const std::type_info* f() {\n"
" return &typeid(S);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void testautovar_extern() {
check("struct foo *f()\n"
"{\n"
" extern struct foo f;\n"
" return &f;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void testautovar_reassigned() {
check("void foo(cb* pcb) {\n"
" int root0;\n"
" pcb->root0 = &root0;\n"
" dostuff(pcb);\n"
" pcb->root0 = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(cb* pcb) {\n"
" int root0;\n"
" pcb->root0 = &root0;\n"
" dostuff(pcb);\n"
" if (condition) return;\n" // <- not reassigned => error
" pcb->root0 = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error, inconclusive) Address of local auto-variable assigned to a function parameter.\n", errout_str());
check("void foo(cb* pcb) {\n"
" int root0;\n"
" pcb->root0 = &root0;\n"
" dostuff(pcb);\n"
" if (condition)\n"
" pcb->root0 = 0;\n" // <- conditional reassign => error
"}");
ASSERT_EQUALS("[test.cpp:3]: (error, inconclusive) Address of local auto-variable assigned to a function parameter.\n", errout_str());
check("struct S { int *p; };\n"
"void g(struct S* s) {\n"
" int a[10];\n"
" s->p = a;\n"
" a[0] = 0;\n"
"}\n"
"void f() {\n"
" struct S s;\n"
" g(&s);\n"
"}");
ASSERT_EQUALS(
"[test.cpp:4]: (error) Address of local auto-variable assigned to a function parameter.\n"
"[test.cpp:4]: (error) Address of local auto-variable assigned to a function parameter.\n", // duplicate
errout_str());
}
void testinvaliddealloc() {
check("void func1() {\n"
" char tmp1[256];\n"
" free(tmp1);\n"
" char tmp2[256];\n"
" delete tmp2;\n"
" char tmp3[256];\n"
" delete tmp3;\n"
" char tmp4[256];\n"
" delete[] (tmp4);\n"
" char tmp5[256];\n"
" delete[] tmp5;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Deallocation of an auto-variable results in undefined behaviour.\n"
"[test.cpp:5]: (error) Deallocation of an auto-variable results in undefined behaviour.\n"
"[test.cpp:7]: (error) Deallocation of an auto-variable results in undefined behaviour.\n"
"[test.cpp:9]: (error) Deallocation of an auto-variable results in undefined behaviour.\n"
"[test.cpp:11]: (error) Deallocation of an auto-variable results in undefined behaviour.\n", errout_str());
check("void func1(char * ptr) {\n"
" free(ptr);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void func1() {\n"
" char* tmp1[256];\n"
" init(tmp1);\n"
" delete tmp1[34];\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void func1() {\n"
" static char tmp1[256];\n"
" char *p = tmp1;\n"
" free(p);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Deallocation of a static variable (tmp1) results in undefined behaviour.\n", errout_str());
check("char tmp1[256];\n"
"void func1() {\n"
" char *p; if (x) p = tmp1;\n"
" free(p);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Deallocation of a global variable (tmp1) results in undefined behaviour.\n", errout_str());
check("void f()\n"
"{\n"
" char psz_title[10];\n"
" {\n"
" char *psz_title = 0;\n"
" abc(0, psz_title);\n"
" free(psz_title);\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// #2298 new check: passing stack-address to free()
check("int main() {\n"
" int *p = malloc(4);\n"
" free(&p);\n"
" return 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Deallocation of an auto-variable results in undefined behaviour.\n", errout_str());
check("int main() {\n"
" int i;\n"
" free(&i);\n"
" return 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Deallocation of an auto-variable results in undefined behaviour.\n", errout_str());
// #5732
check("int main() {\n"
" long (*pKoeff)[256] = new long[9][256];\n"
" delete[] pKoeff;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int main() {\n"
" long *pKoeff[256];\n"
" delete[] pKoeff;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Deallocation of an auto-variable results in undefined behaviour.\n", errout_str());
check("int main() {\n"
" long *pKoeff[256];\n"
" free (pKoeff);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Deallocation of an auto-variable results in undefined behaviour.\n", errout_str());
check("void foo() {\n"
" const intPtr& intref = Getter();\n"
" delete intref;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void test() {\n"
" MyObj& obj = *new MyObj;\n"
" delete &obj;\n"
"}");
ASSERT_EQUALS("", errout_str());
// #6506
check("struct F {\n"
" void free(void*) {}\n"
"};\n"
"void foo() {\n"
" char c1[1];\n"
" F().free(c1);\n"
" char *c2 = 0;\n"
" F().free(&c2);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("class foo {\n"
" void free(void* );\n"
" void someMethod() {\n"
" char **dst_copy = NULL;\n"
" free(&dst_copy);\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
// #6551
check("bool foo( ) {\n"
" SwTxtFld * pTxtFld = GetFldTxtAttrAt();\n"
" delete static_cast<SwFmtFld*>(&pTxtFld->GetAttr());\n"
"}");
ASSERT_EQUALS("", errout_str());
// #8910
check("void f() {\n"
" char stack[512];\n"
" RGNDATA *data;\n"
" if (data_size > sizeof (stack)) data = malloc (data_size);\n"
" else data = (RGNDATA *)stack;\n"
" if ((char *)data != stack) free (data);\n"
"}");
ASSERT_EQUALS("", errout_str());
// #8923
check("void f(char **args1, char *args2[]) {\n"
" free((char **)args1);\n"
" free((char **)args2);\n"
"}");
ASSERT_EQUALS("", errout_str());
// #10097
check("struct Array {\n"
" ~Array() { delete m_Arr; }\n"
" std::array<long, 256>* m_Arr{};\n"
"};\n"
"Array arr;\n");
ASSERT_EQUALS("", errout_str());
// #8174
check("struct S {};\n"
"void f() {\n"
" S s;\n"
" S* p = &s;\n"
" free(p);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5]: (error) Deallocation of an auto-variable (s) results in undefined behaviour.\n", errout_str());
check("void f(bool b, int* q) {\n"
" int i;\n"
" int* p = b ? &i : q;\n"
" if (!b)\n"
" free(p);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct E { int* i; };\n" // #11768
"struct C { E e; };\n"
"int foo(C* cin) {\n"
" E* e = &cin->e;\n"
" e->i = new int[42];\n"
" delete[] e->i;\n"
" return 0;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" S* p = &g();\n"
" delete p;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void testinvaliddealloc_input() {
// #10600
check("void f(int* a[]) {\n"
" free(a);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(int a[]) {\n"
" free(a);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(int* a[]) {\n"
" int * p = *a;\n"
" free(p);\n"
" int ** q = a;\n"
" free(q);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(int a[]) {\n"
" int * p = a;\n"
" free(p);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void testinvaliddealloc_string() {
// #7341
check("void f() {\n"
" char *ptr = \"a\";\n"
" free(\"a\");\n"
" delete \"a\";\n"
" free(ptr);\n"
" delete ptr;\n"
" char * p = malloc(1000);\n"
" p = \"abc\";\n"
" free(p);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (error) Deallocation of a string literal results in undefined behaviour.\n"
"[test.cpp:4]: (error) Deallocation of a string literal results in undefined behaviour.\n"
"[test.cpp:5]: (error) Deallocation of a pointer pointing to a string literal (\"a\") results in undefined behaviour.\n"
"[test.cpp:6]: (error) Deallocation of a pointer pointing to a string literal (\"a\") results in undefined behaviour.\n"
"[test.cpp:9]: (error) Deallocation of a pointer pointing to a string literal (\"abc\") results in undefined behaviour.\n",
errout_str());
check("void f() {\n"
" char *ptr = malloc(10);\n"
" char *empty_str = \"\";\n"
" if (ptr == NULL)\n"
" ptr = empty_str;\n"
" if (ptr != empty_str)\n"
" free(ptr);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void testinvaliddealloc_C() {
// #5691
check("void svn_repos_dir_delta2() {\n"
" struct context c;\n"
" SVN_ERR(delete(&c, root_baton, src_entry, pool));\n"
"}\n", false, /* cpp= */ false);
ASSERT_EQUALS("", errout_str());
}
void testassign1() { // Ticket #1819
check("void f(EventPtr *eventP, ActionPtr **actionsP) {\n"
" EventPtr event = *eventP;\n"
" *actionsP = &event->actions;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void testassign2() { // Ticket #2765
check("static void function(unsigned long **datap) {\n"
" struct my_s *mr = global_structure_pointer;\n"
" *datap = &mr->value;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void assignAddressOfLocalArrayToGlobalPointer() {
check("int *p;\n"
"void f() {\n"
" int x[10];\n"
" p = x;\n"
"}");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:3] -> [test.cpp:4]: (error) Non-local variable 'p' will use pointer to local variable 'x'.\n", errout_str());
check("int *p;\n"
"void f() {\n"
" int x[10];\n"
" p = x;\n"
" p = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void assignAddressOfLocalVariableToGlobalPointer() {
check("int *p;\n"
"void f() {\n"
" int x;\n"
" p = &x;\n"
"}");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:3] -> [test.cpp:4]: (error) Non-local variable 'p' will use pointer to local variable 'x'.\n", errout_str());
check("int *p;\n"
"void f() {\n"
" int x;\n"
" p = &x;\n"
" p = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void assignAddressOfLocalVariableToMemberVariable() {
check("struct A {\n"
" void f() {\n"
" int x;\n"
" ptr = &x;\n"
" }\n"
" int *ptr;\n"
"};");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:3] -> [test.cpp:4]: (error) Non-local variable 'ptr' will use pointer to local variable 'x'.\n", errout_str());
check("struct A {\n"
" void f() {\n"
" int x;\n"
" ptr = &x;\n"
" ptr = 0;\n"
" }\n"
" int *ptr;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void returnLocalVariable1() {
check("char *foo()\n"
"{\n"
" char str[100] = {0};\n"
" return str;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:4] -> [test.cpp:3] -> [test.cpp:4]: (error) Returning pointer to local variable 'str' that will be invalid when returning.\n",
errout_str());
check("char *foo()\n" // use ValueFlow
"{\n"
" char str[100] = {0};\n"
" char *p = str;\n"
" return p;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:4] -> [test.cpp:3] -> [test.cpp:5]: (error) Returning pointer to local variable 'str' that will be invalid when returning.\n",
errout_str());
check("class Fred {\n"
" char *foo();\n"
"};\n"
"char *Fred::foo()\n"
"{\n"
" char str[100] = {0};\n"
" return str;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:7] -> [test.cpp:6] -> [test.cpp:7]: (error) Returning pointer to local variable 'str' that will be invalid when returning.\n",
errout_str());
check("char * format_reg(char *outbuffer_start) {\n"
" return outbuffer_start;\n"
"}\n"
"void print_with_operands() {\n"
" char temp[42];\n"
" char *tp = temp;\n"
" tp = format_reg(tp);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void returnLocalVariable2() {
check("std::string foo()\n"
"{\n"
" char str[100] = {0};\n"
" return str;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("class Fred {\n"
" std::string foo();\n"
"};\n"
"std::string Fred::foo()\n"
"{\n"
" char str[100] = {0};\n"
" return str;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void returnLocalVariable3() { // &x[..]
// #3030
check("char *foo() {\n"
" char q[] = \"AAAAAAAAAAAA\";\n"
" return &q[1];\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:2] -> [test.cpp:3]: (error) Returning pointer to local variable 'q' that will be invalid when returning.\n", errout_str());
check("char *foo()\n"
"{\n"
" static char q[] = \"AAAAAAAAAAAA\";\n"
" return &q[1];\n"
"}");
ASSERT_EQUALS("", errout_str());
check("char *foo()\n"
"{\n"
"char q[] = \"AAAAAAAAAAAA\";\n"
"char *p;\n"
"p = &q[1];\n"
"return p;\n"
"}");
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:3] -> [test.cpp:6]: (error) Returning pointer to local variable 'q' that will be invalid when returning.\n", errout_str());
}
void returnLocalVariable4() { // x+y
check("char *foo() {\n"
" char x[10] = {0};\n"
" return x+5;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3] -> [test.cpp:2] -> [test.cpp:3]: (error) Returning pointer to local variable 'x' that will be invalid when returning.\n",
errout_str());
check("char *foo(int y) {\n"
" char x[10] = {0};\n"
" return (x+8)-y;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3] -> [test.cpp:2] -> [test.cpp:3]: (error) Returning pointer to local variable 'x' that will be invalid when returning.\n",
errout_str());
}
void returnLocalVariable5() { // cast
check("char *foo() {\n"
" int x[10] = {0};\n"
" return (char *)x;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3] -> [test.cpp:2] -> [test.cpp:3]: (error) Returning pointer to local variable 'x' that will be invalid when returning.\n",
errout_str());
}
void returnLocalVariable6() { // valueflow
check("int *foo() {\n"
" int x = 123;\n"
" int p = &x;\n"
" return p;\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:2] -> [test.cpp:4]: (error) Returning object that points to local variable 'x' that will be invalid when returning.\n", errout_str());
}
void returnReference1() {
check("int &foo()\n"
"{\n"
" int s = 0;\n"
" int& x = s;\n"
" return x;\n"
"}");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:5]: (error) Reference to local variable returned.\n", errout_str());
check("std::string &foo()\n"
"{\n"
" std::string s;\n"
" return s;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Reference to local variable returned.\n", errout_str());
check("std::vector<int> &foo()\n"
"{\n"
" std::vector<int> v;\n"
" return v;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Reference to local variable returned.\n", errout_str());
check("std::vector<int> &foo()\n"
"{\n"
" static std::vector<int> v;\n"
" return v;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("std::vector<int> &foo()\n"
"{\n"
" thread_local std::vector<int> v;\n"
" return v;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("std::string hello()\n"
"{\n"
" return \"hello\";\n"
"}\n"
"\n"
"std::string &f()\n"
"{\n"
" return hello();\n"
"}");
ASSERT_EQUALS("[test.cpp:8]: (error) Reference to temporary returned.\n", errout_str());
// make sure scope is used in function lookup
check("class Fred {\n"
" std::string hello() {\n"
" return std::string();\n"
" }\n"
"};\n"
"std::string &f() {\n"
" return hello();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("std::string hello() {\n"
" return std::string();\n"
"}\n"
"\n"
"std::string &f() {\n"
" return hello();\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (error) Reference to temporary returned.\n", errout_str());
check("std::string hello() {\n"
" return \"foo\";\n"
"}\n"
"\n"
"std::string &f() {\n"
" return hello().substr(1);\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (error) Reference to temporary returned.\n", errout_str());
check("class Foo;\n"
"Foo hello() {\n"
" return Foo();\n"
"}\n"
"\n"
"Foo& f() {\n"
" return hello();\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (error) Reference to temporary returned.\n", errout_str());
// make sure function overloads are handled properly
check("class Foo;\n"
"Foo & hello(bool) {\n"
" static Foo foo;\n"
" return foo;\n"
"}\n"
"Foo hello() {\n"
" return Foo();\n"
"}\n"
"\n"
"Foo& f() {\n"
" return hello(true);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("Foo hello() {\n"
" return Foo();\n"
"}\n"
"\n"
"Foo& f() {\n" // Unknown type - might be a reference
" return hello();\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void returnReference2() {
check("class Fred {\n"
" std::string &foo();\n"
"}\n"
"std::string &Fred::foo()\n"
"{\n"
" std::string s;\n"
" return s;\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (error) Reference to local variable returned.\n", errout_str());
check("class Fred {\n"
" std::vector<int> &foo();\n"
"};\n"
"std::vector<int> &Fred::foo()\n"
"{\n"
" std::vector<int> v;\n"
" return v;\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (error) Reference to local variable returned.\n", errout_str());
check("class Fred {\n"
" std::vector<int> &foo();\n"
"};\n"
"std::vector<int> &Fred::foo()\n"
"{\n"
" static std::vector<int> v;\n"
" return v;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("class Fred {\n"
" std::string &f();\n"
"};\n"
"std::string hello()\n"
"{\n"
" return \"hello\";\n"
"}\n"
"std::string &Fred::f()\n"
"{\n"
" return hello();\n"
"}");
ASSERT_EQUALS("[test.cpp:10]: (error) Reference to temporary returned.\n", errout_str());
check("class Fred {\n"
" std::string hello();\n"
" std::string &f();\n"
"};\n"
"std::string Fred::hello()\n"
"{\n"
" return \"hello\";\n"
"}\n"
"std::string &Fred::f()\n"
"{\n"
" return hello();\n"
"}");
ASSERT_EQUALS("[test.cpp:11]: (error) Reference to temporary returned.\n", errout_str());
check("class Bar;\n"
"Bar foo() {\n"
" return something;\n"
"}\n"
"Bar& bar() {\n"
" return foo();\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (error) Reference to temporary returned.\n", errout_str());
check("std::map<int, string> foo() {\n"
" return something;\n"
"}\n"
"std::map<int, string>& bar() {\n"
" return foo();\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Reference to temporary returned.\n", errout_str());
check("Bar foo() {\n"
" return something;\n"
"}\n"
"Bar& bar() {\n" // Unknown type - might be a typedef to a reference type
" return foo();\n"
"}");
ASSERT_EQUALS("", errout_str());
// Don't crash with function in unknown scope (#4076)
check("X& a::Bar() {}"
"X& foo() {"
" return Bar();"
"}");
}
void returnReference3() {
check("double & f(double & rd) {\n"
" double ret = getValue();\n"
" rd = ret;\n"
" return rd;\n"
"}", false);
ASSERT_EQUALS("", errout_str());
}
// Returning reference to global variable
void returnReference4() {
check("double a;\n"
"double & f() {\n"
" return a;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void returnReference5() {
check("struct A {\n"
" int i;\n"
"};\n"
"struct B {\n"
" A a;\n"
"};\n"
"struct C {\n"
" B *b;\n"
" const A& a() const {\n"
" const B *pb = b;\n"
" const A &ra = pb->a;\n"
" return ra;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void returnReference6() {
check("Fred & create() {\n"
" Fred &fred(*new Fred);\n"
" return fred;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void returnReference7() { // 3791 - false positive for overloaded function
check("std::string a();\n"
"std::string &a(int);\n"
"std::string &b() {\n"
" return a(12);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("std::string &a(int);\n"
"std::string a();\n"
"std::string &b() {\n"
" return a(12);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void returnReference8() {
check("int& f(std::vector<int> &v) {\n"
" std::vector<int>::iterator it = v.begin();\n"
" int& value = *it;\n"
" return value;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void returnReference9() {
check("int& f(bool b, int& x, int& y) {\n"
" return b ? x : y;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void returnReference10() {
check("class A { int f() const; };\n"
"int& g() {\n"
" A a;\n"
" return a.f();\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Reference to temporary returned.\n", errout_str());
check("class A { int& f() const; };\n"
"int& g() {\n"
" A a;\n"
" return a.f();\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void returnReference11() {
check("class A { static int f(); };\n"
"int& g() {\n"
" return A::f();\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Reference to temporary returned.\n", errout_str());
check("class A { static int& f(); };\n"
"int& g() {\n"
" return A::f();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("namespace A { int& f(); }\n"
"int& g() {\n"
" return A::f();\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void returnReference12() {
check("class A { static int& f(); };\n"
"auto g() {\n"
" return &A::f;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("class A { static int& f(); };\n"
"auto g() {\n"
" auto x = &A::f;\n"
" return x;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void returnReference13() {
check("std::vector<int> v;\n"
"void* vp = &v;\n"
"int& foo(size_t i) {\n"
" return ((std::vector<int>*)vp)->at(i);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("std::vector<int> v;\n"
"void* vp = &v;\n"
"int& foo(size_t i) {\n"
" return static_cast<std::vector<int>*>(vp)->at(i);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void returnReference14() {
check("struct C { void* m; };\n"
"struct A { void* &f(); };\n"
"C* g() {\n"
" static C c;\n"
" return &c;\n"
"}\n"
"void* &A::f() {\n"
" return g()->m;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void returnReference15() {
check("template <class T>\n"
"const int& f() {\n"
" static int s;\n"
" return s;\n"
"}\n"
"template <class T>\n"
"const int& f(const T&) {\n"
" return f<T>();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("template <class T>\n"
"int g();\n"
"template <class T>\n"
"const int& f(const T&) {\n"
" return g<T>();\n"
"}");
TODO_ASSERT_EQUALS("error", "", errout_str());
}
void returnReference16() {
check("int& f(std::tuple<int>& x) {\n"
" return std::get<0>(x);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int& f(int x) {\n"
" return std::get<0>(std::make_tuple(x));\n"
"}");
TODO_ASSERT_EQUALS("error", "", errout_str());
}
void returnReference17() {
check("auto g() -> int&;\n"
"int& f() {\n"
" return g();\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void returnReference18() {
check("template<class T>\n"
"auto f(T& x) -> decltype(x);\n"
"int& g(int* x) {\n"
" return f(*x);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
// #9597
void returnReference19() {
check("struct C : B {\n"
" const B &f() const { return (const B &)*this; }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
// #9536
void returnReference20() {
check("struct a {\n"
" int& operator()() const;\n"
"};\n"
"int& b() {\n"
" return a()();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("auto a() {\n"
" return []() -> int& {\n"
" static int b;\n"
" return b;\n"
" };\n"
"}\n"
"const int& c() {\n"
" return a()();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("std::function<int&()> a();\n"
"int& b() {\n"
" return a()();\n"
"}");
ASSERT_EQUALS("", errout_str());
// #9889
check("int f(std::vector<std::function<int&()>>& v, int i) {\n"
" auto& j = v[i]();\n"
" return j;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
// #9530
void returnReference21() {
check("int& f(int& x) {\n"
" return {x};\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void returnReference22() {
check("int& f() {\n"
" std::unique_ptr<int> p = std::make_unique<int>(1);\n"
" return *p;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (error) Reference to local variable returned.\n", errout_str());
check("void g(const std::unique_ptr<int>&);\n"
"int& f() {\n"
" std::unique_ptr<int> p = std::make_unique<int>(1);\n"
" g(p);\n"
" return *p;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5]: (error) Reference to local variable returned.\n", errout_str());
check("void g(std::shared_ptr<int>);\n"
"int& f() {\n"
" std::shared_ptr<int> p = std::make_shared<int>(1);\n"
" g(p);\n"
" return *p;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("std::shared_ptr<int> g();\n"
"int& f() {\n"
" return *g();\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("std::unique_ptr<int> g();\n"
"int& f() {\n"
" return *g();\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (error) Reference to temporary returned.\n", errout_str());
check("struct A { int x; };\n"
"int& f() {\n"
" std::unique_ptr<A> p = std::make_unique<A>();\n"
" return p->x;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (error) Reference to local variable returned.\n", errout_str());
}
void returnReference23() {
check("const std::vector<int> * g();\n"
"const std::vector<int>& f() {\n"
" return *g();\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void returnReference24()
{
check("struct A {\n"
" A() {}\n"
"};\n"
"const A& a() {\n"
" return A();\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5]: (error) Reference to temporary returned.\n", errout_str());
}
void returnReference25()
{
check("int& f();\n" // #10983
"auto g() -> decltype(f()) {\n"
" return f();\n"
"}\n"
"int& h() {\n"
" return g();\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void returnReference26()
{
check("const int& f() {\n" // #12153
" int x = 234;\n"
" int& s{ x };\n"
" return s;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (error) Reference to local variable returned.\n", errout_str());
}
void returnReference27()
{
check("struct S {\n" // #12607
" const std::string & f(const std::string& a, const std::string& b) {\n"
" auto status = m.emplace(a, b);\n"
" return status.first->second;\n"
" }\n"
" std::map<std::string, std::string> m;\n"
"};\n");
ASSERT_EQUALS("", errout_str());
}
void returnReference28()
{
check("struct S {\n" // #13373
" int& r;\n"
"};\n"
"int& f(S s) {\n"
" return s.r;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void returnReferenceFunction() {
check("int& f(int& a) {\n"
" return a;\n"
"}\n"
"int& hello() {\n"
" int x = 0;\n"
" return f(x);\n"
"}");
ASSERT_EQUALS(
"[test.cpp:1] -> [test.cpp:2] -> [test.cpp:6] -> [test.cpp:6]: (error) Reference to local variable returned.\n",
errout_str());
check("int& f(int& a) {\n"
" return a;\n"
"}\n"
"int* hello() {\n"
" int x = 0;\n"
" return &f(x);\n"
"}");
ASSERT_EQUALS(
"[test.cpp:1] -> [test.cpp:2] -> [test.cpp:6] -> [test.cpp:6] -> [test.cpp:5] -> [test.cpp:6]: (error) Returning pointer to local variable 'x' that will be invalid when returning.\n",
errout_str());
check("int* f(int * x) {\n"
" return x;\n"
"}\n"
"int * g(int x) {\n"
" return f(&x);\n"
"}");
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:5] -> [test.cpp:4] -> [test.cpp:5]: (error) Returning pointer to local variable 'x' that will be invalid when returning.\n", errout_str());
check("int* f(int * x) {\n"
" x = nullptr;\n"
" return x;\n"
"}\n"
"int * g(int x) {\n"
" return f(&x);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int f(int& a) {\n"
" return a;\n"
"}\n"
"int& hello() {\n"
" int x = 0;\n"
" return f(x);\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (error) Reference to temporary returned.\n", errout_str());
check("int& f(int a) {\n"
" return a;\n"
"}\n"
"int& hello() {\n"
" int x = 0;\n"
" return f(x);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Reference to local variable returned.\n", errout_str());
check("int f(int a) {\n"
" return a;\n"
"}\n"
"int& hello() {\n"
" int x = 0;\n"
" return f(x);\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (error) Reference to temporary returned.\n", errout_str());
check("template<class T>\n"
"int& f(int& x, T y) {\n"
" x += y;\n"
" return x;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void returnReferenceContainer() {
check("auto& f() {\n"
" std::vector<int> x;\n"
" return x[0];\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Reference to local variable returned.\n", errout_str());
check("auto& f() {\n"
" std::vector<int> x;\n"
" return x.front();\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:3]: (error) Reference to local variable returned.\n", errout_str());
check("std::vector<int> g();\n"
"auto& f() {\n"
" return g().front();\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:3]: (error) Reference to temporary returned.\n", errout_str());
check("auto& f() {\n"
" return std::vector<int>{1}.front();\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:2]: (error) Reference to temporary returned.\n", errout_str());
check("struct A { int foo; };\n"
"int& f(std::vector<A> v) {\n"
" auto it = v.begin();\n"
" return it->foo;\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (error) Reference to local variable returned.\n", errout_str());
check("template <class T, class K, class V>\n"
"const V& get_default(const T& t, const K& k, const V& v) {\n"
" auto it = t.find(k);\n"
" if (it == t.end()) return v;\n"
" return it->second;\n"
"}\n"
"const int& bar(const std::unordered_map<int, int>& m, int k) {\n"
" auto x = 0;\n"
" return get_default(m, k, x);\n"
"}\n",
true);
ASSERT_EQUALS(
"[test.cpp:2] -> [test.cpp:4] -> [test.cpp:9] -> [test.cpp:9]: (error, inconclusive) Reference to local variable returned.\n",
errout_str());
check("template <class T, class K, class V>\n"
"const V& get_default(const T& t, const K& k, const V& v) {\n"
" auto it = t.find(k);\n"
" if (it == t.end()) return v;\n"
" return it->second;\n"
"}\n"
"const int& bar(const std::unordered_map<int, int>& m, int k) {\n"
" return get_default(m, k, 0);\n"
"}\n",
true);
ASSERT_EQUALS(
"[test.cpp:2] -> [test.cpp:4] -> [test.cpp:8] -> [test.cpp:8]: (error, inconclusive) Reference to temporary returned.\n",
errout_str());
check("struct A { int foo; };\n"
"int& f(std::vector<A>& v) {\n"
" auto it = v.begin();\n"
" return it->foo;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("static std::vector<int> A[2];\n"
"static std::vector<int> B;\n"
"std::vector<int>& g(int i) {\n"
" return i ? A[i] : B;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void returnReferenceLiteral() {
check("const std::string &a() {\n"
" return \"foo\";\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Reference to temporary returned.\n", errout_str());
check("const std::string a() {\n"
" return \"foo\";\n"
"}");
ASSERT_EQUALS("", errout_str());
check("const std::string& f(const std::string& x) { return x; }\n"
"const std::string &a() {\n"
" return f(\"foo\");\n"
"}");
ASSERT_EQUALS(
"[test.cpp:1] -> [test.cpp:1] -> [test.cpp:3] -> [test.cpp:3]: (error) Reference to temporary returned.\n",
errout_str());
check("const char * f(const char * x) { return x; }\n"
"const std::string &a() {\n"
" return f(\"foo\");\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Reference to temporary returned.\n", errout_str());
}
void returnReferenceCalculation() {
check("const std::string &a(const std::string& str) {\n"
" return \"foo\" + str;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Reference to temporary returned.\n", errout_str());
check("int& operator<<(int out, int path) {\n"
" return out << path;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Reference to temporary returned.\n", errout_str());
check("std::ostream& operator<<(std::ostream& out, const std::string& path) {\n"
" return out << path;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("std::ostream& operator<<(std::ostream* out, const std::string& path) {\n"
" return *out << path;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("Unknown1& operator<<(Unknown1 out, Unknown2 path) {\n"
" return out << path;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int& a(int b) {\n"
" return 2*(b+1);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Reference to temporary returned.\n", errout_str());
check("const std::string &a(const std::string& str) {\n"
" return str;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("const std::string &a(int bar) {\n"
" return foo(bar + 1);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("const std::string a(const std::string& str) {\n"
" return \"foo\" + str;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int& incValue(int& value) {\n"
" return ++value;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void returnReferenceLambda() {
// #6787
check("const Item& foo(const Container& items) const {\n"
" return bar(items.begin(), items.end(),\n"
" [](const Item& lhs, const Item& rhs) {\n"
" return false;\n"
" });\n"
"}");
ASSERT_EQUALS("", errout_str());
// #5844
check("map<string,string> const &getVariableTable() {\n"
"static map<string,string> const s_var = []{\n"
" map<string,string> var;\n"
" return var;\n"
" }();\n"
"return s_var;\n"
"}");
ASSERT_EQUALS("", errout_str());
// #7583
check("Command& foo() {\n"
" return f([]() -> int { return 1; });\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void returnReferenceInnerScope() {
// #6951
check("const Callback& make() {\n"
" struct _Wrapper {\n"
" static ulong call(void* o, const void* f, const void*[]) {\n"
" return 1;\n"
" }\n"
" };\n"
" return _make(_Wrapper::call, pmf);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void returnReferenceRecursive() {
check("int& f() { return f(); }");
ASSERT_EQUALS("", errout_str());
check("int& g(int& i) { return i; }\n"
"int& f() { return g(f()); }");
ASSERT_EQUALS("", errout_str());
}
void extendedLifetime() {
check("void g(int*);\n"
"int h();\n"
"auto f() {\n"
" const int& x = h();\n"
" return [&] { return x; };\n"
"}");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:5] -> [test.cpp:4] -> [test.cpp:5]: (error) Returning lambda that captures local variable 'x' that will be invalid when returning.\n", errout_str());
check("void g(int*);\n"
"int h();\n"
"int* f() {\n"
" const int& x = h();\n"
" return &x;\n"
"}");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:5] -> [test.cpp:4] -> [test.cpp:5]: (error) Returning pointer to local variable 'x' that will be invalid when returning.\n", errout_str());
check("void g(int*);\n"
"int h();\n"
"void f() {\n"
" int& x = h();\n"
" g(&x);\n"
"}");
ASSERT_EQUALS(
"[test.cpp:4] -> [test.cpp:5] -> [test.cpp:4] -> [test.cpp:5]: (error) Using pointer that is a temporary.\n"
"[test.cpp:4] -> [test.cpp:5]: (error) Using reference to dangling temporary.\n",
errout_str());
check("void g(int*);\n"
"int h();\n"
"void f() {\n"
" const int& x = h();\n"
" g(&x);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct Data {\n"
" std::string path;\n"
"};\n"
"const char* foo() {\n"
" const Data& data = getData();\n"
" return data.path.c_str();\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void danglingReference() {
check("int f( int k )\n"
"{\n"
" static int &r = k;\n"
" return r;\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:3]: (error) Non-local reference variable 'r' to local variable 'k'\n",
errout_str());
check("int &f( int & k )\n"
"{\n"
" static int &r = k;\n"
" return r;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void danglingTempReference() {
check("const std::string& g(const std::string& str_cref) {\n"
" return str_cref;\n"
"}\n"
"void f() {\n"
" const auto& str_cref2 = g(std::string(\"hello\"));\n"
" std::cout << str_cref2 << std::endl;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:1] -> [test.cpp:2] -> [test.cpp:5] -> [test.cpp:6]: (error) Using reference to dangling temporary.\n", errout_str());
// Lifetime extended
check("std::string g(const std::string& str_cref) {\n"
" return str_cref;\n"
"}\n"
"void f() {\n"
" const auto& str_cref2 = g(std::string(\"hello\"));\n"
" std::cout << str_cref2 << std::endl;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("char f() {\n"
" char c = 0;\n"
" char&& cr = std::move(c);\n"
" return cr;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #9987
check("void g(std::vector<int>);\n"
"void f() {\n"
" std::vector<int>&& v = {};\n"
" g(std::move(v));\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void g(std::vector<int>);\n"
"std::vector<int> h();\n"
"void f() {\n"
" std::vector<int>&& v = h();\n"
" g(std::move(v));\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #11087
check("struct S1 {\n"
" int& get() { return val; }\n"
" int val{42};\n"
"};\n"
"void f() {\n"
" int& v = S1().get();\n"
" v += 1;\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:6] -> [test.cpp:2] -> [test.cpp:6] -> [test.cpp:7]: (error) Using reference to dangling temporary.\n",
errout_str());
check("struct A {\n"
" const int& g() const { return i; }\n"
" int i;\n"
"};\n"
"A* a();\n"
"int f() {\n"
" const int& i = a()->g();\n"
" return i;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct A {\n"
" const int& g() const { return i; }\n"
" int i;\n"
"};\n"
"std::unique_ptr<A> a();\n"
"int f() {\n"
" const int& i = a()->g();\n"
" return i;\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:7] -> [test.cpp:2] -> [test.cpp:7] -> [test.cpp:8]: (error) Using reference to dangling temporary.\n",
errout_str());
check("struct S1 {\n"
" auto get() -> auto& { return val; }\n"
" int val{42};\n"
"};\n"
"struct S2 {\n"
" auto get() -> S1 { return s; }\n"
" S1 s;\n"
"};\n"
"auto main() -> int {\n"
" S2 c{};\n"
" auto& v = c.get().get();\n"
" v += 1;\n"
" return c.s.val;\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:11] -> [test.cpp:2] -> [test.cpp:11] -> [test.cpp:12]: (error) Using reference to dangling temporary.\n",
errout_str());
check("struct C {\n"
" std::vector<std::vector<int>> v;\n"
"};\n"
"struct P {\n"
" std::vector<C*>::const_iterator find() const { return pv.begin(); }\n"
" std::vector<C*> pv;\n"
"};\n"
"struct M {\n"
" const P* get() const { return p; }\n"
" P* p;\n"
"};\n"
"void f(const M* m) {\n"
" auto it = m->get()->find();\n"
" auto e = (*it)->v.begin();\n"
" const int& x = (*e)[1];\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("int* g();\n" // #11188
"void f() {\n"
" const auto& p = g();\n"
" if (p != nullptr) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("template<typename S, typename T>\n"
"void f(const std::vector<S>& v) {\n"
" T a;\n"
" for (typename std::vector<S>::iterator it = v.begin(); it != v.end(); ++it) {\n"
" const T& b = static_cast<const T&>(it->find(1));\n"
" a = b;\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("using namespace std;\n" // #10971
"struct S { int i = 3; };\n"
"unique_ptr<S> g() {\n"
" auto tp = make_unique<S>();\n"
" return tp;\n"
"}\n"
"void f() {\n"
" const S& s = *g();\n"
" (void)s.i;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:8] -> [test.cpp:9]: (error) Using reference to dangling temporary.\n", errout_str());
check("std::string f() {\n" // #12173
" std::string s;\n"
" for (auto& c : { \"a\", \"b\", \"c\" }) {\n"
" s += c;\n"
" }\n"
" return s;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void testglobalnamespace() {
check("class SharedPtrHolder\n"
"{\n"
" ::std::tr1::shared_ptr<int> pNum;\n"
"public:\n"
" void SetNum(const ::std::tr1::shared_ptr<int> & apNum)\n"
" {\n"
" pNum = apNum;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void returnParameterAddress() {
check("int* foo(int y)\n"
"{\n"
" return &y;\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:1] -> [test.cpp:3]: (error) Returning pointer to local variable 'y' that will be invalid when returning.\n", errout_str());
check("int ** foo(int * y)\n"
"{\n"
" return &y;\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:1] -> [test.cpp:3]: (error) Returning pointer to local variable 'y' that will be invalid when returning.\n", errout_str());
check("const int * foo(const int & y)\n"
"{\n"
" return &y;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int * foo(int * y)\n"
"{\n"
" return y;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct s { void *p; };\n"
"extern struct s* f(void);\n"
"void g(void **q)\n"
"{\n"
" struct s *r = f();\n"
" *q = &r->p;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void testconstructor() { // Ticket #5478 - crash while checking a constructor
check("class const_tree_iterator {\n"
" const_tree_iterator(bool (*_incream)(node_type*&)) {}\n"
" const_tree_iterator& parent() {\n"
" return const_tree_iterator(foo);\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (error) Reference to temporary returned.\n", errout_str());
}
void variableIsUsedInScope() {
check("void removed_cb (GList *uids) {\n"
"for (; uids; uids = uids->next) {\n"
"}\n"
"}\n"
"void opened_cb () {\n"
" g_signal_connect (G_CALLBACK (removed_cb));\n"
"}");
}
void danglingLifetimeLambda() {
check("auto f() {\n"
" int a = 1;\n"
" auto l = [&](){ return a; };\n"
" return l;\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:2] -> [test.cpp:4]: (error) Returning lambda that captures local variable 'a' that will be invalid when returning.\n", errout_str());
check("auto f() {\n"
" int a = 1;\n"
" return [&](){ return a; };\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:2] -> [test.cpp:3]: (error) Returning lambda that captures local variable 'a' that will be invalid when returning.\n", errout_str());
check("auto f(int a) {\n"
" return [&](){ return a; };\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:1] -> [test.cpp:2]: (error) Returning lambda that captures local variable 'a' that will be invalid when returning.\n", errout_str());
check("auto f(int a) {\n"
" auto p = &a;\n"
" return [=](){ return p; };\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3] -> [test.cpp:1] -> [test.cpp:3]: (error) Returning lambda that captures local variable 'a' that will be invalid when returning.\n", errout_str());
check("auto g(int& a) {\n"
" int p = a;\n"
" return [&](){ return p; };\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:2] -> [test.cpp:3]: (error) Returning lambda that captures local variable 'p' that will be invalid when returning.\n", errout_str());
check("auto f() {\n"
" return [=](){\n"
" int a = 1;\n"
" return [&](){ return a; };\n"
" };\n"
"}");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:3] -> [test.cpp:4]: (error) Returning lambda that captures local variable 'a' that will be invalid when returning.\n", errout_str());
check("auto f(int b) {\n"
" return [=](int a){\n"
" a += b;\n"
" return [&](){ return a; };\n"
" };\n"
"}");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:2] -> [test.cpp:4]: (error) Returning lambda that captures local variable 'a' that will be invalid when returning.\n", errout_str());
check("auto g(int& a) {\n"
" return [&](){ return a; };\n"
"}");
ASSERT_EQUALS("", errout_str());
check("auto g(int a) {\n"
" auto p = a;\n"
" return [=](){ return p; };\n"
"}");
ASSERT_EQUALS("", errout_str());
check("auto g(int& a) {\n"
" auto p = a;\n"
" return [=](){ return p; };\n"
"}");
ASSERT_EQUALS("", errout_str());
check("auto g(int& a) {\n"
" int& p = a;\n"
" return [&](){ return p; };\n"
"}");
ASSERT_EQUALS("", errout_str());
check("template<class F>\n"
"void g(F);\n"
"auto f() {\n"
" int x;\n"
" return g([&]() { return x; });\n"
"}");
ASSERT_EQUALS("", errout_str());
check("auto f() {\n"
" int i = 0;\n"
" return [&i] {};\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:2] -> [test.cpp:3]: (error) Returning lambda that captures local variable 'i' that will be invalid when returning.\n", errout_str());
check("auto f() {\n"
" int i = 0;\n"
" return [i] {};\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("auto f() {\n"
" int i = 0;\n"
" return [=, &i] {};\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:2] -> [test.cpp:3]: (error) Returning lambda that captures local variable 'i' that will be invalid when returning.\n", errout_str());
check("auto f() {\n"
" int i = 0;\n"
" int j = 0;\n"
" return [=, &i] { return j; };\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:2] -> [test.cpp:4]: (error) Returning lambda that captures local variable 'i' that will be invalid when returning.\n", errout_str());
check("auto f() {\n"
" int i = 0;\n"
" return [&, i] {};\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("auto f() {\n"
" int i = 0;\n"
" int j = 0;\n"
" return [&, i] { return j; };\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:3] -> [test.cpp:4]: (error) Returning lambda that captures local variable 'j' that will be invalid when returning.\n", errout_str());
check("auto f(int& i) {\n"
" int j = 0;\n"
" return [=, &i] { return j; };\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(int*);\n"
"auto g(int y) {\n"
" int x = y;\n"
" return [=] {\n"
" g(&x);\n"
" };\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct A {\n"
" int x;\n"
"};\n"
"auto f() {\n"
" A a;\n"
" return [=] {\n"
" const A* ap = &a;\n"
" ap->x;\n"
" };\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void danglingLifetimeContainer() {
check("auto f(const std::vector<int>& x) {\n"
" auto it = x.begin();\n"
" return it;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("std::vector<int>::iterator f() {\n"
" std::vector<int> x;\n"
" auto it = x.begin();\n"
" return it;\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:2] -> [test.cpp:4]: (error) Returning iterator to local container 'x' that will be invalid when returning.\n", errout_str());
check("auto f() {\n"
" std::vector<int> x;\n"
" auto it = std::begin(x);\n"
" return it;\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:2] -> [test.cpp:4]: (error) Returning iterator to local container 'x' that will be invalid when returning.\n", errout_str());
check("int* f() {\n"
" std::vector<int> x;\n"
" auto p = x.data();\n"
" return p;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3] -> [test.cpp:2] -> [test.cpp:4]: (error) Returning pointer to local variable 'x' that will be invalid when returning.\n",
errout_str());
check("auto f() {\n"
" std::vector<int> x;\n"
" auto p = &x[0];\n"
" return p;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3] -> [test.cpp:2] -> [test.cpp:4]: (error) Returning pointer to local variable 'x' that will be invalid when returning.\n",
errout_str());
check("struct A { int foo; };\n"
"int* f(std::vector<A> v) {\n"
" auto it = v.begin();\n"
" return &it->foo;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3] -> [test.cpp:4] -> [test.cpp:2] -> [test.cpp:4]: (error) Returning pointer to local variable 'v' that will be invalid when returning.\n",
errout_str());
check("std::vector<int>::iterator f(std::vector<int> x) {\n"
" auto it = x.begin();\n"
" return it;\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:1] -> [test.cpp:3]: (error) Returning iterator to local container 'x' that will be invalid when returning.\n", errout_str());
check("auto f() {\n"
" std::vector<int> x;\n"
" auto it = x.begin();\n"
" return std::next(it);\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3] -> [test.cpp:2] -> [test.cpp:4]: (error) Returning iterator to local container 'x' that will be invalid when returning.\n",
errout_str());
check("auto f() {\n"
" std::vector<int> x;\n"
" auto it = x.begin();\n"
" return it + 1;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3] -> [test.cpp:2] -> [test.cpp:4]: (error) Returning iterator to local container 'x' that will be invalid when returning.\n",
errout_str());
check("auto f() {\n"
" std::vector<int> x;\n"
" auto it = x.begin();\n"
" return std::next(it + 1);\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3] -> [test.cpp:4] -> [test.cpp:2] -> [test.cpp:4]: (error) Returning object that points to local variable 'x' that will be invalid when returning.\n",
errout_str());
check("std::vector<int*> f() {\n"
" int i = 0;\n"
" std::vector<int*> v;\n"
" v.push_back(&i);\n"
" return v;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:4] -> [test.cpp:4] -> [test.cpp:2] -> [test.cpp:5]: (error) Returning object that points to local variable 'i' that will be invalid when returning.\n",
errout_str());
check("std::vector<int*> f() {\n"
" std::vector<int*> r;\n"
" int i = 0;\n"
" std::vector<int*> v;\n"
" v.push_back(&i);\n"
" r.assign(v.begin(), v.end());\n"
" return r;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:5] -> [test.cpp:5] -> [test.cpp:5] -> [test.cpp:3] -> [test.cpp:7]: (error) Returning object that points to local variable 'i' that will be invalid when returning.\n",
errout_str());
check("struct A {\n"
" std::vector<int*> v;\n"
" void f() {\n"
" int i;\n"
" v.push_back(&i);\n"
" }\n"
"};");
ASSERT_EQUALS(
"[test.cpp:5] -> [test.cpp:5] -> [test.cpp:4] -> [test.cpp:5]: (error) Non-local variable 'v' will use object that points to local variable 'i'.\n",
errout_str());
check("struct A {\n"
" std::vector<int*> v;\n"
" void f() {\n"
" int i;\n"
" int * p = &i;\n"
" v.push_back(p);\n"
" }\n"
"};");
ASSERT_EQUALS(
"[test.cpp:5] -> [test.cpp:6] -> [test.cpp:4] -> [test.cpp:6]: (error) Non-local variable 'v' will use object that points to local variable 'i'.\n",
errout_str());
check("struct A {\n"
" std::vector<int*> m;\n"
" void f() {\n"
" int x;\n"
" std::vector<int*> v;\n"
" v.push_back(&x);\n"
" m.insert(m.end(), v.begin(), v.end());\n"
" }\n"
"};");
ASSERT_EQUALS(
"[test.cpp:6] -> [test.cpp:6] -> [test.cpp:6] -> [test.cpp:4] -> [test.cpp:7]: (error) Non-local variable 'm' will use object that points to local variable 'x'.\n"
"[test.cpp:6] -> [test.cpp:6] -> [test.cpp:6] -> [test.cpp:4] -> [test.cpp:7]: (error) Non-local variable 'm' will use object that points to local variable 'x'.\n", // duplicate
errout_str());
check("std::vector<int>::iterator f(std::vector<int> v) {\n"
" for(auto it = v.begin();it != v.end();it++) {\n"
" return it;\n"
" }\n"
" return {};\n"
"}");
ASSERT_EQUALS(
"[test.cpp:2] -> [test.cpp:1] -> [test.cpp:3]: (error) Returning iterator to local container 'v' that will be invalid when returning.\n",
errout_str());
check("const char * f() {\n"
" std::string ba(\"hello\");\n"
" return ba.c_str();\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3] -> [test.cpp:2] -> [test.cpp:3]: (error) Returning pointer to local variable 'ba' that will be invalid when returning.\n",
errout_str());
check("template <class T, class K, class V>\n"
"const V* get_default(const T& t, const K& k, const V* v) {\n"
" auto it = t.find(k);\n"
" if (it == t.end()) return v;\n"
" return &it->second;\n"
"}\n"
"const int* bar(const std::unordered_map<int, int>& m, int k) {\n"
" auto x = 0;\n"
" return get_default(m, k, &x);\n"
"}\n",
true);
ASSERT_EQUALS(
"[test.cpp:9] -> [test.cpp:9] -> [test.cpp:8] -> [test.cpp:9]: (error, inconclusive) Returning pointer to local variable 'x' that will be invalid when returning.\n",
errout_str());
check("std::vector<int> g();\n"
"auto f() {\n"
" return g().begin();\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:3]: (error) Returning iterator that will be invalid when returning.\n",
errout_str());
check("std::vector<int> g();\n"
"std::vector<int>::iterator f() {\n"
" auto it = g().begin();\n"
" return it;\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:3] -> [test.cpp:4]: (error) Using iterator that is a temporary.\n"
"[test.cpp:3] -> [test.cpp:4]: (error) Returning iterator that will be invalid when returning.\n",
errout_str());
check("std::vector<int> g();\n"
"int& f() {\n"
" return *g().begin();\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:3]: (error) Reference to temporary returned.\n", errout_str());
check("struct A {\n"
" std::vector<std::string> v;\n"
" void f() {\n"
" char s[3];\n"
" v.push_back(s);\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("std::vector<std::string> f() {\n"
" const char * s = \"hello\";\n"
" std::vector<std::string> v;\n"
" v.push_back(s);\n"
" return v;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("auto f() {\n"
" static std::vector<int> x;\n"
" return x.begin();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("std::string g() {\n"
" std::vector<char> v;\n"
" return v.data();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("std::vector<int>::iterator f(std::vector<int>* v) {\n"
" return v->begin();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("std::vector<int>::iterator f(std::vector<int>* v) {\n"
" std::vector<int>* v = new std::vector<int>();\n"
" return v->begin();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int f(std::vector<int> v) {\n"
" return *v.begin();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int f(std::vector<int> v) {\n"
" return v.end() - v.begin();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("auto g() {\n"
" std::vector<char> v;\n"
" return {v, [v]() { return v.data(); }};\n"
"}");
ASSERT_EQUALS("", errout_str());
check("template<class F>\n"
"void g(F);\n"
"auto f() {\n"
" std::vector<char> v;\n"
" return g([&]() { return v.data(); });\n"
"}");
ASSERT_EQUALS("", errout_str());
check("std::vector<int> g();\n"
"struct A {\n"
" std::vector<int> m;\n"
" void f() {\n"
" std::vector<int> v = g();\n"
" m.insert(m.end(), v.begin(), v.end());\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("void f(bool b) {\n"
" std::vector<int> v = {1};\n"
" if (b) {\n"
" int a[] = {0};\n"
" v.insert(a, a+1);\n"
" }\n"
" return v.back() == 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("class A {\n"
" int f( P p ) {\n"
" std::vector< S > maps;\n"
" m2.insert( m1.begin(), m1.end() );\n"
" }\n"
" struct B {};\n"
" std::map< S, B > m1;\n"
" std::map< S, B > m2;\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct A {\n"
" std::vector<int*> v;\n"
" int x;\n"
" void f() {\n"
" v.push_back(&x);\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("size_t f(const std::string& x) {\n"
" std::string y = \"x\";\n"
" return y.find(x);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("std::string* f();\n"
"const char* g() {\n"
" std::string* var = f();\n"
" return var->c_str();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("std::string f() {\n"
" std::vector<char> data{};\n"
" data.push_back('a');\n"
" return std::string{ data.data(), data.size() };\n"
"}");
ASSERT_EQUALS("", errout_str());
check("std::vector<char*> f() {\n"
" char a = 0;\n"
" return std::vector<char*>{&a};\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:3] -> [test.cpp:2] -> [test.cpp:3]: (error) Returning object that points to local variable 'a' that will be invalid when returning.\n", errout_str());
check("std::vector<int>* g();\n"
"int& f() {\n"
" auto* p = g();\n"
" return p->front();\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("std::vector<std::vector<int>> g();\n"
"void f() {\n"
" for(auto& x:g())\n"
" std::sort(x.begin(), x.end());\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct A {\n"
" std::vector<int*> v;\n"
" void add(int* i) {\n"
" v.push_back(i);\n"
" }\n"
" void f() {\n"
" int i = 0;\n"
" add(&i);\n"
" }\n"
"};\n");
ASSERT_EQUALS(
"[test.cpp:8] -> [test.cpp:8] -> [test.cpp:4] -> [test.cpp:7] -> [test.cpp:4]: (error) Non-local variable 'v' will use object that points to local variable 'i'.\n",
errout_str());
check("struct A {\n"
" std::vector<int*> v;\n"
" void add(int* i) {\n"
" v.push_back(i);\n"
" }\n"
"};\n"
"void f() {\n"
" A a;\n"
" int i = 0;\n"
" a.add(&i);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct A {\n"
" std::vector<int*> v;\n"
" void add(int* i) {\n"
" v.push_back(i);\n"
" }\n"
" void f() {\n"
" A a;\n"
" int i = 0;\n"
" a.add(&i);\n"
" }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
check("int f() {\n"
" int i;\n"
" {\n"
" std::vector<int> vec;\n"
" const auto iter = vec.begin();\n"
" i = (int)(iter - vec.begin());\n"
" }\n"
" return i;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("int* get(std::vector<int>& container) {\n"
" Sequence seq(container);\n"
" for (auto& r : seq) {\n"
" return &r;\n"
" }\n"
" return &*seq.begin();\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("std::string f(std::string Str, int first, int last) {\n"
" return { Str.begin() + first, Str.begin() + last + 1 };\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("std::string f(std::string s) {\n"
" std::string r = { s.begin(), s.end() };\n"
" return r;\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("struct A {\n"
" std::vector<std::unique_ptr<int>> mA;\n"
" void f(std::unique_ptr<int> a) {\n"
" auto x = a.get();\n"
" mA.push_back(std::move(a));\n"
" }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
check("struct A {\n"
" std::map<std::string, int> m;\n"
" int* f(std::string s) {\n"
" auto r = m.emplace(name, name);\n"
" return &(r.first->second);\n"
" }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" std::queue<int> q;\n"
" auto& h = q.emplace();\n"
" h = 1;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("std::string f(std::string s) {\n"
" std::string ss = (\":\" + s).c_str();\n"
" return ss;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f() {\n" // #12568
" std::string str;\n"
" {\n"
" std::unique_ptr<char[]> b(new char[1]{});\n"
" str.assign(b.get());\n"
" }\n"
" std::cerr << str;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void danglingLifetimeContainerView()
{
check("std::string_view f() {\n"
" std::string s = \"\";\n"
" return s;\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:3] -> [test.cpp:2] -> [test.cpp:3]: (error) Returning object that points to local variable 's' that will be invalid when returning.\n",
errout_str());
check("std::string_view f() {\n"
" std::string s = \"\";\n"
" std::string_view sv = s;\n"
" return sv;\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:3] -> [test.cpp:2] -> [test.cpp:4]: (error) Returning object that points to local variable 's' that will be invalid when returning.\n",
errout_str());
check("std::string_view f() {\n"
" std::string s = \"\";\n"
" return std::string_view{s};\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:3] -> [test.cpp:2] -> [test.cpp:3]: (error) Returning object that points to local variable 's' that will be invalid when returning.\n",
errout_str());
check("std::string_view f(std::string_view s) {\n"
" return s;\n"
"}\n"
"std::string_view g() {\n"
" std::string s = \"\";\n"
" return f(s);\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:6] -> [test.cpp:6] -> [test.cpp:5] -> [test.cpp:6]: (error) Returning object that points to local variable 's' that will be invalid when returning.\n",
errout_str());
check("const char * f() {\n"
" std::string s;\n"
" std::string_view sv = s;\n"
" return sv.begin();\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:4] -> [test.cpp:2] -> [test.cpp:4]: (error) Returning iterator to local container 's' that will be invalid when returning.\n",
errout_str());
check("const char * f() {\n"
" std::string s;\n"
" return std::string_view{s}.begin();\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:3] -> [test.cpp:2] -> [test.cpp:3]: (error) Returning iterator to local container 's' that will be invalid when returning.\n",
errout_str());
check("const char * f() {\n"
" std::string s;\n"
" return std::string_view(s).begin();\n"
"}\n");
TODO_ASSERT_EQUALS(
"[test.cpp:3] -> [test.cpp:2] -> [test.cpp:3]: (error) Returning iterator to local container 's' that will be invalid when returning.\n",
"",
errout_str());
check("const char * f(std::string_view sv) {\n"
" return sv.begin();\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("const char * f(std::string s) {\n"
" std::string_view sv = s;\n"
" return sv.begin();\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:3] -> [test.cpp:1] -> [test.cpp:3]: (error) Returning iterator to local container 's' that will be invalid when returning.\n",
errout_str());
check("std::string_view f(std::string s) {\n"
" return s;\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:2] -> [test.cpp:1] -> [test.cpp:2]: (error) Returning object that points to local variable 's' that will be invalid when returning.\n",
errout_str());
check("const char * f(const std::string& s) {\n"
" std::string_view sv = s;\n"
" return sv.begin();\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("std::string_view f(const std::string_view& sv) {\n"
" return sv;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f() {\n" // #10993
" std::string_view v = std::string();\n"
" v.data();\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:2] -> [test.cpp:3]: (error) Using object that is a temporary.\n", errout_str());
check("std::string convert(std::string_view sv) { return std::string{ sv }; }\n" // #11374
"auto f() {\n"
" std::vector<std::string> v;\n"
" v.push_back(convert(\"foo\"));\n"
" return v[0];\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #10532
check("std::string f(std::string ss) {\n"
" std::string_view sv = true ? \"\" : ss;\n"
" std::string s = sv;\n"
" return s;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:2] -> [test.cpp:3]: (error) Using object that is a temporary.\n",
errout_str());
// #10833
check("struct A { std::string s; };\n"
"const std::string& f(A* a) {\n"
" return a ? a->s : \"\";\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (error) Reference to temporary returned.\n", errout_str());
check("std::span<int> f() {\n"
" std::vector<int> v{};\n"
" return v;\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:3] -> [test.cpp:2] -> [test.cpp:3]: (error) Returning object that points to local variable 'v' that will be invalid when returning.\n",
errout_str());
check("std::span<int> f() {\n"
" std::vector<int> v;\n"
" std::span sp = v;\n"
" return sp;\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:3] -> [test.cpp:2] -> [test.cpp:4]: (error) Returning object that points to local variable 'v' that will be invalid when returning.\n",
errout_str());
check("std::span<int> f() {\n"
" std::vector<int> v;\n"
" return std::span{v};\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:3] -> [test.cpp:2] -> [test.cpp:3]: (error) Returning object that points to local variable 'v' that will be invalid when returning.\n",
errout_str());
check("int f() {\n"
" std::span<int> s;\n"
" {\n"
" std::vector<int> v(1);"
" s = v;\n"
" }\n"
"return s.back()\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:4] -> [test.cpp:4] -> [test.cpp:6]: (error) Using object that points to local variable 'v' that is out of scope.\n",
errout_str());
check("int f() {\n"
" std::span<int> s;\n"
" {\n"
" std::vector<int> v(1);"
" s = v;\n"
" }\n"
"return s.back()\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:4] -> [test.cpp:4] -> [test.cpp:6]: (error) Using object that points to local variable 'v' that is out of scope.\n",
errout_str());
check("int f() {\n"
" std::span<int> s;\n"
" {\n"
" std::vector<int> v(1);"
" s = v;\n"
" }\n"
"return s.front()\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:4] -> [test.cpp:4] -> [test.cpp:6]: (error) Using object that points to local variable 'v' that is out of scope.\n",
errout_str());
check("int f() {\n"
" std::span<int> s;\n"
" {\n"
" std::vector<int> v(1);"
" s = v;\n"
" }\n"
"return s.last(1)\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:4] -> [test.cpp:4] -> [test.cpp:6]: (error) Using object that points to local variable 'v' that is out of scope.\n",
errout_str());
check("int f() {\n"
" std::span<int> s;\n"
" {\n"
" std::vector<int> v(1);"
" s = v;\n"
" }\n"
"return s.first(1)\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:4] -> [test.cpp:4] -> [test.cpp:6]: (error) Using object that points to local variable 'v' that is out of scope.\n",
errout_str());
check("std::span<const int> f() {\n" // #12966
" int a[10]{};\n"
" return a;\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:3] -> [test.cpp:2] -> [test.cpp:3]: (error) Returning pointer to local variable 'a' that will be invalid when returning.\n",
errout_str());
}
void danglingLifetimeUniquePtr()
{
check("int* f(std::unique_ptr<int> p) {\n"
" int * rp = p.get();\n"
" return rp;\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:2] -> [test.cpp:1] -> [test.cpp:3]: (error) Returning pointer to local variable 'p' that will be invalid when returning.\n",
errout_str());
check("int* f();\n" // #11406
"bool g() {\n"
" std::unique_ptr<int> ptr(f());\n"
" return ptr.get();\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("int* f();\n"
"int* g() {\n"
" std::unique_ptr<int> ptr(f());\n"
" return ptr.get();\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:4] -> [test.cpp:3] -> [test.cpp:4]: (error) Returning object that points to local variable 'ptr' that will be invalid when returning.\n",
errout_str());
// #12600
check("struct S { std::unique_ptr<int> p; };\n"
"int* f(const S* s) {\n"
" return s[0].p.get();\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void danglingLifetime() {
check("auto f() {\n"
" std::vector<int> a;\n"
" auto it = a.begin();\n"
" return [=](){ return it; };\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4] -> [test.cpp:2] -> [test.cpp:4]: (error) Returning lambda that captures local variable 'a' that will be invalid when returning.\n", errout_str());
check("auto f(std::vector<int> a) {\n"
" auto it = a.begin();\n"
" return [=](){ return it; };\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3] -> [test.cpp:1] -> [test.cpp:3]: (error) Returning lambda that captures local variable 'a' that will be invalid when returning.\n", errout_str());
check("struct e {};\n"
"e * j() {\n"
" e c[20];\n"
" return c;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:4] -> [test.cpp:3] -> [test.cpp:4]: (error) Returning pointer to local variable 'c' that will be invalid when returning.\n",
errout_str());
check("auto f(std::vector<int>& a) {\n"
" auto it = a.begin();\n"
" return [=](){ return it; };\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int * f(int a[]) {\n"
" return a;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" struct b {\n"
" uint32_t f[6];\n"
" } d;\n"
" uint32_t *a = d.f;\n"
"}");
ASSERT_EQUALS("", errout_str());
// Don't decay std::array
check("std::array<char, 1> f() {\n"
" std::array<char, 1> x;\n"
" return x;\n"
"}");
ASSERT_EQUALS("", errout_str());
// Make sure we don't hang
check("struct A;\n"
"void f() {\n"
" using T = A[3];\n"
" A &&a = T{1, 2, 3}[1];\n"
"}");
ASSERT_EQUALS("", errout_str());
// Make sure we don't hang
check("struct A;\n"
"void f() {\n"
" using T = A[3];\n"
" A &&a = T{1, 2, 3}[1]();\n"
"}");
ASSERT_EQUALS("", errout_str());
// Make sure we don't hang
check("struct A;\n"
"void f() {\n"
" using T = A[3];\n"
" A &&a = T{1, 2, 3}[1];\n"
"}");
ASSERT_EQUALS("", errout_str());
// Make sure we don't hang
check("struct A;\n"
"void f() {\n"
" using T = A[3];\n"
" A &&a = T{1, 2, 3}[1]();\n"
"}");
ASSERT_EQUALS("", errout_str());
// Crash #8872
check("struct a {\n"
" void operator()(b c) override {\n"
" d(c, [&] { c->e });\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct a {\n"
" void operator()(b c) override {\n"
" d(c, [=] { c->e });\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct a {\n"
" a(char* b) {}\n"
"};\n"
"a f() {\n"
" char c[20];\n"
" return c;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct a {\n"
" a(char* b) {}\n"
"};\n"
"a g() {\n"
" char c[20];\n"
" a d = c;\n"
" return d;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" struct a {\n"
" std::vector<int> v;\n"
" auto g() { return v.end(); }\n"
" };\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int * f(std::vector<int>& v) {\n"
" for(int & x : v)\n"
" return &x;\n"
" return nullptr;\n"
"}");
ASSERT_EQUALS("", errout_str());
// #9275
check("struct S {\n"
" void f();\n"
" std::string m;\n"
"}\n"
"void S::f() {\n"
" char buf[1024];\n"
" const char* msg = buf;\n"
" m = msg;\n"
"}");
ASSERT_EQUALS("", errout_str());
// #9201
check("int* f() {\n"
" struct a { int m; };\n"
" static a b{0};\n"
" return &b.m;\n"
"}");
ASSERT_EQUALS("", errout_str());
// #9453
check("int *ptr;\n"
"void foo(int arr[]) {\n"
" ptr = &arr[2];\n"
"}");
ASSERT_EQUALS("", errout_str());
// #9639
check("struct Fred {\n"
" std::string s;\n"
"};\n"
"const Fred &getFred();\n"
"const char * f() {\n"
" const Fred &fred = getFred();\n"
" return fred.s.c_str();\n"
"}");
ASSERT_EQUALS("", errout_str());
// #9534
check("struct A {\n"
" int* x;\n"
"};\n"
"int* f(int i, std::vector<A>& v) {\n"
" A& y = v[i];\n"
" return &y.x[i];\n"
"}");
ASSERT_EQUALS("", errout_str());
// #9712
check("std::string f(const char *str) {\n"
" char value[256];\n"
" return value;\n"
"}");
ASSERT_EQUALS("", errout_str());
// #9770
check("class C {\n"
" std::string f(const char*);\n"
"};\n"
"std::string C::f(const char*) {\n"
" const char data[] = \"x\";\n"
" return data;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #9899
check("struct A {\n"
" std::vector<int> v;\n"
" void f(std::vector<int> w) {\n"
" v = std::move(w);\n"
" }\n"
" void g(std::vector<int> w) {\n"
" f(std::move(w));\n"
" }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
//Make sure we can still take the address of a reference without warning
check("int* foo() {\n"
" int& x = getX();\n"
" return &x;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct C {\n"
" int* m_x;\n"
" void foo() {\n"
" const int& x = getX();\n"
" m_x = &x;\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #10090
check("struct a {\n"
" int b{};\n"
"};\n"
"struct c {\n"
" int* c{};\n"
" a* d{};\n"
"};\n"
"a* f();\n"
"c g() {\n"
" c e;\n"
" e.d = f();\n"
" if (e.d)\n"
" e.c = &e.d->b;\n"
" return e;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #10214
check("struct A {\n"
" std::string key;\n"
" const char *value;\n"
"};\n"
"const char *f(const std::string &key, const std::vector<A> &lookup) {\n"
" const auto &entry =\n"
" std::find_if(lookup.begin(), lookup.end(),\n"
" [key](const auto &v) { return v.key == key; });\n"
" return (entry == lookup.end()) ? \"\" : entry->value;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #9811
check("struct Base {\n"
" virtual auto get() -> int & = 0;\n"
"};\n"
"struct A : public Base {\n"
" int z = 42;\n"
" auto get() -> int & override { return z; }\n"
" auto getMore() -> int & { return get(); }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
// #10575
check("struct Data {\n"
" int x=0;\n"
" int y=0;\n"
"};\n"
"struct MoreData {\n"
" Data *data1;\n"
"};\n"
"struct Fred {\n"
" Fred() {\n"
" Data data;\n"
" mMoreData.data1 = &data;\n"
" }\n"
" MoreData mMoreData;\n"
"};\n");
ASSERT_EQUALS(
"[test.cpp:11] -> [test.cpp:10] -> [test.cpp:11]: (error) Non-local variable 'mMoreData.data1' will use pointer to local variable 'data'.\n",
errout_str());
// #10784
check("template <class... Ts>\n"
"auto f(int i, Ts&... xs) {\n"
" return std::tie(xs[i]...);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #11362
check("int* f() {\n"
" static struct { int x; } a[] = { { 1 } };\n"
" return &a[0].x;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #11666
check("template <class T, int M, int N>\n"
"struct Matrix;\n"
"template <class T, int N>\n"
"struct Matrix<T, 1, N> {\n"
" std::array<T, N> x;\n"
"private:\n"
" static constexpr decltype(&Matrix::x) members[] = {&Matrix::x};\n"
"};\n"
"template <class T, int N>\n"
"struct Matrix<T, 2, N> {\n"
" std::array<T, N> x;\n"
" std::array<T, N> y;\n"
"private:\n"
" static constexpr decltype(&Matrix::x) members[] = {&Matrix::x, &Matrix::y};\n"
"};\n"
"template <class T>\n"
"Matrix<T, 2, 2> O() {\n"
" return { {}, {} };\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #11729
check("struct T {\n"
" void add(int* i) {\n"
" v.push_back(i);\n"
" }\n"
" void f() {\n"
" static int val = 1;\n"
" add(&val);\n"
" }\n"
" std::vector<int*> v;\n"
"};\n");
ASSERT_EQUALS("", errout_str());
}
void danglingLifetimeFunction() {
check("auto f() {\n"
" int a;\n"
" return std::ref(a);\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3] -> [test.cpp:2] -> [test.cpp:3]: (error) Returning object that points to local variable 'a' that will be invalid when returning.\n",
errout_str());
check("auto f() {\n"
" int a;\n"
" return std::make_tuple(std::ref(a));\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3] -> [test.cpp:3] -> [test.cpp:2] -> [test.cpp:3]: (error) Returning object that points to local variable 'a' that will be invalid when returning.\n",
errout_str());
check("template<class T>\n"
"auto by_value(T x) {\n"
" return [=] { return x; };\n"
"}\n"
"auto g() {\n"
" std::vector<int> v;\n"
" return by_value(v.begin());\n"
"}");
ASSERT_EQUALS(
"[test.cpp:7] -> [test.cpp:7] -> [test.cpp:3] -> [test.cpp:3] -> [test.cpp:6] -> [test.cpp:7]: (error) Returning object that points to local variable 'v' that will be invalid when returning.\n",
errout_str());
check("template<class T>\n"
"auto by_value(const T& x) {\n"
" return [=] { return x; };\n"
"}\n"
"auto g() {\n"
" std::vector<int> v;\n"
" return by_value(v.begin());\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:7] -> [test.cpp:7] -> [test.cpp:3] -> [test.cpp:3] -> [test.cpp:6] -> [test.cpp:7]: (error) Returning object that points to local variable 'v' that will be invalid when returning.\n",
errout_str());
check("auto by_ref(int& x) {\n"
" return [&] { return x; };\n"
"}\n"
"auto f() {\n"
" int i = 0;\n"
" return by_ref(i);\n"
"}");
ASSERT_EQUALS(
"[test.cpp:2] -> [test.cpp:1] -> [test.cpp:2] -> [test.cpp:6] -> [test.cpp:5] -> [test.cpp:6]: (error) Returning object that points to local variable 'i' that will be invalid when returning.\n",
errout_str());
check("auto by_ref(const int& x) {\n"
" return [=] { return x; };\n"
"}\n"
"auto f() {\n"
" int i = 0;\n"
" return by_ref(i);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("auto f(int x) {\n"
" int a;\n"
" std::tie(a) = x;\n"
" return a;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("std::pair<std::string, std::string>\n"
"str_pair(std::string const & a, std::string const & b) {\n"
" return std::make_pair(a, b);\n"
"}\n"
"std::vector<std::pair<std::string, std::string> > create_parameters() {\n"
" std::vector<std::pair<std::string, std::string> > par;\n"
" par.push_back(str_pair(\"param1\", \"prop_a\"));\n"
" par.push_back(str_pair(\"param2\", \"prop_b\"));\n"
" par.push_back(str_pair(\"param3\", \"prop_c\"));\n"
" return par;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct S { int* (*ptr)(const int*); };\n" // #13057
"int* f(S* s) {\n"
" int x = 0;\n"
" return s->ptr(&x);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void danglingLifetimeUserConstructor()
{
check("struct A {\n"
" int* i;\n"
" A(int& x)\n"
" : i(&x)\n"
" {}\n"
"};\n"
"A f() {\n"
" int i = 0;\n"
" A a{i};\n"
" return a;\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:9] -> [test.cpp:8] -> [test.cpp:10]: (error) Returning object that points to local variable 'i' that will be invalid when returning.\n",
errout_str());
check("struct A {\n"
" int* i;\n"
" A(int& x);\n"
"};\n"
"A f() {\n"
" int i = 0;\n"
" A a{i};\n"
" return a;\n"
"}\n",
true);
ASSERT_EQUALS(
"[test.cpp:7] -> [test.cpp:6] -> [test.cpp:8]: (error, inconclusive) Returning object that points to local variable 'i' that will be invalid when returning.\n",
errout_str());
check("struct A {\n"
" int* i;\n"
" A(const int& x);\n"
"};\n"
"A f() {\n"
" int i = 0;\n"
" A a{i};\n"
" return a;\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("struct A {\n"
" int& i;\n"
" A(int& x)\n"
" : i(x)\n"
" {}\n"
"};\n"
"A f() {\n"
" int i = 0;\n"
" A a{i};\n"
" return a;\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:9] -> [test.cpp:8] -> [test.cpp:10]: (error) Returning object that points to local variable 'i' that will be invalid when returning.\n",
errout_str());
check("struct A {\n"
" int& i;\n"
" A(const std::vector<int>& x)\n"
" : i(x[0])\n"
" {}\n"
"};\n"
"A f() {\n"
" std::vector<int> v = {0};\n"
" A a{v};\n"
" return a;\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:9] -> [test.cpp:8] -> [test.cpp:10]: (error) Returning object that points to local variable 'v' that will be invalid when returning.\n",
errout_str());
check("struct A {\n"
" int* i;\n"
" A(const std::vector<int>& x)\n"
" : i(x.data())\n"
" {}\n"
"};\n"
"A f() {\n"
" std::vector<int> v = {0};\n"
" A a{v};\n"
" return a;\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:9] -> [test.cpp:8] -> [test.cpp:10]: (error) Returning object that points to local variable 'v' that will be invalid when returning.\n",
errout_str());
check("struct A {\n"
" const int* i;\n"
" A(const int& x)\n"
" : i(&x)\n"
" {}\n"
"};\n"
"A f() {\n"
" A a{0};\n"
" return a;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:8] -> [test.cpp:9]: (error) Returning object that will be invalid when returning.\n",
errout_str());
check("struct A {\n"
" const int* i;\n"
" A(const int& x)\n"
" : i(&x)\n"
" {}\n"
"};\n"
"A f() {\n"
" int i = 0;\n"
" return A{i};\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:9] -> [test.cpp:8] -> [test.cpp:9]: (error) Returning object that points to local variable 'i' that will be invalid when returning.\n",
errout_str());
check("struct A {\n"
" std::string v;\n"
" A(const std::string& s)\n"
" : v(s)\n"
" {}\n"
"};\n"
"A f() {\n"
" std::string s;\n"
" return A{s};\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct A {\n"
" std::string_view v;\n"
" A(const std::string& s)\n"
" : v(s)\n"
" {}\n"
"};\n"
"A f() {\n"
" std::string s;\n"
" return A{s};\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:9] -> [test.cpp:8] -> [test.cpp:9]: (error) Returning object that points to local variable 's' that will be invalid when returning.\n",
errout_str());
check("struct A {\n"
" const int* i;\n"
" A(const int& x)\n"
" : i(&x)\n"
" {}\n"
"};\n"
"A f() {\n"
" return A{0};\n"
"}\n");
ASSERT_EQUALS("[test.cpp:8] -> [test.cpp:8]: (error) Returning object that will be invalid when returning.\n",
errout_str());
check("struct A {\n"
" int n;\n"
" A(const int &x) : n(x) {}\n"
"};\n"
"A f() {\n"
" A m(4);\n"
" return m;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct B {};\n"
"struct A {\n"
" B n;\n"
" A(const B &x) : n(x) {}\n"
"};\n"
"A f() {\n"
" A m(B{});\n"
" return m;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct A {\n"
" A(std::vector<std::string> &filenames)\n"
" : files(filenames) {}\n"
" std::vector<std::string> &files;\n"
"};\n"
"A f() {\n"
" std::vector<std::string> files;\n"
" return A(files);\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:8] -> [test.cpp:7] -> [test.cpp:8]: (error) Returning object that points to local variable 'files' that will be invalid when returning.\n",
errout_str());
check("struct S {\n"
" explicit S(std::string& s);\n"
"}\n"
"S f() {\n"
" std::string m(\"abc\");\n"
" return S(m);\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("struct S {\n"
" std::string msg;\n"
" explicit S(const char* m) : msg(m) {}\n"
"};\n"
"S f() {\n"
" std::string s(\"abc\");\n"
" return S(s.c_str());\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("struct S {\n"
" explicit S(const char* p) { m = p; }\n"
" void g();\n"
" std::string m;\n"
" int* t{};\n"
"};\n"
"void f(const std::stringstream& buffer) {\n"
" S s(buffer.str().c_str());\n"
" s.g();\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
}
void danglingLifetimeAggegrateConstructor() {
check("struct A {\n"
" const int& x;\n"
" int y;\n"
"};\n"
"A f() {\n"
" int i = 0;\n"
" return A{i, i};\n"
"}");
ASSERT_EQUALS(
"[test.cpp:7] -> [test.cpp:6] -> [test.cpp:7]: (error) Returning object that points to local variable 'i' that will be invalid when returning.\n",
errout_str());
check("struct A {\n"
" const int& x;\n"
" int y;\n"
"};\n"
"A f() {\n"
" int i = 0;\n"
" return {i, i};\n"
"}");
ASSERT_EQUALS(
"[test.cpp:7] -> [test.cpp:6] -> [test.cpp:7]: (error) Returning object that points to local variable 'i' that will be invalid when returning.\n",
errout_str());
check("struct A {\n"
" const int& x;\n"
" int y;\n"
"};\n"
"A f() {\n"
" int i = 0;\n"
" A r{i, i};\n"
" return r;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:7] -> [test.cpp:6] -> [test.cpp:8]: (error) Returning object that points to local variable 'i' that will be invalid when returning.\n",
errout_str());
check("struct A {\n"
" const int& x;\n"
" int y;\n"
"};\n"
"A f() {\n"
" int i = 0;\n"
" A r = {i, i};\n"
" return r;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:7] -> [test.cpp:6] -> [test.cpp:8]: (error) Returning object that points to local variable 'i' that will be invalid when returning.\n",
errout_str());
check("struct A {\n"
" const int& x;\n"
" int y;\n"
"};\n"
"A f(int& x) {\n"
" int i = 0;\n"
" return A{i, x};\n"
"}");
ASSERT_EQUALS(
"[test.cpp:7] -> [test.cpp:6] -> [test.cpp:7]: (error) Returning object that points to local variable 'i' that will be invalid when returning.\n",
errout_str());
check("struct A {\n"
" const int& x;\n"
" int y;\n"
"};\n"
"A f(int& x) {\n"
" int i = 0;\n"
" return A{x, i};\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct A {\n"
" const int& x;\n"
" int y;\n"
"};\n"
"A f(int& x) {\n"
" return A{x, x};\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct A { int i; const int& j; };\n"
"A f(int& x) {\n"
" int y = 0;\n"
" return A{y, x};\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct a {\n"
" std::string m;\n"
"};\n"
"a f() {\n"
" std::array<char, 1024> m {};\n"
" return { m.data() };\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void danglingLifetimeInitList() {
check("std::vector<int*> f() {\n"
" int i = 0;\n"
" std::vector<int*> v = {&i, &i};\n"
" return v;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3] -> [test.cpp:3] -> [test.cpp:2] -> [test.cpp:4]: (error) Returning object that points to local variable 'i' that will be invalid when returning.\n"
"[test.cpp:3] -> [test.cpp:3] -> [test.cpp:2] -> [test.cpp:4]: (error) Returning object that points to local variable 'i' that will be invalid when returning.\n", // duplicate
errout_str());
check("std::vector<int*> f() {\n"
" int i = 0;\n"
" std::vector<int*> v{&i, &i};\n"
" return v;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3] -> [test.cpp:3] -> [test.cpp:2] -> [test.cpp:4]: (error) Returning object that points to local variable 'i' that will be invalid when returning.\n"
"[test.cpp:3] -> [test.cpp:3] -> [test.cpp:2] -> [test.cpp:4]: (error) Returning object that points to local variable 'i' that will be invalid when returning.\n", // duplicate
errout_str());
check("std::vector<int*> f() {\n"
" int i = 0;\n"
" return {&i, &i};\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3] -> [test.cpp:3] -> [test.cpp:2] -> [test.cpp:3]: (error) Returning object that points to local variable 'i' that will be invalid when returning.\n"
"[test.cpp:3] -> [test.cpp:3] -> [test.cpp:2] -> [test.cpp:3]: (error) Returning object that points to local variable 'i' that will be invalid when returning.\n", // duplicate
errout_str());
check("std::vector<int*> f(int& x) {\n"
" return {&x, &x};\n"
"}");
ASSERT_EQUALS("", errout_str());
check("std::vector<std::string> f() {\n"
" std::set<std::string> x;\n"
" x.insert(\"1\");\n"
" x.insert(\"2\");\n"
" return { x.begin(), x.end() };\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void danglingLifetimeImplicitConversion() {
check("struct A { A(const char *a); };\n"
"A f() {\n"
" std::string ba(\"hello\");\n"
" return ba.c_str();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct A { A(const char *a); };\n"
"A f() {\n"
" std::string ba(\"hello\");\n"
" A bp = ba.c_str();\n"
" return bp;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct A { A(const char *a); };\n"
"std::vector<A> f() {\n"
" std::string ba(\"hello\");\n"
" std::vector<A> v;\n"
" v.push_back(ba.c_str());\n"
" return v;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("std::string f(const std::string& x) {\n"
" const char c[] = \"\";\n"
" if (!x.empty())\n"
" return x + c;\n"
" return \"\";\n"
"}");
ASSERT_EQUALS("", errout_str());
check("std::string f(const std::string& x) {\n"
" const char c[] = \"123\";\n"
" if (!x.empty())\n"
" return c + 1;\n"
" return \"\";\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void danglingTemporaryLifetime() {
check("struct C {\n" // #11091
" C(C& rhs);\n"
" explicit C(const S& n, const S& p = {});\n"
" bool f() const;\n"
" S m;\n"
"};\n"
"void f() {\n"
" C c(\"\");\n"
" while (c.f()) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("const int& g(const int& x) {\n"
" return x;\n"
"}\n"
"void f(int& i) {\n"
" int* x = &g(0);\n"
" i += *x;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:1] -> [test.cpp:2] -> [test.cpp:5] -> [test.cpp:5] -> [test.cpp:5] -> [test.cpp:6]: (error) Using pointer that is a temporary.\n",
errout_str());
check("QString f() {\n"
" QString a(\"dummyValue\");\n"
" const char* b = a.toStdString().c_str();\n"
" QString c = b;\n"
" return c;\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:3] -> [test.cpp:4]: (error) Using pointer that is a temporary.\n",
errout_str());
check("auto f(std::string s) {\n"
" const char *x = s.substr(1,2).c_str();\n"
" auto i = s.substr(4,5).begin();\n"
" return *i;\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:3] -> [test.cpp:4]: (error) Using iterator that is a temporary.\n",
errout_str());
check("std::string f() {\n"
" std::stringstream tmp;\n"
" const std::string &str = tmp.str();\n"
" return std::string(str.c_str(), 1);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int get_value();\n"
"const int &get_reference1() {\n"
" const int &x = get_value();\n"
" return x;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (error) Reference to temporary returned.\n", errout_str());
check("int get_value();\n"
"const int &get_reference2() {\n"
" const int &x1 = get_value();\n"
" const int &x2 = x1;\n"
" return x2;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:3] -> [test.cpp:5]: (error) Reference to temporary returned.\n",
errout_str());
check("const std::string& getState() {\n"
" static const std::string& state = \"\";\n"
" return state;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct var {\n"
" void fun();\n"
"}x;\n"
"var* T(const char*) {\n"
" return &x;\n"
"}\n"
"std::string GetTemp();\n"
"void f() {\n"
" auto a = T(GetTemp().c_str());\n"
" a->fun();\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct A {\n"
" std::map<int, int> m_;\n"
"};\n"
"struct B {\n"
" A a_;\n"
"};\n"
"B func();\n"
"void f() {\n"
" const std::map<int, int>::iterator& m = func().a_.m_.begin();\n"
" (void)m->first;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:9] -> [test.cpp:9] -> [test.cpp:10]: (error) Using iterator that is a temporary.\n",
errout_str());
check("void f(bool b) {\n"
" std::vector<int> ints = g();\n"
" auto *ptr = &ints;\n"
" if (b)\n"
" ptr = &ints;\n"
" for (auto it = ptr->begin(); it != ptr->end(); ++it)\n"
" {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct String {\n" // #10469
" void Append(uint8_t Val);\n"
" String& operator+=(const char s[]);\n"
" String& operator+=(const std::string& Str) {\n"
" return operator+=(Str.c_str());\n"
" }\n"
" void operator+=(uint8_t Val) {\n"
" Append(Val);\n"
" }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
// #11057
check("struct S {\n"
" int& r;\n"
"};\n"
"void f(int i) {\n"
" const S a[] = { { i } };\n"
" for (const auto& s : a) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("std::vector<char*> f(const std::vector<std::string>& args) {\n" // #9773
" std::vector<char*> cargs;\n"
" for (const auto& a : args) {\n"
" cargs.push_back(const_cast<char*>(a.data()));\n"
" }\n"
" return cargs;\n"
"}\n"
"void g() {\n"
" std::vector<char*> cargs = f({ \"0\", \"0\" });\n"
" (void)cargs;\n"
"};\n");
ASSERT_EQUALS("[test.cpp:6] -> [test.cpp:4] -> [test.cpp:3] -> [test.cpp:1] -> [test.cpp:4] -> [test.cpp:9] -> [test.cpp:9] -> [test.cpp:10]: (error) Using object that is a temporary.\n", errout_str());
check("struct C {\n" // #9194
" const int& m;\n"
" C(const int& i) : m(i) {}\n"
" int get() { return m; }\n"
"};\n"
"int f() {\n"
" C c(42);\n"
" return c.get();\n"
"}\n");
ASSERT_EQUALS("[test.cpp:7] -> [test.cpp:7] -> [test.cpp:8]: (error) Using object that is a temporary.\n", errout_str());
// #11298
check("struct S {\n"
" std::string g(); \n"
"};\n"
"struct T {\n"
" void f(); \n"
" S* p = nullptr;\n"
"};\n"
"struct U {\n"
" explicit U(const char* s);\n"
" bool h();\n"
" int i;\n"
"};\n"
"void T::f() {\n"
" U u(p->g().c_str());\n"
" if (u.h()) {}\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
// #11442
check("const std::string& f(const P< std::string >& value) {\n"
" static const std::string empty;\n"
" return value.get() == nullptr ? empty : *value;\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
// #11472
check("namespace N {\n"
" struct T { int m; };\n"
" int i;\n"
" const T& f(const T* p) {\n"
" return p != nullptr ? *p : *reinterpret_cast<const ::N::T*>(&i);\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #11609
check("struct S {\n"
" void f(const std::string& s) {\n"
" auto it = m.find(s.substr(1,4));\n"
" if (it == m.end()) {}\n"
" }\n"
" std::map<std::string, int> m;\n"
"};\n");
ASSERT_EQUALS("", errout_str());
// #11628
check("std::vector<int>* g();\n"
"void f() {\n"
" std::unique_ptr<std::vector<int>> p(g());\n"
" if (!p) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void danglingLifetimeBorrowedMembers()
{
// #10585
check("struct Info { int k; };\n"
"struct MoreInfo {\n"
" int* k;\n"
" char dat;\n"
"};\n"
"struct Fields {\n"
" Info info;\n"
"};\n"
"template <typename T> void func1(T val){}\n"
"template <typename T> void func2(T val){}\n"
"Fields* get();\n"
"void doit() {\n"
" MoreInfo rech;\n"
" rech.k = &get()->info.k;\n"
" func1(&rech.dat);\n"
" func2(rech.k);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct A { int x; };\n"
"A* g();\n"
"void f() {\n"
" A** ap = &g();\n"
" (*ap)->x;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:4] -> [test.cpp:5]: (error) Using pointer that is a temporary.\n",
errout_str());
check("struct A { int* x; };\n"
"A g();\n"
"void f() {\n"
" int* x = g().x;\n"
" (void)*x + 1;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct A { int x; };\n"
"struct B { A* a; }\n"
"B g();\n"
"void f() {\n"
" int* x = &g()->a.x;\n"
" (void)*x + 1;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct A { int x; };\n"
"struct B { A* g(); };\n"
"A* g();\n"
"void f(B b) {\n"
" A** ap = &b.g();\n"
" (*ap)->x;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:5] -> [test.cpp:6]: (error) Using pointer that is a temporary.\n",
errout_str());
}
void danglingLifetimeClassMemberFunctions()
{
check("struct S {\n"
" S(int i) : i(i) {}\n"
" int i;\n"
" int* ptr() { return &i; }\n"
"};\n"
"int* fun(int i) { \n"
" return S(i).ptr();\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:4] -> [test.cpp:4] -> [test.cpp:7] -> [test.cpp:7]: (error) Returning pointer that will be invalid when returning.\n",
errout_str());
check("struct Fred\n"
"{\n"
" int x[2];\n"
" Fred() {\n"
" x[0] = 0x41;\n"
" x[1] = 0x42;\n"
" }\n"
" const int *get_x() {\n"
" return x;\n"
" }\n"
"};\n"
"static const int *foo() {\n"
" Fred fred;\n"
" return fred.get_x();\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:9] -> [test.cpp:9] -> [test.cpp:14] -> [test.cpp:13] -> [test.cpp:14]: (error) Returning pointer to local variable 'fred' that will be invalid when returning.\n",
errout_str());
check("struct A {\n"
" int i;\n"
" auto f() const {\n"
" return [=]{ return i; };\n"
" }\n"
"};\n"
"auto g() {\n"
" return A().f();\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:4] -> [test.cpp:4] -> [test.cpp:8] -> [test.cpp:8]: (error) Returning object that will be invalid when returning.\n",
errout_str());
check("struct A {\n"
" int i;\n"
" auto f() const {\n"
" return [*this]{ return i; };\n"
" }\n"
"};\n"
"auto g() {\n"
" return A().f();\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct A {\n"
" int* i;\n"
" auto f() const {\n"
" return [*this]{ return i; };\n"
" }\n"
"};\n"
"auto g() {\n"
" int i = 0;\n"
" return A{&i}.f();\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:9] -> [test.cpp:9] -> [test.cpp:9] -> [test.cpp:4] -> [test.cpp:4] -> [test.cpp:8] -> [test.cpp:9]: (error) Returning object that points to local variable 'i' that will be invalid when returning.\n",
errout_str());
check("struct S {\n"
" int i{};\n"
"};\n"
"struct T {\n"
" S getS() const { return S{ j }; }\n"
" int j{};\n"
"};\n"
"void f(S* p) {\n"
" S ret;\n"
" {\n"
" T t;\n"
" ret = t.getS();\n"
" }\n"
" *p = ret;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void invalidLifetime() {
check("void foo(int a) {\n"
" std::function<void()> f;\n"
" if (a > 0) {\n"
" int b = a + 1;\n"
" f = [&]{ return b; };\n"
" }\n"
" f();\n"
"}");
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:4] -> [test.cpp:7]: (error) Using lambda that captures local variable 'b' that is out of scope.\n", errout_str());
check("void f(bool b) {\n"
" int* x;\n"
" if(b) {\n"
" int y[6] = {0,1,2,3,4,5};\n"
" x = y;\n"
" }\n"
" x[3];\n"
"}");
ASSERT_EQUALS(
"[test.cpp:5] -> [test.cpp:4] -> [test.cpp:7]: (error) Using pointer to local variable 'y' that is out of scope.\n",
errout_str());
check("void foo(int a) {\n"
" std::function<void()> f;\n"
" if (a > 0) {\n"
" int b = a + 1;\n"
" f = [&]{ return b; };\n"
" f();\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct a {\n"
" b();\n"
" std::list<int> c;\n"
"};\n"
"void a::b() {\n"
" c.end()\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void b(char f[], char c[]) {\n"
" std::string d(c); {\n"
" std::string e;\n"
" b(f, e.c_str())\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(bool b) {\n"
" std::string s;\n"
" if(b) {\n"
" char buf[3];\n"
" s = buf;\n"
" }\n"
" std::cout << s;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int &a[];\n"
"void b(){int *c = a};");
ASSERT_EQUALS("", errout_str());
check("struct A {\n"
" int x;\n"
"};\n"
"struct B {\n"
" std::function<void()> x;\n"
" void f() {\n"
" this->x = [&] {\n"
" B y;\n"
" return y.x;\n"
" };\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("namespace test {\n"
"class Foo {};\n"
"struct Bar {\n"
" Foo *_foo;\n"
"};\n"
"\n"
"int f(Bar *bar);\n"
"\n"
"void g(Bar *bar) {\n"
" {\n"
" Foo foo;\n"
" bar->_foo = &foo;\n"
" bar->_foo = nullptr;\n"
" }\n"
" f(bar);\n"
"}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("class Foo {};\n"
"struct Bar {\n"
" Foo *_foo;\n"
"};\n"
"\n"
"int f(Bar *bar);\n"
"\n"
"void g(Bar *bar) {\n"
" {\n"
" Foo foo;\n"
" bar->_foo = &foo;\n"
" bar->_foo = nullptr;\n"
" }\n"
" f(bar);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("namespace test {\n"
"class Foo {};\n"
"struct Bar {\n"
" Foo *_foo;\n"
"};\n"
"\n"
"int f(Bar *bar);\n"
"\n"
"void g(Bar *bar) {\n"
" {\n"
" Foo foo;\n"
" bar->_foo = &foo;\n"
" }\n"
" f(bar);\n"
"}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:12]: (error) Address of local auto-variable assigned to a function parameter.\n", errout_str());
check("class Foo {};\n"
"struct Bar {\n"
" Foo *_foo;\n"
"};\n"
"\n"
"int f(Bar *bar);\n"
"\n"
"void g(Bar *bar) {\n"
" {\n"
" Foo foo;\n"
" bar->_foo = &foo;\n"
" }\n"
" f(bar);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:11]: (error) Address of local auto-variable assigned to a function parameter.\n", errout_str());
check("class Foo {};\n" // #10750
"struct Bar {\n"
" Foo *_foo;\n"
"};\n"
"int f(Bar *bar);\n"
"void g(Bar *bar) {\n"
" {\n"
" Foo foo;\n"
" {\n"
" bar->_foo = &foo;\n"
" }\n"
" }\n"
" f(bar);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:10]: (error) Address of local auto-variable assigned to a function parameter.\n", errout_str());
check("void f(std::string_view text);\n" // #11508
"void g() {\n"
" std::string teststr;\n"
" f(teststr);"
"}\n"
"void f(std::string_view text) {"
" g(text.data());\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(std::span<int> data);\n" // #11508
"void g() {\n"
" std::vector<int> v;\n"
" f(v);"
"}\n"
"void f(std::span<int> data) {"
" g(data.begin());\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void deadPointer() {
check("void f() {\n"
" int *p = p1;\n"
" if (cond) {\n"
" int x;\n"
" p = &x;\n"
" }\n"
" *p = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:4] -> [test.cpp:7]: (error) Using pointer to local variable 'x' that is out of scope.\n", errout_str());
// FP: don't warn in subfunction
check("void f(struct KEY *key) {\n"
" key->x = 0;\n"
"}\n"
"\n"
"int main() {\n"
" struct KEY *tmp = 0;\n"
" struct KEY k;\n"
"\n"
" if (condition) {\n"
" tmp = &k;\n"
" } else {\n"
" }\n"
" f(tmp);\n"
"}");
ASSERT_EQUALS("", errout_str());
// Don't warn about references (#6399)
check("void f() {\n"
" wxAuiToolBarItem* former_hover = NULL;\n"
" for (i = 0, count = m_items.GetCount(); i < count; ++i) {\n"
" wxAuiToolBarItem& item = m_items.Item(i);\n"
" former_hover = &item;\n"
" }\n"
" if (former_hover != pitem)\n"
" dosth();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" wxAuiToolBarItem* former_hover = NULL;\n"
" for (i = 0, count = m_items.GetCount(); i < count; ++i) {\n"
" wxAuiToolBarItem item = m_items.Item(i);\n"
" former_hover = &item;\n"
" }\n"
" if (former_hover != pitem)\n"
" dosth();\n"
"}");
ASSERT_EQUALS(
"[test.cpp:5] -> [test.cpp:3] -> [test.cpp:4] -> [test.cpp:7]: (error) Using pointer to local variable 'item' that is out of scope.\n",
errout_str());
// #6575
check("void trp_deliver_signal() {\n"
" union {\n"
" Uint32 theData[25];\n"
" EventReport repData;\n"
" };\n"
" EventReport * rep = &repData;\n"
" rep->setEventType(NDB_LE_Connected);\n"
"}");
ASSERT_EQUALS("", errout_str());
// #8785
check("int f(bool a, bool b) {\n"
" int *iPtr = 0;\n"
" if(b) {\n"
" int x = 42;\n"
" iPtr = &x;\n"
" }\n"
" if(b && a)\n"
" return *iPtr;\n"
" return 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:4] -> [test.cpp:8]: (error) Using pointer to local variable 'x' that is out of scope.\n", errout_str());
// #11753
check("int main(int argc, const char *argv[]) {\n"
" const char* s = \"\";\n"
" if (argc > 0) {\n"
" char buff[32]{};\n"
" s = std::strncpy(buff, argv[0], 31);\n"
" }\n"
" std::cout << s;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:4] -> [test.cpp:7]: (error) Using pointer to local variable 'buff' that is out of scope.\n", errout_str());
check("char* f(char* dst) {\n"
" const char* src = \"abc\";\n"
" return strcpy(dst, src);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void splitNamespaceAuto() { // #10473
check("namespace ns\n"
"{\n"
" auto var{ 0 };\n"
"}\n"
"namespace ns\n"
"{\n"
" int i;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
};
REGISTER_TEST(TestAutoVariables)
| null |
1,017 | cpp | cppcheck | testcharvar.cpp | test/testcharvar.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#include "checkother.h"
#include "errortypes.h"
#include "fixture.h"
#include "helpers.h"
#include "platform.h"
#include "settings.h"
#include <cstddef>
class TestCharVar : public TestFixture {
public:
TestCharVar() : TestFixture("TestCharVar") {}
private:
const Settings settings = settingsBuilder().severity(Severity::warning).severity(Severity::portability).platform(Platform::Type::Unspecified).build();
void run() override {
TEST_CASE(array_index_1);
TEST_CASE(array_index_2);
TEST_CASE(bitop);
}
#define check(code) check_(code, __FILE__, __LINE__)
template<size_t size>
void check_(const char (&code)[size], const char* file, int line) {
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
// Check char variable usage..
CheckOther checkOther(&tokenizer, &settings, this);
checkOther.checkCharVariable();
}
void array_index_1() {
check("int buf[256];\n"
"void foo()\n"
"{\n"
" unsigned char ch = 0x80;\n"
" buf[ch] = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int buf[256];\n"
"void foo()\n"
"{\n"
" char ch = 0x80;\n"
" buf[ch] = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (portability) 'char' type used as array index.\n", errout_str());
check("int buf[256];\n"
"void foo()\n"
"{\n"
" char ch = 0;\n"
" buf[ch] = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int buf[256];\n"
"void foo()\n"
"{\n"
" signed char ch = 0;\n"
" buf[ch] = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int buf[256];\n"
"void foo()\n"
"{\n"
" char ch = 0x80;\n"
" buf[ch] = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (portability) 'char' type used as array index.\n", errout_str());
check("int buf[256];\n"
"void foo(signed char ch)\n"
"{\n"
" buf[ch] = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int buf[256];\n"
"void foo(char ch)\n"
"{\n"
" buf[ch] = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(char* buf)\n"
"{\n"
" char ch = 0x80;"
" buf[ch] = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (portability) 'char' type used as array index.\n", errout_str());
check("void foo(char* buf)\n"
"{\n"
" char ch = 0;"
" buf[ch] = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(char* buf)\n"
"{\n"
" buf['A'] = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(char* buf, char ch)\n"
"{\n"
" buf[ch] = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int flags[256];\n"
"void foo(const char* str)\n"
"{\n"
" flags[*str] = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int flags[256];\n"
"void foo(const char* str)\n"
"{\n"
" flags[(unsigned char)*str] = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(const char str[])\n"
"{\n"
" map[str] = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void array_index_2() {
// #3282 - False positive
check("void foo(char i);\n"
"void bar(int i) {\n"
" const char *s = \"abcde\";\n"
" foo(s[i]);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void bitop() {
check("void foo(int *result) {\n"
" signed char ch = -1;\n"
" *result = a | ch;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) When using 'char' variables in bit operations, sign extension can generate unexpected results.\n", errout_str());
check("void foo(int *result) {\n"
" unsigned char ch = -1;\n"
" *result = a | ch;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(char *result) {\n"
" signed char ch = -1;\n"
" *result = a | ch;\n"
"}");
ASSERT_EQUALS("", errout_str());
// 0x03 & ..
check("void foo(int *result) {\n"
" signed char ch = -1;\n"
" *result = 0x03 | ch;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) When using 'char' variables in bit operations, sign extension can generate unexpected results.\n", errout_str());
check("void foo(int *result) {\n"
" signed char ch = -1;\n"
" *result = 0x03 & ch;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
};
REGISTER_TEST(TestCharVar)
| null |
1,018 | cpp | cppcheck | testinternal.cpp | test/testinternal.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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 "fixture.h"
#include "helpers.h"
#include "settings.h"
#include <cstddef>
class TestInternal : public TestFixture {
public:
TestInternal() : TestFixture("TestInternal") {}
private:
/*const*/ Settings settings;
void run() override {
ASSERT_EQUALS("", settings.addEnabled("internal"));
TEST_CASE(simplePatternInTokenMatch);
TEST_CASE(complexPatternInTokenSimpleMatch);
TEST_CASE(simplePatternSquareBrackets);
TEST_CASE(simplePatternAlternatives);
TEST_CASE(missingPercentCharacter);
TEST_CASE(unknownPattern);
TEST_CASE(redundantNextPrevious);
TEST_CASE(internalError);
TEST_CASE(orInComplexPattern);
TEST_CASE(extraWhitespace);
TEST_CASE(checkRedundantTokCheck);
}
#define check(code) check_(code, __FILE__, __LINE__)
template<size_t size>
void check_(const char (&code)[size], const char* file, int line) {
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
// Check..
runChecks<CheckInternal>(tokenizer, this);
}
void simplePatternInTokenMatch() {
check("void f() {\n"
" const Token *tok;\n"
" Token::Match(tok, \";\");\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Found simple pattern inside Token::Match() call: \";\"\n", errout_str());
check("void f() {\n"
" const Token *tok;\n"
" Token::Match(tok, \"%type%\");\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" const Token *tok;\n"
" Token::Match(tok, \"%or%\");\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Found simple pattern inside Token::Match() call: \"%or%\"\n", errout_str());
check("void f() {\n"
" const Token *tok;\n"
" Token::findmatch(tok, \";\");\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Found simple pattern inside Token::findmatch() call: \";\"\n", errout_str());
}
void complexPatternInTokenSimpleMatch() {
check("void f() {\n"
" const Token *tok;\n"
" Token::simpleMatch(tok, \"%type%\");\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Found complex pattern inside Token::simpleMatch() call: \"%type%\"\n", errout_str());
check("void f() {\n"
" const Token *tok;\n"
" Token::findsimplematch(tok, \"%type%\");\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Found complex pattern inside Token::findsimplematch() call: \"%type%\"\n", errout_str());
check("void f() {\n"
" const Token *tok;\n"
" Token::findsimplematch(tok, \"} !!else\");\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Found complex pattern inside Token::findsimplematch() call: \"} !!else\"\n", errout_str());
check("void f() {\n"
" const Token *tok;\n"
" Token::findsimplematch(tok, \"foobar\");\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" const Token *tok;\n"
" Token::findsimplematch(tok, \"%\");\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void simplePatternSquareBrackets() {
check("void f() {\n"
" const Token *tok;\n"
" Token::simpleMatch(tok, \"[\");\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" const Token *tok;\n"
" Token::simpleMatch(tok, \"[ ]\");\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" const Token *tok;\n"
" Token::simpleMatch(tok, \"[]\");\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Found complex pattern inside Token::simpleMatch() call: \"[]\"\n", errout_str());
check("void f() {\n"
" const Token *tok;\n"
" Token::simpleMatch(tok, \"] [\");\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" const Token *tok;\n"
" Token::simpleMatch(tok, \"] [ [abc]\");\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Found complex pattern inside Token::simpleMatch() call: \"] [ [abc]\"\n", errout_str());
check("void f() {\n"
" const Token *tok;\n"
" Token::simpleMatch(tok, \"[.,;]\");\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Found complex pattern inside Token::simpleMatch() call: \"[.,;]\"\n", errout_str());
}
void simplePatternAlternatives() {
check("void f() {\n"
" const Token *tok;\n"
" Token::simpleMatch(tok, \"||\");\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" const Token *tok;\n"
" Token::simpleMatch(tok, \"|\");\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" const Token *tok;\n"
" Token::simpleMatch(tok, \"a|b\");\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Found complex pattern inside Token::simpleMatch() call: \"a|b\"\n", errout_str());
check("void f() {\n"
" const Token *tok;\n"
" Token::simpleMatch(tok, \"|= 0\");\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" const Token *tok;\n"
" Token::simpleMatch(tok, \"| 0 )\");\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void missingPercentCharacter() {
check("void f() {\n"
" const Token *tok;\n"
" Token::Match(tok, \"%type%\");\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" const Token *tok;\n"
" Token::Match(tok, \"foo %type% bar\");\n"
"}");
ASSERT_EQUALS("", errout_str());
// Missing % at the end of string
check("void f() {\n"
" const Token *tok;\n"
" Token::Match(tok, \"%type\");\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Missing percent end character in Token::Match() pattern: \"%type\"\n", errout_str());
// Missing % in the middle of a pattern
check("void f() {\n"
" const Token *tok;\n"
" Token::Match(tok, \"foo %type bar\");\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Missing percent end character in Token::Match() pattern: \"foo %type bar\"\n", errout_str());
// Bei quiet on single %
check("void f() {\n"
" const Token *tok;\n"
" Token::Match(tok, \"foo % %type% bar\");\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" const Token *tok;\n"
" Token::Match(tok, \"foo % %type % bar\");\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Missing percent end character in Token::Match() pattern: \"foo % %type % bar\"\n"
"[test.cpp:3]: (error) Unknown pattern used: \"%type %\"\n", errout_str());
// Find missing % also in 'alternatives' pattern
check("void f() {\n"
" const Token *tok;\n"
" Token::Match(tok, \"foo|%type|bar\");\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Missing percent end character in Token::Match() pattern: \"foo|%type|bar\"\n"
, errout_str());
// Make sure we don't take %or% for a broken %oror%
check("void f() {\n"
" const Token *tok;\n"
" Token::Match(tok, \"foo|%oror%|bar\");\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void unknownPattern() {
check("void f() {\n"
" Token::Match(tok, \"%typ%\");\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Unknown pattern used: \"%typ%\"\n", errout_str());
// Make sure we don't take %or% for a broken %oror%
check("void f() {\n"
" Token::Match(tok, \"%type%\");\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void redundantNextPrevious() {
check("void f() {\n"
" return tok->next()->previous();\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Call to 'Token::next()' followed by 'Token::previous()' can be simplified.\n", errout_str());
check("void f() {\n"
" return tok->tokAt(5)->previous();\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Call to 'Token::tokAt()' followed by 'Token::previous()' can be simplified.\n", errout_str());
check("void f() {\n"
" return tok->previous()->linkAt(5);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Call to 'Token::previous()' followed by 'Token::linkAt()' can be simplified.\n", errout_str());
check("void f() {\n"
" tok->next()->previous(foo);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" return tok->next()->next();\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Call to 'Token::next()' followed by 'Token::next()' can be simplified.\n", errout_str());
check("void f() {\n"
" return tok->previous()->previous();\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Call to 'Token::previous()' followed by 'Token::previous()' can be simplified.\n", errout_str());
check("void f() {\n"
" return tok->tokAt(foo+bar)->tokAt();\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Call to 'Token::tokAt()' followed by 'Token::tokAt()' can be simplified.\n", errout_str());
check("void f() {\n"
" return tok->tokAt(foo+bar)->link();\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Call to 'Token::tokAt()' followed by 'Token::link()' can be simplified.\n", errout_str());
check("void f() {\n"
" tok->tokAt(foo+bar)->link(foo);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" return tok->next()->next()->str();\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Call to 'Token::next()' followed by 'Token::next()' can be simplified.\n"
"[test.cpp:2]: (style) Call to 'Token::next()' followed by 'Token::str()' can be simplified.\n",
errout_str());
check("void f() {\n"
" return tok->previous()->next()->str();\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Call to 'Token::previous()' followed by 'Token::next()' can be simplified.\n"
"[test.cpp:2]: (style) Call to 'Token::next()' followed by 'Token::str()' can be simplified.\n",
errout_str());
}
void internalError() {
// Make sure cppcheck does not raise an internal error of Token::Match ( Ticket #3727 )
check("class DELPHICLASS X;\n"
"class Y {\n"
"private:\n"
" X* x;\n"
"};\n"
"class Z {\n"
" char z[1];\n"
" Z(){\n"
" z[0] = 0;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void orInComplexPattern() {
check("void f() {\n"
" Token::Match(tok, \"||\");\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Token::Match() pattern \"||\" contains \"||\" or \"|\". Replace it by \"%oror%\" or \"%or%\".\n", errout_str());
check("void f() {\n"
" Token::Match(tok, \"|\");\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Token::Match() pattern \"|\" contains \"||\" or \"|\". Replace it by \"%oror%\" or \"%or%\".\n", errout_str());
check("void f() {\n"
" Token::Match(tok, \"[|+-]\");\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" Token::Match(tok, \"foo | bar\");\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Token::Match() pattern \"foo | bar\" contains \"||\" or \"|\". Replace it by \"%oror%\" or \"%or%\".\n", errout_str());
check("void f() {\n"
" Token::Match(tok, \"foo |\");\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Token::Match() pattern \"foo |\" contains \"||\" or \"|\". Replace it by \"%oror%\" or \"%or%\".\n", errout_str());
check("void f() {\n"
" Token::Match(tok, \"bar foo|\");\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void extraWhitespace() {
// whitespace at the end
check("void f() {\n"
" const Token *tok;\n"
" Token::Match(tok, \"%str% \");\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Found extra whitespace inside Token::Match() call: \"%str% \"\n", errout_str());
// whitespace at the begin
check("void f() {\n"
" const Token *tok;\n"
" Token::Match(tok, \" %str%\");\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Found extra whitespace inside Token::Match() call: \" %str%\"\n", errout_str());
// two whitespaces or more
check("void f() {\n"
" const Token *tok;\n"
" Token::Match(tok, \"%str% bar\");\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Found extra whitespace inside Token::Match() call: \"%str% bar\"\n", errout_str());
// test simpleMatch
check("void f() {\n"
" const Token *tok;\n"
" Token::simpleMatch(tok, \"foobar \");\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Found extra whitespace inside Token::simpleMatch() call: \"foobar \"\n", errout_str());
// test findmatch
check("void f() {\n"
" const Token *tok;\n"
" Token::findmatch(tok, \"%str% \");\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Found extra whitespace inside Token::findmatch() call: \"%str% \"\n", errout_str());
// test findsimplematch
check("void f() {\n"
" const Token *tok;\n"
" Token::findsimplematch(tok, \"foobar \");\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Found extra whitespace inside Token::findsimplematch() call: \"foobar \"\n", errout_str());
}
void checkRedundantTokCheck() {
// findsimplematch
check("void f() {\n"
" const Token *tok;\n"
" if(tok && Token::findsimplematch(tok, \"foobar\")) {};\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Unnecessary check of \"tok\", match-function already checks if it is null.\n", errout_str());
// findmatch
check("void f() {\n"
" const Token *tok;\n"
" if(tok && Token::findmatch(tok, \"%str% foobar\")) {};\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Unnecessary check of \"tok\", match-function already checks if it is null.\n", errout_str());
// Match
check("void f() {\n"
" const Token *tok;\n"
" if(tok && Token::Match(tok, \"5str% foobar\")) {};\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Unnecessary check of \"tok\", match-function already checks if it is null.\n", errout_str());
check("void f() {\n"
" const Token *tok;\n"
" if(a && tok && Token::Match(tok, \"5str% foobar\")) {};\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Unnecessary check of \"tok\", match-function already checks if it is null.\n", errout_str());
check("void f() {\n"
" const Token *tok;\n"
" if(a && b && tok && Token::Match(tok, \"5str% foobar\")) {};\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Unnecessary check of \"tok\", match-function already checks if it is null.\n", errout_str());
check("void f() {\n"
" const Token *tok;\n"
" if(a && b && c && tok && Token::Match(tok, \"5str% foobar\")) {};\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Unnecessary check of \"tok\", match-function already checks if it is null.\n", errout_str());
check("void f() {\n"
" const Token *tok;\n"
" if(a && b && c && tok && d && Token::Match(tok, \"5str% foobar\")) {};\n"
"}");
ASSERT_EQUALS("", errout_str());
// simpleMatch
check("void f() {\n"
" const Token *tok;\n"
" if(tok && Token::simpleMatch(tok, \"foobar\")) {};\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Unnecessary check of \"tok\", match-function already checks if it is null.\n", errout_str());
// Match
check("void f() {\n"
" const Token *tok;\n"
" if(tok->previous() && Token::Match(tok->previous(), \"5str% foobar\")) {};\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Unnecessary check of \"tok->previous()\", match-function already checks if it is null.\n", errout_str());
// don't report:
// tok->previous() vs tok
check("void f() {\n"
" const Token *tok;\n"
" if(tok->previous() && Token::Match(tok, \"5str% foobar\")) {};\n"
"}");
ASSERT_EQUALS("", errout_str());
// tok vs tok->previous())
check("void f() {\n"
" const Token *tok;\n"
" if(tok && Token::Match(tok->previous(), \"5str% foobar\")) {};\n"
"}");
ASSERT_EQUALS("", errout_str());
// tok->previous() vs tok->previous()->previous())
check("void f() {\n"
" const Token *tok;\n"
" if(tok->previous() && Token::Match(tok->previous()->previous(), \"5str% foobar\")) {};\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Call to 'Token::previous()' followed by 'Token::previous()' can be simplified.\n", errout_str());
// if a && fn(a) triggers, make sure !a || !fn(a) triggers as well!
check("void f() {\n"
" const Token *tok;\n"
" if(!tok || !Token::simpleMatch(tok, \"foobar\")) {};\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Unnecessary check of \"tok\", match-function already checks if it is null.\n", errout_str());
check("void f() {\n"
" const Token *tok;\n"
" if(a || !tok || !Token::simpleMatch(tok, \"foobar\")) {};\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Unnecessary check of \"tok\", match-function already checks if it is null.\n", errout_str());
// if tok || !Token::simpleMatch...
check("void f() {\n"
" const Token *tok;\n"
" if(tok || !Token::simpleMatch(tok, \"foobar\")) {};\n"
"}");
ASSERT_EQUALS("", errout_str());
// if !tok || Token::simpleMatch...
check("void f() {\n"
" const Token *tok;\n"
" if(!tok || Token::simpleMatch(tok, \"foobar\")) {};\n"
"}");
ASSERT_EQUALS("", errout_str());
// something more complex
check("void f() {\n"
" const Token *tok;\n"
" if(!tok->previous()->previous() || !Token::simpleMatch(tok->previous()->previous(), \"foobar\")) {};\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Call to 'Token::previous()' followed by 'Token::previous()' can be simplified.\n"
"[test.cpp:3]: (style) Call to 'Token::previous()' followed by 'Token::previous()' can be simplified.\n"
"[test.cpp:3]: (style) Unnecessary check of \"tok->previous()->previous()\", match-function already checks if it is null.\n", errout_str());
}
};
REGISTER_TEST(TestInternal)
#endif // #ifdef CHECK_INTERNAL
| null |
1,019 | cpp | cppcheck | testnullpointer.cpp | test/testnullpointer.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#include "check.h"
#include "checknullpointer.h"
#include "ctu.h"
#include "errortypes.h"
#include "fixture.h"
#include "helpers.h"
#include "library.h"
#include "settings.h"
#include "token.h"
#include "tokenize.h"
#include <cstddef>
#include <list>
#include <string>
#include <vector>
class TestNullPointer : public TestFixture {
public:
TestNullPointer() : TestFixture("TestNullPointer") {}
private:
const Settings settings = settingsBuilder().library("std.cfg").severity(Severity::warning).build();
void run() override {
TEST_CASE(nullpointerAfterLoop);
TEST_CASE(nullpointer1);
TEST_CASE(nullpointer2);
TEST_CASE(structDerefAndCheck); // dereferencing struct and then checking if it's null
TEST_CASE(pointerDerefAndCheck);
TEST_CASE(nullpointer5); // References should not be checked
TEST_CASE(nullpointerExecutionPaths);
TEST_CASE(nullpointerExecutionPathsLoop);
TEST_CASE(nullpointer7);
TEST_CASE(nullpointer9);
TEST_CASE(nullpointer10);
TEST_CASE(nullpointer11); // ticket #2812
TEST_CASE(nullpointer12); // ticket #2470
TEST_CASE(nullpointer15); // #3560 (fp: return p ? f(*p) : f(0))
TEST_CASE(nullpointer16); // #3591
TEST_CASE(nullpointer17); // #3567
TEST_CASE(nullpointer18); // #1927
TEST_CASE(nullpointer19); // #3811
TEST_CASE(nullpointer20); // #3807 (fp: return p ? (p->x() || p->y()) : z)
TEST_CASE(nullpointer21); // #4038 (fp: if (x) p=q; else return;)
TEST_CASE(nullpointer23); // #4665 (false positive)
TEST_CASE(nullpointer24); // #5082 fp: chained assignment
TEST_CASE(nullpointer25); // #5061
TEST_CASE(nullpointer26); // #3589
TEST_CASE(nullpointer27); // #6568
TEST_CASE(nullpointer28); // #6491
TEST_CASE(nullpointer30); // #6392
TEST_CASE(nullpointer31); // #8482
TEST_CASE(nullpointer32); // #8460
TEST_CASE(nullpointer33);
TEST_CASE(nullpointer34);
TEST_CASE(nullpointer35);
TEST_CASE(nullpointer36); // #9264
TEST_CASE(nullpointer37); // #9315
TEST_CASE(nullpointer38);
TEST_CASE(nullpointer39); // #2153
TEST_CASE(nullpointer40);
TEST_CASE(nullpointer41);
TEST_CASE(nullpointer42);
TEST_CASE(nullpointer43); // #9404
TEST_CASE(nullpointer44); // #9395, #9423
TEST_CASE(nullpointer45);
TEST_CASE(nullpointer46); // #9441
TEST_CASE(nullpointer47); // #6850
TEST_CASE(nullpointer48); // #9196
TEST_CASE(nullpointer49); // #7804
TEST_CASE(nullpointer50); // #6462
TEST_CASE(nullpointer51);
TEST_CASE(nullpointer52);
TEST_CASE(nullpointer53); // #8005
TEST_CASE(nullpointer54); // #9573
TEST_CASE(nullpointer55); // #8144
TEST_CASE(nullpointer56); // #9701
TEST_CASE(nullpointer57); // #9751
TEST_CASE(nullpointer58); // #9807
TEST_CASE(nullpointer59); // #9897
TEST_CASE(nullpointer60); // #9842
TEST_CASE(nullpointer61);
TEST_CASE(nullpointer62);
TEST_CASE(nullpointer63);
TEST_CASE(nullpointer64);
TEST_CASE(nullpointer65); // #9980
TEST_CASE(nullpointer66); // #10024
TEST_CASE(nullpointer67); // #10062
TEST_CASE(nullpointer68);
TEST_CASE(nullpointer69); // #8143
TEST_CASE(nullpointer70);
TEST_CASE(nullpointer71); // #10178
TEST_CASE(nullpointer72); // #10215
TEST_CASE(nullpointer73); // #10321
TEST_CASE(nullpointer74);
TEST_CASE(nullpointer75);
TEST_CASE(nullpointer76); // #10408
TEST_CASE(nullpointer77);
TEST_CASE(nullpointer78); // #7802
TEST_CASE(nullpointer79); // #10400
TEST_CASE(nullpointer80); // #10410
TEST_CASE(nullpointer81); // #8724
TEST_CASE(nullpointer82); // #10331
TEST_CASE(nullpointer83); // #9870
TEST_CASE(nullpointer84); // #9873
TEST_CASE(nullpointer85); // #10210
TEST_CASE(nullpointer86);
TEST_CASE(nullpointer87); // #9291
TEST_CASE(nullpointer88); // #9949
TEST_CASE(nullpointer89); // #10640
TEST_CASE(nullpointer90); // #6098
TEST_CASE(nullpointer91); // #10678
TEST_CASE(nullpointer92);
TEST_CASE(nullpointer93); // #3929
TEST_CASE(nullpointer94); // #11040
TEST_CASE(nullpointer95); // #11142
TEST_CASE(nullpointer96); // #11416
TEST_CASE(nullpointer97); // #11229
TEST_CASE(nullpointer98); // #11458
TEST_CASE(nullpointer99); // #10602
TEST_CASE(nullpointer100); // #11636
TEST_CASE(nullpointer101); // #11382
TEST_CASE(nullpointer102);
TEST_CASE(nullpointer103);
TEST_CASE(nullpointer_addressOf); // address of
TEST_CASE(nullpointerSwitch); // #2626
TEST_CASE(nullpointer_cast); // #4692
TEST_CASE(nullpointer_castToVoid); // #3771
TEST_CASE(nullpointer_subfunction);
TEST_CASE(pointerCheckAndDeRef); // check if pointer is null and then dereference it
TEST_CASE(nullConstantDereference); // Dereference NULL constant
TEST_CASE(gcc_statement_expression); // Don't crash
TEST_CASE(snprintf_with_zero_size);
TEST_CASE(snprintf_with_non_zero_size);
TEST_CASE(printf_with_invalid_va_argument);
TEST_CASE(scanf_with_invalid_va_argument);
TEST_CASE(nullpointer_in_return);
TEST_CASE(nullpointer_in_typeid);
TEST_CASE(nullpointer_in_alignof); // #11401
TEST_CASE(nullpointer_in_for_loop);
TEST_CASE(nullpointerDeadCode); // #11311
TEST_CASE(nullpointerDelete);
TEST_CASE(nullpointerSubFunction);
TEST_CASE(nullpointerExit);
TEST_CASE(nullpointerStdString);
TEST_CASE(nullpointerStdStream);
TEST_CASE(nullpointerSmartPointer);
TEST_CASE(nullpointerOutOfMemory);
TEST_CASE(functioncall);
TEST_CASE(functioncalllibrary); // use Library to parse function call
TEST_CASE(functioncallDefaultArguments);
TEST_CASE(nullpointer_internal_error); // #5080
TEST_CASE(ticket6505);
TEST_CASE(subtract);
TEST_CASE(addNull);
TEST_CASE(isPointerDeRefFunctionDecl);
TEST_CASE(ctuTest);
}
#define check(...) check_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
void check_(const char* file, int line, const char (&code)[size], bool inconclusive = false, bool cpp = true) {
const Settings settings1 = settingsBuilder(settings).certainty(Certainty::inconclusive, inconclusive).build();
// Tokenize..
SimpleTokenizer tokenizer(settings1, *this);
ASSERT_LOC(tokenizer.tokenize(code, cpp), file, line);
// Check for null pointer dereferences..
runChecks<CheckNullPointer>(tokenizer, this);
}
#define checkP(...) checkP_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
void checkP_(const char* file, int line, const char (&code)[size]) {
const Settings settings1 = settingsBuilder(settings).certainty(Certainty::inconclusive, false).build();
std::vector<std::string> files(1, "test.cpp");
Tokenizer tokenizer(settings1, *this);
PreprocessorHelper::preprocess(code, files, tokenizer, *this);
// Tokenizer..
ASSERT_LOC(tokenizer.simplifyTokens1(""), file, line);
// Check for null pointer dereferences..
runChecks<CheckNullPointer>(tokenizer, this);
}
void nullpointerAfterLoop() {
// extracttests.start: struct Token { const Token *next() const; std::string str() const; };
check("void foo(const Token *tok)\n"
"{\n"
" while (tok);\n"
" tok = tok->next();\n"
"}", true);
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (warning) Either the condition 'tok' is redundant or there is possible null pointer dereference: tok.\n", errout_str());
// #2681
{
const char code[] = "void foo(const Token *tok)\n"
"{\n"
" while (tok && tok->str() == \"=\")\n"
" tok = tok->next();\n"
"\n"
" if (tok->str() != \";\")\n"
" ;\n"
"}\n";
check(code);
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:6]: (warning) Either the condition 'tok' is redundant or there is possible null pointer dereference: tok.\n", errout_str());
}
check("void foo()\n"
"{\n"
" for (const Token *tok = tokens; tok; tok = tok->next())\n"
" {\n"
" while (tok && tok->str() != \";\")\n"
" tok = tok->next();\n"
" }\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:3]: (warning) Either the condition 'while' is redundant or there is possible null pointer dereference: tok.\n", "", errout_str());
check("void foo(Token &tok)\n"
"{\n"
" for (int i = 0; i < tok.size(); i++ )\n"
" {\n"
" while (!tok)\n"
" char c = tok.read();\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo()\n"
"{\n"
" for (const Token *tok = tokens; tok; tok = tok->next())\n"
" {\n"
" while (tok && tok->str() != \";\")\n"
" tok = tok->next();\n"
" if( !tok ) break;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo()\n"
"{\n"
" for (const Token *tok = tokens; tok; tok = tok ? tok->next() : NULL)\n"
" {\n"
" while (tok && tok->str() != \";\")\n"
" tok = tok->next();\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(A*a)\n"
"{\n"
" switch (a->b()) {\n"
" case 1:\n"
" while( a ){\n"
" a = a->next;\n"
" }\n"
" break;\n"
" case 2:\n"
" a->b();\n"
" break;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// dereference in outer scope..
check("void foo(int x, const Token *tok) {\n"
" if (x == 123) {\n"
" while (tok) tok = tok->next();\n"
" }\n"
" tok->str();\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:5]: (warning) Either the condition 'tok' is redundant or there is possible null pointer dereference: tok.\n", errout_str());
check("int foo(const Token *tok)\n"
"{\n"
" while (tok){;}\n"
"}\n", true);
ASSERT_EQUALS("", errout_str());
check("int foo(const Token *tok)\n"
"{\n"
" while (tok){;}\n"
" char a[2] = {0,0};\n"
"}\n", true);
ASSERT_EQUALS("", errout_str());
check("struct b {\n"
" b * c;\n"
" int i;\n"
"}\n"
"void a(b * e) {\n"
" for (b *d = e;d; d = d->c)\n"
" while (d && d->i == 0)\n"
" d = d->c;\n"
" if (!d) throw;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct b {\n"
" b * c;\n"
" int i;\n"
"};\n"
"void f(b* e1, b* e2) {\n"
" for (const b* d = e1; d != e2; d = d->c) {\n"
" if (d && d->i != 0) {}\n"
" }\n"
"}\n");
ASSERT_EQUALS("[test.cpp:7] -> [test.cpp:6]: (warning) Either the condition 'd' is redundant or there is possible null pointer dereference: d.\n", errout_str());
}
void nullpointer1() {
// ticket #1923 - no false positive when using else if
check("void f(A *a)\n"
"{\n"
" if (a->x == 1)\n"
" {\n"
" a = a->next;\n"
" }\n"
" else if (a->x == 2) { }\n"
" if (a) { }\n"
"}");
ASSERT_EQUALS("", errout_str());
// ticket #2134 - sizeof doesn't dereference
check("void f() {\n"
" int c = 1;\n"
" int *list = NULL;\n"
" sizeof(*list);\n"
" if (!list)\n"
" ;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
// ticket #2245 - sizeof doesn't dereference
check("void f(Bar *p) {\n"
" if (!p) {\n"
" int sz = sizeof(p->x);\n"
" }\n"
"}", true);
ASSERT_EQUALS("", errout_str());
}
void nullpointer2() {
// Null pointer dereference can only happen with pointers
check("void foo()\n"
"{\n"
" Fred fred;\n"
" while (fred);\n"
" fred.hello();\n"
"}", true);
ASSERT_EQUALS("", errout_str());
}
// Dereferencing a struct and then checking if it is null
// This is checked by this function:
// CheckOther::nullPointerStructByDeRefAndCheck
void structDerefAndCheck() {
// extracttests.start: struct ABC { int a; int b; int x; };
// errors..
check("void foo(struct ABC *abc)\n"
"{\n"
" int a = abc->a;\n"
" if (!abc)\n"
" ;\n"
"}");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:3]: (warning) Either the condition '!abc' is redundant or there is possible null pointer dereference: abc.\n", errout_str());
check("void foo(struct ABC *abc) {\n"
" bar(abc->a);\n"
" bar(x, abc->a);\n"
" bar(x, y, abc->a);\n"
" if (!abc)\n"
" ;\n"
"}");
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:2]: (warning) Either the condition '!abc' is redundant or there is possible null pointer dereference: abc.\n"
"[test.cpp:5] -> [test.cpp:3]: (warning) Either the condition '!abc' is redundant or there is possible null pointer dereference: abc.\n"
"[test.cpp:5] -> [test.cpp:4]: (warning) Either the condition '!abc' is redundant or there is possible null pointer dereference: abc.\n", errout_str());
check("void foo(ABC *abc) {\n"
" if (abc->a == 3) {\n"
" return;\n"
" }\n"
" if (abc) {}\n"
"}");
ASSERT_EQUALS(
"[test.cpp:5] -> [test.cpp:2]: (warning) Either the condition 'abc' is redundant or there is possible null pointer dereference: abc.\n",
errout_str());
check("void f(ABC *abc) {\n"
" if (abc->x == 0) {\n"
" return;\n"
" }\n"
" if (!abc);\n"
"}");
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:2]: (warning) Either the condition '!abc' is redundant or there is possible null pointer dereference: abc.\n", errout_str());
// TODO: False negative if member of member is dereferenced
check("void foo(ABC *abc) {\n"
" abc->next->a = 0;\n"
" if (abc->next)\n"
" ;\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:2]: (warning) Possible null pointer dereference: abc - otherwise it is redundant to check it against null.\n", "", errout_str());
check("void foo(ABC *abc) {\n"
" abc->a = 0;\n"
" if (abc && abc->b == 0)\n"
" ;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3] -> [test.cpp:2]: (warning) Either the condition 'abc' is redundant or there is possible null pointer dereference: abc.\n",
errout_str());
// ok dereferencing in a condition
check("void foo(struct ABC *abc)\n"
"{\n"
" if (abc && abc->a);\n"
" if (!abc)\n"
" ;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(struct ABC *abc) {\n"
" int x = abc && a(abc->x);\n"
" if (abc) { }\n"
"}");
ASSERT_EQUALS("", errout_str());
// ok to use a linked list..
check("void foo(struct ABC *abc)\n"
"{\n"
" abc = abc->next;\n"
" if (!abc)\n"
" ;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("void f(struct ABC *abc) {\n"
" abc = (ABC *)(abc->_next);\n"
" if (abc) { }"
"}", true);
ASSERT_EQUALS("", errout_str());
// reassign struct..
check("void foo(struct ABC *abc)\n"
"{\n"
" int a = abc->a;\n"
" abc = abc->next;\n"
" if (!abc)\n"
" ;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("void foo(struct ABC *abc)\n"
"{\n"
" int a = abc->a;\n"
" f(&abc);\n"
" if (!abc)\n"
" ;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
// goto..
check("void foo(struct ABC *abc)\n"
"{\n"
" int a;\n"
" if (!abc)\n"
" goto out;"
" a = abc->a;\n"
" return;\n"
"out:\n"
" if (!abc)\n"
" ;\n"
"}");
ASSERT_EQUALS("", errout_str());
// loops..
check("void foo(struct ABC *abc)\n"
"{\n"
" int a = abc->a;"
" do\n"
" {\n"
" if (abc)\n"
" abc = abc->next;\n"
" --a;\n"
" }\n"
" while (a > 0);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f()\n"
"{\n"
" for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next())\n"
" {\n"
" while (tok && tok->str() != \"{\")\n"
" tok = tok->next();\n"
" if (!tok)\n"
" return;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// dynamic_cast..
check("void foo(ABC *abc)\n"
"{\n"
" int a = abc->a;\n"
" if (!dynamic_cast<DEF *>(abc))\n"
" ;\n"
"}");
ASSERT_EQUALS("", errout_str());
// #2641 - global pointer, function call
check("ABC *abc;\n"
"void f() {\n"
" abc->a = 0;\n"
" do_stuff();\n"
" if (abc) { }\n"
"}");
ASSERT_EQUALS("",errout_str());
check("Fred *fred;\n"
"void f() {\n"
" fred->foo();\n"
" if (fred) { }\n"
"}");
ASSERT_EQUALS("",errout_str());
// #2641 - local pointer, function call
check("void f() {\n"
" ABC *abc = abc1;\n"
" abc->a = 0;\n"
" do_stuff();\n"
" if (abc) { }\n"
"}");
ASSERT_EQUALS(
"[test.cpp:5] -> [test.cpp:3]: (warning) Either the condition 'abc' is redundant or there is possible null pointer dereference: abc.\n",
errout_str());
// #2641 - local pointer, function call
check("void f(ABC *abc) {\n"
" abc->a = 0;\n"
" do_stuff();\n"
" if (abc) { }\n"
"}");
ASSERT_EQUALS(
"[test.cpp:4] -> [test.cpp:2]: (warning) Either the condition 'abc' is redundant or there is possible null pointer dereference: abc.\n",
errout_str());
// #2691 - switch/break
check("void f(ABC *abc) {\n"
" switch ( x ) {\n"
" case 14:\n"
" sprintf(buf, \"%d\", abc->a);\n"
" break;\n"
" case 15:\n"
" if ( abc ) {}\n"
" break;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// #3128
check("void f(ABC *abc) {\n"
" x(!abc || y(abc->a));\n"
" if (abc) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(ABC *abc) {\n"
" x(def || !abc || y(def, abc->a));\n"
" if (abc) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(ABC *abc) {\n"
" x(abc && y(def, abc->a));\n"
" if (abc) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(ABC *abc) {\n"
" x(def && abc && y(def, abc->a));\n"
" if (abc) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
// #3228 - calling function with null object
{
const char code[] = "void f(Fred *fred) {\n"
" fred->x();\n"
" if (fred) { }\n"
"}";
check(code);
ASSERT_EQUALS(
"[test.cpp:3] -> [test.cpp:2]: (warning) Either the condition 'fred' is redundant or there is possible null pointer dereference: fred.\n",
errout_str());
}
// #3425 - false positives when there are macros
checkP("#define IF if\n"
"void f(struct FRED *fred) {\n"
" fred->x = 0;\n"
" IF(!fred){}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" BUFFER *buffer = get_buffer();\n"
" if (!buffer)\n"
" uv_fatal_error();\n"
" buffer->x = 11;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
// Dereferencing a pointer and then checking if it is null
void pointerDerefAndCheck() {
// extracttests.start: void bar(int);
// errors..
check("void foo(int *p)\n"
"{\n"
" *p = 0;\n"
" if (!p)\n"
" ;\n"
"}");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:3]: (warning) Either the condition '!p' is redundant or there is possible null pointer dereference: p.\n", errout_str());
check("void foo(int *p)\n"
"{\n"
" *p = 0;\n"
" if (p) { }\n"
"}");
ASSERT_EQUALS(
"[test.cpp:4] -> [test.cpp:3]: (warning) Either the condition 'p' is redundant or there is possible null pointer dereference: p.\n",
errout_str());
check("void foo(int *p)\n"
"{\n"
" *p = 0;\n"
" if (p || q) { }\n"
"}");
ASSERT_EQUALS(
"[test.cpp:4] -> [test.cpp:3]: (warning) Either the condition 'p' is redundant or there is possible null pointer dereference: p.\n",
errout_str());
check("void foo(int *p)\n"
"{\n"
" bar(*p);\n"
" if (!p)\n"
" ;\n"
"}");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:3]: (warning) Either the condition '!p' is redundant or there is possible null pointer dereference: p.\n", errout_str());
check("void foo(char *p)\n"
"{\n"
" strcpy(p, \"abc\");\n"
" if (!p)\n"
" ;\n"
"}");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:3]: (warning) Either the condition '!p' is redundant or there is possible null pointer dereference: p.\n", errout_str());
check("void foo(char *p)\n"
"{\n"
" if (*p == 0) { }\n"
" if (!p) { }\n"
"}");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:3]: (warning) Either the condition '!p' is redundant or there is possible null pointer dereference: p.\n", errout_str());
// no error
check("void foo()\n"
"{\n"
" int *p;\n"
" f(&p);\n"
" if (!p)\n"
" ;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo()\n"
"{\n"
" int **p = f();\n"
" if (!p)\n"
" ;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("void foo(int *p)\n"
"{\n"
" if (x)\n"
" p = 0;\n"
" else\n"
" *p = 0;\n"
" if (!p)\n"
" ;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(int x)\n"
"{\n"
" int a = 2 * x;"
" if (x == 0)\n"
" ;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("void foo(int *p)\n"
"{\n"
" int var1 = p ? *p : 0;\n"
" if (!p)\n"
" ;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(int *p, bool x)\n"
"{\n"
" int var1 = x ? *p : 5;\n"
" if (!p)\n"
" ;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:4] -> [test.cpp:3]: (warning) Either the condition '!p' is redundant or there is possible null pointer dereference: p.\n",
errout_str());
// while
check("void f(int *p) {\n"
" *p = 0;\n"
" while (p) { p = 0; }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int *p) {\n"
" *p = 0;\n"
" while (p) { }\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3] -> [test.cpp:2]: (warning) Either the condition 'p' is redundant or there is possible null pointer dereference: p.\n",
errout_str());
// Ticket #3125
check("void foo(ABC *p)\n"
"{\n"
" int var1 = p ? (p->a) : 0;\n"
" if (!p)\n"
" ;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(ABC *p)\n"
"{\n"
" int var1 = p ? (1 + p->a) : 0;\n"
" if (!p)\n"
" ;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int * a=0;\n"
" if (!a) {};\n"
" int c = a ? 0 : 1;\n"
"}\n",true);
ASSERT_EQUALS("", errout_str());
// #3686
check("void f() {\n"
" int * a=0;\n"
" if (!a) {};\n"
" int c = a ? b : b+1;\n"
"}\n",true);
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int * a=0;\n"
" if (!a) {};\n"
" int c = (a) ? b : b+1;\n"
"}\n",true);
ASSERT_EQUALS("", errout_str());
check("void foo(P *p)\n"
"{\n"
" while (p)\n"
" if (p->check())\n"
" break;\n"
" else\n"
" p = p->next();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(Document *doc) {\n"
" int x = doc && doc->x;\n"
" if (!doc) {\n"
" return;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// #3128 - false positive
check("void f(int *p) {\n"
" assert(!p || (*p<=6));\n"
" if (p) { *p = 0; }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int *p) {\n"
" assert(p && (*p<=6));\n"
" if (p) { *p = 0; }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int *p) {\n"
" *p = 12;\n"
" assert(p && (*p<=6));\n"
" if (p) { *p = 0; }\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3] -> [test.cpp:2]: (warning) Either the condition 'p' is redundant or there is possible null pointer dereference: p.\n",
errout_str());
check("void foo(x *p)\n"
"{\n"
" p = p->next;\n"
" if (!p)\n"
" ;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(x *p)\n"
"{\n"
" p = bar(p->next);\n"
" if (!p)\n"
" ;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(x *p)\n"
"{\n"
" p = aa->bar(p->next);\n"
" if (!p)\n"
" ;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(x *p)\n"
"{\n"
" p = *p2 = p->next;\n"
" if (!p)\n"
" ;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(struct ABC *abc)\n"
"{\n"
" abc = abc ? abc->next : 0;\n"
" if (!abc)\n"
" ;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(struct ABC *abc) {\n" // #4523
" abc = (*abc).next;\n"
" if (abc) { }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(struct ABC *abc) {\n" // #4523
" abc = (*abc->ptr);\n"
" if (abc) { }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int f(Item *item) {\n"
" x = item ? ab(item->x) : 0;\n"
" if (item) { }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int f(Item *item) {\n"
" item->x = 0;\n"
" a = b ? c : d;\n"
" if (item) { }\n"
"}");
ASSERT_EQUALS(
"[test.cpp:4] -> [test.cpp:2]: (warning) Either the condition 'item' is redundant or there is possible null pointer dereference: item.\n",
errout_str());
check("BOOL GotoFlyAnchor()\n" // #2243
"{\n"
" const SwFrm* pFrm = GetCurrFrm();\n"
" do {\n"
" pFrm = pFrm->GetUpper();\n"
" } while( pFrm && !pFrm->IsFlyFrm() );\n"
"\n"
" if( !pFrm )\n"
" return FALSE;\n"
"}");
ASSERT_EQUALS("", errout_str());
// Ticket #2463
check("struct A\n"
"{\n"
" B* W;\n"
"\n"
" void f() {\n"
" switch (InData) {\n"
" case 2:\n"
" if (!W) return;\n"
" W->foo();\n"
" break;\n"
" case 3:\n"
" f();\n"
" if (!W) return;\n"
" break;\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// #2525 - sizeof
check("void f() {\n"
" int *test = NULL;\n"
" int c = sizeof(test[0]);\n"
" if (!test)\n"
" ;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("void f(type* p) {\n" // #4983
" x(sizeof p[0]);\n"
" if (!p)\n"
" ;\n"
"}");
ASSERT_EQUALS("", errout_str());
// #3023 - checked deref
check("void f(struct ABC *abc) {\n"
" WARN_ON(!abc || abc->x == 0);\n"
" if (!abc) { }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(struct ABC *abc) {\n"
" WARN_ON(!abc || abc->x == 7);\n"
" if (!abc) { }\n"
"}");
ASSERT_EQUALS("", errout_str());
// #3425 - false positives when there are macros
checkP("#define IF if\n"
"void f(int *p) {\n"
" *p = 0;\n"
" IF(!p){}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n" // #3914 - false positive
" int *p;\n"
" ((p=ret()) && (x=*p));\n"
" if (p);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct S { struct T { char c; } *p; };\n" // #6541
"char f(S* s) { return s->p ? 'a' : s->p->c; }\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:2]: (warning) Either the condition 's->p' is redundant or there is possible null pointer dereference: s->p.\n",
errout_str());
}
void nullpointer5() {
// errors..
check("void foo(A &a)\n"
"{\n"
" char c = a.c();\n"
" if (!a)\n"
" return;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
// Execution paths..
void nullpointerExecutionPaths() {
// errors..
check("static void foo()\n"
"{\n"
" Foo *p = 0;\n"
" if (a == 1) {\n"
" p = new FooBar;\n"
" } else { if (a == 2) {\n"
" p = new FooCar; } }\n"
" p->abcd();\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:8]: (error) Possible null pointer dereference: p\n",
"", errout_str());
check("static void foo() {\n"
" int &r = *(int*)0;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Null pointer dereference: (int*)0\n", errout_str());
check("static void foo(int x) {\n"
" int y = 5 + *(int*)0;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Null pointer dereference: (int*)0\n", errout_str());
{
const char code[] = "static void foo() {\n"
" Foo<int> *abc = 0;\n"
" abc->a();\n"
"}\n";
check(code);
ASSERT_EQUALS("[test.cpp:3]: (error) Null pointer dereference: abc\n", errout_str());
}
check("static void foo() {\n"
" std::cout << *(int*)0;"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Null pointer dereference: (int*)0\n", errout_str());
check("void f()\n"
"{\n"
" char *c = 0;\n"
" {\n"
" delete c;\n"
" }\n"
" c[0] = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (error) Null pointer dereference: c\n", errout_str());
check("static void foo() {\n"
" if (3 > *(int*)0);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Null pointer dereference: (int*)0\n", errout_str());
// no false positive..
check("static void foo()\n"
"{\n"
" Foo *p = 0;\n"
" p = new Foo;\n"
" p->abcd();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo()\n"
"{\n"
" int sz = sizeof((*(struct dummy *)0).x);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void get_offset(long &offset)\n"
"{\n"
" mystruct * temp; temp = 0;\n"
" offset = (long)(&(temp->z));\n"
"}");
ASSERT_EQUALS("", errout_str());
// Ticket #1893 - try/catch inside else
check("int *test(int *Z)\n"
"{\n"
" int *Q=NULL;\n"
" if (Z) {\n"
" Q = Z;\n"
" }\n"
" else {\n"
" Z = new int;\n"
" try {\n"
" } catch(...) {\n"
" }\n"
" Q = Z;\n"
" }\n"
" *Q=1;\n"
" return Q;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int *test(int *Z)\n"
"{\n"
" int *Q=NULL;\n"
" if (Z) {\n"
" Q = Z;\n"
" }\n"
" else {\n"
" try {\n"
" } catch(...) {\n"
" }\n"
" }\n"
" *Q=1;\n"
" return Q;\n"
"}");
ASSERT_EQUALS("[test.cpp:12]: (warning) Possible null pointer dereference: Q\n", errout_str());
// Ticket #2052 (false positive for 'else continue;')
check("void f() {\n"
" for (int x = 0; x < 5; ++x) {"
" int *p = 0;\n"
" if (a(x)) p=b(x);\n"
" else continue;\n"
" *p = 0;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// function pointer..
check("void foo()\n"
"{\n"
" void (*f)();\n"
" f = 0;\n"
" f();\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Null pointer dereference: f\n", errout_str());
check("int* g();\n" // #11007
"int* f() {\n"
" static int* (*fun)() = 0;\n"
" if (!fun)\n"
" fun = g;\n"
" return fun();\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// loops..
check("void f() {\n"
" int *p = 0;\n"
" for (int i = 0; i < 10; ++i) {\n"
" int x = *p + 1;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Null pointer dereference: p\n", errout_str());
check("void f(int a) {\n"
" const char *p = 0;\n"
" if (a) {\n"
" p = \"abcd\";\n"
" }\n"
" for (int i = 0; i < 3; i++) {\n"
" if (a && (p[i] == '1'));\n"
" }\n"
"}", true);
ASSERT_EQUALS("", errout_str());
// ticket #2251: taking the address of member
check("void f() {\n"
" Fred *fred = 0;\n"
" int x = &fred->x;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
// ticket #3220: dereferencing a null pointer is UB
check("void f() {\n"
" Fred *fred = NULL;\n"
" fred->do_something();\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Null pointer dereference: fred\n", errout_str());
// ticket #3570 - parsing of conditions
{
check("void f() {\n"
" int *p = NULL;\n"
" if (x)\n"
" p = q;\n"
" if (p && *p) { }\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int *p = NULL;\n"
" if (x)\n"
" p = q;\n"
" if (!p || *p) { }\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int *p = NULL;\n"
" if (x)\n"
" p = q;\n"
" if (p || *p) { }\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (warning) Possible null pointer dereference: p\n", errout_str());
}
// ticket #8831 - FP triggered by if/return/else sequence
{
check("void f(int *p, int *q) {\n"
" if (p == NULL)\n"
" return;\n"
" else if (q == NULL)\n"
" return;\n"
" *q = 0;\n"
"}\n"
"\n"
"void g() {\n"
" f(NULL, NULL);\n"
"}", true);
ASSERT_EQUALS("", errout_str());
}
check("void f() {\n" // #5979
" int* const crash = 0;\n"
" *crash = 0;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (error) Null pointer dereference: crash\n", errout_str());
}
// Ticket #2350
void nullpointerExecutionPathsLoop() {
// No false positive:
check("void foo() {\n"
" int n;\n"
" int *argv32 = p;\n"
" if (x) {\n"
" n = 0;\n"
" argv32 = 0;\n"
" }\n"
"\n"
" for (int i = 0; i < n; i++) {\n"
" argv32[i] = 0;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// No false negative:
check("void foo() {\n"
" int n;\n"
" int *argv32;\n"
" if (x) {\n"
" n = 10;\n"
" argv32 = 0;\n"
" }\n"
"\n"
" for (int i = 0; i < n; i++) {\n"
" argv32[i] = 0;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:10]: (warning) Possible null pointer dereference: argv32\n", errout_str());
// #2231 - error if assignment in loop is not used
// extracttests.start: int y[20];
check("void f() {\n"
" char *p = 0;\n"
"\n"
" for (int x = 0; x < 3; ++x) {\n"
" if (y[x] == 0) {\n"
" p = (char *)malloc(10);\n"
" break;\n"
" }\n"
" }\n"
"\n"
" *p = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:11]: (warning) Possible null pointer dereference: p\n", errout_str());
}
void nullpointer7() {
check("void foo()\n"
"{\n"
" wxLongLong x = 0;\n"
" int y = x.GetValue();\n"
"}", true);
ASSERT_EQUALS("", errout_str());
}
void nullpointer9() { //#ticket 1778
check("void foo()\n"
"{\n"
" std::string * x = 0;\n"
" *x = \"test\";\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Null pointer dereference: x\n", errout_str());
}
void nullpointer10() {
// extracttests.start: struct my_type { int x; };
check("void foo()\n"
"{\n"
" struct my_type* p = 0;\n"
" p->x = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Null pointer dereference: p\n", errout_str());
}
void nullpointer11() { // ticket #2812
// extracttests.start: struct my_type { int x; };
check("int foo()\n"
"{\n"
" struct my_type* p;\n"
" p = 0;\n"
" return p->x;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Null pointer dereference: p\n", errout_str());
}
void nullpointer12() { // ticket #2470, #4035
const char code[] = "int foo()\n"
"{\n"
" int* i = nullptr;\n"
" return *i;\n"
"}\n";
check(code, false, true); // C++ file => nullptr means NULL
ASSERT_EQUALS("[test.cpp:4]: (error) Null pointer dereference: i\n", errout_str());
check(code, false, false); // C file => nullptr does not mean NULL
ASSERT_EQUALS("", errout_str());
}
void nullpointer15() { // #3560
check("void f() {\n"
" char *p = 0;\n"
" if (x) p = \"abcd\";\n"
" return p ? f(*p) : f(0);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void nullpointer16() { // #3591
check("void foo() {\n"
" int *p = 0;\n"
" bar(&p);\n"
" *p = 0;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
}
void nullpointer17() { // #3567
check("int foo() {\n"
" int *p = 0;\n"
" if (x) { return 0; }\n"
" return !p || *p;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("int foo() {\n"
" int *p = 0;\n"
" if (x) { return 0; }\n"
" return p && *p;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
}
void nullpointer18() { // #1927
check("void f ()\n"
"{\n"
" int i=0;\n"
" char *str=NULL;\n"
" while (str[i])\n"
" {\n"
" i++;\n"
" };\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Null pointer dereference: str\n", errout_str());
}
void nullpointer19() { // #3811
check("int foo() {\n"
" perror(0);\n"
"}", true);
ASSERT_EQUALS("", errout_str());
}
void nullpointer20() { // #3807
check("void f(int x) {\n"
" struct xy *p = 0;\n"
" if (x) p = q;\n"
" if (p ? p->x || p->y : 0) { }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x) {\n" // false negative
" struct xy *p = 0;\n"
" if (x) p = q;\n"
" if (y ? p->x : p->y) { }\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:4]: (warning) Possible null pointer dereference: p\n", "", errout_str());
}
void nullpointer21() { // #4038 - fp: if (x) p=q; else return;
check("void f(int x) {\n"
" int *p = 0;\n"
" if (x) p = q;\n"
" else return;\n"
" *p = 0;\n" // <- p is not NULL
"}");
ASSERT_EQUALS("", errout_str());
}
void nullpointer23() { // #4665
check("void f(){\n"
" char *c = NULL;\n"
" char cBuf[10];\n"
" sprintf(cBuf, \"%s\", c ? c : \"0\" );\n"
"}");
ASSERT_EQUALS("",errout_str());
}
void nullpointer24() { // #5083 - fp: chained assignment
check("void f(){\n"
" char *c = NULL;\n"
" x = c = new char[10];\n"
" *c = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void nullpointer25() { // #5061
check("void f(int *data, int i)\n"
"{\n"
" int *array = NULL;\n"
" if (data == 1 && array[i] == 0)\n"
" std::cout << \"test\";\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Null pointer dereference: array\n", errout_str());
}
void nullpointer26() { // #3589
check("double foo() {\n"
" sk *t1 = foo();\n"
" sk *t2 = foo();\n"
" if ((!t1) && (!t2))\n"
" return 0.0;\n"
" if (t1 && (!t2))\n"
" return t1->Inter();\n"
" if (t2->GetT() == t)\n"
" return t2->Inter();\n"
" if (t2 && (!t1))\n"
" return 0.0;\n"
" return 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void nullpointer27() { // #6568
check("template<class Type>\n"
"class Foo {\n"
" Foo<Type>& operator = ( Type* );\n"
"};\n"
"template<class Type>\n"
"Foo<Type>& Foo<Type>::operator = ( Type* pointer_ ) {\n"
" pointer_=NULL;\n"
" *pointer_=0;\n"
" return *this;\n"
"}");
ASSERT_EQUALS("[test.cpp:8]: (error) Null pointer dereference: pointer_\n", errout_str());
}
void nullpointer28() { // #6491
check("typedef struct { int value; } S;\n"
"int f(const S *s) {\n"
" int i = s ? s->value + 1\n"
" : s->value - 1; // <-- null ptr dereference\n"
" return i;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3] -> [test.cpp:4]: (warning) Either the condition 's' is redundant or there is possible null pointer dereference: s.\n",
errout_str());
}
void nullpointer30() { // #6392
check("void f(std::vector<std::string> *values)\n"
"{\n"
" values->clear();\n"
" if (values)\n"
" {\n"
" for (int i = 0; i < values->size(); ++i)\n"
" {\n"
" values->push_back(\"test\");\n"
" }\n"
" }\n"
"}\n", true);
ASSERT_EQUALS(
"[test.cpp:4] -> [test.cpp:3]: (warning) Either the condition 'values' is redundant or there is possible null pointer dereference: values.\n",
errout_str());
}
void nullpointer31() { // #8482
check("struct F\n"
"{\n"
" int x;\n"
"};\n"
"\n"
"static void foo(F* f)\n"
"{\n"
" if( f ) {}\n"
" else { return; }\n"
" (void)f->x;\n"
"}\n", true);
ASSERT_EQUALS("", errout_str());
check("typedef struct\n"
"{\n"
" int x;\n"
"} F;\n"
"\n"
"static void foo(F* f)\n"
"{\n"
" if( !f || f->x == 0 )\n"
" {\n"
" if( !f )\n"
" return;\n"
" }\n"
"\n"
" (void)f->x;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
}
void nullpointer32() { // #8460
check("int f(int * ptr) {\n"
" if(ptr)\n"
" { return 0;}\n"
" else{\n"
" int *p1 = ptr;\n"
" return *p1;\n"
" }\n"
"}\n", true);
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:6]: (warning) Either the condition 'ptr' is redundant or there is possible null pointer dereference: p1.\n", errout_str());
}
void nullpointer33() {
check("void f(int * x) {\n"
" if (x != nullptr)\n"
" *x = 2;\n"
" else\n"
" *x = 3;\n"
"}\n", true);
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:5]: (warning) Either the condition 'x!=nullptr' is redundant or there is possible null pointer dereference: x.\n", errout_str());
}
void nullpointer34() {
check("void g() {\n"
" throw " ";\n"
"}\n"
"bool f(int * x) {\n"
" if (x) *x += 1;\n"
" if (!x) g();\n"
" return *x;\n"
"}\n", true);
ASSERT_EQUALS("", errout_str());
}
void nullpointer35() {
check("bool f(int*);\n"
"void g(int* x) {\n"
" if (f(x)) {\n"
" *x = 1;\n"
" }\n"
"}\n"
"void h() {\n"
" g(0);\n"
"}\n", true);
ASSERT_EQUALS("", errout_str());
check("bool f(int*);\n"
"void g(int* x) {\n"
" bool b = f(x);\n"
" if (b) {\n"
" *x = 1;\n"
" }\n"
"}\n"
"void h() {\n"
" g(0);\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
}
void nullpointer36() {
check("char* f(char* s) {\n"
" char* start = s;\n"
" if (!s)\n"
" return (s);\n"
" while (isspace(*start))\n"
" start++;\n"
" return (start);\n"
"}\n", true);
ASSERT_EQUALS("", errout_str());
}
void nullpointer37() {
check("void f(int value, char *string) {\n"
" char *ptr1 = NULL, *ptr2 = NULL;\n"
" unsigned long count = 0;\n"
" if(!string)\n"
" return;\n"
" ptr1 = string;\n"
" ptr2 = strrchr(string, 'a');\n"
" if(ptr2 == NULL)\n"
" return;\n"
" while(ptr1 < ptr2) {\n"
" count++;\n"
" ptr1++;\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
}
void nullpointer38() {
check("void f(int * x) {\n"
" std::vector<int*> v;\n"
" if (x) {\n"
" v.push_back(x);\n"
" *x;\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
}
void nullpointer39() {
check("struct A { int * x; };\n"
"void f(struct A *a) {\n"
" if (a->x == NULL) {}\n"
" *(a->x);\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3] -> [test.cpp:4]: (warning) Either the condition 'a->x==NULL' is redundant or there is possible null pointer dereference: a->x.\n",
errout_str());
}
void nullpointer40() {
check("struct A { std::unique_ptr<int> x; };\n"
"void f(struct A *a) {\n"
" if (a->x == nullptr) {}\n"
" *(a->x);\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3] -> [test.cpp:4]: (warning) Either the condition 'a->x==nullptr' is redundant or there is possible null pointer dereference: a->x.\n",
errout_str());
}
void nullpointer41() {
check("struct A { int * g() const; };\n"
"void f(struct A *a) {\n"
" if (a->g() == nullptr) {}\n"
" *(a->g());\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3] -> [test.cpp:4]: (warning) Either the condition 'a->g()==nullptr' is redundant or there is possible null pointer dereference: a->g().\n",
errout_str());
check("struct A { int * g(); };\n"
"void f(struct A *a) {\n"
" if (a->g() == nullptr) {}\n"
" *(a->g());\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void nullpointer42() {
check("struct A { std::unique_ptr<int> g() const; };\n"
"void f(struct A *a) {\n"
" if (a->g() == nullptr) {}\n"
" *(a->g());\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3] -> [test.cpp:4]: (warning) Either the condition 'a->g()==nullptr' is redundant or there is possible null pointer dereference: a->g().\n",
errout_str());
}
void nullpointer43() {
check("struct A { int* x; };\n"
"void f(A* a) {\n"
" int * x = a->x;\n"
" if (x) {\n"
" (void)*a->x;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void nullpointer44() {
// #9395
check("int foo( ) {\n"
" const B* b = getB();\n"
" const double w = ( nullptr != b) ? 42. : 0.0;\n"
" if ( w == 0.0 )\n"
" return 0;\n"
" return b->get();\n"
"}");
ASSERT_EQUALS("", errout_str());
// #9423
check("extern F* GetF();\n"
"extern L* GetL();\n"
"void Foo() {\n"
" const F* const fPtr = GetF();\n"
" const bool fPtrOk = fPtr != NULL;\n"
" assert(fPtrOk);\n"
" if (!fPtrOk)\n"
" return;\n"
" L* const lPtr = fPtr->l;\n"
" const bool lPtrOk = lPtr != NULL;\n"
" assert(lPtrOk);\n"
" if (!lPtrOk)\n"
" return;\n"
" lPtr->Clear();\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void nullpointer45() {
check("struct a {\n"
" a *b() const;\n"
"};\n"
"void g() { throw 0; }\n"
"a h(a * c) {\n"
" if (c && c->b()) {}\n"
" if (!c)\n"
" g();\n"
" if (!c->b())\n"
" g();\n"
" a d = *c->b();\n"
" return d;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct a {\n"
" a *b() const;\n"
"};\n"
"void e() { throw 0; }\n"
"a f() {\n"
" a *c = 0;\n"
" if (0 && c->b()) {}\n"
" if (!c)\n"
" e();\n"
" if (!c->b())\n"
" e();\n"
" a d = *c->b();\n"
" return d;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void nullpointer46() {
check("void f() {\n"
" char* p = new(std::nothrow) char[1];\n"
" if( p ) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void nullpointer47() {
check("void f(int *p) {\n"
" if(!p[0]) {}\n"
" const int *const a = p;\n"
" if(!a){}\n"
"}");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:2]: (warning) Either the condition '!a' is redundant or there is possible null pointer dereference: p.\n", errout_str());
}
void nullpointer48() {
check("template<class T>\n"
"auto f(T& x) -> decltype(x);\n"
"int& g(int* x) {\n"
" return f(*x);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void nullpointer49() {
check("void f(int *p, int n) {\n"
" int *q = 0;\n"
" if(n > 10) q = p;\n"
" *p +=2;\n"
" if(n < 120) *q+=12;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (warning) Possible null pointer dereference: q\n", errout_str());
check("void f(int *p, int n) {\n"
" int *q = 0;\n"
" if(n > 10) q = p;\n"
" *p +=2;\n"
" if(n > 10) *q+=12;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void nullpointer50() {
check("void f(int *p, int a) {\n"
" if(!p) {\n"
" if(a > 0) {\n"
" if(a > 10){}\n"
" else {\n"
" *p = 0;\n"
" }\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS(
"[test.cpp:2] -> [test.cpp:6]: (warning) Either the condition '!p' is redundant or there is possible null pointer dereference: p.\n",
errout_str());
}
void nullpointer51() {
check("struct a {\n"
" a *b();\n"
"};\n"
"bool c(a *, const char *);\n"
"a *d(a *e) {\n"
" if (e) {}\n"
" if (c(e, \"\"))\n"
" return nullptr;\n"
" return e->b();\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void nullpointer52() {
check("int f(int a, int* b) {\n"
" int* c = nullptr;\n"
" if(b) c = b;\n"
" if (!c) c = &a;\n"
" return *c;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int f(int a, int* b) {\n"
" int* c = nullptr;\n"
" if(b) c = b;\n"
" bool d = !c;\n"
" if (d) c = &a;\n"
" return *c;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct A { int* x; };\n"
"int f(int a, int* b) {\n"
" A c;\n"
" c.x = nullptr;\n"
" if(b) c.x = b;\n"
" if (!c.x) c.x = &a;\n"
" return *c.x;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct A { int* x; };\n"
"int f(int a, int* b) {\n"
" A c;\n"
" c.x = nullptr;\n"
" if(b) c.x = b;\n"
" bool d = !c.x;\n"
" if (d) c.x = &a;\n"
" return *c.x;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct A { int* x; };\n"
"int f(int a, int* b) {\n"
" A c;\n"
" c.x = nullptr;\n"
" if(b) c.x = b;\n"
" bool d = !c.x;\n"
" if (!d) c.x = &a;\n"
" return *c.x;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:8]: (warning) Possible null pointer dereference: c.x\n", errout_str());
}
void nullpointer53() {
check("void f(int nParams, int* params) {\n"
" for (int n=1; n<nParams+10; ++n) {\n"
" params[n]=42;\n"
" }\n"
"}\n"
"void bar() {\n"
" f(0, 0);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Possible null pointer dereference: params\n", errout_str());
}
void nullpointer54() {
check("int foo (int **array, size_t n_array) {\n"
" size_t i;\n"
" for (i = 0; i < n_array; ++i) {\n"
" if (*array[i] == 1)\n"
" return 1;\n"
" }\n"
" return 0;\n"
"}\n"
"int bar() {\n"
" int **array = NULL;\n"
" foo (array, 0);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void nullpointer55() {
check("void f(const Token* tok) {\n"
" const Token* tok3 = tok;\n"
" while (tok3->astParent() && tok3->str() == \",\")\n"
" tok3 = tok3->astParent();\n"
" if (tok3 && tok3->str() == \"(\") {}\n"
"}");
ASSERT_EQUALS(
"[test.cpp:5] -> [test.cpp:3]: (warning) Either the condition 'tok3' is redundant or there is possible null pointer dereference: tok3.\n",
errout_str());
check("void f(int* t1, int* t2) {\n"
" while (t1 && t2 &&\n"
" *t1 == *t2) {\n"
" t1 = nullptr;\n"
" t2 = nullptr;\n"
" }\n"
" if (!t1 || !t2)\n"
" return;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("bool f(int* i);\n"
"void g(int* i) {\n"
" while(f(i) && *i == 0)\n"
" i++;\n"
" if (!i) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void nullpointer56() {
check("struct ListEntry {\n"
" struct ListEntry *next;\n"
"};\n"
"static void dostuff(ListEntry * listHead) {\n"
" ListEntry *prev = NULL;\n"
" for (ListEntry *cursor = listHead; cursor != NULL; prev = cursor, cursor = cursor->next) {}\n"
" if (prev) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void nullpointer57() {
check("void f() {\n"
" FILE* fptr = fopen(\"test\", \"r\");\n"
" if (fptr != nullptr) {\n"
" std::function<void()> fn([&] {\n"
" fclose(fptr);\n"
" fptr = NULL;\n"
" });\n"
" fgetc(fptr);\n"
" fn();\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void nullpointer58() {
check("struct myStruct { char entry[0]; };\n"
"void f() {\n"
" struct myStruct* sPtr = NULL;\n"
" int sz = (!*(&sPtr) || ((*(&sPtr))->entry[0] > 15)) ?\n"
" sizeof((*(&sPtr))->entry[0]) : 123456789;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void nullpointer59() {
check("struct Box {\n"
" struct Box* prev;\n"
" struct Box* next;\n"
"};\n"
"void foo(Box** pfreeboxes) {\n"
" Box *b = *pfreeboxes;\n"
" *pfreeboxes = b->next;\n"
" if( *pfreeboxes )\n"
" (*pfreeboxes)->prev = nullptr;\n"
" b->next = nullptr;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void nullpointer60() {
check("void f(){\n"
" char uuid[128];\n"
" char *s1;\n"
" memset(uuid, 0, sizeof(uuid));\n"
" s1 = strchr(uuid, '=');\n"
" s1 = s1 ? s1 + 1 : &uuid[5];\n"
" if (!strcmp(\"00000000000000000000000000000000\", s1) )\n"
" return;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void nullpointer61() {
check("struct a {\n"
" int *e;\n"
"};\n"
"struct f {\n"
" a *g() const;\n"
"};\n"
"void h() {\n"
" for (f b;;) {\n"
" a *c = b.g();\n"
" int *d = c->e;\n"
" if (d)\n"
" ;\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct A {\n"
" A* g() const;\n"
" A* h() const;\n"
"};\n"
"void f(A* a) {\n"
" if (!a->h())\n"
" return;\n"
" const A *b = a;\n"
" while (b && !b->h())\n"
" b = b->g();\n"
" if (!b || b == b->g()->h())\n"
" return;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void nullpointer62() {
check("struct A {\n"
" bool f()() const;\n"
"};\n"
"void a(A *x) {\n"
" std::string b = x && x->f() ? \"\" : \"\";\n"
" if (x) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct A {\n"
" bool f()() const;\n"
"};\n"
"void a(A *x) {\n"
" std::string b = (!x || x->f()) ? \"\" : \"\";\n"
" if (x) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct A {\n"
" A * aa;\n"
"};\n"
"void b(A*);\n"
"void a(A *x) {\n"
" b(x ? x->aa : nullptr);\n"
" if (!x) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void nullpointer63() {
check("struct A {\n"
" A* a() const;\n"
" A* b() const;\n"
"};\n"
"A* f(A*);\n"
"void g(const A* x) {\n"
" A *d = x->a();\n"
" d = f(d->b()) ? d->a() : nullptr;\n"
" if (d && f(d->b())) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void nullpointer64() {
check("struct A {\n"
" A* f() const;\n"
" int g() const;\n"
"};\n"
"bool a;\n"
"bool b(A* c) {\n"
" if (c->g() == 0)\n"
" ;\n"
" A *aq = c;\n"
" if (c->g() == 0)\n"
" c = c->f();\n"
" if (c)\n"
" for (A *d = c; d != aq; d = d->f()) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct A {\n"
" A* g() const;\n"
" A* h() const;\n"
"};\n"
"bool i(A*);\n"
"void f(A* x) {\n"
" if (i(x->g())) {\n"
" A *y = x->g();\n"
" x = x->g()->h();\n"
" if (x && x->g()) {\n"
" y = x->g()->h();\n"
" }\n"
" if (!y) {}\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void nullpointer65() {
check("struct A {\n"
" double get();\n"
"};\n"
"double x;\n"
"double run(A** begin, A** end) {\n"
" A* a = nullptr;\n"
" while (begin != end) {\n"
" a = *begin;\n"
" x = a->get();\n"
" ++begin;\n"
" }\n"
" x = 0;\n"
" if (a)\n"
" return a->get();\n"
" return 0;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void nullpointer66() {
check("int f() {\n"
" int ret = 0;\n"
" int *v = nullptr;\n"
" if (!MyAlloc(&v)) {\n"
" ret = -1;\n"
" goto done;\n"
" }\n"
" DoSomething(*v);\n"
"done:\n"
" if (v)\n"
" MyFree(&v);\n"
" return ret;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void nullpointer67() {
check("int result;\n"
"\n"
"int test_b(void) {\n"
" char **string = NULL;\n"
"\n"
" /* The bug disappears if \"result =\" is omitted. */\n"
" result = some_other_call(&string);\n"
" if (string && string[0])\n"
" return 0;\n"
" return -1;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("int result;\n"
"\n"
"int test_b(void) {\n"
" char **string = NULL;\n"
"\n"
" some_other_call(&string);\n"
" if (string && string[0])\n"
" return 0;\n"
" return -1;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void nullpointer68() {
check("struct A {\n"
" A* b;\n"
"};\n"
"void f(A* c) {\n"
" c = c->b;\n"
" if (c->b) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct A {\n"
" A* b;\n"
"};\n"
"void f(A* c) {\n"
" A* d = c->b;\n"
" A *e = c;\n"
" while (nullptr != (e = e->b)) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void nullpointer69() {
check("void f(const Scope *scope) {\n"
" if (scope->definedType) {}\n"
" while (scope) {\n"
" scope = scope->nestedIn;\n"
" enumerator = scope->findEnumerator();\n"
" }\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:3] -> [test.cpp:5]: (warning) Either the condition 'scope' is redundant or there is possible null pointer dereference: scope.\n",
errout_str());
check("void f(const Scope *scope) {\n"
" if (scope->definedType) {}\n"
" while (scope && scope->nestedIn) {\n"
" if (scope->type == Scope::eFunction && scope->functionOf)\n"
" scope = scope->functionOf;\n"
" else\n"
" scope = scope->nestedIn;\n"
" enumerator = scope->findEnumerator();\n"
" }\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:3] -> [test.cpp:8]: (warning) Either the condition 'scope' is redundant or there is possible null pointer dereference: scope.\n",
errout_str());
check("struct a {\n"
" a *b() const;\n"
" void c();\n"
"};\n"
"void d() {\n"
" for (a *e;;) {\n"
" e->b()->c();\n"
" while (e)\n"
" e = e->b();\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void nullpointer70() {
check("struct Token {\n"
" const Token* nextArgument() const;\n"
" const Token* next() const;\n"
" int varId() const;\n"
"};\n"
"int f(const Token *first, const Token* second) {\n"
" first = first->nextArgument();\n"
" if (first)\n"
" first = first->next();\n"
" if (second->next()->varId() == 0) {\n"
" second = second->nextArgument();\n"
" if (!first || !second)\n"
" return 0;\n"
" } else if (!first) {\n"
" return 0;\n"
" }\n"
" return first->varId();\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct Token {\n"
" const Token* nextArgument() const;\n"
" const Token* next() const;\n"
" int varId() const;\n"
" void str() const;"
"};\n"
"void f(const Token *first) {\n"
" first = first->nextArgument();\n"
" if (first)\n"
" first = first->next();\n"
" first->str();\n"
"}\n");
TODO_ASSERT_EQUALS(
"[test.cpp:8] -> [test.cpp:10]: (warning) Either the condition 'first' is redundant or there is possible null pointer dereference: first.\n",
"",
errout_str());
}
void nullpointer71() {
check("void f() {\n"
" Device* dev = Get();\n"
" SetCount(dev == nullptr ? 0 : dev->size());\n"
" if (dev)\n"
" DoSomething(dev);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" Device* dev = Get();\n"
" SetCount(dev != nullptr ? dev->size() : 0);\n"
" if (dev)\n"
" DoSomething(dev);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void nullpointer72() { // #10215
check("int test() {\n"
" int* p0 = nullptr, *p1 = nullptr;\n"
" getFoo(p0);\n"
" getBar(p1);\n"
" if (!(p0 != nullptr && p1 != nullptr))\n"
" return {};\n"
" return *p0 + *p1;\n"
"}\n", true /*inconclusive*/);
ASSERT_EQUALS("", errout_str());
check("int test2() {\n"
" int* p0 = nullptr;\n"
" if (!(getBaz(p0) && p0 != nullptr))\n"
" return 0;\n"
" return *p0;\n"
"}\n", true /*inconclusive*/);
ASSERT_EQUALS("", errout_str());
check("int test3() {\n"
" Obj* PObj = nullptr;\n"
" if (!(GetObj(PObj) && PObj != nullptr))\n"
" return 1;\n"
" if (!PObj->foo())\n"
" test();\n"
" PObj->bar();\n"
"}\n", true /*inconclusive*/);
ASSERT_EQUALS("", errout_str());
}
void nullpointer73() {
check("void f(bool flag2, int* ptr) {\n"
" bool flag1 = true;\n"
" if (flag2) {\n"
" if (ptr != nullptr)\n"
" (*ptr)++;\n"
" else\n"
" flag1 = false;\n"
" }\n"
" if (flag1 && flag2)\n"
" (*ptr)++;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(bool flag2, int* ptr) {\n"
" bool flag1 = true;\n"
" if (flag2) {\n"
" if (ptr != nullptr)\n"
" (*ptr)++;\n"
" else\n"
" flag1 = false;\n"
" }\n"
" if (!flag1 && flag2)\n"
" (*ptr)++;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:10]: (warning) Either the condition 'ptr!=nullptr' is redundant or there is possible null pointer dereference: ptr.\n", errout_str());
}
void nullpointer74() {
check("struct d {\n"
" d* e();\n"
"};\n"
"void g(d* f) {\n"
" do {\n"
" f = f->e();\n"
" if (f) {}\n"
" } while (0);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct d {\n"
" d* e();\n"
"};\n"
"void g(d* f, int i) {\n"
" do {\n"
" i--;\n"
" f = f->e();\n"
" if (f) {}\n"
" } while (i > 0);\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:8] -> [test.cpp:7]: (warning) Either the condition 'f' is redundant or there is possible null pointer dereference: f.\n",
errout_str());
check("struct d {\n"
" d* e();\n"
"};\n"
"void g(d* f, int i) {\n"
" do {\n"
" i--;\n"
" f = f->e();\n"
" if (f) {}\n"
" } while (f && i > 0);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void nullpointer75() {
check("struct a {\n"
" a *b() const;\n"
" void c();\n"
" int d() const;\n"
"};\n"
"void e(a *x) {\n"
" while (x->b()->d() == 0)\n"
" x->c();\n"
" x->c();\n"
" if (x->b()) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void nullpointer76()
{
check("int* foo(int y) {\n"
" std::unique_ptr<int> x = std::make_unique<int>(0);\n"
" if( y == 0 )\n"
" return x.release();\n"
" (*x) ++;\n"
" return x.release();\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void nullpointer77()
{
check("bool h(int*);\n"
"void f(int* i) {\n"
" int* i = nullptr;\n"
" if (h(i) && *i == 1) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("bool h(int*);\n"
"void f(int* i) {\n"
" int* i = nullptr;\n"
" if (h(i))\n"
" if (*i == 1) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("bool h(int*);\n"
"void f(int* x) {\n"
" int* i = x;\n"
" if (h(i))\n"
" i = nullptr;\n"
" if (h(i) && *i == 1) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void nullpointer78() // #7802
{
check("void f()\n"
"{\n"
" int **pp;\n"
" int *p = 0;\n"
" pp = &p;\n"
" **pp = 1;\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (error) Null pointer dereference: *pp\n", errout_str());
}
void nullpointer79() // #10400
{
check("void resize(size_t nF, size_t nT) {\n"
" double* pValues = nullptr;\n"
" if (nF > 0 && nT > 0)\n"
" pValues = new double[nF * nT];\n"
" for (size_t cc = 0; cc < nF * nT; ++cc)\n"
" pValues[cc] = 42;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void nullpointer80() // #10410
{
check("int f(int* a, int* b) {\n"
" if( a || b ) {\n"
" int n = a ? *a : *b;\n"
" if( b )\n"
" n++;\n"
" return n;\n"
" }\n"
" return 0;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void nullpointer81() // #8724
{
check("void f(A **list) {\n"
" A *tmp_List = NULL;\n"
" *list = NULL;\n"
" while (1) {\n"
" if (*list == NULL) {\n"
" tmp_List = malloc (sizeof (ArchiveList_struct));\n"
" *list = tmp_List;\n"
" } else {\n"
" tmp_List->next = malloc (sizeof (ArchiveList_struct));\n"
" }\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void nullpointer82() // #10331
{
check("bool g();\n"
"int* h();\n"
"void f(int* ptr) {\n"
" if (!ptr) {\n"
" if (g())\n"
" goto done;\n"
" ptr = h();\n"
" if (!ptr)\n"
" return;\n"
" }\n"
" if (*ptr == 1)\n"
" return;\n"
"\n"
"done:\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void nullpointer83() // #9870
{
check("int* qux();\n"
"int* f7c2(int *x) {\n"
" int* p = 0;\n"
" if (nullptr == x)\n"
" p = qux();\n"
" if (nullptr == x)\n"
" return x;\n"
" *p = 1;\n"
" return x;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:8]: (warning) Possible null pointer dereference: p\n", errout_str());
}
void nullpointer84() // #9873
{
check("void f(std::unique_ptr<A> P) {\n"
" A *RP = P.get();\n"
" if (!RP) {\n"
" P->foo();\n"
" }\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:3] -> [test.cpp:4]: (warning) Either the condition '!RP' is redundant or there is possible null pointer dereference: P.\n",
errout_str());
}
void nullpointer85() // #10210
{
check("struct MyStruct {\n"
" int GetId() const {\n"
" int id = 0;\n"
" int page = m_notebook->GetSelection();\n"
" if (m_notebook && (m_notebook->GetPageCount() > 0))\n"
" id = page;\n"
" return id;\n"
" }\n"
" wxNoteBook *m_notebook = nullptr;\n"
"};\n"
"int f() {\n"
" const MyStruct &s = Get();\n"
" return s.GetId();\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:5] -> [test.cpp:4]: (warning) Either the condition 'm_notebook' is redundant or there is possible null pointer dereference: m_notebook.\n",
errout_str());
}
void nullpointer86()
{
check("struct A {\n"
" A* a() const;\n"
" int b() const;\n"
"};\n"
"A* f(A* t) {\n"
" if (t->b() == 0) {\n"
" return t;\n"
" }\n"
" return t->a();\n"
"}\n"
"void g(A* t) {\n"
" t = f(t->a());\n"
" if (!t->a()) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void nullpointer87() // #9291
{
check("int f(bool b, int* x) {\n"
" if (b && x == nullptr)\n"
" return 0;\n"
" else if (!b && x == nullptr)\n"
" return 1;\n"
" else if (!b && x != nullptr)\n"
" return *x;\n"
" else\n"
" return *x + 1;\n"
"}\n");
TODO_ASSERT_EQUALS("", "[test.cpp:6] -> [test.cpp:9]: (warning) Either the condition 'x!=nullptr' is redundant or there is possible null pointer dereference: x.\n", errout_str());
check("void f(int n, int* p) {\n"
" int* r = nullptr;\n"
" if (n < 0)\n"
" return;\n"
" if (n == 0)\n"
" r = p;\n"
" else if (n > 0)\n"
" r = p + 1;\n"
" *r;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void nullpointer88() // #9949
{
check("struct S { char **ppc; };\n"
"int alloc(struct S* s) {\n"
" char** ppc = malloc(4096);\n"
" if (ppc != NULL) {\n"
" s->ppc = ppc;\n"
" return 1;\n"
" }\n"
" return 0;\n"
"}\n"
"void f() {\n"
" struct S* s = malloc(sizeof(struct S));\n"
" if (!s) return;\n"
" s->ppc = NULL;\n"
" if (alloc(s))\n"
" s->ppc[0] = \"\";\n"
"}\n", /*inconclusive*/ false, false);
ASSERT_EQUALS("", errout_str());
}
void nullpointer89() // #10640
{
check("typedef struct {\n"
" int x;\n"
"} foo_t;\n"
"typedef struct {\n"
" foo_t *y;\n"
"} bar_t;\n"
"void f(bar_t *ptr) {\n"
" if(ptr->y->x)\n"
" if(ptr->y != nullptr) {}\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:9] -> [test.cpp:8]: (warning) Either the condition 'ptr->y!=nullptr' is redundant or there is possible null pointer dereference: ptr->y.\n",
errout_str());
check("bool argsMatch(const Token *first, const Token *second) {\n" // #6145
" if (first->str() == \")\")\n"
" return true;\n"
" else if (first->next()->str() == \"=\")\n"
" first = first->nextArgument();\n"
" else if (second->next()->str() == \"=\") {\n"
" second = second->nextArgument();\n"
" if (second)\n"
" second = second->tokAt(-2);\n"
" if (!first || !second) {\n"
" return !first && !second;\n"
" }\n"
" }\n"
" return false;\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:10] -> [test.cpp:2]: (warning) Either the condition '!first' is redundant or there is possible null pointer dereference: first.\n"
"[test.cpp:10] -> [test.cpp:4]: (warning) Either the condition '!first' is redundant or there is possible null pointer dereference: first.\n",
errout_str());
}
void nullpointer90() // #6098
{
check("std::string definitionToName(Definition *ctx)\n"
"{\n"
" if (ctx->definitionType()==Definition::TypeMember)\n" // possible null pointer dereference
" {\n"
" return \"y\";\n"
" }\n"
" else if (ctx)\n" // ctx is checked against null
" {\n"
" if(ctx->definitionType()!=Definition::TypeMember)\n"
" {\n"
" return \"x\";\n"
" }\n"
" }\n"
" return \"unknown\";\n"
"}");
ASSERT_EQUALS(
"[test.cpp:7] -> [test.cpp:3]: (warning) Either the condition 'ctx' is redundant or there is possible null pointer dereference: ctx.\n",
errout_str());
}
void nullpointer91() // #10678
{
check("void f(const char* PBeg, const char* PEnd) {\n"
" while (PEnd != nullptr) {\n"
" const int N = h(PEnd);\n"
" PEnd = g();\n"
" const int Length = PEnd == nullptr ? 0 : PEnd - PBeg;\n"
" };\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void nullpointer92()
{
check("bool g(bool);\n"
"int f(int* i) {\n"
" if (!g(!!i)) return 0;\n"
" return *i;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("bool g(bool);\n"
"int f(int* i) {\n"
" if (!g(!i)) return 0;\n"
" return *i;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void nullpointer93() // #3929
{
check("int* GetThing( ) { return 0; }\n"
"int main() {\n"
" int* myNull = GetThing();\n"
" *myNull=42;\n"
" return 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Null pointer dereference: myNull\n", errout_str());
check("struct foo {\n"
" int* GetThing(void) { return 0; }\n"
"};\n"
"int main(void) {\n"
" foo myFoo;\n"
" int* myNull = myFoo.GetThing();\n"
" *myNull=42;\n"
" return 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (error) Null pointer dereference: myNull\n", errout_str());
check("struct T { bool g() const; };\n"
"void f(T* p) {\n"
" if (!p)\n"
" return;\n"
" while (p->g())\n"
" p = nullptr;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5]: (warning) Possible null pointer dereference: p\n", errout_str());
}
void nullpointer94() // #11040
{
check("struct entry { struct entry* next; size_t len; };\n"
"void f(struct entry **kep, size_t slen) {\n"
" while (*kep)\n"
" kep = &(*kep)->next;\n"
" *kep = (struct entry*)malloc(sizeof(**kep));\n"
" (*kep)->next = 0;\n"
" (*kep)->len = slen;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:6]: (warning) If memory allocation fails, then there is a possible null pointer dereference: *kep\n", errout_str());
}
void nullpointer95() // #11142
{
check("void f(std::vector<int*>& v) {\n"
" for (auto& p : v)\n"
" if (*p < 2)\n"
" p = nullptr;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void nullpointer96()
{
check("struct S {\n"
" int x;\n"
"};\n"
"S *create_s();\n"
"void test() {\n"
" S *s = create_s();\n"
" for (int i = 0; i < s->x; i++) {\n"
" if (s->x == 17) {\n"
" s = nullptr;\n"
" break;\n"
" }\n"
" }\n"
" if (s) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void nullpointer97() // #11229
{
check("struct B { virtual int f() = 0; };\n"
"struct D : public B { int f() override; };\n"
"int g(B* p) {\n"
" if (p) {\n"
" auto d = dynamic_cast<D*>(p);\n"
" return d ? d->f() : 0;\n"
" }\n"
" return 0;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void nullpointer98() // #11458
{
check("struct S { double* d() const; };\n"
"struct T {\n"
" virtual void g(double* b, double* d) const = 0;\n"
" void g(S* b) const { g(b->d(), nullptr); }\n"
" void g(S* b, S* d) const { g(b->d(), d->d()); }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void nullpointer99() // #10602
{
check("class A\n"
"{\n"
" int *foo(const bool b)\n"
" {\n"
" if(b)\n"
" return nullptr;\n"
" else\n"
" return new int [10];\n"
" }\n"
"public:\n"
" void bar(void)\n"
" {\n"
" int * buf = foo(true);\n"
" buf[2] = 0;" // <<
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:14]: (error) Null pointer dereference: buf\n", errout_str());
}
void nullpointer100() // #11636
{
check("const char* type_of(double) { return \"unknown\"; }\n"
"void f() {\n"
" double tmp = 0.0;\n"
" const char* t = type_of(tmp);\n"
" std::cout << t;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void nullpointer101() // #11382
{
check("struct Base { virtual ~Base(); };\n"
"struct Derived : Base {};\n"
"bool is_valid(const Derived&);\n"
"void f(const Base* base) {\n"
" const Derived* derived = dynamic_cast<const Derived*>(base);\n"
" if (derived && !is_valid(*derived) || base == nullptr) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void nullpointer102()
{
check("struct S { std::string str; };\n" // #11534
"struct T { S s; };\n"
"struct U { T t[1]; };\n"
"void f(const T& t, const U& u, std::string& str) {\n"
" if (str.empty())\n"
" str = t.s.str;\n"
" else\n"
" str = u.t[0].s.str;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void nullpointer103()
{
check("struct S {\n" // #10572
" int f();\n"
" int* m_P{};\n"
"};\n"
"int S::f() {\n"
" if (!m_P) {\n"
" try {\n"
" m_P = new int(1);\n"
" }\n"
" catch (...) {\n"
" return 0;\n"
" }\n"
" }\n"
" return *m_P;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(int* p, const int* q) {\n" // #11873
" if (*q == -1)\n"
" *p = 0;\n"
"}\n"
"void g() {\n"
" int x = -2;\n"
" f(nullptr, &x);\n"
"}\n");
TODO_ASSERT_EQUALS("", "[test.cpp:3]: (warning) Possible null pointer dereference: p\n", errout_str());
}
void nullpointer_addressOf() { // address of
check("void f() {\n"
" struct X *x = 0;\n"
" if (addr == &x->y) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" struct X *x = 0;\n"
" if (addr == &x->y.z[0]) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
checkP("typedef int Count;\n" // #10018
"#define offsetof(TYPE, MEMBER) ((Count) & ((TYPE*)0)->MEMBER)\n"
"struct S {\n"
" int a[20];\n"
"};\n"
"int g(int i) {\n"
" return offsetof(S, a[i]);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void nullpointerSwitch() { // #2626
// extracttests.start: char *do_something();
check("char *f(int x) {\n"
" char *p = do_something();\n"
" switch (x) {\n"
" case 1:\n"
" p = 0;\n"
" case 2:\n"
" *p = 0;\n"
" break;\n"
" }\n"
" return p;\n"
"}", true);
ASSERT_EQUALS("[test.cpp:7]: (warning) Possible null pointer dereference: p\n", errout_str());
}
void nullpointer_cast() {
check("char *nasm_skip_spaces(const char *p) {\n" // #4692
" if (p)\n"
" while (*p && nasm_isspace(*p))\n"
" p++;\n"
" return p;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(char* origin) {\n" // #11449
" char* cp = (strchr)(origin, '\\0');\n"
" if (cp[-1] != '/')\n"
" *cp++ = '/';\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void nullpointer_castToVoid() { // #3771
check("void f () {\n"
" int *buf; buf = NULL;\n"
" buf;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
}
void nullpointer_subfunction() {
check("int f(int* x, int* y) {\n"
" if (!x)\n"
" return;\n"
" return *x + *y;\n"
"}\n"
"void g() {\n"
" f(nullptr, nullptr);\n"
"}\n", true);
ASSERT_EQUALS("", errout_str());
}
// Check if pointer is null and the dereference it
void pointerCheckAndDeRef() {
check("void foo(char *p) {\n"
" if (!p) {\n"
" }\n"
" *p = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:4]: (warning) Either the condition '!p' is redundant or there is possible null pointer dereference: p.\n", errout_str());
check("void foo(char *p) {\n"
" if (p && *p == 0) {\n"
" }\n"
" printf(\"%c\", *p);\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:4]: (warning) Either the condition 'p' is redundant or there is possible null pointer dereference: p.\n", errout_str());
check("void foo(char *p) {\n"
" if (p && *p == 0) {\n"
" } else { *p = 0; }\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (warning) Either the condition 'p' is redundant or there is possible null pointer dereference: p.\n", errout_str());
check("void foo(char *p) {\n"
" if (p) {\n"
" }\n"
" strcpy(p, \"abc\");\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:4]: (warning) Either the condition 'p' is redundant or there is possible null pointer dereference: p.\n", errout_str());
check("void foo(char *p) {\n"
" if (p) {\n"
" }\n"
" bar();\n"
" strcpy(p, \"abc\");\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:5]: (warning) Either the condition 'p' is redundant or there is possible null pointer dereference: p.\n", errout_str());
check("void foo(abc *p) {\n"
" if (!p) {\n"
" }\n"
" else { if (!p->x) {\n"
" } }\n"
"}");
ASSERT_EQUALS("", errout_str());
{
static const char code[] =
"void foo(char *p) {\n"
" if (!p) {\n"
" abort();\n"
" }\n"
" *p = 0;\n"
"}";
check(code, false);
ASSERT_EQUALS("", errout_str());
check(code, true);
ASSERT_EQUALS("", errout_str());
}
check("void foo(char *p) {\n"
" if (!p) {\n"
" (*bail)();\n"
" }\n"
" *p = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(char *p) {\n"
" if (!p) {\n"
" throw x;\n"
" }\n"
" *p = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(char *p) {\n"
" if (!p) {\n"
" ab.abort();\n"
" }\n"
" *p = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(char *p) {\n"
" if (!p) {\n"
" switch (x) { }\n"
" }\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("void foo(char *p) {\n"
" if (!p) {\n"
" }\n"
" return *x;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("int foo(int *p) {\n"
" if (!p) {\n"
" x = *p;\n"
" return 5+*p;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (warning) Either the condition '!p' is redundant or there is possible null pointer dereference: p.\n"
"[test.cpp:2] -> [test.cpp:4]: (warning) Either the condition '!p' is redundant or there is possible null pointer dereference: p.\n", errout_str());
// operator!
check("void f() {\n"
" A a;\n"
" if (!a) {\n"
" a.x();\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// This is why this check can't be used on the simplified token list
check("void f(Foo *foo) {\n"
" if (!dynamic_cast<bar *>(foo)) {\n"
" *foo = 0;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// ticket: #2300 - calling unknown function that may initialize the pointer
check("Fred *fred;\n"
"void a() {\n"
" if (!fred) {\n"
" initfred();\n"
" fred->x = 0;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// ticket #1219
check("void foo(char *p) {\n"
" if (p) {\n"
" return;\n"
" }\n"
" *p = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:5]: (warning) Either the condition 'p' is redundant or there is possible null pointer dereference: p.\n", errout_str());
// #2467 - unknown macro may terminate the application
check("void f(Fred *fred) {\n"
" if (fred == NULL) {\n"
" MACRO;\n"
" }\n"
" fred->a();\n"
"}");
ASSERT_EQUALS("", errout_str());
// #2493 - switch
check("void f(Fred *fred) {\n"
" if (fred == NULL) {\n"
" x = 0;\n"
" }\n"
" switch (x) {\n"
" case 1:\n"
" fred->a();\n"
" break;\n"
" };\n"
"}");
ASSERT_EQUALS("", errout_str());
// #4118 - second if
check("void f(char *p) {\n"
" int x = 1;\n"
" if (!p) x = 0;\n"
" if (x) *p = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
// #2674 - different functions
check("class Fred {\n"
"public:\n"
" Wilma *wilma;\n"
" void a();\n"
" void b();\n"
"};\n"
"\n"
"void Fred::a() {\n"
" if ( wilma ) { }\n"
"}\n"
"\n"
"void Fred::b() {\n"
" wilma->Reload();\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("void test(int *i) {\n"
" if(i == NULL) { }\n"
" else {\n"
" int b = *i;\n"
" }\n"
"}", true);
ASSERT_EQUALS("", errout_str());
// #2696 - false positives nr 1
check("void f()\n"
"{\n"
" struct foo *pFoo = NULL;\n"
" size_t len;\n"
"\n"
" len = sizeof(*pFoo) - sizeof(pFoo->data);\n"
"\n"
" if (pFoo)\n"
" bar();\n"
"}", true);
ASSERT_EQUALS("", errout_str());
// #2696 - false positives nr 2
check("void f()\n"
"{\n"
" struct foo *pFoo = NULL;\n"
" size_t len;\n"
"\n"
" while (pFoo)\n"
" pFoo = pFoo->next;\n"
"\n"
" len = sizeof(pFoo->data);\n"
"}", true);
ASSERT_EQUALS("", errout_str());
// #2696 - false positives nr 3
check("void f()\n"
"{\n"
" struct foo *pFoo = NULL;\n"
" size_t len;\n"
"\n"
" while (pFoo)\n"
" pFoo = pFoo->next;\n"
"\n"
" len = decltype(*pFoo);\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("int foo(struct Fred *fred) {\n"
" if (fred) { }\n"
" return fred->a;\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (warning) Either the condition 'fred' is redundant or there is possible null pointer dereference: fred.\n", errout_str());
// #2789 - assign and check pointer
check("void f() {\n"
" char *p; p = x();\n"
" if (!p) { }\n"
" *p = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (warning) Either the condition '!p' is redundant or there is possible null pointer dereference: p.\n", errout_str());
// check, assign and use
check("void f() {\n"
" char *p;\n"
" if (p == 0 && (p = malloc(10)) != 0) {\n"
" *p = 0;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// check, assign and use
check("void f() {\n"
" char *p;\n"
" if (p == 0 && (p = malloc(10)) != a && (*p = a)) {\n"
" *p = 0;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// check, and use
check("void f() {\n"
" char *p;\n"
" if (p == 0 && (*p = 0)) {\n"
" return;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:3]: (warning) Either the condition 'p==0' is redundant or there is possible null pointer dereference: p.\n", errout_str());
// check, and use
check("void f() {\n"
" struct foo *p;\n"
" if (p == 0 && p->x == 10) {\n"
" return;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:3]: (warning) Either the condition 'p==0' is redundant or there is possible null pointer dereference: p.\n", errout_str());
// check, and use
check("void f() {\n"
" struct foo *p;\n"
" if (p == 0 || p->x == 10) {\n"
" return;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// check, and use
check("void f() {\n"
" char *p; p = malloc(10);\n"
" if (p == NULL && (*p = a)) {\n"
" return;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:3]: (warning) Either the condition 'p==NULL' is redundant or there is possible null pointer dereference: p.\n", errout_str());
// check, and use
check("void f(struct X *p, int x) {\n"
" if (!p && x==1 || p && p->x==0) {\n"
" return;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
{
const char code[] = "void f(Fred *fred) {\n"
" if (fred == NULL) { }\n"
" fred->x();\n"
"}";
check(code); // inconclusive
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (warning) Either the condition 'fred==NULL' is redundant or there is possible null pointer dereference: fred.\n", errout_str());
}
check("void f(char *s) {\n" // #3358
" if (s==0);\n"
" strcpy(a, s?b:c);\n"
"}");
ASSERT_EQUALS("", errout_str());
// sizeof
check("void f(struct fred_t *fred) {\n"
" if (!fred)\n"
" int sz = sizeof(fred->x);\n"
"}", true);
ASSERT_EQUALS("", errout_str());
// check in macro
check("void f(int *x) {\n"
" $if (!x) {}\n"
" *x = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
// return ?:
check("int f(ABC *p) {\n" // FP : return ?:
" if (!p) {}\n"
" return p ? p->x : 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int f(ABC *p) {\n" // no fn
" if (!p) {}\n"
" return q ? p->x : 0;\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (warning) Either the condition '!p' is redundant or there is possible null pointer dereference: p.\n", "", errout_str());
check("int f(ABC *p) {\n" // FP : return &&
" if (!p) {}\n"
" return p && p->x;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x, int *p) {\n"
" if (x || !p) {}\n"
" *p = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (warning) Either the condition '!p' is redundant or there is possible null pointer dereference: p.\n", errout_str());
// sizeof
check("void f() {\n"
" int *pointer = NULL;\n"
" pointer = func(sizeof pointer[0]);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
// Test CheckNullPointer::nullConstantDereference
void nullConstantDereference() {
check("int f() {\n"
" int* p = 0;\n"
" return p[4];\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Null pointer dereference: p\n", errout_str());
check("void f() {\n"
" typeof(*NULL) y;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("int * f() {\n"
" return NULL;\n"
"}\n"
"int main() {\n"
" return *f();\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Null pointer dereference: f()\n", errout_str());
}
void gcc_statement_expression() {
// Ticket #2621
check("void f(struct ABC *abc) {\n"
" ({ if (abc) dbg(); })\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void snprintf_with_zero_size() {
// Ticket #2840
check("void f() {\n"
" int bytes = snprintf(0, 0, \"%u\", 1);\n"
"}", true);
ASSERT_EQUALS("", errout_str());
}
void snprintf_with_non_zero_size() {
// Ticket #2840
check("void f() {\n"
" int bytes = snprintf(0, 10, \"%u\", 1);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Null pointer dereference\n", errout_str());
}
void printf_with_invalid_va_argument() {
check("void f() {\n"
" printf(\"%s\", 0);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Null pointer dereference\n", errout_str());
check("void f(char* s) {\n"
" printf(\"%s\", s);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" char* s = 0;\n"
" printf(\"%s\", s);\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3]: (error) Null pointer dereference: s\n"
"[test.cpp:3]: (error) Null pointer dereference\n",
errout_str());
check("void f() {\n"
" char *s = 0;\n"
" printf(\"%s\", s == 0 ? a : s);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" printf(\"%u%s\", 0, 0);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Null pointer dereference\n", errout_str());
check("void f(char* s) {\n"
" printf(\"%u%s\", 0, s);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" char* s = 0;\n"
" printf(\"%u%s\", 123, s);\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3]: (error) Null pointer dereference: s\n"
"[test.cpp:3]: (error) Null pointer dereference\n",
errout_str());
check("void f() {\n"
" printf(\"%%%s%%\", 0);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Null pointer dereference\n", errout_str());
check("void f(char* s) {\n"
" printf(\"text: %s, %s\", s, 0);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Null pointer dereference\n", errout_str());
check("void f() {\n"
" char* s = \"blabla\";\n"
" printf(\"%s\", s);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(char* s) {\n"
" printf(\"text: %m%s, %s\", s, 0);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Null pointer dereference\n", errout_str());
check("void f(char* s) {\n"
" printf(\"text: %*s, %s\", s, 0);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Null pointer dereference\n", errout_str());
// Ticket #3364
check("void f() {\n"
" printf(\"%-*.*s\", s, 0);\n"
" sprintf(\"%*\", s);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void scanf_with_invalid_va_argument() {
check("void f(char* s) {\n"
" sscanf(s, \"%s\", 0);\n"
"}");
ASSERT_EQUALS(
"[test.cpp:2]: (error) Null pointer dereference\n"
"[test.cpp:2]: (error) Null pointer dereference\n", // duplicate
errout_str());
check("void f() {\n"
" scanf(\"%d\", 0);\n"
"}");
ASSERT_EQUALS(
"[test.cpp:2]: (error) Null pointer dereference\n"
"[test.cpp:2]: (error) Null pointer dereference\n", // duplicate
errout_str());
check("void f(char* foo) {\n"
" char location[200];\n"
" int width, height;\n"
" sscanf(imgInfo, \"%s %d %d\", location, &width, &height);\n"
"}");
ASSERT_EQUALS("", errout_str()); // ticket #3207
check("void f(char *dummy) {\n"
" int iVal;\n"
" sscanf(dummy, \"%d%c\", &iVal);\n"
"}");
ASSERT_EQUALS("", errout_str()); // ticket #3211
check("void f(char *dummy) {\n"
" int* iVal = 0;\n"
" sscanf(dummy, \"%d\", iVal);\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3]: (error) Null pointer dereference: iVal\n"
"[test.cpp:3]: (error) Null pointer dereference\n"
"[test.cpp:3]: (error) Null pointer dereference\n", // duplicate
errout_str());
check("void f(char *dummy) {\n"
" int* iVal;\n"
" sscanf(dummy, \"%d\", foo(iVal));\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(char *dummy) {\n"
" int* iVal = 0;\n"
" sscanf(dummy, \"%d%d\", foo(iVal), iVal);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(char* dummy) {\n"
" sscanf(dummy, \"%*d%u\", 0);\n"
"}");
ASSERT_EQUALS(
"[test.cpp:2]: (error) Null pointer dereference\n"
"[test.cpp:2]: (error) Null pointer dereference\n", // duplicate
errout_str());
}
void nullpointer_in_return() {
// extracttests.start: int maybe(); int *g();
check("int foo() {\n"
" int* iVal = 0;\n"
" if(maybe()) iVal = g();\n"
" return iVal[0];\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (warning) Possible null pointer dereference: iVal\n", errout_str());
check("int foo(int* iVal) {\n"
" return iVal[0];\n"
"}", true);
ASSERT_EQUALS("", errout_str());
}
void nullpointer_in_typeid() {
// Should throw std::bad_typeid
check("struct PolymorphicA { virtual ~A() {} };\n"
"bool foo() {\n"
" PolymorphicA* a = 0;\n"
" return typeid(*a) == typeid(*a);\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("struct NonPolymorphicA { ~A() {} };\n"
"bool foo() {\n"
" NonPolymorphicA* a = 0;\n"
" return typeid(*a) == typeid(*a);\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("bool foo() {\n"
" char* c = 0;\n"
" return typeid(*c) == typeid(*c);\n"
"}", true);
ASSERT_EQUALS("", errout_str());
}
void nullpointer_in_alignof() // #11401
{
check("size_t foo() {\n"
" char* c = 0;\n"
" return alignof(*c);\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("size_t foo() {\n"
" return alignof(*0);\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("void foo(int *p) {\n"
" f(alignof(*p));\n"
" if (p) {}\n"
" return;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("size_t foo() {\n"
" char* c = 0;\n"
" return _Alignof(*c);\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("size_t foo() {\n"
" return _alignof(*0);\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("size_t foo() {\n"
" return __alignof(*0);\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("size_t foo() {\n"
" return __alignof__(*0);\n"
"}", true);
ASSERT_EQUALS("", errout_str());
}
void nullpointer_in_for_loop() {
// Ticket #3278
check("void f(int* ptr, int cnt){\n"
" if (!ptr)\n"
" cnt = 0;\n"
" for (int i = 0; i < cnt; ++i)\n"
" *ptr++ = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
// #11635
check("void f(char *cons, int rlen, int pos) {\n"
" int i;\n"
" char* cp1;\n"
" for (cp1 = &cons[pos], i = 1; i < rlen; cp1--)\n"
" if (*cp1 == '*')\n"
" continue;\n"
" else\n"
" i++;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void nullpointerDeadCode() {
// Ticket #11311
check ("void f() {\n"
" if (0)\n"
" *(int *)0 = 1;\n"
" else\n"
" ;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check ("void f() {\n"
" if (0)\n"
" *(int *)0 = 1;\n"
" else {\n"
" if (0)\n"
" *(int *)0 = 2;\n"
" else\n"
" ;\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check ("void f() {\n"
" while(0)\n"
" *(int*)0 = 1;\n"
" do {\n"
" } while(0);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check ("int f() {\n"
" return 0 ? *(int*)0 = 1 : 1;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check ("int f() {\n"
" return 1 ? 1 : *(int*)0 = 1;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void nullpointerDelete() {
check("void f() {\n"
" K *k = getK();\n"
" if (k)\n"
" k->doStuff();\n"
" delete k;\n"
"}\n", true);
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" K *k = getK();\n"
" if (k)\n"
" k[0] = ptr;\n"
" delete [] k;\n"
" k = new K[10];\n"
"}\n", true);
ASSERT_EQUALS("", errout_str());
}
void nullpointerSubFunction() {
check("void g(int* x) { *x; }\n"
"void f(int* x) {\n"
" if (x)\n"
" g(x);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void nullpointerExit() {
check("void f() {\n"
" K *k = getK();\n"
" if (!k)\n"
" exit(1);\n"
" k->f();\n"
"}\n", true);
ASSERT_EQUALS("", errout_str());
}
void nullpointerStdString() {
check("void f(std::string s1) {\n"
" void* p = 0;\n"
" s1 = 0;\n"
" s1 = '\\0';\n"
" std::string s2 = 0;\n"
" std::string s2 = '\\0';\n"
" std::string s3(0);\n"
" foo(std::string(0));\n"
" s1 = p;\n"
" std::string s4 = p;\n"
" std::string s5(p);\n"
" foo(std::string(p));\n"
"}", true);
ASSERT_EQUALS("[test.cpp:9]: (error) Null pointer dereference: p\n"
"[test.cpp:10]: (error) Null pointer dereference: p\n"
"[test.cpp:11]: (error) Null pointer dereference: p\n"
"[test.cpp:12]: (error) Null pointer dereference: p\n"
"[test.cpp:3]: (error) Null pointer dereference\n"
"[test.cpp:5]: (error) Null pointer dereference\n"
"[test.cpp:7]: (error) Null pointer dereference\n"
"[test.cpp:8]: (error) Null pointer dereference\n"
, errout_str());
check("void f(std::string s1) {\n"
" s1 = nullptr;\n"
" std::string s2 = nullptr;\n"
" std::string s3(nullptr);\n"
" foo(std::string(nullptr));\n"
"}", true);
ASSERT_EQUALS("[test.cpp:2]: (error) Null pointer dereference\n"
"[test.cpp:3]: (error) Null pointer dereference\n"
"[test.cpp:4]: (error) Null pointer dereference\n"
"[test.cpp:5]: (error) Null pointer dereference\n"
, errout_str());
check("void f(std::string s1) {\n"
" s1 = NULL;\n"
" std::string s2 = NULL;\n"
" std::string s3(NULL);\n"
" foo(std::string(NULL));\n"
"}", true);
ASSERT_EQUALS("[test.cpp:2]: (error) Null pointer dereference\n"
"[test.cpp:3]: (error) Null pointer dereference\n"
"[test.cpp:4]: (error) Null pointer dereference\n"
"[test.cpp:5]: (error) Null pointer dereference\n"
, errout_str());
check("void f(std::string s1, const std::string& s2, const std::string* s3) {\n"
" void* p = 0;\n"
" if (x) { return; }\n"
" foo(s1 == p);\n"
" foo(s2 == p);\n"
" foo(s3 == p);\n"
" foo(p == s1);\n"
" foo(p == s2);\n"
" foo(p == s3);\n"
"}", true);
ASSERT_EQUALS("[test.cpp:4]: (error) Null pointer dereference: p\n"
"[test.cpp:5]: (error) Null pointer dereference: p\n"
"[test.cpp:7]: (error) Null pointer dereference: p\n"
"[test.cpp:8]: (error) Null pointer dereference: p\n", errout_str());
check("void f(std::string s1, const std::string& s2, const std::string* s3) {\n"
" void* p = 0;\n"
" if (x) { return; }\n"
" foo(0 == s1.size());\n"
" foo(0 == s2.size());\n"
" foo(0 == s3->size());\n"
" foo(s1.size() == 0);\n"
" foo(s2.size() == 0);\n"
" foo(s3->size() == 0);\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("void f(std::string s1, const std::string& s2) {\n"
" if (x) { return; }\n"
" foo(0 == s1[0]);\n"
" foo(0 == s2[0]);\n"
" foo(s1[0] == 0);\n"
" foo(s2[0] == 0);\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("void f(std::string s1, const std::string& s2) {\n"
" if (x) { return; }\n"
" foo(s1 == '\\0');\n"
" foo(s2 == '\\0');\n"
" foo('\\0' == s1);\n"
" foo('\\0' == s2);\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("class Bar {\n"
" std::string s;\n"
" Bar() : s(0) {}\n"
"};\n"
"class Foo {\n"
" std::string s;\n"
" Foo();\n"
"};\n"
"Foo::Foo() : s(0) {}");
ASSERT_EQUALS("[test.cpp:3]: (error) Null pointer dereference\n"
"[test.cpp:9]: (error) Null pointer dereference\n", errout_str());
check("void f() {\n"
" std::string s = 0 == x ? \"a\" : \"b\";\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" const std::string s = g();\n"
" ASSERT_MESSAGE(\"Error on s\", 0 == s.compare(\"Some text\"));\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(int i, std::string s);\n"
"void bar() {\n"
" foo(0, \"\");\n"
" foo(0, 0);\n"
" foo(var, 0);\n"
" foo(var, NULL);\n"
" foo(var, nullptr);\n"
" foo(0, var);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Null pointer dereference\n"
"[test.cpp:5]: (error) Null pointer dereference\n"
"[test.cpp:6]: (error) Null pointer dereference\n"
"[test.cpp:7]: (error) Null pointer dereference\n", errout_str());
check("std::string f() {\n" // #9827
" char* p = NULL;\n"
" int r = g(p);\n"
" if (!r)\n"
" return \"\";\n"
" std::string s(p);\n"
" return s;\n"
"}\n", /*inconclusive*/ true);
ASSERT_EQUALS("", errout_str());
check("void f() {\n" // #11078
" const char* p = nullptr;\n"
" std::string s1{ p };\n"
" std::string s2{ nullptr };\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (error) Null pointer dereference: p\n"
"[test.cpp:4]: (error) Null pointer dereference\n",
errout_str());
check("const char* g(long) { return nullptr; }\n" // #11561
"void f() { std::string s = g(0L); }\n");
ASSERT_EQUALS("[test.cpp:2]: (error) Null pointer dereference: g(0L)\n",
errout_str());
}
void nullpointerStdStream() {
check("void f(std::ifstream& is) {\n"
" char* p = 0;\n"
" is >> p;\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:3]: (error) Possible null pointer dereference: p\n", "", errout_str());
check("void f(const std::ostringstream& oss, char* q) {\n"
" char const* p = 0;\n" // Simplification makes detection of bug difficult
" oss << p;\n"
" oss << foo << p;\n"
" if(q == 0)\n"
" oss << foo << q;\n"
"}", false);
ASSERT_EQUALS("[test.cpp:3]: (error) Null pointer dereference: p\n"
"[test.cpp:4]: (error) Null pointer dereference: p\n"
"[test.cpp:5] -> [test.cpp:6]: (warning) Either the condition 'q==0' is redundant or there is possible null pointer dereference: q.\n", errout_str());
check("void f(const char* p) {\n"
" if(p == 0) {\n"
" std::cout << p;\n"
" std::cerr << p;\n"
" std::cin >> p;\n"
" std::cout << abc << p;\n"
" }\n"
"}", false);
TODO_ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (warning) Either the condition 'p==0' is redundant or there is possible null pointer dereference: p.\n"
"[test.cpp:2] -> [test.cpp:4]: (warning) Either the condition 'p==0' is redundant or there is possible null pointer dereference: p.\n"
"[test.cpp:2] -> [test.cpp:5]: (warning) Either the condition 'p==0' is redundant or there is possible null pointer dereference: p.\n"
"[test.cpp:2] -> [test.cpp:6]: (warning) Either the condition 'p==0' is redundant or there is possible null pointer dereference: p.\n",
"[test.cpp:2] -> [test.cpp:3]: (warning) Either the condition 'p==0' is redundant or there is possible null pointer dereference: p.\n"
"[test.cpp:2] -> [test.cpp:4]: (warning) Either the condition 'p==0' is redundant or there is possible null pointer dereference: p.\n",
errout_str());
check("void f() {\n"
" void* p1 = 0;\n"
" std::cout << p1;\n" // No char*
" char* p2 = 0;\n"
" std::cin >> (int)p;\n" // result casted
" std::cout << (int)p;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("void f(const std::string& str) {\n"
" long long ret = 0;\n"
" std::istringstream istr(str);\n"
" istr >> std::hex >> ret;\n" // Read integer
" return ret;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("void f(int* i) {\n"
" if(i) return;\n"
" std::cout << i;\n" // Its no char* (#4240)
"}", true);
ASSERT_EQUALS("", errout_str());
// #5811 false positive: (error) Null pointer dereference
check("using namespace std;\n"
"std::string itoip(int ip) {\n"
" stringstream out;\n"
" out << ((ip >> 0) & 0xFF);\n"
" return out.str();\n"
"}", true);
ASSERT_EQUALS("", errout_str());
// avoid regression from first fix attempt for #5811...
check("void deserialize(const std::string &data) {\n"
"std::istringstream iss(data);\n"
"unsigned int len = 0;\n"
"if (!(iss >> len))\n"
" return;\n"
"}\n", true);
ASSERT_EQUALS("", errout_str());
}
void nullpointerSmartPointer() {
// extracttests.start: void dostuff(int);
check("struct Fred { int x; };\n"
"void f(std::shared_ptr<Fred> p) {\n"
" if (p) {}\n"
" dostuff(p->x);\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (warning) Either the condition 'p' is redundant or there is possible null pointer dereference: p.\n", errout_str());
check("struct Fred { int x; };\n"
"void f(std::shared_ptr<Fred> p) {\n"
" p = nullptr;\n"
" dostuff(p->x);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Null pointer dereference: p\n", errout_str());
check("struct Fred { int x; };\n"
"void f(std::unique_ptr<Fred> p) {\n"
" if (p) {}\n"
" dostuff(p->x);\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (warning) Either the condition 'p' is redundant or there is possible null pointer dereference: p.\n", errout_str());
check("struct Fred { int x; };\n"
"void f(std::unique_ptr<Fred> p) {\n"
" p = nullptr;\n"
" dostuff(p->x);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Null pointer dereference: p\n", errout_str());
check("struct Fred { int x; };\n"
"void f() {\n"
" std::shared_ptr<Fred> p;\n"
" dostuff(p->x);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Null pointer dereference: p\n", errout_str());
check("struct Fred { int x; };\n"
"void f(std::shared_ptr<Fred> p) {\n"
" p.reset();\n"
" dostuff(p->x);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Null pointer dereference: p\n", errout_str());
check("struct Fred { int x; };\n"
"void f(std::shared_ptr<Fred> p) {\n"
" Fred * pp = nullptr;\n"
" p.reset(pp);\n"
" dostuff(p->x);\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Null pointer dereference: p\n", errout_str());
check("struct Fred { int x; };\n"
"void f(Fred& f) {\n"
" std::shared_ptr<Fred> p;\n"
" p.reset(&f);\n"
" dostuff(p->x);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct Fred { int x; };\n"
"void f(std::shared_ptr<Fred> p) {\n"
" p.reset();\n"
" dostuff(p->x);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Null pointer dereference: p\n", errout_str());
check("struct Fred { int x; };\n"
"void f() {\n"
" std::shared_ptr<Fred> p(nullptr);\n"
" dostuff(p->x);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Null pointer dereference: p\n", errout_str());
check("struct A {};\n"
"void f(int n) {\n"
" std::unique_ptr<const A*[]> p;\n"
" p.reset(new const A*[n]);\n"
"}");
ASSERT_EQUALS("", errout_str());
// #9216
check("struct A {\n"
" void reset();\n"
" void f();\n"
"};\n"
"void g(std::unique_ptr<A> var) {\n"
" var->reset();\n"
" var->f();\n"
"}");
ASSERT_EQUALS("", errout_str());
// #9439
check("char* g();\n"
"char* f() {\n"
" std::unique_ptr<char> x(g());\n"
" if( x ) {}\n"
" return x.release();\n"
"}\n", true);
ASSERT_EQUALS("", errout_str());
// #9496
check("std::shared_ptr<int> f() {\n"
" return std::shared_ptr<int>(nullptr);\n"
"}\n"
"void g() {\n"
" int a = *f();\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:5]: (error) Null pointer dereference: f()\n", errout_str());
}
void nullpointerOutOfMemory() {
check("void f() {\n"
" int *p = malloc(10);\n"
" *p = 0;\n"
" free(p);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) If memory allocation fails, then there is a possible null pointer dereference: p\n", errout_str());
check("void f() {\n"
" int *p = malloc(10);\n"
" *(p+2) = 0;\n"
" free(p);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) If memory allocation fail: pointer addition with NULL pointer.\n", errout_str());
}
void functioncall() { // #3443 - function calls
// dereference pointer and then check if it's null
{
// function not seen
check("void f(int *p) {\n"
" *p = 0;\n"
" foo(p);\n"
" if (p) { }\n"
"}");
ASSERT_EQUALS("", errout_str());
// function seen (taking pointer parameter)
check("void foo(int *p) { }\n"
"\n"
"void f(int *p) {\n"
" *p = 0;\n"
" foo(p);\n"
" if (p) { }\n"
"}");
ASSERT_EQUALS(
"[test.cpp:6] -> [test.cpp:4]: (warning) Either the condition 'p' is redundant or there is possible null pointer dereference: p.\n",
errout_str());
// function seen (taking reference parameter)
check("void foo(int *&p) { }\n"
"\n"
"void f(int *p) {\n"
" *p = 0;\n"
" foo(p);\n"
" if (p) { }\n"
"}", true);
ASSERT_EQUALS("", errout_str());
// function implementation not seen
check("void foo(int *p);\n"
"\n"
"void f(int *p) {\n"
" *p = 0;\n"
" foo(p);\n"
" if (p) { }\n"
"}");
ASSERT_EQUALS(
"[test.cpp:6] -> [test.cpp:4]: (warning) Either the condition 'p' is redundant or there is possible null pointer dereference: p.\n",
errout_str());
// inconclusive
check("void f(int *p) {\n"
" *p = 0;\n"
" foo(p);\n"
" if (p) { }\n"
"}", true);
ASSERT_EQUALS(
"[test.cpp:4] -> [test.cpp:2]: (warning, inconclusive) Either the condition 'p' is redundant or there is possible null pointer dereference: p.\n",
errout_str());
}
// dereference struct pointer and then check if it's null
{
// function not seen
check("void f(struct ABC *abc) {\n"
" abc->a = 0;\n"
" foo(abc);\n"
" if (abc) { }\n"
"}");
ASSERT_EQUALS("", errout_str());
// function seen (taking pointer parameter)
check("void foo(struct ABC *abc) { }\n"
"\n"
"void f(struct ABC *abc) {\n"
" abc->a = 0;\n"
" foo(abc);\n"
" if (abc) { }\n"
"}");
ASSERT_EQUALS(
"[test.cpp:6] -> [test.cpp:4]: (warning) Either the condition 'abc' is redundant or there is possible null pointer dereference: abc.\n",
errout_str());
// function implementation not seen
check("void foo(struct ABC *abc);\n"
"\n"
"void f(struct ABC *abc) {\n"
" abc->a = 0;\n"
" foo(abc);\n"
" if (abc) { }\n"
"}");
ASSERT_EQUALS(
"[test.cpp:6] -> [test.cpp:4]: (warning) Either the condition 'abc' is redundant or there is possible null pointer dereference: abc.\n",
errout_str());
// inconclusive
check("void f(struct ABC *abc) {\n"
" abc->a = 0;\n"
" foo(abc);\n"
" if (abc) { }\n"
"}", true);
ASSERT_EQUALS(
"[test.cpp:4] -> [test.cpp:2]: (warning, inconclusive) Either the condition 'abc' is redundant or there is possible null pointer dereference: abc.\n",
errout_str());
}
}
void functioncalllibrary() {
SimpleTokenizer tokenizer(settingsDefault,*this);
const char code[] = "void f() { int a,b,c; x(a,b,c); }";
ASSERT_EQUALS(true, tokenizer.tokenize(code, false));
const Token *xtok = Token::findsimplematch(tokenizer.tokens(), "x");
// nothing bad..
{
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <function name=\"x\">\n"
" <arg nr=\"1\"></arg>\n"
" <arg nr=\"2\"></arg>\n"
" <arg nr=\"3\"></arg>\n"
" </function>\n"
"</def>";
Library library;
ASSERT(LibraryHelper::loadxmldata(library, xmldata, sizeof(xmldata)));
std::list<const Token *> null;
CheckNullPointer::parseFunctionCall(*xtok, null, library);
ASSERT_EQUALS(0U, null.size());
}
// for 1st parameter null pointer is not ok..
{
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <function name=\"x\">\n"
" <arg nr=\"1\"><not-null/></arg>\n"
" <arg nr=\"2\"></arg>\n"
" <arg nr=\"3\"></arg>\n"
" </function>\n"
"</def>";
Library library;
ASSERT(LibraryHelper::loadxmldata(library, xmldata, sizeof(xmldata)));
std::list<const Token *> null;
CheckNullPointer::parseFunctionCall(*xtok, null, library);
ASSERT_EQUALS(1U, null.size());
ASSERT_EQUALS("a", null.front()->str());
}
}
void functioncallDefaultArguments() {
check("void f(int *p = 0) {\n"
" *p = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Possible null pointer dereference if the default parameter value is used: p\n", errout_str());
check("void f(int *p = 0) {\n"
" if (!p)\n"
" return;\n"
" *p = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(char a, int *p = 0) {\n"
" *p = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Possible null pointer dereference if the default parameter value is used: p\n", errout_str());
check("void f(int *p = 0) {\n"
" printf(\"p = %d\", *p);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Possible null pointer dereference if the default parameter value is used: p\n", errout_str());
check("void f(int *p = 0) {\n"
" printf(\"p[1] = %d\", p[1]);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Possible null pointer dereference if the default parameter value is used: p\n", errout_str());
check("void f(int *p = 0) {\n"
" buf[p] = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int *p = 0) {\n"
" if (p != 0 && bar())\n"
" *p = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int *p) {\n"
" *p = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int *p = 0) {\n"
" if (p != 0)\n"
" *p = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int *p = 0) {\n"
" int y;\n"
" if (p == 0)\n"
" p = &y;\n"
" *p = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int a, int *p = 0) {\n"
" if (a != 0)\n"
" *p = 0;\n"
"}", true);
ASSERT_EQUALS(
"[test.cpp:3]: (warning) Possible null pointer dereference if the default parameter value is used: p\n",
errout_str());
check("void f(int *p = 0) {\n"
" p = a;\n"
" *p = 0;\n" // <- don't simplify and verify
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int *p = 0) {\n"
" p += a;\n"
" *p = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int f(int *p = 0) {\n"
" if (p == 0) {\n"
" return 0;\n"
" }\n"
" return *p;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int *p = 0) {\n"
" std::cout << p ? *p : 0;\n" // Due to operator precedence, this is equivalent to: (std::cout << p) ? *p : 0;
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Possible null pointer dereference if the default parameter value is used: p\n", errout_str()); // Check the first branch of ternary
check("void f(char *p = 0) {\n"
" std::cout << p ? *p : 0;\n" // Due to operator precedence, this is equivalent to: (std::cout << p) ? *p : 0;
"}");
ASSERT_EQUALS(
"[test.cpp:2]: (warning) Possible null pointer dereference if the default parameter value is used: p\n"
"[test.cpp:2]: (warning) Possible null pointer dereference if the default parameter value is used: p\n", // duplicate
errout_str());
check("void f(int *p = 0) {\n"
" std::cout << (p ? *p : 0);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int *p = 0) {\n"
" std::cout << p;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int *p = 0) {\n"
" std::cout << (p && p[0] ? *p : 42);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void isEmpty(int *p = 0) {\n"
" return p && *p;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void g(int *p = 0) {\n"
" return !p || *p;\n"
"}");
ASSERT_EQUALS("", errout_str());
// bar may initialize p but be can't know for sure without knowing
// if p is passed in by reference and is modified by bar()
check("void f(int *p = 0) {\n"
" bar(p);\n"
" *p = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int *p = 0) {\n"
" printf(\"%p\", p);\n"
" *p = 0;\n"
"}", true);
ASSERT_EQUALS("[test.cpp:3]: (warning) Possible null pointer dereference if the default parameter value is used: p\n", errout_str());
// The init() function may or may not initialize p, but since the address
// of p is passed in, it's a good bet that p may be modified and
// so we should not report an error.
check("void f(int *p = 0) {\n"
" init(&p);\n"
" *p = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void init(int* &g);\n"
"void f(int *p = 0) {\n"
" init(p);\n"
" *p = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int *p = 0) {\n"
" if (p == 0) {\n"
" init(&p);\n"
" }\n"
" *p = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int *p = 0) {\n"
" if (p == 0) {\n"
" throw SomeException;\n"
" }\n"
" *p = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(int x, int *p = 0) {\n"
" int var1 = x ? *p : 5;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Possible null pointer dereference if the default parameter value is used: p\n", errout_str());
check("void f(int* i = nullptr) { *i = 0; }\n" // #11567
"void g() { f(); }\n");
ASSERT_EQUALS("[test.cpp:1]: (warning) Possible null pointer dereference if the default parameter value is used: i\n", errout_str());
}
void nullpointer_internal_error() { // ticket #5080
check("struct A { unsigned int size; };\n"
"struct B { struct A *a; };\n"
"void f(struct B *b) {\n"
" unsigned int j;\n"
" for (j = 0; j < b[0].a->size; ++j) {\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void ticket6505() {
check("void foo(MythSocket *socket) {\n"
" bool do_write=0;\n"
" if (socket) {\n"
" do_write=something();\n"
" }\n"
" if (do_write) {\n"
" socket->func();\n"
" }\n"
"}\n"
"void bar() {\n"
" foo(0);\n"
"}\n", true, false);
ASSERT_EQUALS("", errout_str());
}
void subtract() {
check("void foo(char *s) {\n"
" char *p = s - 20;\n"
"}\n"
"void bar() { foo(0); }");
ASSERT_EQUALS("[test.cpp:2]: (error) Overflow in pointer arithmetic, NULL pointer is subtracted.\n",
errout_str());
check("void foo(char *s) {\n"
" if (!s) {}\n"
" char *p = s - 20;\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (warning) Either the condition '!s' is redundant or there is overflow in pointer subtraction.\n", errout_str());
check("void foo(char *s) {\n"
" s -= 20;\n"
"}\n"
"void bar() { foo(0); }");
ASSERT_EQUALS("[test.cpp:2]: (error) Overflow in pointer arithmetic, NULL pointer is subtracted.\n",
errout_str());
check("void foo(char *s) {\n"
" if (!s) {}\n"
" s -= 20;\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (warning) Either the condition '!s' is redundant or there is overflow in pointer subtraction.\n", errout_str());
check("int* f8() { int *x = NULL; return --x; }");
ASSERT_EQUALS("[test.cpp:1]: (error) Overflow in pointer arithmetic, NULL pointer is subtracted.\n", errout_str());
check("int* f9() { int *x = NULL; return x--; }");
ASSERT_EQUALS("[test.cpp:1]: (error) Overflow in pointer arithmetic, NULL pointer is subtracted.\n", errout_str());
}
void addNull() {
check("void foo(char *s) {\n"
" char * p = s + 20;\n"
"}\n"
"void bar() { foo(0); }");
ASSERT_EQUALS("[test.cpp:2]: (error) Pointer addition with NULL pointer.\n", errout_str());
check("void foo(char *s) {\n"
" if (!s) {}\n"
" char * p = s + 20;\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (warning) Either the condition '!s' is redundant or there is pointer arithmetic with NULL pointer.\n", errout_str());
check("void foo(char *s) {\n"
" char * p = 20 + s;\n"
"}\n"
"void bar() { foo(0); }");
ASSERT_EQUALS("[test.cpp:2]: (error) Pointer addition with NULL pointer.\n", errout_str());
check("void foo(char *s) {\n"
" if (!s) {}\n"
" char * p = 20 + s;\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (warning) Either the condition '!s' is redundant or there is pointer arithmetic with NULL pointer.\n", errout_str());
check("void foo(char *s) {\n"
" s += 20;\n"
"}\n"
"void bar() { foo(0); }");
ASSERT_EQUALS("[test.cpp:2]: (error) Pointer addition with NULL pointer.\n", errout_str());
check("void foo(char *s) {\n"
" if (!s) {}\n"
" s += 20;\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (warning) Either the condition '!s' is redundant or there is pointer arithmetic with NULL pointer.\n", errout_str());
check("int* f7() { int *x = NULL; return ++x; }");
ASSERT_EQUALS("[test.cpp:1]: (error) Pointer addition with NULL pointer.\n", errout_str());
check("int* f10() { int *x = NULL; return x++; }");
ASSERT_EQUALS("[test.cpp:1]: (error) Pointer addition with NULL pointer.\n", errout_str());
check("class foo {};\n"
"const char* get() const { return 0; }\n"
"void f(foo x) { if (get()) x += get(); }");
ASSERT_EQUALS("", errout_str());
check("typedef struct { uint8_t* buf, *buf_end; } S;\n" // #11117
"void f(S* s, uint8_t* buffer, int buffer_size) {\n"
" if (buffer_size < 0) {\n"
" buffer_size = 0;\n"
" buffer = NULL;\n"
" }\n"
" s->buf = buffer;\n"
" s->buf_end = s->buf + buffer_size;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void isPointerDeRefFunctionDecl() {
check("const char** get() { return 0; }");
ASSERT_EQUALS("", errout_str());
}
#define ctu(code) ctu_(code, __FILE__, __LINE__)
template<size_t size>
void ctu_(const char (&code)[size], const char* file, int line) {
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
CTU::FileInfo *ctu = CTU::getFileInfo(tokenizer);
// Check code..
std::list<Check::FileInfo*> fileInfo;
Check& c = getCheck<CheckNullPointer>();
fileInfo.push_back(c.getFileInfo(tokenizer, settings));
c.analyseWholeProgram(ctu, fileInfo, settings, *this); // TODO: check result
while (!fileInfo.empty()) {
delete fileInfo.back();
fileInfo.pop_back();
}
delete ctu;
}
void ctuTest() {
setMultiline();
ctu("void f(int *fp) {\n"
" a = *fp;\n"
"}\n"
"int main() {\n"
" int *p = 0;\n"
" f(p);\n"
"}");
ASSERT_EQUALS("test.cpp:2:error:Null pointer dereference: fp\n"
"test.cpp:5:note:Assignment 'p=0', assigned value is 0\n"
"test.cpp:6:note:Calling function f, 1st argument is null\n"
"test.cpp:2:note:Dereferencing argument fp that is null\n", errout_str());
ctu("void use(int *p) { a = *p + 3; }\n"
"void call(int x, int *p) { x++; use(p); }\n"
"int main() {\n"
" call(4,0);\n"
"}");
ASSERT_EQUALS("test.cpp:1:error:Null pointer dereference: p\n"
"test.cpp:4:note:Calling function call, 2nd argument is null\n"
"test.cpp:2:note:Calling function use, 1st argument is null\n"
"test.cpp:1:note:Dereferencing argument p that is null\n", errout_str());
ctu("void dostuff(int *x, int *y) {\n"
" if (!var)\n"
" return -1;\n" // <- early return
" *x = *y;\n"
"}\n"
"\n"
"void f() {\n"
" dostuff(a, 0);\n"
"}");
ASSERT_EQUALS("", errout_str());
ctu("void dostuff(int *x, int *y) {\n"
" if (cond)\n"
" *y = -1;\n" // <- conditionally written
" *x = *y;\n"
"}\n"
"\n"
"void f() {\n"
" dostuff(a, 0);\n"
"}");
ASSERT_EQUALS("", errout_str());
// else
ctu("void dostuff(int mask, int *p) {\n"
" if (mask == 13) ;\n"
" else *p = 45;\n"
"}\n"
"\n"
"void f() {\n"
" dostuff(0, 0);\n"
"}");
ASSERT_EQUALS("", errout_str());
// ?, &&, ||
ctu("void dostuff(int mask, int *p) {\n"
" x = (mask & 1) ? *p : 0;\n"
"}\n"
"\n"
"void f() {\n"
" dostuff(0, 0);\n"
"}");
ASSERT_EQUALS("", errout_str());
ctu("void g(int* x) { *x; }\n"
"void f(int* x) {\n"
" if (x)\n"
" g(x);\n"
"}");
ASSERT_EQUALS("", errout_str());
ctu("size_t f(int* p) {\n"
" size_t len = sizeof(*p);\n"
" return len;\n"
"}\n"
"void g() {\n"
" f(NULL);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
ctu("size_t f(int* p) {\n"
" size_t len = alignof(*p);\n"
" return len;\n"
"}\n"
"void g() {\n"
" f(NULL);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
};
REGISTER_TEST(TestNullPointer)
| null |
1,020 | cpp | cppcheck | testsimplifytokens.cpp | test/testsimplifytokens.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#include "errortypes.h"
#include "helpers.h"
#include "platform.h"
#include "settings.h"
#include "standards.h"
#include "fixture.h"
#include "token.h"
#include <cstddef>
#include <string>
class TestSimplifyTokens : public TestFixture {
public:
TestSimplifyTokens() : TestFixture("TestSimplifyTokens") {}
private:
const Settings settings0 = settingsBuilder().severity(Severity::portability).build();
const Settings settings1 = settingsBuilder().severity(Severity::style).build();
const Settings settings_std = settingsBuilder().library("std.cfg").build();
const Settings settings_windows = settingsBuilder().library("windows.cfg").severity(Severity::portability).build();
void run() override {
TEST_CASE(combine_strings);
TEST_CASE(combine_wstrings);
TEST_CASE(combine_ustrings);
TEST_CASE(combine_Ustrings);
TEST_CASE(combine_u8strings);
TEST_CASE(combine_mixedstrings);
TEST_CASE(double_plus);
TEST_CASE(redundant_plus);
TEST_CASE(redundant_plus_numbers);
TEST_CASE(declareVar);
TEST_CASE(declareArray);
TEST_CASE(dontRemoveIncrement);
TEST_CASE(elseif1);
TEST_CASE(namespaces);
// Simplify "not" to "!" (#345)
TEST_CASE(not1);
// Simplify "and" to "&&" (#620)
TEST_CASE(and1);
// Simplify "or" to "||"
TEST_CASE(or1);
TEST_CASE(cAlternativeTokens);
TEST_CASE(comma_keyword);
TEST_CASE(simplifyOperator1);
TEST_CASE(simplifyOperator2);
TEST_CASE(simplifyArrayAccessSyntax);
TEST_CASE(pointeralias1);
TEST_CASE(pointeralias3);
// struct ABC { } abc; => struct ABC { }; ABC abc;
TEST_CASE(simplifyStructDecl1);
TEST_CASE(simplifyStructDecl2); // ticket #2579
TEST_CASE(simplifyStructDecl3);
TEST_CASE(simplifyStructDecl4);
TEST_CASE(simplifyStructDecl6); // ticket #3732
TEST_CASE(simplifyStructDecl7); // ticket #476 (static anonymous struct array)
TEST_CASE(simplifyStructDecl8); // ticket #7698
TEST_CASE(simplifyStructDecl9);
// register int var; => int var;
// inline int foo() {} => int foo() {}
TEST_CASE(removeUnwantedKeywords);
// remove calling convention __cdecl, __stdcall, ...
TEST_CASE(simplifyCallingConvention);
// remove __attribute, __attribute__
TEST_CASE(simplifyAttribute);
TEST_CASE(simplifyFunctorCall);
TEST_CASE(simplifyFunctionPointer); // ticket #5339 (simplify function pointer after comma)
TEST_CASE(simplifyFunctionReturn);
TEST_CASE(consecutiveBraces);
TEST_CASE(simplifyOverride); // ticket #5069
TEST_CASE(simplifyNestedNamespace);
TEST_CASE(simplifyNamespaceAliases1);
TEST_CASE(simplifyNamespaceAliases2); // ticket #10281
TEST_CASE(simplifyNamespaceAliases3);
TEST_CASE(simplifyKnownVariables2);
TEST_CASE(simplifyKnownVariables3);
TEST_CASE(simplifyKnownVariables4);
TEST_CASE(simplifyKnownVariables5);
TEST_CASE(simplifyKnownVariables13);
TEST_CASE(simplifyKnownVariables14);
TEST_CASE(simplifyKnownVariables16);
TEST_CASE(simplifyKnownVariables17);
TEST_CASE(simplifyKnownVariables18);
TEST_CASE(simplifyKnownVariables19);
TEST_CASE(simplifyKnownVariables21);
TEST_CASE(simplifyKnownVariables25);
// FIXME Does expression id handle these? TEST_CASE(simplifyKnownVariables29); // ticket #1811
TEST_CASE(simplifyKnownVariables30);
TEST_CASE(simplifyKnownVariables34);
TEST_CASE(simplifyKnownVariables36); // ticket #5972
TEST_CASE(simplifyKnownVariables42); // ticket #2031 - known string value after strcpy
TEST_CASE(simplifyKnownVariables43);
TEST_CASE(simplifyKnownVariables44); // ticket #3117 - don't simplify static variables
TEST_CASE(simplifyKnownVariables46); // ticket #3587 - >>
TEST_CASE(simplifyKnownVariables47); // ticket #3627 - >>
TEST_CASE(simplifyKnownVariables48); // ticket #3754 - wrong simplification in for loop header
TEST_CASE(simplifyKnownVariables49); // #3691 - continue in switch
TEST_CASE(simplifyKnownVariables50); // #4066 sprintf changes
TEST_CASE(simplifyKnownVariables51); // #4409 hang
TEST_CASE(simplifyKnownVariables54); // #4913 'x' is not 0 after *--x=0;
TEST_CASE(simplifyKnownVariables56); // ticket #5301 - >>
TEST_CASE(simplifyKnownVariables58); // ticket #5268
TEST_CASE(simplifyKnownVariables59); // skip for header
TEST_CASE(simplifyKnownVariables61); // #7805
TEST_CASE(simplifyKnownVariables62); // #5666 - p=&str[0]
TEST_CASE(simplifyKnownVariables63); // #10798
TEST_CASE(simplifyKnownVariablesBailOutAssign1);
TEST_CASE(simplifyKnownVariablesBailOutAssign2);
TEST_CASE(simplifyKnownVariablesBailOutFor1);
TEST_CASE(simplifyKnownVariablesBailOutFor2);
TEST_CASE(simplifyKnownVariablesBailOutFor3);
TEST_CASE(simplifyKnownVariablesBailOutMemberFunction);
TEST_CASE(simplifyKnownVariablesBailOutConditionalIncrement);
TEST_CASE(simplifyKnownVariablesBailOutSwitchBreak); // ticket #2324
TEST_CASE(simplifyKnownVariablesClassMember); // #2815 - value of class member may be changed by function call
TEST_CASE(simplifyKnownVariablesFunctionCalls); // Function calls (don't assume pass by reference)
TEST_CASE(simplifyKnownVariablesGlobalVars);
TEST_CASE(simplifyKnownVariablesNamespace); // #10059
TEST_CASE(simplify_constants6); // Ticket #5625: Ternary operator as template parameter
TEST_CASE(simplifyVarDeclInitLists);
}
#define tok(...) tok_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
std::string tok_(const char* file, int line, const char (&code)[size], bool cpp = true, Platform::Type type = Platform::Type::Native) {
const Settings settings = settingsBuilder(settings0).platform(type).build();
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code, cpp), file, line);
return tokenizer.tokens()->stringifyList(nullptr, false);
}
#define tokenizeAndStringify(...) tokenizeAndStringify_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
std::string tokenizeAndStringify_(const char* file, int linenr, const char (&code)[size], bool expand = true, Platform::Type platform = Platform::Type::Native, bool cpp = true, bool cpp11 = true) {
const Settings settings = settingsBuilder(settings1).debugwarnings().platform(platform).cpp(cpp11 ? Standards::CPP11 : Standards::CPP03).build();
// tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code, cpp), file, linenr);
if (tokenizer.tokens())
return tokenizer.tokens()->stringifyList(false, expand, false, true, false, nullptr, nullptr);
return "";
}
#define tokenizeDebugListing(...) tokenizeDebugListing_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
std::string tokenizeDebugListing_(const char* file, int line, const char (&code)[size], bool cpp = true) {
SimpleTokenizer tokenizer(settings0, *this);
ASSERT_LOC(tokenizer.tokenize(code, cpp), file, line);
// result..
return tokenizer.tokens()->stringifyList(true);
}
void combine_strings() {
const char code1[] = "void foo()\n"
"{\n"
"const char *a =\n"
"{\n"
"\"hello \"\n"
"\"world\"\n"
"};\n"
"}\n";
const char code2[] = "void foo()\n"
"{\n"
"const char *a =\n"
"{\n"
"\"hello world\"\n"
"};\n"
"}\n";
ASSERT_EQUALS(tok(code2), tok(code1));
const char code3[] = "x = L\"1\" TEXT(\"2\") L\"3\";";
ASSERT_EQUALS("x = L\"123\" ;", tok(code3, true, Platform::Type::Win64));
const char code4[] = "x = TEXT(\"1\") L\"2\";";
ASSERT_EQUALS("x = L\"1\" L\"2\" ;", tok(code4, true, Platform::Type::Win64));
}
void combine_wstrings() {
const char code[] = "a = L\"hello \" L\"world\" ;\n";
const char expected[] = "a = L\"hello world\" ;";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
ASSERT_EQUALS(expected, tokenizer.tokens()->stringifyList(nullptr, false));
}
void combine_ustrings() {
const char code[] = "abcd = u\"ab\" u\"cd\";";
const char expected[] = "abcd = u\"abcd\" ;";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
ASSERT_EQUALS(expected, tokenizer.tokens()->stringifyList(nullptr, false));
}
void combine_Ustrings() {
const char code[] = "abcd = U\"ab\" U\"cd\";";
const char expected[] = "abcd = U\"abcd\" ;";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
ASSERT_EQUALS(expected, tokenizer.tokens()->stringifyList(nullptr, false));
}
void combine_u8strings() {
const char code[] = "abcd = u8\"ab\" u8\"cd\";";
const char expected[] = "abcd = u8\"abcd\" ;";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
ASSERT_EQUALS(expected, tokenizer.tokens()->stringifyList(nullptr, false));
}
void combine_mixedstrings() {
const char code[] = "abcdef = \"ab\" L\"cd\" \"ef\";";
const char expected[] = "abcdef = L\"abcdef\" ;";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
ASSERT_EQUALS(expected, tokenizer.tokens()->stringifyList(nullptr, false));
}
void double_plus() {
{
const char code1[] = "void foo( int a )\n"
"{\n"
"a++;\n"
"a--;\n"
"++a;\n"
"--a;\n"
"}\n";
ASSERT_EQUALS("void foo ( int a ) { a ++ ; a -- ; ++ a ; -- a ; }", tok(code1));
}
{
const char code1[] = "void foo( int a )\n"
"{\n"
"a=a+a;\n"
"}\n";
ASSERT_EQUALS("void foo ( int a ) { a = a + a ; }", tok(code1));
}
{
const char code1[] = "void foo( int a, int b )\n"
"{\n"
"a=a+++b;\n"
"}\n";
ASSERT_EQUALS("void foo ( int a , int b ) { a = a ++ + b ; }", tok(code1));
}
{
const char code1[] = "void foo( int a, int b )\n"
"{\n"
"a=a---b;\n"
"}\n";
ASSERT_EQUALS("void foo ( int a , int b ) { a = a -- - b ; }", tok(code1));
}
{
const char code1[] = "void foo( int a, int b )\n"
"{\n"
"a=a--+b;\n"
"}\n";
ASSERT_EQUALS("void foo ( int a , int b ) { a = a -- + b ; }", tok(code1));
}
{
const char code1[] = "void foo( int a, int b )\n"
"{\n"
"a=a++-b;\n"
"}\n";
ASSERT_EQUALS("void foo ( int a , int b ) { a = a ++ - b ; }", tok(code1));
}
{
const char code1[] = "void foo( int a, int b )\n"
"{\n"
"a=a+--b;\n"
"}\n";
ASSERT_EQUALS("void foo ( int a , int b ) { a = a + -- b ; }", tok(code1));
}
{
const char code1[] = "void foo( int a, int b )\n"
"{\n"
"a=a-++b;\n"
"}\n";
ASSERT_EQUALS("void foo ( int a , int b ) { a = a - ++ b ; }", tok(code1));
}
}
void redundant_plus() {
{
const char code1[] = "void foo( int a, int b )\n"
"{\n"
"a=a + + b;\n"
"}\n";
ASSERT_EQUALS("void foo ( int a , int b ) { a = a + b ; }", tok(code1));
}
{
const char code1[] = "void foo( int a, int b )\n"
"{\n"
"a=a + + + b;\n"
"}\n";
ASSERT_EQUALS("void foo ( int a , int b ) { a = a + b ; }", tok(code1));
}
{
const char code1[] = "void foo( int a, int b )\n"
"{\n"
"a=a + - b;\n"
"}\n";
ASSERT_EQUALS("void foo ( int a , int b ) { a = a - b ; }", tok(code1));
}
{
const char code1[] = "void foo( int a, int b )\n"
"{\n"
"a=a - + b;\n"
"}\n";
ASSERT_EQUALS("void foo ( int a , int b ) { a = a - b ; }", tok(code1));
}
{
const char code1[] = "void foo( int a, int b )\n"
"{\n"
"a=a - - b;\n"
"}\n";
ASSERT_EQUALS("void foo ( int a , int b ) { a = a + b ; }", tok(code1));
}
{
const char code1[] = "void foo( int a, int b )\n"
"{\n"
"a=a - + - b;\n"
"}\n";
ASSERT_EQUALS("void foo ( int a , int b ) { a = a + b ; }", tok(code1));
}
{
const char code1[] = "void foo( int a, int b )\n"
"{\n"
"a=a - - - b;\n"
"}\n";
ASSERT_EQUALS("void foo ( int a , int b ) { a = a - b ; }", tok(code1));
}
}
void redundant_plus_numbers() {
{
const char code1[] = "void foo( int a )\n"
"{\n"
"a=a + + 1;\n"
"}\n";
ASSERT_EQUALS("void foo ( int a ) { a = a + 1 ; }", tok(code1));
}
{
const char code1[] = "void foo( int a )\n"
"{\n"
"a=a + + + 1;\n"
"}\n";
ASSERT_EQUALS("void foo ( int a ) { a = a + 1 ; }", tok(code1));
}
{
const char code1[] = "void foo( int a )\n"
"{\n"
"a=a + - 1;\n"
"}\n";
ASSERT_EQUALS("void foo ( int a ) { a = a - 1 ; }", tok(code1));
}
{
const char code1[] = "void foo( int a )\n"
"{\n"
"a=a - + 1;\n"
"}\n";
ASSERT_EQUALS("void foo ( int a ) { a = a - 1 ; }", tok(code1));
}
{
const char code1[] = "void foo( int a )\n"
"{\n"
"a=a - - 1;\n"
"}\n";
ASSERT_EQUALS("void foo ( int a ) { a = a + 1 ; }", tok(code1));
}
{
const char code1[] = "void foo( int a )\n"
"{\n"
"a=a - + - 1;\n"
"}\n";
ASSERT_EQUALS("void foo ( int a ) { a = a + 1 ; }", tok(code1));
}
{
const char code1[] = "void foo( int a )\n"
"{\n"
"a=a - - - 1;\n"
"}\n";
ASSERT_EQUALS("void foo ( int a ) { a = a - 1 ; }", tok(code1));
}
}
void declareVar() {
const char code[] = "void f ( ) { char str [ 100 ] = \"100\" ; }";
ASSERT_EQUALS(code, tok(code));
}
void declareArray() {
const char code1[] = "void f ( ) { char str [ ] = \"100\" ; }";
const char expected1[] = "void f ( ) { char str [ 4 ] = \"100\" ; }";
ASSERT_EQUALS(expected1, tok(code1));
const char code2[] = "char str [ ] = \"\\x00\";";
const char expected2[] = "char str [ 2 ] = \"\\0\" ;";
ASSERT_EQUALS(expected2, tok(code2));
const char code3[] = "char str [ ] = \"\\0\";";
const char expected3[] = "char str [ 2 ] = \"\\0\" ;";
ASSERT_EQUALS(expected3, tok(code3));
const char code4[] = "char str [ ] = \"\\n\\n\";";
const char expected4[] = "char str [ 3 ] = \"\\n\\n\" ;";
ASSERT_EQUALS(expected4, tok(code4));
}
void dontRemoveIncrement() {
{
const char code[] = "void f(int a)\n"
"{\n"
" if (a > 10)\n"
" a = 5;\n"
" else\n"
" a = 10;\n"
" a++;\n"
"}\n";
ASSERT_EQUALS("void f ( int a ) { if ( a > 10 ) { a = 5 ; } else { a = 10 ; } a ++ ; }", tok(code));
}
{
const char code[] = "void f(int a)\n"
"{\n"
" if (a > 10)\n"
" a = 5;\n"
" else\n"
" a = 10;\n"
" ++a;\n"
"}\n";
ASSERT_EQUALS("void f ( int a ) { if ( a > 10 ) { a = 5 ; } else { a = 10 ; } ++ a ; }", tok(code));
}
}
void elseif1() {
const char code[] = "void f(){ if(x) {} else if(ab) { cd } else { ef }gh; }";
ASSERT_EQUALS("\n\n##file 0\n1: void f ( ) { if ( x ) { } else { if ( ab ) { cd } else { ef } } gh ; }\n", tokenizeDebugListing(code));
// syntax error: assert there is no segmentation fault
ASSERT_EQUALS("\n\n##file 0\n1: void f ( ) { if ( x ) { } else { if ( x ) { } } }\n", tokenizeDebugListing("void f(){ if(x) {} else if (x) { } }"));
{
const char src[] = "void f(int g,int f) {\n"
"if(g==1) {poo();}\n"
"else if( g == 2 )\n"
"{\n"
" if( f == 0 ){coo();}\n"
" else if( f==1)\n"
" goo();\n"
"}\n"
"}";
const char expected[] = "void f ( int g , int f ) "
"{ "
"if ( g == 1 ) { poo ( ) ; } "
"else { "
"if ( g == 2 ) "
"{ "
"if ( f == 0 ) { coo ( ) ; } "
"else { "
"if ( f == 1 ) "
"{ "
"goo ( ) ; "
"} "
"} "
"} "
"} "
"}";
ASSERT_EQUALS(tok(expected), tok(src));
}
// Ticket #6860 - lambdas
{
const char src[] = "( []{if (ab) {cd}else if(ef) { gh } else { ij }kl}() );";
const char expected[] = "\n\n##file 0\n1: ( [ ] { if ( ab ) { cd } else { if ( ef ) { gh } else { ij } } kl } ( ) ) ;\n";
ASSERT_EQUALS(expected, tokenizeDebugListing(src));
}
{
const char src[] = "[ []{if (ab) {cd}else if(ef) { gh } else { ij }kl}() ];";
const char expected[] = "\n\n##file 0\n1: [ [ ] { if ( ab ) { cd } else { if ( ef ) { gh } else { ij } } kl } ( ) ] ;\n";
ASSERT_EQUALS(expected, tokenizeDebugListing(src));
}
{
const char src[] = "= { []{if (ab) {cd}else if(ef) { gh } else { ij }kl}() }";
const char expected[] = "\n\n##file 0\n1: = { [ ] { if ( ab ) { cd } else { if ( ef ) { gh } else { ij } } kl } ( ) }\n";
ASSERT_EQUALS(expected, tokenizeDebugListing(src));
}
}
void namespaces() {
{
const char code[] = "namespace std { }";
ASSERT_EQUALS(";", tok(code));
}
{
const char code[] = "; namespace std { }";
ASSERT_EQUALS(";", tok(code));
}
{
const char code[] = "using namespace std; namespace a{ namespace b{ void f(){} } }";
const char expected[] = "namespace a { namespace b { void f ( ) { } } }";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "namespace b{ void f(){} }";
const char expected[] = "namespace b { void f ( ) { } }";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "void f(int namespace) { }";
ASSERT_THROW_INTERNAL(tok(code), SYNTAX);
}
}
void not1() {
ASSERT_EQUALS("void f ( ) { if ( ! p ) { ; } }", tok("void f() { if (not p); }", false));
ASSERT_EQUALS("void f ( ) { if ( p && ! q ) { ; } }", tok("void f() { if (p && not q); }", false));
ASSERT_EQUALS("void f ( ) { a = ! ( p && q ) ; }", tok("void f() { a = not(p && q); }", false));
// Don't simplify 'not' or 'compl' if they are defined as a type;
// in variable declaration and in function declaration/definition
ASSERT_EQUALS("struct not { int x ; } ;", tok("struct not { int x; };", false));
ASSERT_EQUALS("void f ( ) { not p ; compl c ; }", tok(" void f() { not p; compl c; }", false));
ASSERT_EQUALS("void foo ( not i ) ;", tok("void foo(not i);", false));
ASSERT_EQUALS("int foo ( not i ) { return g ( i ) ; }", tok("int foo(not i) { return g(i); }", false));
}
void and1() {
ASSERT_EQUALS("void f ( ) { if ( p && q ) { ; } }",
tok("void f() { if (p and q) ; }", false));
ASSERT_EQUALS("void f ( ) { if ( foo ( ) && q ) { ; } }",
tok("void f() { if (foo() and q) ; }", false));
ASSERT_EQUALS("void f ( ) { if ( foo ( ) && bar ( ) ) { ; } }",
tok("void f() { if (foo() and bar()) ; }", false));
ASSERT_EQUALS("void f ( ) { if ( p && bar ( ) ) { ; } }",
tok("void f() { if (p and bar()) ; }", false));
ASSERT_EQUALS("void f ( ) { if ( p && ! q ) { ; } }",
tok("void f() { if (p and not q) ; }", false));
ASSERT_EQUALS("void f ( ) { r = a && b ; }",
tok("void f() { r = a and b; }", false));
ASSERT_EQUALS("void f ( ) { r = ( a || b ) && ( c || d ) ; }",
tok("void f() { r = (a || b) and (c || d); }", false));
ASSERT_EQUALS("void f ( ) { if ( test1 [ i ] == 'A' && test2 [ i ] == 'C' ) { } }",
tok("void f() { if (test1[i] == 'A' and test2[i] == 'C') {} }", false));
}
void or1() {
ASSERT_EQUALS("void f ( ) { if ( p || q ) { ; } }",
tok("void f() { if (p or q) ; }", false));
ASSERT_EQUALS("void f ( ) { if ( foo ( ) || q ) { ; } }",
tok("void f() { if (foo() or q) ; }", false));
ASSERT_EQUALS("void f ( ) { if ( foo ( ) || bar ( ) ) { ; } }",
tok("void f() { if (foo() or bar()) ; }", false));
ASSERT_EQUALS("void f ( ) { if ( p || bar ( ) ) { ; } }",
tok("void f() { if (p or bar()) ; }", false));
ASSERT_EQUALS("void f ( ) { if ( p || ! q ) { ; } }",
tok("void f() { if (p or not q) ; }", false));
ASSERT_EQUALS("void f ( ) { r = a || b ; }",
tok("void f() { r = a or b; }", false));
ASSERT_EQUALS("void f ( ) { r = ( a && b ) || ( c && d ) ; }",
tok("void f() { r = (a && b) or (c && d); }", false));
}
void cAlternativeTokens() {
ASSERT_EQUALS("void f ( ) { err |= ( ( r & s ) && ! t ) ; }",
tok("void f() { err or_eq ((r bitand s) and not t); }", false));
ASSERT_EQUALS("void f ( ) const { r = f ( a [ 4 ] | 0x0F , ~ c , ! d ) ; }",
tok("void f() const { r = f(a[4] bitor 0x0F, compl c, not d) ; }", false));
}
void comma_keyword() {
{
const char code[] = "void foo()\n"
"{\n"
" char *a, *b;\n"
" delete a, delete b;\n"
"}\n";
ASSERT_EQUALS("void foo ( ) { char * a ; char * b ; delete a , delete b ; }", tok(code));
}
{
const char code[] = "void foo()\n"
"{\n"
" struct A *a, *b;\n"
"}\n";
ASSERT_EQUALS("void foo ( ) { struct A * a ; struct A * b ; }", tok(code));
}
{
const char code[] = "void foo()\n"
"{\n"
" struct A **a, **b;\n"
"}\n";
ASSERT_EQUALS("void foo ( ) { struct A * * a ; struct A * * b ; }", tok(code));
}
{
const char code[] = "void foo()\n"
"{\n"
" char *a, *b;\n"
" delete a, b;\n"
"}\n";
ASSERT_EQUALS("void foo ( ) { char * a ; char * b ; delete a , b ; }", tok(code));
}
{
const char code[] = "void foo()\n"
"{\n"
" char *a, *b, *c;\n"
" delete a, b, c;\n"
"}\n";
// delete a; b; c; would be better but this will do too
ASSERT_EQUALS("void foo ( ) { char * a ; char * b ; char * c ; delete a , b , c ; }", tok(code));
}
{
const char code[] = "void foo()\n"
"{\n"
" char *a, *b;\n"
" if (x)\n"
" delete a, b;\n"
"}\n";
ASSERT_EQUALS("void foo ( ) { char * a ; char * b ; if ( x ) { delete a , b ; } }", tok(code));
}
{
const char code[] = "void foo()\n"
"{\n"
" char *a, *b, *c;\n"
" if (x) \n"
" delete a, b, c;\n"
"}\n";
// delete a; b; c; would be better but this will do too
ASSERT_EQUALS("void foo ( ) { char * a ; char * b ; char * c ; if ( x ) { delete a , b , c ; } }", tok(code));
}
{
const char code[] = "void foo()\n"
"{\n"
" char **a, **b, **c;\n"
"}\n";
ASSERT_EQUALS("void foo ( ) { char * * a ; char * * b ; char * * c ; }", tok(code));
}
{
const char code[] = "void foo()\n"
"{\n"
" delete [] a, a = 0;\n"
"}\n";
ASSERT_EQUALS("void foo ( ) { delete [ ] a , a = 0 ; }", tok(code));
}
{
const char code[] = "void foo()\n"
"{\n"
" delete a, a = 0;\n"
"}\n";
ASSERT_EQUALS("void foo ( ) { delete a , a = 0 ; }", tok(code));
}
{
const char code[] = "void foo()\n"
"{\n"
" if( x ) delete a, a = 0;\n"
"}\n";
ASSERT_EQUALS("void foo ( ) { if ( x ) { delete a , a = 0 ; } }", tok(code));
}
{
const char code[] = "void f()\n"
"{\n"
" for(int a,b; a < 10; a = a + 1, b = b + 1);\n"
"}\n";
ASSERT_EQUALS("void f ( ) { for ( int a , b ; a < 10 ; a = a + 1 , b = b + 1 ) { ; } }", tok(code));
}
{
const char code[] = "void f()\n"
"{\n"
" char buf[BUFSIZ], **p;\n"
" char *ptrs[BUFSIZ], **pp;\n"
"}\n";
ASSERT_EQUALS("void f ( ) { char buf [ BUFSIZ ] ; char * * p ; char * ptrs [ BUFSIZ ] ; char * * pp ; }", tok(code));
}
{
// #4786 - don't replace , with ; in ".. : public B, C .." code
const char code[] = "template < class T = X > class A : public B , C { } ;";
ASSERT_EQUALS(code, tok(code));
}
}
void simplifyOperator1() {
// #3237 - error merging namespaces with operators
const char code[] = "class c {\n"
"public:\n"
" operator std::string() const;\n"
" operator string() const;\n"
"};\n";
const char expected[] = "class c { "
"public: "
"operatorstd::string ( ) const ; "
"operatorstring ( ) const ; "
"} ;";
ASSERT_EQUALS(expected, tok(code));
}
void simplifyOperator2() {
// #6576
ASSERT_EQUALS("template < class T > class SharedPtr { "
"SharedPtr & operator= ( const SharedPtr < Y > & r ) ; "
"} ; "
"class TClass { "
"public: TClass & operator= ( const TClass & rhs ) ; "
"} ; "
"TClass :: TClass ( const TClass & other ) { operator= ( other ) ; }",
tok("template<class T>\n"
" class SharedPtr {\n"
" SharedPtr& operator=(SharedPtr<Y> const & r);\n"
"};\n"
"class TClass {\n"
"public:\n"
" TClass& operator=(const TClass& rhs);\n"
"};\n"
"TClass::TClass(const TClass &other) {\n"
" operator=(other);\n"
"}"));
}
void simplifyArrayAccessSyntax() {
ASSERT_EQUALS("\n\n##file 0\n"
"1: int a@1 ; a@1 [ 13 ] ;\n", tokenizeDebugListing("int a; 13[a];"));
}
void pointeralias1() {
{
const char code[] = "void f(char *p1)\n"
"{\n"
" char *p = p1;\n"
" p1 = 0;"
" x(p);\n"
"}\n";
const char expected[] = "void f ( char * p1 ) "
"{ "
"char * p ; p = p1 ; "
"p1 = 0 ; "
"x ( p ) ; "
"}";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "void foo(Result* ptr)\n"
"{\n"
" Result* obj = ptr;\n"
" ++obj->total;\n"
"}\n";
const char expected[] = "void foo ( Result * ptr ) "
"{ "
"Result * obj ; obj = ptr ; "
"++ obj . total ; "
"}";
ASSERT_EQUALS(expected, tok(code));
}
}
void pointeralias3() {
const char code[] = "void f()\n"
"{\n"
" int i, j, *p;\n"
" if (ab) p = &i;\n"
" else p = &j;\n"
" *p = 0;\n"
"}\n";
const char expected[] = "void f ( ) "
"{"
" int i ; int j ; int * p ;"
" if ( ab ) { p = & i ; }"
" else { p = & j ; }"
" * p = 0 ; "
"}";
ASSERT_EQUALS(expected, tok(code));
}
void simplifyStructDecl1() {
{
const char code[] = "struct ABC { } abc;";
const char expected[] = "struct ABC { } ; struct ABC abc ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "struct ABC { } * pabc;";
const char expected[] = "struct ABC { } ; struct ABC * pabc ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "struct ABC { } abc[4];";
const char expected[] = "struct ABC { } ; struct ABC abc [ 4 ] ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "struct ABC { } abc, def;";
const char expected[] = "struct ABC { } ; struct ABC abc ; struct ABC def ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "struct ABC { } abc, * pabc;";
const char expected[] = "struct ABC { } ; struct ABC abc ; struct ABC * pabc ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "struct ABC { struct DEF {} def; } abc;";
const char expected[] = "struct ABC { struct DEF { } ; struct DEF def ; } ; struct ABC abc ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "struct { } abc;";
const char expected[] = "struct Anonymous0 { } ; struct Anonymous0 abc ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "struct { } * pabc;";
const char expected[] = "struct Anonymous0 { } ; struct Anonymous0 * pabc ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "struct { } abc[4];";
const char expected[] = "struct Anonymous0 { } ; struct Anonymous0 abc [ 4 ] ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "struct {int a;} const array[3] = {0};";
const char expected[] = "struct Anonymous0 { int a ; } ; struct Anonymous0 const array [ 3 ] = { 0 } ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "static struct {int a;} const array[3] = {0};";
const char expected[] = "struct Anonymous0 { int a ; } ; static struct Anonymous0 const array [ 3 ] = { 0 } ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "struct { } abc, def;";
const char expected[] = "struct Anonymous0 { } ; struct Anonymous0 abc ; struct Anonymous0 def ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "struct { } abc, * pabc;";
const char expected[] = "struct Anonymous0 { } ; struct Anonymous0 abc ; struct Anonymous0 * pabc ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "struct { struct DEF {} def; } abc;";
const char expected[] = "struct Anonymous0 { struct DEF { } ; struct DEF def ; } ; struct Anonymous0 abc ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "struct ABC { struct {} def; } abc;";
const char expected[] = "struct ABC { struct Anonymous0 { } ; struct Anonymous0 def ; } ; struct ABC abc ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "struct { struct {} def; } abc;";
const char expected[] = "struct Anonymous0 { struct Anonymous1 { } ; struct Anonymous1 def ; } ; struct Anonymous0 abc ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "union ABC { int i; float f; } abc;";
const char expected[] = "union ABC { int i ; float f ; } ; union ABC abc ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "struct ABC { struct {} def; };";
const char expected[] = "struct ABC { struct Anonymous0 { } ; struct Anonymous0 def ; } ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "struct ABC : public XYZ { struct {} def; };";
const char expected[] = "struct ABC : public XYZ { struct Anonymous0 { } ; struct Anonymous0 def ; } ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "struct { int x; }; int y;";
const char expected[] = "int x ; int y ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "struct { int x; };";
const char expected[] = "int x ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "struct { };";
const char expected[] = ";";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "struct { struct { struct { } ; } ; };";
const char expected[] = ";";
ASSERT_EQUALS(expected, tok(code));
}
// ticket 2464
{
const char code[] = "static struct ABC { } abc ;";
const char expected[] = "struct ABC { } ; static struct ABC abc ;";
ASSERT_EQUALS(expected, tok(code));
}
// ticket #980
{
const char code[] = "void f() { int A(1),B(2),C=3,D,E(5),F=6; }";
const char expected[] = "void f ( ) { int A ; A = 1 ; int B ; B = 2 ; int C ; C = 3 ; int D ; int E ; E = 5 ; int F ; F = 6 ; }";
ASSERT_EQUALS(expected, tok(code));
}
// ticket #8284
{
const char code[] = "void f() { class : foo<int> { } abc; }";
const char expected[] = "void f ( ) { class Anonymous0 : foo < int > { } ; Anonymous0 abc ; }";
ASSERT_EQUALS(expected, tok(code));
}
}
void simplifyStructDecl2() { // ticket #2479 (segmentation fault)
const char code[] = "struct { char c; }";
const char expected[] = "struct { char c ; }";
ASSERT_EQUALS(expected, tok(code));
}
void simplifyStructDecl3() {
{
const char code[] = "class ABC { } abc;";
const char expected[] = "class ABC { } ; ABC abc ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "class ABC { } * pabc;";
const char expected[] = "class ABC { } ; ABC * pabc ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "class ABC { } abc[4];";
const char expected[] = "class ABC { } ; ABC abc [ 4 ] ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "class ABC { } abc, def;";
const char expected[] = "class ABC { } ; ABC abc ; ABC def ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "class ABC { } abc, * pabc;";
const char expected[] = "class ABC { } ; ABC abc ; ABC * pabc ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "class ABC { class DEF {} def; } abc;";
const char expected[] = "class ABC { class DEF { } ; DEF def ; } ; ABC abc ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "class { } abc;";
const char expected[] = "class { } abc ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "class { } * pabc;";
const char expected[] = "class { } * pabc ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "class { } abc[4];";
const char expected[] = "class { } abc [ 4 ] ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "class { } abc, def;";
const char expected[] = "class { } abc , def ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "class { } abc, * pabc;";
const char expected[] = "class { } abc , * pabc ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "struct { class DEF {} def; } abc;";
const char expected[] = "struct Anonymous0 { class DEF { } ; DEF def ; } ; struct Anonymous0 abc ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "class ABC { struct {} def; } abc;";
const char expected[] = "class ABC { struct Anonymous0 { } ; struct Anonymous0 def ; } ; ABC abc ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "class { class {} def; } abc;";
const char expected[] = "class { class { } def ; } abc ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "class ABC { struct {} def; };";
const char expected[] = "class ABC { struct Anonymous0 { } ; struct Anonymous0 def ; } ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "class ABC : public XYZ { struct {} def; };";
const char expected[] = "class ABC : public XYZ { struct Anonymous0 { } ; struct Anonymous0 def ; } ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "class { int x; }; int y;";
const char expected[] = "class { int x ; } ; int y ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "class { int x; };";
const char expected[] = "class { int x ; } ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "class { };";
const char expected[] = "class { } ;";
ASSERT_EQUALS(expected, tok(code));
}
}
void simplifyStructDecl4() {
const char code[] = "class ABC {\n"
" void foo() {\n"
" union {\n"
" int i;\n"
" float f;\n"
" };\n"
" struct Fee { } fee;\n"
" }\n"
" union {\n"
" long long ll;\n"
" double d;\n"
" };\n"
"} abc;\n";
const char expected[] = "class ABC { "
"void foo ( ) { "
"union { int i ; float f ; } ; "
"struct Fee { } ; struct Fee fee ; "
"} "
"union { "
"long ll ; "
"double d ; "
"} ; "
"} ; ABC abc ;";
ASSERT_EQUALS(expected, tok(code));
}
void simplifyStructDecl6() {
ASSERT_EQUALS("struct A { "
"char integers [ X ] ; "
"} ; struct A arrays ; arrays = { { 0 } } ;",
tok("struct A {\n"
" char integers[X];\n"
"} arrays = {{0}};"));
}
void simplifyStructDecl7() {
ASSERT_EQUALS("struct Anonymous0 { char x ; } ; struct Anonymous0 a [ 2 ] ;",
tok("struct { char x; } a[2];"));
ASSERT_EQUALS("struct Anonymous0 { char x ; } ; static struct Anonymous0 a [ 2 ] ;",
tok("static struct { char x; } a[2];"));
}
void simplifyStructDecl8() {
ASSERT_EQUALS("enum A { x , y , z } ; enum A a ; a = x ;", tok("enum A { x, y, z } a(x);"));
ASSERT_EQUALS("enum B { x , y , z } ; enum B b ; b = x ;", tok("enum B { x , y, z } b{x};"));
ASSERT_EQUALS("struct C { int i ; } ; struct C c ; c = C { 0 } ;", tok("struct C { int i; } c{0};"));
ASSERT_EQUALS("enum Anonymous0 { x , y , z } ; enum Anonymous0 d ; d = x ;", tok("enum { x, y, z } d(x);"));
ASSERT_EQUALS("enum Anonymous0 { x , y , z } ; enum Anonymous0 e ; e = x ;", tok("enum { x, y, z } e{x};"));
ASSERT_EQUALS("struct Anonymous0 { int i ; } ; struct Anonymous0 f ; f = Anonymous0 { 0 } ;", tok("struct { int i; } f{0};"));
ASSERT_EQUALS("struct Anonymous0 { } ; struct Anonymous0 x ; x = { 0 } ;", tok("struct {} x = {0};"));
ASSERT_EQUALS("enum G : short { x , y , z } ; enum G g ; g = x ;", tok("enum G : short { x, y, z } g(x);"));
ASSERT_EQUALS("enum H : short { x , y , z } ; enum H h ; h = x ;", tok("enum H : short { x, y, z } h{x};"));
ASSERT_EQUALS("enum class I : short { x , y , z } ; enum I i ; i = x ;", tok("enum class I : short { x, y, z } i(x);"));
ASSERT_EQUALS("enum class J : short { x , y , z } ; enum J j ; j = x ;", tok("enum class J : short { x, y, z } j{x};"));
}
void simplifyStructDecl9() {
const char *exp{};
{
const char code[] = "enum E : int;\n" // #12588
"void f() {}\n"
"namespace {\n"
" struct S {\n"
" explicit S(int i) : m(i) {}\n"
" int m;\n"
" };\n"
"}\n"
"void g() { S s(0); }\n";
exp = "enum E : int ; "
"void f ( ) { } "
"namespace { "
"struct S { "
"explicit S ( int i ) : m ( i ) { } "
"int m ; "
"} ; "
"} "
"void g ( ) { S s ( 0 ) ; }";
ASSERT_EQUALS(exp, tok(code));
}
{
const char code[] = "struct S {\n" // 12595
" explicit S() {\n"
" e = E1;\n"
" }\n"
" enum { E1 } e = E1;\n"
"};\n";
exp = "struct S { "
"explicit S ( ) { e = E1 ; } "
"enum Anonymous0 { E1 } ; "
"enum Anonymous0 e ; "
"e = E1 ; "
"} ;";
ASSERT_EQUALS(exp, tok(code));
}
{
const char code[] = "struct S {\n"
" explicit S() {\n"
" e = E1;\n"
" }\n"
" enum : std::uint8_t { E1 } e = E1;\n"
"};\n";
exp = "struct S { "
"explicit S ( ) { e = E1 ; } "
"enum Anonymous0 : std :: uint8_t { E1 } ; "
"enum Anonymous0 e ; "
"e = E1 ; "
"} ;";
ASSERT_EQUALS(exp, tok(code));
}
}
void removeUnwantedKeywords() {
ASSERT_EQUALS("int var ;", tok("register int var ;"));
ASSERT_EQUALS("short var ;", tok("register short int var ;"));
ASSERT_EQUALS("int foo ( ) { }", tok("inline int foo ( ) { }"));
ASSERT_EQUALS("int foo ( ) { }", tok("__inline int foo ( ) { }"));
ASSERT_EQUALS("int foo ( ) { }", tok("__forceinline int foo ( ) { }"));
ASSERT_EQUALS("constexpr int foo ( ) { }", tok("constexpr int foo() { }"));
ASSERT_EQUALS("constexpr int foo ( ) { }", tok("consteval int foo() { }"));
ASSERT_EQUALS("int x ; x = 0 ;", tok("constinit int x = 0;"));
ASSERT_EQUALS("void f ( ) { int final [ 10 ] ; }", tok("void f() { int final[10]; }"));
ASSERT_EQUALS("int * p ;", tok("int * __restrict p;", false));
ASSERT_EQUALS("int * * p ;", tok("int * __restrict__ * p;", false));
ASSERT_EQUALS("void foo ( float * a , float * b ) ;", tok("void foo(float * __restrict__ a, float * __restrict__ b);", false));
ASSERT_EQUALS("int * p ;", tok("int * restrict p;", false));
ASSERT_EQUALS("int * * p ;", tok("int * restrict * p;", false));
ASSERT_EQUALS("void foo ( float * a , float * b ) ;", tok("void foo(float * restrict a, float * restrict b);", false));
ASSERT_EQUALS("void foo ( int restrict ) ;", tok("void foo(int restrict);"));
ASSERT_EQUALS("int * p ;", tok("typedef int * __restrict__ rint; rint p;", false));
// don't remove struct members:
ASSERT_EQUALS("a = b . _inline ;", tok("a = b._inline;"));
ASSERT_EQUALS("int i ; i = 0 ;", tok("auto int i = 0;", false));
ASSERT_EQUALS("auto i ; i = 0 ;", tok("auto i = 0;", true));
}
void simplifyCallingConvention() {
ASSERT_EQUALS("int f ( ) ;", tok("int __cdecl f();"));
ASSERT_EQUALS("int f ( ) ;", tok("int __stdcall f();"));
ASSERT_EQUALS("int f ( ) ;", tok("int __fastcall f();"));
ASSERT_EQUALS("int f ( ) ;", tok("int __clrcall f();"));
ASSERT_EQUALS("int f ( ) ;", tok("int __thiscall f();"));
ASSERT_EQUALS("int f ( ) ;", tok("int __syscall f();"));
ASSERT_EQUALS("int f ( ) ;", tok("int __pascal f();"));
ASSERT_EQUALS("int f ( ) ;", tok("int __fortran f();"));
ASSERT_EQUALS("int f ( ) ;", tok("int __far __cdecl f();"));
ASSERT_EQUALS("int f ( ) ;", tok("int __far __stdcall f();"));
ASSERT_EQUALS("int f ( ) ;", tok("int __far __fastcall f();"));
ASSERT_EQUALS("int f ( ) ;", tok("int __far __clrcall f();"));
ASSERT_EQUALS("int f ( ) ;", tok("int __far __thiscall f();"));
ASSERT_EQUALS("int f ( ) ;", tok("int __far __syscall f();"));
ASSERT_EQUALS("int f ( ) ;", tok("int __far __pascal f();"));
ASSERT_EQUALS("int f ( ) ;", tok("int __far __fortran f();"));
ASSERT_EQUALS("int f ( ) ;", tok("int WINAPI f();", true, Platform::Type::Win32A));
ASSERT_EQUALS("int f ( ) ;", tok("int APIENTRY f();", true, Platform::Type::Win32A));
ASSERT_EQUALS("int f ( ) ;", tok("int CALLBACK f();", true, Platform::Type::Win32A));
// don't simplify Microsoft defines in unix code (#7554)
ASSERT_EQUALS("enum E { CALLBACK } ;", tok("enum E { CALLBACK } ;", true, Platform::Type::Unix32));
}
void simplifyAttribute() {
ASSERT_EQUALS("int f ( ) ;", tok("__attribute__ ((visibility(\"default\"))) int f();"));
ASSERT_EQUALS("int f ( ) ;", tok("__attribute__((visibility(\"default\"))) int f();"));
ASSERT_EQUALS("int f ( ) ;", tok("__attribute ((visibility(\"default\"))) int f();"));
ASSERT_EQUALS("int f ( ) ;", tok("__attribute__ ((visibility(\"default\"))) __attribute__ ((warn_unused_result)) int f();"));
ASSERT_EQUALS("blah :: blah f ( ) ;", tok("__attribute__ ((visibility(\"default\"))) blah::blah f();"));
ASSERT_EQUALS("template < T > Result < T > f ( ) ;", tok("template<T> __attribute__ ((warn_unused_result)) Result<T> f();"));
ASSERT_EQUALS("template < T , U > Result < T , U > f ( ) ;", tok("template<T, U> __attribute__ ((warn_unused_result)) Result<T, U> f();"));
ASSERT_EQUALS("void ( * fp ) ( ) ; fp = nullptr ;", tok("typedef void (*fp_t)() __attribute__((noreturn)); fp_t fp = nullptr;")); // #12137
}
void simplifyFunctorCall() {
ASSERT_EQUALS("IncrementFunctor ( ) ( a ) ;", tok("IncrementFunctor()(a);"));
}
// #ticket #5339 (simplify function pointer after comma)
void simplifyFunctionPointer() {
ASSERT_EQUALS("f ( double x , double ( * y ) ( ) ) ;", tok("f (double x, double (*y) ());"));
}
void simplifyFunctionReturn() {
{
const char code[] = "typedef void (*testfp)();\n"
"struct Fred\n"
"{\n"
" testfp get1() { return 0; }\n"
" void ( * get2 ( ) ) ( ) { return 0 ; }\n"
" testfp get3();\n"
" void ( * get4 ( ) ) ( );\n"
"};";
const char expected[] = "struct Fred "
"{ "
"void * get1 ( ) { return 0 ; } "
"void * get2 ( ) { return 0 ; } "
"void * get3 ( ) ; "
"void * get4 ( ) ; "
"} ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "class Fred {\n"
" std::string s;\n"
" const std::string & foo();\n"
"};\n"
"const std::string & Fred::foo() { return \"\"; }";
const char expected[] = "class Fred { "
"std :: string s ; "
"const std :: string & foo ( ) ; "
"} ; "
"const std :: string & Fred :: foo ( ) { return \"\" ; }";
ASSERT_EQUALS(expected, tok(code));
}
{
// Ticket #7916
// Tokenization would include "int fact < 2 > ( ) { return 2 > ( ) ; }" and generate
// a parse error (and use after free)
const char code[] = "extern \"C\" void abort ();\n"
"template <int a> inline int fact2 ();\n"
"template <int a> inline int fact () {\n"
" return a * fact2<a-1> ();\n"
"}\n"
"template <> inline int fact<1> () {\n"
" return 1;\n"
"}\n"
"template <int a> inline int fact2 () {\n"
" return a * fact<a-1>();\n"
"}\n"
"template <> inline int fact2<1> () {\n"
" return 1;\n"
"}\n"
"int main() {\n"
" fact2<3> ();\n"
" fact2<2> ();\n"
"}";
(void)tok(code);
}
}
void consecutiveBraces() {
ASSERT_EQUALS("void f ( ) { }", tok("void f(){{}}"));
ASSERT_EQUALS("void f ( ) { }", tok("void f(){{{}}}"));
ASSERT_EQUALS("void f ( ) { for ( ; ; ) { } }", tok("void f () { for(;;){} }"));
ASSERT_EQUALS("void f ( ) { { scope_lock lock ; foo ( ) ; } { scope_lock lock ; bar ( ) ; } }", tok("void f () { {scope_lock lock; foo();} {scope_lock lock; bar();} }"));
}
void simplifyOverride() { // ticket #5069
const char code[] = "void fun() {\n"
" unsigned char override[] = {0x01, 0x02};\n"
" doSomething(override, sizeof(override));\n"
"}\n";
ASSERT_EQUALS("void fun ( ) { char override [ 2 ] = { 0x01 , 0x02 } ; doSomething ( override , sizeof ( override ) ) ; }",
tok(code));
}
void simplifyNestedNamespace() {
ASSERT_EQUALS("namespace A { namespace B { namespace C { int i ; } } }", tok("namespace A::B::C { int i; }"));
}
void simplifyNamespaceAliases1() {
ASSERT_EQUALS(";",
tok("namespace ios = boost::iostreams;"));
ASSERT_EQUALS("boost :: iostreams :: istream foo ( \"foo\" ) ;",
tok("namespace ios = boost::iostreams; ios::istream foo(\"foo\");"));
ASSERT_EQUALS("boost :: iostreams :: istream foo ( \"foo\" ) ;",
tok("using namespace std; namespace ios = boost::iostreams; ios::istream foo(\"foo\");"));
ASSERT_EQUALS(";",
tok("using namespace std; namespace ios = boost::iostreams;"));
ASSERT_EQUALS("namespace NS { boost :: iostreams :: istream foo ( \"foo\" ) ; }",
tok("namespace NS { using namespace std; namespace ios = boost::iostreams; ios::istream foo(\"foo\"); }"));
// duplicate namespace aliases
ASSERT_EQUALS(";",
tok("namespace ios = boost::iostreams;\nnamespace ios = boost::iostreams;"));
ASSERT_EQUALS(";",
tok("namespace ios = boost::iostreams;\nnamespace ios = boost::iostreams;\nnamespace ios = boost::iostreams;"));
ASSERT_EQUALS("namespace A { namespace B { void foo ( ) { bar ( A :: B :: ab ( ) ) ; } } }",
tok("namespace A::B {"
"namespace AB = A::B;"
"void foo() {"
" namespace AB = A::B;" // duplicate declaration
" bar(AB::ab());"
"}"
"namespace AB = A::B;" //duplicate declaration
"}"));
ASSERT_EQUALS(";",
tok("namespace p = boost::python;\n"
"namespace np = boost::numpy;\n"));
// redeclared nested namespace aliases
TODO_ASSERT_EQUALS("namespace A { namespace B { void foo ( ) { bar ( A :: B :: ab ( ) ) ; { baz ( A :: a ( ) ) ; } bar ( A :: B :: ab ( ) ) ; } } }",
"namespace A { namespace B { void foo ( ) { bar ( A :: B :: ab ( ) ) ; { baz ( A :: B :: a ( ) ) ; } bar ( A :: B :: ab ( ) ) ; } } }",
tok("namespace A::B {"
"namespace AB = A::B;"
"void foo() {"
" namespace AB = A::B;" // duplicate declaration
" bar(AB::ab());"
" {"
" namespace AB = A;"
" baz(AB::a());" // redeclaration OK
" }"
" bar(AB::ab());"
"}"
"namespace AB = A::B;" //duplicate declaration
"}"));
// variable and namespace alias with same name
ASSERT_EQUALS("namespace external { namespace ns { "
"class A { "
"public: "
"static void f ( const std :: string & json ) ; "
"} ; "
"} } "
"namespace external { namespace ns { "
"void A :: f ( const std :: string & json ) { } "
"} }",
tok("namespace external::ns {"
" class A {"
" public:"
" static void f(const std::string& json);"
" };"
"}"
"namespace json = rapidjson;"
"namespace external::ns {"
" void A::f(const std::string& json) { }"
"}"));
}
void simplifyNamespaceAliases2() {
ASSERT_EQUALS("void foo ( ) "
"{ "
"int maxResults ; maxResults = :: a :: b :: c :: d :: ef :: MAX ; "
"}",
tok("namespace ef = ::a::b::c::d::ef;"
"void foo()"
"{"
" int maxResults = ::a::b::c::d::ef::MAX;"
"}"));
}
void simplifyNamespaceAliases3() {
ASSERT_EQUALS("namespace N { namespace O { int g ( ) ; } } " // #12586
"void f ( ) { "
"int s ; s = 3 * :: N :: O :: g ( ) ; "
"}",
tok("namespace N { namespace O { int g(); } }\n"
"namespace _n = ::N::O;\n"
"void f() {\n"
" int s = 3 * ::_n::g();\n"
"}\n"));
}
#define simplifyKnownVariables(code) simplifyKnownVariables_(code, __FILE__, __LINE__)
template<size_t size>
std::string simplifyKnownVariables_(const char (&code)[size], const char* file, int line) {
SimpleTokenizer tokenizer(settings0, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
return tokenizer.tokens()->stringifyList(nullptr, false);
}
void simplifyKnownVariables2() {
const char code[] = "void f()\n"
"{\n"
" int a = 10;\n"
" a = g();\n"
" if (a);\n"
"}\n";
ASSERT_EQUALS(
"void f ( ) { int a ; a = 10 ; a = g ( ) ; if ( a ) { ; } }",
simplifyKnownVariables(code));
}
void simplifyKnownVariables3() {
const char code[] = "void f()\n"
"{\n"
" int a = 4;\n"
" while(true){\n"
" break;\n"
" a = 10;\n"
" }\n"
" if (a);\n"
"}\n";
ASSERT_EQUALS(
"void f ( ) { int a ; a = 4 ; while ( true ) { break ; a = 10 ; } if ( a ) { ; } }",
simplifyKnownVariables(code));
}
void simplifyKnownVariables4() {
const char code[] = "void f()\n"
"{\n"
" int a = 4;\n"
" if ( g(a));\n"
"}\n";
// TODO: if a is passed by value is is ok to simplify..
ASSERT_EQUALS(
"void f ( ) { int a ; a = 4 ; if ( g ( a ) ) { ; } }",
simplifyKnownVariables(code));
}
void simplifyKnownVariables5() {
const char code[] = "void f()\n"
"{\n"
" int a = 4;\n"
" if ( a = 5 );\n"
"}\n";
ASSERT_EQUALS(
"void f ( ) { int a ; a = 4 ; if ( a = 5 ) { ; } }",
simplifyKnownVariables(code));
}
void simplifyKnownVariables13() {
const char code[] = "void f()\n"
"{\n"
" int i = 10;\n"
" while(--i) {}\n"
"}\n";
ASSERT_EQUALS(
"void f ( ) { int i ; i = 10 ; while ( -- i ) { } }",
simplifyKnownVariables(code));
}
void simplifyKnownVariables14() {
// ticket #753
const char code[] = "void f ( ) { int n ; n = 1 ; do { ++ n ; } while ( n < 10 ) ; }";
ASSERT_EQUALS(code, simplifyKnownVariables(code));
}
void simplifyKnownVariables16() {
// ticket #807 - segmentation fault when macro isn't found
const char code[] = "void f ( ) { int n = 1; DISPATCH(while); }";
ASSERT_THROW_INTERNAL(simplifyKnownVariables(code), UNKNOWN_MACRO);
}
void simplifyKnownVariables17() {
// ticket #807 - segmentation fault when macro isn't found
const char code[] = "void f ( ) { char *s = malloc(100);mp_ptr p = s; p++; }";
ASSERT_EQUALS(
"void f ( ) { char * s ; s = malloc ( 100 ) ; mp_ptr p ; p = s ; p ++ ; }",
simplifyKnownVariables(code));
}
void simplifyKnownVariables18() {
const char code[] = "void f ( ) { char *s = malloc(100);mp_ptr p = s; ++p; }";
ASSERT_EQUALS(
"void f ( ) { char * s ; s = malloc ( 100 ) ; mp_ptr p ; p = s ; ++ p ; }",
simplifyKnownVariables(code));
}
void simplifyKnownVariables19() {
const char code[] = "void f ( ) { int i=0; do { if (i>0) { a(); } i=b(); } while (i != 12); }";
ASSERT_EQUALS(
"void f ( ) { int i ; i = 0 ; do { if ( i > 0 ) { a ( ) ; } i = b ( ) ; } while ( i != 12 ) ; }",
simplifyKnownVariables(code));
}
void simplifyKnownVariables21() {
ASSERT_EQUALS(
"void foo ( int i ) { int n ; n = i ; for ( i = 0 ; i < n ; ++ i ) { } }",
simplifyKnownVariables("void foo(int i) { int n = i; for (i = 0; i < n; ++i) { } }"));
}
void simplifyKnownVariables25() {
{
// This testcase is related to ticket #1646
const char code[] = "void foo(char *str)\n"
"{\n"
" int i;\n"
" for (i=0;i<10;++i) {\n"
" if (*str == 0) goto label;\n"
" }\n"
" return;\n"
"label:\n"
" str[i] = 0;\n"
"}\n";
// Current result
ASSERT_EQUALS(
"void foo ( char * str ) "
"{"
" int i ;"
" for ( i = 0 ; i < 10 ; ++ i ) {"
" if ( * str == 0 ) { goto label ; }"
" }"
" return ;"
" label : ;"
" str [ i ] = 0 ; "
"}",
simplifyKnownVariables(code));
}
{
// This testcase is related to ticket #1646
const char code[] = "void foo(char *str)\n"
"{\n"
" int i;\n"
" for (i=0;i<10;++i) { }\n"
" return;\n"
" str[i] = 0;\n"
"}\n";
// Current result
ASSERT_EQUALS(
"void foo ( char * str ) "
"{"
" int i ;"
" for ( i = 0 ; i < 10 ; ++ i ) { }"
" return ;"
" str [ i ] = 0 ; "
"}",
simplifyKnownVariables(code));
}
}
// cppcheck-suppress unusedPrivateFunction
void simplifyKnownVariables29() { // ticket #1811
{
const char code[] = "int foo(int u, int v)\n"
"{\n"
" int h = u;\n"
" int i = v;\n"
" return h + i;\n"
"}\n";
const char expected[] = "\n\n"
"##file 0\n"
"1: int foo ( int u@1 , int v@2 )\n"
"2: {\n"
"3:\n"
"4:\n"
"5: return u@1 + v@2 ;\n"
"6: }\n";
ASSERT_EQUALS(expected, tokenizeDebugListing(code));
}
{
const char code[] = "int foo(int u, int v)\n"
"{\n"
" int h = u;\n"
" int i = v;\n"
" return h - i;\n"
"}\n";
const char expected[] = "\n\n"
"##file 0\n"
"1: int foo ( int u@1 , int v@2 )\n"
"2: {\n"
"3:\n"
"4:\n"
"5: return u@1 - v@2 ;\n"
"6: }\n";
ASSERT_EQUALS(expected, tokenizeDebugListing(code));
}
{
const char code[] = "int foo(int u, int v)\n"
"{\n"
" int h = u;\n"
" int i = v;\n"
" return h * i;\n"
"}\n";
const char expected[] = "\n\n"
"##file 0\n"
"1: int foo ( int u@1 , int v@2 )\n"
"2: {\n"
"3:\n"
"4:\n"
"5: return u@1 * v@2 ;\n"
"6: }\n";
ASSERT_EQUALS(expected, tokenizeDebugListing(code));
}
{
const char code[] = "int foo(int u, int v)\n"
"{\n"
" int h = u;\n"
" int i = v;\n"
" return h / i;\n"
"}\n";
const char expected[] = "\n\n"
"##file 0\n"
"1: int foo ( int u@1 , int v@2 )\n"
"2: {\n"
"3:\n"
"4:\n"
"5: return u@1 / v@2 ;\n"
"6: }\n";
ASSERT_EQUALS(expected, tokenizeDebugListing(code));
}
{
const char code[] = "int foo(int u, int v)\n"
"{\n"
" int h = u;\n"
" int i = v;\n"
" return h & i;\n"
"}\n";
const char expected[] = "\n\n"
"##file 0\n"
"1: int foo ( int u@1 , int v@2 )\n"
"2: {\n"
"3:\n"
"4:\n"
"5: return u@1 & v@2 ;\n"
"6: }\n";
ASSERT_EQUALS(expected, tokenizeDebugListing(code));
}
{
const char code[] = "int foo(int u, int v)\n"
"{\n"
" int h = u;\n"
" int i = v;\n"
" return h | i;\n"
"}\n";
const char expected[] = "\n\n"
"##file 0\n"
"1: int foo ( int u@1 , int v@2 )\n"
"2: {\n"
"3:\n"
"4:\n"
"5: return u@1 | v@2 ;\n"
"6: }\n";
ASSERT_EQUALS(expected, tokenizeDebugListing(code));
}
{
const char code[] = "int foo(int u, int v)\n"
"{\n"
" int h = u;\n"
" int i = v;\n"
" return h ^ i;\n"
"}\n";
const char expected[] = "\n\n"
"##file 0\n"
"1: int foo ( int u@1 , int v@2 )\n"
"2: {\n"
"3:\n"
"4:\n"
"5: return u@1 ^ v@2 ;\n"
"6: }\n";
ASSERT_EQUALS(expected, tokenizeDebugListing(code));
}
{
const char code[] = "int foo(int u, int v)\n"
"{\n"
" int h = u;\n"
" int i = v;\n"
" return h % i;\n"
"}\n";
const char expected[] = "\n\n"
"##file 0\n"
"1: int foo ( int u@1 , int v@2 )\n"
"2: {\n"
"3:\n"
"4:\n"
"5: return u@1 % v@2 ;\n"
"6: }\n";
ASSERT_EQUALS(expected, tokenizeDebugListing(code));
}
{
const char code[] = "int foo(int u, int v)\n"
"{\n"
" int h = u;\n"
" int i = v;\n"
" return h >> i;\n"
"}\n";
const char expected[] = "\n\n"
"##file 0\n"
"1: int foo ( int u@1 , int v@2 )\n"
"2: {\n"
"3:\n"
"4:\n"
"5: return u@1 >> v@2 ;\n"
"6: }\n";
ASSERT_EQUALS(expected, tokenizeDebugListing(code));
}
{
const char code[] = "int foo(int u, int v)\n"
"{\n"
" int h = u;\n"
" int i = v;\n"
" return h << i;\n"
"}\n";
const char expected[] = "\n\n"
"##file 0\n"
"1: int foo ( int u@1 , int v@2 )\n"
"2: {\n"
"3:\n"
"4:\n"
"5: return u@1 << v@2 ;\n"
"6: }\n";
ASSERT_EQUALS(expected, tokenizeDebugListing(code));
}
{
const char code[] = "bool foo(int u, int v)\n"
"{\n"
" int h = u;\n"
" int i = v;\n"
" return h == i;\n"
"}\n";
const char expected[] = "\n\n"
"##file 0\n"
"1: bool foo ( int u@1 , int v@2 )\n"
"2: {\n"
"3:\n"
"4:\n"
"5: return u@1 == v@2 ;\n"
"6: }\n";
ASSERT_EQUALS(expected, tokenizeDebugListing(code));
}
{
const char code[] = "bool foo(int u, int v)\n"
"{\n"
" int h = u;\n"
" int i = v;\n"
" return h != i;\n"
"}\n";
const char expected[] = "\n\n"
"##file 0\n"
"1: bool foo ( int u@1 , int v@2 )\n"
"2: {\n"
"3:\n"
"4:\n"
"5: return u@1 != v@2 ;\n"
"6: }\n";
ASSERT_EQUALS(expected, tokenizeDebugListing(code));
}
{
const char code[] = "bool foo(int u, int v)\n"
"{\n"
" int h = u;\n"
" int i = v;\n"
" return h > i;\n"
"}\n";
const char expected[] = "\n\n"
"##file 0\n"
"1: bool foo ( int u@1 , int v@2 )\n"
"2: {\n"
"3:\n"
"4:\n"
"5: return u@1 > v@2 ;\n"
"6: }\n";
ASSERT_EQUALS(expected, tokenizeDebugListing(code));
}
{
const char code[] = "bool foo(int u, int v)\n"
"{\n"
" int h = u;\n"
" int i = v;\n"
" return h >= i;\n"
"}\n";
const char expected[] = "\n\n"
"##file 0\n"
"1: bool foo ( int u@1 , int v@2 )\n"
"2: {\n"
"3:\n"
"4:\n"
"5: return u@1 >= v@2 ;\n"
"6: }\n";
ASSERT_EQUALS(expected, tokenizeDebugListing(code));
}
{
const char code[] = "bool foo(int u, int v)\n"
"{\n"
" int h = u;\n"
" int i = v;\n"
" return h < i;\n"
"}\n";
const char expected[] = "\n\n"
"##file 0\n"
"1: bool foo ( int u@1 , int v@2 )\n"
"2: {\n"
"3:\n"
"4:\n"
"5: return u@1 < v@2 ;\n"
"6: }\n";
ASSERT_EQUALS(expected, tokenizeDebugListing(code));
}
{
const char code[] = "bool foo(int u, int v)\n"
"{\n"
" int h = u;\n"
" int i = v;\n"
" return h <= i;\n"
"}\n";
const char expected[] = "\n\n"
"##file 0\n"
"1: bool foo ( int u@1 , int v@2 )\n"
"2: {\n"
"3:\n"
"4:\n"
"5: return u@1 <= v@2 ;\n"
"6: }\n";
ASSERT_EQUALS(expected, tokenizeDebugListing(code));
}
{
const char code[] = "bool foo(int u, int v)\n"
"{\n"
" int h = u;\n"
" int i = v;\n"
" return h && i;\n"
"}\n";
const char expected[] = "\n\n"
"##file 0\n"
"1: bool foo ( int u@1 , int v@2 )\n"
"2: {\n"
"3:\n"
"4:\n"
"5: return u@1 && v@2 ;\n"
"6: }\n";
ASSERT_EQUALS(expected, tokenizeDebugListing(code));
}
{
const char code[] = "bool foo(int u, int v)\n"
"{\n"
" int h = u;\n"
" int i = v;\n"
" return h || i;\n"
"}\n";
const char expected[] = "\n\n"
"##file 0\n"
"1: bool foo ( int u@1 , int v@2 )\n"
"2: {\n"
"3:\n"
"4:\n"
"5: return u@1 || v@2 ;\n"
"6: }\n";
ASSERT_EQUALS(expected, tokenizeDebugListing(code));
}
}
void simplifyKnownVariables30() {
const char code[] = "int foo() {\n"
" iterator it1 = ints.begin();\n"
" iterator it2 = it1;\n"
" for (++it2;it2!=ints.end();++it2);\n"
"}\n";
const char expected[] = "int foo ( ) {\n"
"iterator it1 ; it1 = ints . begin ( ) ;\n"
"iterator it2 ; it2 = it1 ;\n"
"for ( ++ it2 ; it2 != ints . end ( ) ; ++ it2 ) { ; }\n"
"}";
ASSERT_EQUALS(expected, tokenizeAndStringify(code, true));
}
void simplifyKnownVariables34() {
const char code[] = "void f() {\n"
" int x = 10;\n"
" do { cin >> x; } while (x > 5);\n"
" a[x] = 0;\n"
"}\n";
const char expected[] = "void f ( ) {\n"
"int x ; x = 10 ;\n"
"do { cin >> x ; } while ( x > 5 ) ;\n"
"a [ x ] = 0 ;\n"
"}";
ASSERT_EQUALS(expected, tokenizeAndStringify(code, true));
ASSERT_EQUALS(
"[test.cpp:3]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable cin\n",
errout_str());
}
void simplifyKnownVariables36() {
// Ticket #5972
const char code2[] = "void f() {"
" char buf[10] = \"ab\";"
" memset(buf, 0, 10);"
"}";
const char expected2[] = "void f ( ) { char buf [ 10 ] = \"ab\" ; memset ( buf , 0 , 10 ) ; }";
ASSERT_EQUALS(expected2, tokenizeAndStringify(code2, true));
}
void simplifyKnownVariables42() {
{
const char code[] = "void f() {\n"
" char a[10];\n"
" strcpy(a, \"hello\");\n"
" strcat(a, \"!\");\n"
"}";
const char expected[] = "void f ( ) {\n"
"char a [ 10 ] ;\n"
"strcpy ( a , \"hello\" ) ;\n"
"strcat ( a , \"!\" ) ;\n"
"}";
ASSERT_EQUALS(expected, tokenizeAndStringify(code, true, Platform::Type::Native, false));
}
{
const char code[] = "void f() {"
" char *s = malloc(10);"
" strcpy(s, \"\");"
" free(s);"
"}";
const char expected[] = "void f ( ) {"
" char * s ; s = malloc ( 10 ) ;"
" strcpy ( s , \"\" ) ;"
" free ( s ) ; "
"}";
ASSERT_EQUALS(expected, tokenizeAndStringify(code, true));
}
{
const char code[] = "void f(char *p, char *q) {"
" strcpy(p, \"abc\");"
" q = p;"
"}";
const char expected[] = "void f ( char * p , char * q ) {"
" strcpy ( p , \"abc\" ) ;"
" q = p ; "
"}";
ASSERT_EQUALS(expected, tokenizeAndStringify(code, true));
}
// 3538
{
const char code[] = "void f() {\n"
" char s[10];\n"
" strcpy(s, \"123\");\n"
" if (s[6] == ' ');\n"
"}";
const char expected[] = "void f ( ) {\n"
"char s [ 10 ] ;\n"
"strcpy ( s , \"123\" ) ;\n"
"if ( s [ 6 ] == ' ' ) { ; }\n"
"}";
ASSERT_EQUALS(expected, tokenizeAndStringify(code,true));
ASSERT_EQUALS("", filter_valueflow(errout_str()));
}
}
void simplifyKnownVariables43() {
{
const char code[] = "void f() {\n"
" int a, *p; p = &a;\n"
" { int a = *p; }\n"
"}";
const char expected[] = "void f ( ) {\n"
"int a ; int * p ; p = & a ;\n"
"{ int a ; a = * p ; }\n"
"}";
ASSERT_EQUALS(expected, tokenizeAndStringify(code, true));
}
{
const char code[] = "void f() {\n"
" int *a, **p; p = &a;\n"
" { int *a = *p; }\n"
"}";
const char expected[] = "void f ( ) {\n"
"int * a ; int * * p ; p = & a ;\n"
"{ int * a ; a = * p ; }\n"
"}";
ASSERT_EQUALS(expected, tokenizeAndStringify(code, true));
}
}
void simplifyKnownVariables44() {
const char code[] = "void a() {\n"
" static int i = 10;\n"
" b(i++);\n"
"}";
const char expected[] = "void a ( ) {\n"
"static int i = 10 ;\n"
"b ( i ++ ) ;\n"
"}";
ASSERT_EQUALS(expected, tokenizeAndStringify(code, true));
}
void simplifyKnownVariables46() {
const char code[] = "void f() {\n"
" int x = 0;\n"
" cin >> x;\n"
" return x;\n"
"}";
const char expected[] = "void f ( ) {\n"
"int x ; x = 0 ;\n"
"cin >> x ;\n"
"return x ;\n"
"}";
ASSERT_EQUALS(expected, tokenizeAndStringify(code, true, Platform::Type::Native, true));
ASSERT_EQUALS(
"[test.cpp:3]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable cin\n",
errout_str());
}
void simplifyKnownVariables47() {
// #3621
const char code[] = "void f() {\n"
" int x = 0;\n"
" cin >> std::hex >> x;\n"
"}";
const char expected[] = "void f ( ) {\n"
"int x ; x = 0 ;\n"
"cin >> std :: hex >> x ;\n"
"}";
ASSERT_EQUALS(expected, tokenizeAndStringify(code, true, Platform::Type::Native, true));
ASSERT_EQUALS(
"[test.cpp:3]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable cin\n",
errout_str());
}
void simplifyKnownVariables48() {
// #3754
const char code[] = "void f(int sz) {\n"
" int i;\n"
" for (i = 0; ((i<sz) && (sz>3)); ++i) { }\n"
"}";
const char expected[] = "void f ( int sz ) {\n"
"int i ;\n"
"for ( i = 0 ; ( i < sz ) && ( sz > 3 ) ; ++ i ) { }\n"
"}";
ASSERT_EQUALS(expected, tokenizeAndStringify(code, true, Platform::Type::Native, false));
}
void simplifyKnownVariables49() { // #3691
const char code[] = "void f(int sz) {\n"
" switch (x) {\n"
" case 1: sz = 2; continue;\n"
" case 2: x = sz; break;\n"
" }\n"
"}";
const char expected[] = "void f ( int sz ) {\n"
"switch ( x ) {\n"
"case 1 : ; sz = 2 ; continue ;\n"
"case 2 : ; x = sz ; break ;\n"
"}\n"
"}";
ASSERT_EQUALS(expected, tokenizeAndStringify(code, true, Platform::Type::Native, false));
ASSERT_EQUALS(
"[test.c:2]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable x\n",
errout_str());
}
void simplifyKnownVariables50() { // #4066
{
//don't simplify '&x'!
const char code[] = "const char * foo ( ) {\n"
"const char x1 = 'b' ;\n"
"f ( & x1 ) ;\n"
"const char x2 = 'b' ;\n"
"f ( y , & x2 ) ;\n"
"const char x3 = 'b' ;\n"
"t = & x3 ;\n"
"const char x4 = 'b' ;\n"
"t = y + & x4 ;\n"
"const char x5 = 'b' ;\n"
"z [ & x5 ] = y ;\n"
"const char x6 = 'b' ;\n"
"v = { & x6 } ;\n"
"const char x7 = 'b' ;\n"
"return & x7 ;\n"
"}";
ASSERT_EQUALS(code, tokenizeAndStringify(code, true));
ASSERT_EQUALS(
"[test.cpp:5]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable y\n",
errout_str());
}
{
//don't simplify '&x'!
const char code[] = "const int * foo ( ) {\n"
"const int x1 = 1 ;\n"
"f ( & x1 ) ;\n"
"const int x2 = 1 ;\n"
"f ( y , & x2 ) ;\n"
"const int x3 = 1 ;\n"
"t = & x3 ;\n"
"const int x4 = 1 ;\n"
"t = y + & x4 ;\n"
"const int x5 = 1 ;\n"
"z [ & x5 ] = y ;\n"
"const int x6 = 1 ;\n"
"v = { & x6 } ;\n"
"const int x7 = 1 ;\n"
"return & x7 ;\n"
"}";
ASSERT_EQUALS(code, tokenizeAndStringify(code, true));
ASSERT_EQUALS(
"[test.cpp:5]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable y\n",
errout_str());
}
}
void simplifyKnownVariables51() { // #4409 hang
const char code[] = "void mhz_M(int enough) {\n"
" TYPE *x=&x, **p=x, **q = NULL;\n"
" BENCH1(q = _mhz_M(n); n = 1;)\n"
" use_pointer(q);\n"
"}";
ASSERT_THROW_INTERNAL(tokenizeAndStringify(code, true), UNKNOWN_MACRO);
}
void simplifyKnownVariables54() { // #4913
ASSERT_EQUALS("void f ( int * p ) { * -- p = 0 ; * p = 0 ; }", tokenizeAndStringify("void f(int*p) { *--p=0; *p=0; }", true));
}
void simplifyKnownVariables56() { // ticket #5301 - >>
ASSERT_EQUALS("void f ( ) { int a ; a = 0 ; int b ; b = 0 ; * p >> a >> b ; return a / b ; }",
tokenizeAndStringify("void f() { int a=0,b=0; *p>>a>>b; return a/b; }", true));
ASSERT_EQUALS(
"[test.cpp:1]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable p\n",
errout_str());
}
void simplifyKnownVariables58() { // #5268
const char code[] = "enum e { VAL1 = 1, VAL2 }; "
"typedef char arr_t[VAL2]; "
"int foo(int) ; "
"void bar () { "
" throw foo (VAL1); "
"} "
"int baz() { "
" return sizeof(arr_t); "
"}";
ASSERT_EQUALS("enum e { VAL1 = 1 , VAL2 } ; "
"int foo ( int ) ; "
"void bar ( ) { "
"throw foo ( VAL1 ) ; "
"} "
"int baz ( ) { "
"return sizeof ( char [ VAL2 ] ) ; "
"}", tokenizeAndStringify(code, true));
}
void simplifyKnownVariables59() { // #5062 - for head
const char code[] = "void f() {\n"
" int a[3], i, j;\n"
" for(i = 0, j = 1; i < 3, j < 12; i++,j++) {\n"
" a[i] = 0;\n"
" }\n"
"}";
ASSERT_EQUALS("void f ( ) {\n"
"int a [ 3 ] ; int i ; int j ;\n"
"for ( i = 0 , j = 1 ; i < 3 , j < 12 ; i ++ , j ++ ) {\n"
"a [ i ] = 0 ;\n"
"}\n"
"}", tokenizeAndStringify(code, true));
}
void simplifyKnownVariables61() { // #7805
ASSERT_NO_THROW(tokenizeAndStringify("static const int XX = 0;\n"
"enum E { XX };\n"
"struct s {\n"
" enum Bar {\n"
" XX,\n"
" Other\n"
" };\n"
" enum { XX };\n"
"};", /*expand=*/ true));
ASSERT_EQUALS("", errout_str());
}
void simplifyKnownVariables62() { // #5666
ASSERT_EQUALS("void foo ( std :: string str ) {\n"
"char * p ; p = & str [ 0 ] ;\n"
"* p = 0 ;\n"
"}",
tokenizeAndStringify("void foo(std::string str) {\n"
" char *p = &str[0];\n"
" *p = 0;\n"
"}", /*expand=*/ true));
}
void simplifyKnownVariables63() { // #10798
ASSERT_NO_THROW(tokenizeAndStringify("typedef void (*a)();\n"
"enum class E { a };\n"));
ASSERT_EQUALS("", errout_str());
}
void simplifyKnownVariablesBailOutAssign1() {
const char code[] = "int foo() {\n"
" int i; i = 0;\n"
" if (x) { i = 10; }\n"
" return i;\n"
"}\n";
const char expected[] = "int foo ( ) {\n"
"int i ; i = 0 ;\n"
"if ( x ) { i = 10 ; }\n"
"return i ;\n"
"}";
ASSERT_EQUALS(expected, tokenizeAndStringify(code, true));
ASSERT_EQUALS(
"[test.cpp:3]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable x\n",
filter_valueflow(errout_str()));
}
void simplifyKnownVariablesBailOutAssign2() {
// ticket #3032 - assignment in condition
const char code[] = "void f(struct ABC *list) {\n"
" struct ABC *last = NULL;\n"
" nr = (last = list->prev)->nr;\n" // <- don't replace "last" with 0
"}\n";
const char expected[] = "void f ( struct ABC * list ) {\n"
"struct ABC * last ; last = NULL ;\n"
"nr = ( last = list . prev ) . nr ;\n"
"}";
ASSERT_EQUALS(expected, tokenizeAndStringify(code, true));
ASSERT_EQUALS(
"[test.cpp:3]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable nr\n",
errout_str());
}
void simplifyKnownVariablesBailOutFor1() {
const char code[] = "void foo() {\n"
" for (int i = 0; i < 10; ++i) { }\n"
"}\n";
const char expected[] = "void foo ( ) {\n"
"for ( int i = 0 ; i < 10 ; ++ i ) { }\n"
"}";
ASSERT_EQUALS(expected, tokenizeAndStringify(code, true));
ASSERT_EQUALS("", errout_str()); // debug warnings
}
void simplifyKnownVariablesBailOutFor2() {
const char code[] = "void foo() {\n"
" int i = 0;\n"
" while (i < 10) { ++i; }\n"
"}\n";
const char expected[] = "void foo ( ) {\n"
"int i ; i = 0 ;\n"
"while ( i < 10 ) { ++ i ; }\n"
"}";
ASSERT_EQUALS(expected, tokenizeAndStringify(code, true));
ASSERT_EQUALS("", errout_str()); // debug warnings
}
void simplifyKnownVariablesBailOutFor3() {
const char code[] = "void foo() {\n"
" for (std::string::size_type pos = 0; pos < 10; ++pos)\n"
" { }\n"
"}\n";
const char expected[] = "void foo ( ) {\n"
"for ( std :: string :: size_type pos = 0 ; pos < 10 ; ++ pos )\n"
"{ }\n"
"}";
ASSERT_EQUALS(expected, tokenizeAndStringify(code, true));
ASSERT_EQUALS("", errout_str()); // debug warnings
}
void simplifyKnownVariablesBailOutMemberFunction() {
const char code[] = "void foo(obj a) {\n"
" obj b = a;\n"
" b.f();\n"
"}\n";
const char expected[] = "void foo ( obj a ) {\n"
"obj b ; b = a ;\n"
"b . f ( ) ;\n"
"}";
ASSERT_EQUALS(expected, tokenizeAndStringify(code, true));
}
void simplifyKnownVariablesBailOutConditionalIncrement() {
const char code[] = "int f() {\n"
" int a = 0;\n"
" if (x) {\n"
" ++a;\n" // conditional increment
" }\n"
" return a;\n"
"}\n";
(void)tokenizeAndStringify(code,true);
ASSERT_EQUALS(
"[test.cpp:3]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable x\n",
filter_valueflow(errout_str())); // no debug warnings
}
void simplifyKnownVariablesBailOutSwitchBreak() {
// Ticket #2324
const char code[] = "int f(char *x) {\n"
" char *p;\n"
" char *q;\n"
"\n"
" switch (x & 0x3)\n"
" {\n"
" case 1:\n"
" p = x;\n"
" x = p;\n"
" break;\n"
" case 2:\n"
" q = x;\n" // x is not equal with p
" x = q;\n"
" break;\n"
" }\n"
"}\n";
const char expected[] = "int f ( char * x ) {\n"
"char * p ;\n"
"char * q ;\n"
"\n"
"switch ( x & 0x3 )\n"
"{\n"
"case 1 : ;\n"
"p = x ;\n"
"x = p ;\n"
"break ;\n"
"case 2 : ;\n"
"q = x ;\n"
"x = q ;\n"
"break ;\n"
"}\n"
"}";
ASSERT_EQUALS(expected, tokenizeAndStringify(code,true));
}
void simplifyKnownVariablesFunctionCalls() {
{
const char code[] = "void a(int &x);" // <- x is passed by reference
"void b() {"
" int x = 123;"
" a(x);" // <- don't replace with a(123);
"}";
const char expected[] = "void a ( int & x ) ; void b ( ) { int x ; x = 123 ; a ( x ) ; }";
ASSERT_EQUALS(expected, tokenizeAndStringify(code,true));
}
}
void simplifyKnownVariablesGlobalVars() {
// #8054
const char code[] = "static int x;"
"void f() {"
" x = 123;"
" while (!x) { dostuff(); }"
"}";
ASSERT_EQUALS("static int x ; void f ( ) { x = 123 ; while ( ! x ) { dostuff ( ) ; } }", tokenizeAndStringify(code,true));
ASSERT_EQUALS("", filter_valueflow(errout_str()));
}
void simplifyKnownVariablesNamespace() {
{ // #10059
const char code[] = "namespace N {\n"
" const int n = 0;\n"
" namespace M { const int m = 0; }\n"
"}\n"
"using namespace N;\n"
"int i(n);\n"
"int j(M::m);\n"
"using namespace N::M;\n"
"int k(m);\n"
"int l(N::M::m);\n";
const char exp[] = "\n\n##file 0\n"
"1: namespace N {\n"
"2: const int n@1 = 0 ;\n"
"3: namespace M { const int m@2 = 0 ; }\n"
"4: }\n"
"5: using namespace N ;\n"
"6: int i ; i = n@1 ;\n"
"7: int j ( M :: m@2 ) ;\n"
"8: using namespace N :: M ;\n"
"9: int k ; k = m@2 ;\n"
"10: int l ( N :: M :: m@2 ) ;\n";
ASSERT_EQUALS(exp, tokenizeDebugListing(code));
}
{ // #10835
const char code[] = "using namespace X;\n"
"namespace N {\n"
" struct A {\n"
" static int i;\n"
" struct B {\n"
" double x;\n"
" void f();\n"
" };\n"
" };\n"
"}\n"
"namespace N {\n"
" int A::i = 0;\n"
" void A::B::f() {\n"
" x = 0;\n"
" }\n"
"}\n";
const char exp[] = "\n\n##file 0\n"
"1: using namespace X ;\n"
"2: namespace N {\n"
"3: struct A {\n"
"4: static int i@1 ;\n"
"5: struct B {\n"
"6: double x@2 ;\n"
"7: void f ( ) ;\n"
"8: } ;\n"
"9: } ;\n"
"10: }\n"
"11: namespace N {\n"
"12: int A :: i@1 = 0 ;\n"
"13: void A :: B :: f ( ) {\n"
"14: x@2 = 0 ;\n"
"15: }\n"
"16: }\n";
ASSERT_EQUALS(exp, tokenizeDebugListing(code));
}
}
void simplifyKnownVariablesClassMember() {
// Ticket #2815
{
const char code[] = "char *a;\n"
"void f(const char *s) {\n"
" a = NULL;\n"
" x();\n"
" memcpy(a, s, 10);\n" // <- don't simplify "a" here
"}\n";
const std::string s(tokenizeAndStringify(code, true));
ASSERT_EQUALS(true, s.find("memcpy ( a , s , 10 ) ;") != std::string::npos);
}
// If the variable is local then perform simplification..
{
const char code[] = "void f(const char *s) {\n"
" char *a = NULL;\n"
" x();\n"
" memcpy(a, s, 10);\n" // <- simplify "a"
"}\n";
const std::string s(tokenizeAndStringify(code, true));
TODO_ASSERT_EQUALS(true, false, s.find("memcpy ( 0 , s , 10 ) ;") != std::string::npos);
}
}
void simplify_constants6() { // Ticket #5625
{
const char code[] = "template < class T > struct foo ;\n"
"void bar ( ) {\n"
"foo < 1 ? 0 ? 1 : 6 : 2 > x ;\n"
"foo < 1 ? 0 : 2 > y ;\n"
"}";
const char exp[] = "template < class T > struct foo ; "
"void bar ( ) { "
"foo < 6 > x ; "
"foo < 0 > y ; "
"}";
ASSERT_EQUALS(exp, tok(code));
}
{
const char code[] = "bool b = true ? false : 1 > 2 ;";
const char exp[] = "bool b ; b = true ? false : 1 > 2 ;";
ASSERT_EQUALS(exp, tok(code));
}
}
void simplifyVarDeclInitLists()
{
{
const char code[] = "std::vector<int> v{a * b, 1};";
const char exp[] = "std :: vector < int > v { a * b , 1 } ;";
ASSERT_EQUALS(exp, tok(code));
}
{
const char code[] = "enum E { E0 } e{};";
const char exp[] = "enum E { E0 } ; enum E e ; e = { } ;";
ASSERT_EQUALS(exp, tok(code));
}
}
};
REGISTER_TEST(TestSimplifyTokens)
| null |
1,021 | cpp | cppcheck | testbool.cpp | test/testbool.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#include "checkbool.h"
#include "errortypes.h"
#include "fixture.h"
#include "helpers.h"
#include "settings.h"
#include <cstddef>
class TestBool : public TestFixture {
public:
TestBool() : TestFixture("TestBool") {}
private:
const Settings settings = settingsBuilder().severity(Severity::style).severity(Severity::warning).certainty(Certainty::inconclusive).build();
void run() override {
TEST_CASE(bitwiseOnBoolean); // if (bool & bool)
TEST_CASE(incrementBoolean);
TEST_CASE(assignBoolToPointer);
TEST_CASE(assignBoolToFloat);
TEST_CASE(comparisonOfBoolExpressionWithInt1);
TEST_CASE(comparisonOfBoolExpressionWithInt2);
TEST_CASE(comparisonOfBoolExpressionWithInt3);
TEST_CASE(comparisonOfBoolExpressionWithInt4);
TEST_CASE(comparisonOfBoolWithInt1);
TEST_CASE(comparisonOfBoolWithInt2);
TEST_CASE(comparisonOfBoolWithInt3);
TEST_CASE(comparisonOfBoolWithInt4);
TEST_CASE(comparisonOfBoolWithInt5);
TEST_CASE(comparisonOfBoolWithInt6); // #4224 - integer is casted to bool
TEST_CASE(comparisonOfBoolWithInt7); // #4846 - (!x == true)
TEST_CASE(comparisonOfBoolWithInt8); // #9165
TEST_CASE(comparisonOfBoolWithInt9); // #9304
TEST_CASE(comparisonOfBoolWithInt10); // #10935
TEST_CASE(checkComparisonOfFuncReturningBool1);
TEST_CASE(checkComparisonOfFuncReturningBool2);
TEST_CASE(checkComparisonOfFuncReturningBool3);
TEST_CASE(checkComparisonOfFuncReturningBool4);
TEST_CASE(checkComparisonOfFuncReturningBool5);
TEST_CASE(checkComparisonOfFuncReturningBool6);
TEST_CASE(checkComparisonOfFuncReturningBool7); // #7197
TEST_CASE(checkComparisonOfFuncReturningBool8); // #4103
// Integration tests..
TEST_CASE(checkComparisonOfFuncReturningBoolIntegrationTest1); // #7798 overloaded functions
TEST_CASE(checkComparisonOfBoolWithBool);
// Converting pointer addition result to bool
TEST_CASE(pointerArithBool1);
TEST_CASE(returnNonBool);
TEST_CASE(returnNonBoolLambda);
TEST_CASE(returnNonBoolLogicalOp);
TEST_CASE(returnNonBoolClass);
}
#define check(...) check_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
void check_(const char* file, int line, const char (&code)[size], bool cpp = true) {
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code, cpp), file, line);
// Check...
runChecks<CheckBool>(tokenizer, this);
}
void assignBoolToPointer() {
check("void foo(bool *p) {\n"
" p = false;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Boolean value assigned to pointer.\n", errout_str());
check("void foo(bool *p) {\n"
" p = (x<y);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Boolean value assigned to pointer.\n", errout_str());
check("void foo(bool *p) {\n"
" p = (x||y);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Boolean value assigned to pointer.\n", errout_str());
check("void foo(bool *p) {\n"
" p = (x&&y);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Boolean value assigned to pointer.\n", errout_str());
// check against potential false positives
check("void foo(bool *p) {\n"
" *p = false;\n"
"}");
ASSERT_EQUALS("", errout_str());
// ticket #5046 - false positive: Boolean value assigned to pointer
check("struct S {\n"
" bool *p;\n"
"};\n"
"void f() {\n"
" S s = {0};\n"
" *s.p = true;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct S {\n"
" bool *p;\n"
"};\n"
"void f() {\n"
" S s = {0};\n"
" s.p = true;\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (error) Boolean value assigned to pointer.\n", errout_str());
// ticket #5627 - false positive: template
check("void f() {\n"
" X *p = new ::std::pair<int,int>[rSize];\n"
"}");
ASSERT_EQUALS("", errout_str());
// ticket #6588 (c mode)
check("struct MpegEncContext { int *q_intra_matrix, *q_chroma_intra_matrix; };\n"
"void dnxhd_10bit_dct_quantize(MpegEncContext *ctx, int n, int qscale) {\n"
" const int *qmat = n < 4;\n" /* KO */
" const int *rmat = n < 4 ? " /* OK */
" ctx->q_intra_matrix :"
" ctx->q_chroma_intra_matrix;\n"
"}", false);
ASSERT_EQUALS("[test.c:3]: (error) Boolean value assigned to pointer.\n", errout_str());
// ticket #6588 (c++ mode)
check("struct MpegEncContext { int *q_intra_matrix, *q_chroma_intra_matrix; };\n"
"void dnxhd_10bit_dct_quantize(MpegEncContext *ctx, int n, int qscale) {\n"
" const int *qmat = n < 4;\n" /* KO */
" const int *rmat = n < 4 ? " /* OK */
" ctx->q_intra_matrix :"
" ctx->q_chroma_intra_matrix;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Boolean value assigned to pointer.\n", errout_str());
// ticket #6665
check("void pivot_big(char *first, int compare(const void *, const void *)) {\n"
" char *a = first, *b = first + 1, *c = first + 2;\n"
" char* m1 = compare(a, b) < 0\n"
" ? (compare(b, c) < 0 ? b : (compare(a, c) < 0 ? c : a))\n"
" : (compare(a, c) < 0 ? a : (compare(b, c) < 0 ? c : b));\n"
"}", false);
ASSERT_EQUALS("", errout_str());
// #7381
check("void foo(bool *p, bool b) {\n"
" p = b;\n"
" p = &b;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Boolean value assigned to pointer.\n", errout_str());
}
void assignBoolToFloat() {
check("void foo1() {\n"
" double d = false;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Boolean value assigned to floating point variable.\n", errout_str());
check("void foo2() {\n"
" float d = true;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Boolean value assigned to floating point variable.\n", errout_str());
check("void foo3() {\n"
" long double d = (2>1);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Boolean value assigned to floating point variable.\n", errout_str());
// stability - don't crash:
check("void foo4() {\n"
" unknown = false;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct S {\n"
" float p;\n"
"};\n"
"void f() {\n"
" S s = {0};\n"
" s.p = true;\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (style) Boolean value assigned to floating point variable.\n", errout_str());
check("struct S {\n"
" float* p[1];\n"
"};\n"
"void f() {\n"
" S s = {0};\n"
" *s.p[0] = true;\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (style) Boolean value assigned to floating point variable.\n", errout_str());
}
void comparisonOfBoolExpressionWithInt1() {
check("void f(int x) {\n"
" if ((x && 0x0f)==6)\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Comparison of a boolean expression with an integer other than 0 or 1.\n", errout_str());
check("void f(int x) {\n"
" if ((x && 0x0f)==0)\n"
" a++;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x) {\n"
" if ((x || 0x0f)==6)\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Comparison of a boolean expression with an integer other than 0 or 1.\n", errout_str());
check("void f(int x) {\n"
" if ((x || 0x0f)==0)\n"
" a++;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x) {\n"
" if ((x & 0x0f)==6)\n"
" a++;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x) {\n"
" if ((x | 0x0f)==6)\n"
" a++;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x) {\n"
" if ((5 && x)==3)\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Comparison of a boolean expression with an integer other than 0 or 1.\n", errout_str());
check("void f(int x) {\n"
" if ((5 && x)==3 || (8 && x)==9)\n"
" a++;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:2]: (warning) Comparison of a boolean expression with an integer other than 0 or 1.\n"
"[test.cpp:2]: (warning) Comparison of a boolean expression with an integer other than 0 or 1.\n", // duplicate
errout_str());
check("void f(int x) {\n"
" if ((5 && x)!=3)\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Comparison of a boolean expression with an integer other than 0 or 1.\n", errout_str());
check("void f(int x) {\n"
" if ((5 && x) > 3)\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Comparison of a boolean expression with an integer other than 0 or 1.\n", errout_str());
check("void f(int x) {\n"
" if ((5 && x) > 0)\n"
" a++;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x) {\n"
" if ((5 && x) < 0)\n"
" a++;\n"
"}"
);
ASSERT_EQUALS("[test.cpp:2]: (warning) Comparison of a boolean expression with an integer.\n", errout_str());
check("void f(int x) {\n"
" if ((5 && x) < 1)\n"
" a++;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x) {\n"
" if ((5 && x) > 1)\n"
" a++;\n"
"}"
);
ASSERT_EQUALS("[test.cpp:2]: (warning) Comparison of a boolean expression with an integer.\n", errout_str());
check("void f(int x) {\n"
" if (0 < (5 && x))\n"
" a++;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x) {\n"
" if (0 > (5 && x))\n"
" a++;\n"
"}"
);
ASSERT_EQUALS("[test.cpp:2]: (warning) Comparison of a boolean expression with an integer.\n", errout_str());
check("void f(int x) {\n"
" if (1 > (5 && x))\n"
" a++;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x) {\n"
" if (1 < (5 && x))\n"
" a++;\n"
"}"
);
ASSERT_EQUALS("[test.cpp:2]: (warning) Comparison of a boolean expression with an integer.\n", errout_str());
check("void f(bool x ) {\n"
" if ( x > false )\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Comparison of a boolean value using relational operator (<, >, <= or >=).\n", errout_str());
check("void f(bool x ) {\n"
" if ( false < x )\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Comparison of a boolean value using relational operator (<, >, <= or >=).\n", errout_str());
check("void f(bool x ) {\n"
" if ( x < false )\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Comparison of a boolean value using relational operator (<, >, <= or >=).\n", errout_str());
check("void f(bool x ) {\n"
" if ( false > x )\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Comparison of a boolean value using relational operator (<, >, <= or >=).\n", errout_str());
check("void f(bool x ) {\n"
" if ( x >= false )\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Comparison of a boolean value using relational operator (<, >, <= or >=).\n", errout_str());
check("void f(bool x ) {\n"
" if ( false >= x )\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Comparison of a boolean value using relational operator (<, >, <= or >=).\n", errout_str());
check("void f(bool x ) {\n"
" if ( x <= false )\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Comparison of a boolean value using relational operator (<, >, <= or >=).\n", errout_str());
check("void f(bool x ) {\n"
" if ( false <= x )\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Comparison of a boolean value using relational operator (<, >, <= or >=).\n", errout_str());
check("typedef int (*func)(bool invert);\n"
"void x(int, func f);\n"
"void foo(int error) {\n"
" if (error == ABC) { }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int f() { return !a+b<c; }"); // #5072
ASSERT_EQUALS("",errout_str());
check("int f() { return (!a+b<c); }");
ASSERT_EQUALS("",errout_str());
check("int f() { return (a+(b<5)<=c); }");
ASSERT_EQUALS("",errout_str());
}
void comparisonOfBoolExpressionWithInt2() {
check("void f(int x) {\n"
" if (!x == 10) {\n"
" printf(\"x not equal to 10\");\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Comparison of a boolean expression with an integer other than 0 or 1.\n", errout_str());
check("void f(int x) {\n"
" if (!x != 10) {\n"
" printf(\"x not equal to 10\");\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Comparison of a boolean expression with an integer other than 0 or 1.\n", errout_str());
check("void f(int x) {\n"
" if (x != 10) {\n"
" printf(\"x not equal to 10\");\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x) {\n"
" if (10 == !x) {\n"
" printf(\"x not equal to 10\");\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Comparison of a boolean expression with an integer other than 0 or 1.\n", errout_str());
check("void f(int x) {\n"
" if (10 != !x) {\n"
" printf(\"x not equal to 10\");\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Comparison of a boolean expression with an integer other than 0 or 1.\n", errout_str());
check("void f(int x, int y) {\n"
" if (y != !x) {\n"
" printf(\"x not equal to 10\");\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x, bool y) {\n"
" if (y != !x) {\n"
" printf(\"x not equal to 10\");\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x) {\n"
" if (10 != x) {\n"
" printf(\"x not equal to 10\");\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x, int y) {\n"
" return (!y == !x);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int f(int a) {\n"
" return (x()+1 == !a);\n"
"}");
TODO_ASSERT_EQUALS("error", "", errout_str());
check("void f() { if (!!a+!!b+!!c>1){} }");
ASSERT_EQUALS("",errout_str());
check("void f(int a, int b, int c) { if (a != !b || c) {} }");
ASSERT_EQUALS("",errout_str());
check("void f(int a, int b, int c) { if (1 < !!a + !!b + !!c) {} }");
ASSERT_EQUALS("",errout_str());
check("void f(int a, int b, int c) { if (1 < !(a+b)) {} }");
ASSERT_EQUALS("[test.cpp:1]: (warning) Comparison of a boolean expression with an integer.\n",errout_str());
}
void comparisonOfBoolExpressionWithInt3() {
check("int f(int x) {\n"
" return t<0>() && x;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void comparisonOfBoolExpressionWithInt4() {
// #5016
check("void f() {\n"
" for(int i = 4; i > -1 < 5 ; --i) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Comparison of a boolean expression with an integer other than 0 or 1.\n", errout_str());
check("void f(int a, int b, int c) {\n"
" return (a > b) < c;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int a, int b, int c) {\n"
" return x(a > b) < c;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int a, int b, int c) {\n"
" return a > b == c;\n"
"}");
ASSERT_EQUALS("", errout_str());
// templates
check("struct Tokenizer { TokenList list; };\n"
"void Tokenizer::f() {\n"
" std::list<Token*> locationList;\n"
"}");
ASSERT_EQUALS("", errout_str());
// #5063 - or
check("void f() {\n"
" return a > b or c < d;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int f() {\n"
" return (a < b) != 0U;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int f() {\n"
" return (a < b) != 0x0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int f() {\n"
" return (a < b) != 42U;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Comparison of a boolean expression with an integer other than 0 or 1.\n", errout_str());
}
void checkComparisonOfFuncReturningBool1() {
check("void f(){\n"
" int temp = 4;\n"
" if(compare1(temp) > compare2(temp)){\n"
" printf(\"foo\");\n"
" }\n"
"}\n"
"bool compare1(int temp){\n"
" if(temp==4){\n"
" return true;\n"
" }\n"
" else\n"
" return false;\n"
"}\n"
"bool compare2(int temp){\n"
" if(temp==4){\n"
" return false;\n"
" }\n"
" else\n"
" return true;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Comparison of two functions returning boolean value using relational (<, >, <= or >=) operator.\n", errout_str());
}
void checkComparisonOfFuncReturningBool2() {
check("void leftOfComparison(){\n"
" int temp = 4;\n"
" bool a = true;\n"
" if(compare(temp) > a){\n"
" printf(\"foo\");\n"
" }\n"
"}\n"
"void rightOfComparison(){\n"
" int temp = 4;\n"
" bool a = true;\n"
" if(a < compare(temp)){\n"
" printf(\"foo\");\n"
" }\n"
"}\n"
"bool compare(int temp){\n"
" if(temp==4){\n"
" return true;\n"
" }\n"
" else\n"
" return false;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Comparison of a function returning boolean value using relational (<, >, <= or >=) operator.\n"
"[test.cpp:11]: (style) Comparison of a function returning boolean value using relational (<, >, <= or >=) operator.\n", errout_str());
}
void checkComparisonOfFuncReturningBool3() {
check("void f(){\n"
" int temp = 4;\n"
" if(compare(temp) > temp){\n"
" printf(\"foo\");\n"
" }\n"
"}\n"
"bool compare(int temp);");
ASSERT_EQUALS("[test.cpp:3]: (warning) Comparison of a boolean expression with an integer other than 0 or 1.\n"
"[test.cpp:3]: (style) Comparison of a function returning boolean value using relational (<, >, <= or >=) operator.\n", errout_str());
}
void checkComparisonOfFuncReturningBool4() {
check("void f(){\n"
" int temp = 4;\n"
" bool b = compare2(6);\n"
" if(compare1(temp)> b){\n"
" printf(\"foo\");\n"
" }\n"
"}\n"
"bool compare1(int temp){\n"
" if(temp==4){\n"
" return true;\n"
" }\n"
" else\n"
" return false;\n"
"}\n"
"bool compare2(int temp){\n"
" if(temp == 5){\n"
" return true;\n"
" }\n"
" else\n"
" return false;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Comparison of a function returning boolean value using relational (<, >, <= or >=) operator.\n", errout_str());
}
void checkComparisonOfFuncReturningBool5() {
check("void f(){\n"
" int temp = 4;\n"
" if(compare1(temp) > !compare2(temp)){\n"
" printf(\"foo\");\n"
" }\n"
"}\n"
"bool compare1(int temp){\n"
" if(temp==4){\n"
" return true;\n"
" }\n"
" else\n"
" return false;\n"
"}\n"
"bool compare2(int temp){\n"
" if(temp==4){\n"
" return false;\n"
" }\n"
" else\n"
" return true;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Comparison of two functions returning boolean value using relational (<, >, <= or >=) operator.\n", errout_str());
}
void checkComparisonOfFuncReturningBool6() {
check("int compare1(int temp);\n"
"namespace Foo {\n"
" bool compare1(int temp);\n"
"}\n"
"void f(){\n"
" int temp = 4;\n"
" if(compare1(temp) > compare2(temp)){\n"
" printf(\"foo\");\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("namespace Foo {\n"
" bool compare1(int temp);\n"
"}\n"
"int compare1(int temp);\n"
"void f(){\n"
" int temp = 4;\n"
" if(compare1(temp) > compare2(temp)){\n"
" printf(\"foo\");\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int compare1(int temp);\n"
"namespace Foo {\n"
" bool compare1(int temp);\n"
" void f(){\n"
" int temp = 4;\n"
" if(compare1(temp) > compare2(temp)){\n"
" printf(\"foo\");\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (style) Comparison of a function returning boolean value using relational (<, >, <= or >=) operator.\n", errout_str());
check("int compare1(int temp);\n"
"namespace Foo {\n"
" bool compare1(int temp);\n"
" void f(){\n"
" int temp = 4;\n"
" if(::compare1(temp) > compare2(temp)){\n"
" printf(\"foo\");\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("bool compare1(int temp);\n"
"void f(){\n"
" int temp = 4;\n"
" if(foo.compare1(temp) > compare2(temp)){\n"
" printf(\"foo\");\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void checkComparisonOfFuncReturningBool7() { // #7197
check("struct C {\n"
" bool isEmpty();\n"
"};\n"
"void f() {\n"
" C c1, c2;\n"
" if ((c1.isEmpty()) < (c2.isEmpty())) {}\n"
" if (!c1.isEmpty() < !!c2.isEmpty()) {}\n"
" if ((int)c1.isEmpty() < (int)c2.isEmpty()) {}\n"
" if (static_cast<int>(c1.isEmpty()) < static_cast<int>(c2.isEmpty())) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:6]: (style) Comparison of two functions returning boolean value using relational (<, >, <= or >=) operator.\n"
"[test.cpp:7]: (style) Comparison of two functions returning boolean value using relational (<, >, <= or >=) operator.\n"
"[test.cpp:8]: (style) Comparison of two functions returning boolean value using relational (<, >, <= or >=) operator.\n"
"[test.cpp:9]: (style) Comparison of two functions returning boolean value using relational (<, >, <= or >=) operator.\n",
errout_str());
}
void checkComparisonOfFuncReturningBool8() { // #4103
// op: >
check("int main(void){\n"
" bool a = true;\n"
" bool b = false;\n"
" if(b > a){ \n" // here warning should be displayed
" ;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Comparison of a variable having boolean value using relational (<, >, <= or >=) operator.\n", errout_str());
// op: <
check("int main(void){\n"
" bool a = true;\n"
" bool b = false;\n"
" if(b < a){ \n" // here warning should be displayed
" ;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Comparison of a variable having boolean value using relational (<, >, <= or >=) operator.\n", errout_str());
// op: >=
check("int main(void){\n"
" bool a = true;\n"
" bool b = false;\n"
" if(b >= a){ \n" // here warning should be displayed
" ;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Comparison of a variable having boolean value using relational (<, >, <= or >=) operator.\n", errout_str());
// op: <=
check("int main(void){\n"
" bool a = true;\n"
" bool b = false;\n"
" if(b <= a){ \n" // here warning should be displayed
" ;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Comparison of a variable having boolean value using relational (<, >, <= or >=) operator.\n", errout_str());
}
void checkComparisonOfFuncReturningBoolIntegrationTest1() { // #7798
check("bool eval(double *) { return false; }\n"
"double eval(char *) { return 1.0; }\n"
"int main(int argc, char *argv[])\n"
"{\n"
" if ( eval(argv[1]) > eval(argv[2]) )\n"
" return 1;\n"
" return 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void checkComparisonOfBoolWithBool() {
const char code[] = "void f(){\n"
" int temp = 4;\n"
" bool b = compare2(6);\n"
" bool a = compare1(4);\n"
" if(b > a){\n"
" printf(\"foo\");\n"
" }\n"
"}\n"
"bool compare1(int temp){\n"
" if(temp==4){\n"
" return true;\n"
" }\n"
" else\n"
" return false;\n"
"}\n"
"bool compare2(int temp){\n"
" if(temp == 5){\n"
" return true;\n"
" }\n"
" else\n"
" return false;\n"
"}\n";
check(code);
ASSERT_EQUALS("[test.cpp:5]: (style) Comparison of a variable having boolean value using relational (<, >, <= or >=) operator.\n", errout_str());
}
void bitwiseOnBoolean() { // 3062
check("void f(_Bool a, _Bool b) {\n"
" if(a & b) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style, inconclusive) Boolean expression 'a' is used in bitwise operation. Did you mean '&&'?\n", errout_str());
check("void f(_Bool a, _Bool b) {\n"
" if(a | b) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style, inconclusive) Boolean expression 'a' is used in bitwise operation. Did you mean '||'?\n", errout_str());
check("void f(bool a, bool b) {\n"
" if(a & !b) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style, inconclusive) Boolean expression 'a' is used in bitwise operation. Did you mean '&&'?\n", errout_str());
check("void f(bool a, bool b) {\n"
" if(a | !b) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style, inconclusive) Boolean expression 'a' is used in bitwise operation. Did you mean '||'?\n", errout_str());
check("bool a, b;\n"
"void f() {\n"
" if(a & b) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style, inconclusive) Boolean expression 'a' is used in bitwise operation. Did you mean '&&'?\n", errout_str());
check("bool a, b;\n"
"void f() {\n"
" if(a & !b) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style, inconclusive) Boolean expression 'a' is used in bitwise operation. Did you mean '&&'?\n", errout_str());
check("bool a, b;\n"
"void f() {\n"
" if(a | b) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style, inconclusive) Boolean expression 'a' is used in bitwise operation. Did you mean '||'?\n", errout_str());
check("bool a, b;\n"
"void f() {\n"
" if(a | !b) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style, inconclusive) Boolean expression 'a' is used in bitwise operation. Did you mean '||'?\n", errout_str());
check("void f(bool a, int b) {\n"
" if(a & b) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style, inconclusive) Boolean expression 'a' is used in bitwise operation. Did you mean '&&'?\n", errout_str());
check("void f(int a, bool b) {\n"
" if(a & b) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style, inconclusive) Boolean expression 'b' is used in bitwise operation. Did you mean '&&'?\n", errout_str());
check("void f(int a, int b) {\n"
" if((a > 0) & (b < 0)) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style, inconclusive) Boolean expression 'a>0' is used in bitwise operation. Did you mean '&&'?\n", errout_str());
check("void f(bool a, int b) {\n"
" if(a | b) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style, inconclusive) Boolean expression 'a' is used in bitwise operation. Did you mean '||'?\n", errout_str());
check("void f(int a, bool b) {\n"
" if(a | b) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style, inconclusive) Boolean expression 'b' is used in bitwise operation. Did you mean '||'?\n", errout_str());
check("int f(bool a, int b) {\n"
" return a | b;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("bool f(bool a, int b) {\n"
" return a | b;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style, inconclusive) Boolean expression 'a' is used in bitwise operation. Did you mean '||'?\n", errout_str());
check("void f(int a, int b) {\n"
" if(a & b) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(bool b) {\n"
" foo(bar, &b);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(bool b) {\n" // #9405
" class C { void foo(bool &b) {} };\n"
"}");
ASSERT_EQUALS("", errout_str());
check("bool f();\n"
"bool g() {\n"
" return f() | f();\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("uint8 outcode(float p) {\n"
" float d = 0.;\n"
" return ((p - xm >= d) << 1) | (x - p > d);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("int g();\n" // #10655
"void f(bool b) {\n"
" if (g() | b) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (style, inconclusive) Boolean expression 'b' is used in bitwise operation. Did you mean '||'?\n", errout_str());
check("int g();\n"
"void f(bool b) {\n"
" if (b | g()) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("int g();\n"
"bool f(bool b, bool c) {\n"
" return b | g() | c;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (style, inconclusive) Boolean expression 'c' is used in bitwise operation. Did you mean '||'?\n", errout_str());
check("void f(int i) {\n" // #4233
" bool b = true, c = false;\n"
" b &= i;\n"
" c |= i;\n"
" if (b || c) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (style, inconclusive) Boolean expression 'b' is used in bitwise operation.\n"
"[test.cpp:4]: (style, inconclusive) Boolean expression 'c' is used in bitwise operation.\n",
errout_str());
check("void f(int i, int j, bool b) {\n"
" i &= b;\n"
" j |= b;\n"
" if (b || c) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("bool f(bool b, int i) {\n"
" b &= (i == 5);\n"
" return b;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct S { bool b{}; };\n" // #12455
"void f(const std::unordered_map<int, S> m) {\n"
" for (const auto& e : m) {\n"
" S s;\n"
" s.b |= e.second.b;\n"
" (void)s.b;\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void incrementBoolean() {
check("bool bValue = true;\n"
"void f() { bValue++; }");
ASSERT_EQUALS("[test.cpp:2]: (style) Incrementing a variable of type 'bool' with postfix operator++ is deprecated by the C++ Standard. You should assign it the value 'true' instead.\n", errout_str());
check("void f(bool test){\n"
" test++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Incrementing a variable of type 'bool' with postfix operator++ is deprecated by the C++ Standard. You should assign it the value 'true' instead.\n", errout_str());
check("void f(bool* test){\n"
" (*test)++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Incrementing a variable of type 'bool' with postfix operator++ is deprecated by the C++ Standard. You should assign it the value 'true' instead.\n", errout_str());
check("void f(bool* test){\n"
" test[0]++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Incrementing a variable of type 'bool' with postfix operator++ is deprecated by the C++ Standard. You should assign it the value 'true' instead.\n", errout_str());
check("void f(int test){\n"
" test++;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void comparisonOfBoolWithInt1() {
check("void f(bool x) {\n"
" if (x < 10) {\n"
" printf(\"foo\");\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Comparison of a boolean expression with an integer other than 0 or 1.\n", errout_str());
check("void f(bool x) {\n"
" if (10 >= x) {\n"
" printf(\"foo\");\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Comparison of a boolean expression with an integer other than 0 or 1.\n", errout_str());
check("void f(bool x) {\n"
" if (x != 0) {\n"
" printf(\"foo\");\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(bool x) {\n" // #3356
" if (x == 1) {\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(bool x) {\n"
" if (x != 10) {\n"
" printf(\"foo\");\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Comparison of a boolean expression with an integer other than 0 or 1.\n", errout_str());
check("void f(bool x) {\n"
" if (x == 10) {\n"
" printf(\"foo\");\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Comparison of a boolean expression with an integer other than 0 or 1.\n", errout_str());
check("void f(bool x) {\n"
" if (x == 0) {\n"
" printf(\"foo\");\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("DensePropertyMap<int, true> visited;"); // #4075
ASSERT_EQUALS("", errout_str());
}
void comparisonOfBoolWithInt2() {
check("void f(bool x, int y) {\n"
" if (x == y) {\n"
" printf(\"foo\");\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x, bool y) {\n"
" if (x == y) {\n"
" printf(\"foo\");\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(bool x, bool y) {\n"
" if (x == y) {\n"
" printf(\"foo\");\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(bool x, fooClass y) {\n"
" if (x == y) {\n"
" printf(\"foo\");\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void comparisonOfBoolWithInt3() {
check("void f(int y) {\n"
" if (y > false) {\n"
" printf(\"foo\");\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Comparison of a boolean value using relational operator (<, >, <= or >=).\n", errout_str());
check("void f(int y) {\n"
" if (true == y) {\n"
" printf(\"foo\");\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(bool y) {\n"
" if (y == true) {\n"
" printf(\"foo\");\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(bool y) {\n"
" if (false < 5) {\n"
" printf(\"foo\");\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Comparison of a boolean expression with an integer other than 0 or 1.\n", errout_str());
}
void comparisonOfBoolWithInt4() {
check("void f(int x) {\n"
" if (!x == 1) { }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void comparisonOfBoolWithInt5() {
check("void SetVisible(int index, bool visible) {\n"
" bool (SciTEBase::*ischarforsel)(char ch);\n"
" if (visible != GetVisible(index)) { }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void comparisonOfBoolWithInt6() { // #4224 - integer is casted to bool
check("void SetVisible(bool b, int i) {\n"
" if (b == (bool)i) { }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void comparisonOfBoolWithInt7() { // #4846 - (!x==true)
check("void f(int x) {\n"
" if (!x == true) { }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void comparisonOfBoolWithInt8() { // #9165
check("bool Fun();\n"
"void Test(bool expectedResult) {\n"
" auto res = Fun();\n"
" if (expectedResult == res)\n"
" throw 2;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int Fun();\n"
"void Test(bool expectedResult) {\n"
" auto res = Fun();\n"
" if (expectedResult == res)\n"
" throw 2;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("bool Fun();\n"
"void Test(bool expectedResult) {\n"
" auto res = Fun();\n"
" if (5 + expectedResult == res)\n"
" throw 2;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int Fun();\n"
"void Test(bool expectedResult) {\n"
" auto res = Fun();\n"
" if (5 + expectedResult == res)\n"
" throw 2;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int Fun();\n"
"void Test(bool expectedResult) {\n"
" auto res = Fun();\n"
" if (expectedResult == res + 5)\n"
" throw 2;\n"
"}");
TODO_ASSERT_EQUALS("error", "", errout_str());
}
void comparisonOfBoolWithInt9() { // #9304
check("bool f(int a, bool b)\n"
"{\n"
" if ((a == 0 ? false : true) != b) {\n"
" b = !b;\n"
" }\n"
" return b;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void comparisonOfBoolWithInt10() { // #10935
check("enum class E { H = 2 };\n"
"template <bool H>\n"
"void f(bool v) {\n"
" if (v == H) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("namespace N {\n"
" enum class E { H = 2 };\n"
"}\n"
"void f(bool v) {\n"
" if (v == N::H) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void pointerArithBool1() { // #5126
check("void f(char *p) {\n"
" if (p+1){}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Converting pointer arithmetic result to bool. The bool is always true unless there is undefined behaviour.\n", errout_str());
check("void f(char *p) {\n"
" do {} while (p+1);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Converting pointer arithmetic result to bool. The bool is always true unless there is undefined behaviour.\n", errout_str());
check("void f(char *p) {\n"
" while (p-1) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Converting pointer arithmetic result to bool. The bool is always true unless there is undefined behaviour.\n", errout_str());
check("void f(char *p) {\n"
" for (int i = 0; p+1; i++) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Converting pointer arithmetic result to bool. The bool is always true unless there is undefined behaviour.\n", errout_str());
check("void f(char *p) {\n"
" if (p && p+1){}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Converting pointer arithmetic result to bool. The bool is always true unless there is undefined behaviour.\n", errout_str());
check("void f(char *p) {\n"
" if (p+2 || p) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Converting pointer arithmetic result to bool. The bool is always true unless there is undefined behaviour.\n", errout_str());
}
void returnNonBool() {
check("bool f(void) {\n"
" return 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("bool f(void) {\n"
" return 1;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("bool f(void) {\n"
" return 2;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Non-boolean value returned from function returning bool\n", errout_str());
check("bool f(void) {\n"
" return -1;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Non-boolean value returned from function returning bool\n", errout_str());
check("bool f(void) {\n"
" return 1 + 1;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Non-boolean value returned from function returning bool\n", errout_str());
check("bool f(void) {\n"
" int x = 0;\n"
" return x;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("bool f(void) {\n"
" int x = 10;\n"
" return x;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Non-boolean value returned from function returning bool\n", errout_str());
check("bool f(void) {\n"
" return 2 < 1;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("bool f(void) {\n"
" int ret = 0;\n"
" if (a)\n"
" ret = 1;\n"
" return ret;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("bool f(void) {\n"
" int ret = 0;\n"
" if (a)\n"
" ret = 3;\n"
" return ret;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (style) Non-boolean value returned from function returning bool\n", errout_str());
check("bool f(void) {\n"
" if (a)\n"
" return 3;\n"
" return 4;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Non-boolean value returned from function returning bool\n"
"[test.cpp:4]: (style) Non-boolean value returned from function returning bool\n", errout_str());
check("bool f(void) {\n"
" return;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void returnNonBoolLambda() {
check("bool f(void) {\n"
" auto x = [](void) { return -1; };\n"
" return false;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("bool f(void) {\n"
" auto x = [](void) { return -1; };\n"
" return 2;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Non-boolean value returned from function returning bool\n", errout_str());
check("bool f(void) {\n"
" auto x = [](void) -> int { return -1; };\n"
" return false;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("bool f(void) {\n"
" auto x = [](void) -> int { return -1; };\n"
" return 2;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Non-boolean value returned from function returning bool\n", errout_str());
}
void returnNonBoolLogicalOp() {
check("bool f(int x) {\n"
" return x & 0x4;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("bool f(int x, int y) {\n"
" return x | y;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("bool f(int x) {\n"
" return (x & 0x2);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void returnNonBoolClass() {
check("class X {\n"
" public:\n"
" bool f() { return -1;}\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Non-boolean value returned from function returning bool\n", errout_str());
check("bool f() {\n"
" struct X {\n"
" public:\n"
" int f() { return -1;}\n"
" };\n"
" return false;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("bool f() {\n"
" class X {\n"
" public:\n"
" int f() { return -1;}\n"
" };\n"
" return false;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("bool f() {\n"
" class X {\n"
" public:\n"
" bool f() { return -1;}\n"
" };\n"
" return -1;\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (style) Non-boolean value returned from function returning bool\n"
"[test.cpp:4]: (style) Non-boolean value returned from function returning bool\n", errout_str());
}
};
REGISTER_TEST(TestBool)
| null |
1,022 | cpp | cppcheck | testsizeof.cpp | test/testsizeof.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#include "checksizeof.h"
#include "errortypes.h"
#include "fixture.h"
#include "helpers.h"
#include "settings.h"
#include "tokenize.h"
#include <cstddef>
#include <string>
#include <vector>
class TestSizeof : public TestFixture {
public:
TestSizeof() : TestFixture("TestSizeof") {}
private:
const Settings settings = settingsBuilder().severity(Severity::warning).severity(Severity::portability).certainty(Certainty::inconclusive).library("std.cfg").build();
void run() override {
TEST_CASE(sizeofsizeof);
TEST_CASE(sizeofCalculation);
TEST_CASE(sizeofFunction);
TEST_CASE(checkPointerSizeof);
TEST_CASE(checkPointerSizeofStruct);
TEST_CASE(sizeofDivisionMemset);
TEST_CASE(sizeofForArrayParameter);
TEST_CASE(sizeofForNumericParameter);
TEST_CASE(suspiciousSizeofCalculation);
TEST_CASE(sizeofVoid);
TEST_CASE(customStrncat);
}
#define check(code) check_(code, __FILE__, __LINE__)
template<size_t size>
void check_(const char (&code)[size], const char* file, int line) {
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
// Check...
runChecks<CheckSizeof>(tokenizer, this);
}
#define checkP(...) checkP_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
void checkP_(const char* file, int line, const char (&code)[size]) {
std::vector<std::string> files(1, "test.cpp");
Tokenizer tokenizer(settings, *this);
PreprocessorHelper::preprocess(code, files, tokenizer, *this);
// Tokenize..
ASSERT_LOC(tokenizer.simplifyTokens1(""), file, line);
// Check...
runChecks<CheckSizeof>(tokenizer, this);
}
void sizeofsizeof() {
check("void foo()\n"
"{\n"
" int i = sizeof sizeof char;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Calling 'sizeof' on 'sizeof'.\n", errout_str());
check("void foo()\n"
"{\n"
" int i = sizeof (sizeof long);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Calling 'sizeof' on 'sizeof'.\n", errout_str());
check("void foo(long *p)\n"
"{\n"
" int i = sizeof (sizeof (p));\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Calling 'sizeof' on 'sizeof'.\n", errout_str());
}
void sizeofCalculation() {
check("int a, b; int a,sizeof(a+b)");
ASSERT_EQUALS("[test.cpp:1]: (warning) Found calculation inside sizeof().\n", errout_str());
check("int a, b; sizeof(a*b)");
ASSERT_EQUALS("[test.cpp:1]: (warning) Found calculation inside sizeof().\n", errout_str());
check("int a, b; sizeof(-a)");
ASSERT_EQUALS("[test.cpp:1]: (warning) Found calculation inside sizeof().\n", errout_str());
check("int a, b; sizeof(*a)");
ASSERT_EQUALS("", errout_str());
check("sizeof(void * const)");
ASSERT_EQUALS("", errout_str());
check("sizeof(int*[2])");
ASSERT_EQUALS("", errout_str());
check("sizeof(Fred**)");
ASSERT_EQUALS("", errout_str());
check("sizeof(foo++)");
ASSERT_EQUALS("[test.cpp:1]: (warning) Found calculation inside sizeof().\n", errout_str());
check("sizeof(--foo)");
ASSERT_EQUALS("[test.cpp:1]: (warning) Found calculation inside sizeof().\n", errout_str());
// #6888
checkP("#define SIZEOF1 sizeof(i != 2)\n"
"#define SIZEOF2 ((sizeof(i != 2)))\n"
"#define VOIDCAST1 (void)\n"
"#define VOIDCAST2(SZ) static_cast<void>(SZ)\n"
"int f(int i) {\n"
" VOIDCAST1 SIZEOF1;\n"
" VOIDCAST1 SIZEOF2;\n"
" VOIDCAST2(SIZEOF1);\n"
" VOIDCAST2(SIZEOF2);\n"
" return i + foo(1);\n"
"}");
ASSERT_EQUALS("", errout_str());
checkP("#define SIZEOF1 sizeof(i != 2)\n"
"#define SIZEOF2 ((sizeof(i != 2)))\n"
"int f(int i) {\n"
" SIZEOF1;\n"
" SIZEOF2;\n"
" return i + foo(1);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (warning, inconclusive) Found calculation inside sizeof().\n"
"[test.cpp:5]: (warning, inconclusive) Found calculation inside sizeof().\n", errout_str());
checkP("#define MACRO(data) f(data, sizeof(data))\n"
"x = MACRO((unsigned int *)data + 4);");
ASSERT_EQUALS("[test.cpp:2]: (warning, inconclusive) Found calculation inside sizeof().\n", errout_str());
}
void sizeofFunction() {
check("class Foo\n"
"{\n"
" int bar() { return 1; };\n"
"}\n"
"Foo f;int a=sizeof(f.bar());");
ASSERT_EQUALS("[test.cpp:5]: (warning) Found function call inside sizeof().\n", errout_str());
check("class Foo\n"
"{\n"
" int bar() { return 1; };\n"
" int bar() const { return 1; };\n"
"}\n"
"Foo f;int a=sizeof(f.bar());");
ASSERT_EQUALS("", errout_str());
check("class Foo\n"
"{\n"
" int bar() { return 1; };\n"
"}\n"
"Foo * fp;int a=sizeof(fp->bar());");
ASSERT_EQUALS("[test.cpp:5]: (warning) Found function call inside sizeof().\n", errout_str());
check("int a=sizeof(foo());");
ASSERT_EQUALS("", errout_str());
check("int foo() { return 1; }; int a=sizeof(foo());");
ASSERT_EQUALS("[test.cpp:1]: (warning) Found function call inside sizeof().\n", errout_str());
check("int foo() { return 1; }; sizeof(decltype(foo()));");
ASSERT_EQUALS("", errout_str());
check("int foo(int) { return 1; }; int a=sizeof(foo(0))");
ASSERT_EQUALS("[test.cpp:1]: (warning) Found function call inside sizeof().\n", errout_str());
check("char * buf; int a=sizeof(*buf);");
ASSERT_EQUALS("", errout_str());
check("int a=sizeof(foo())");
ASSERT_EQUALS("", errout_str());
check("int foo(int) { return 1; }; char buf[1024]; int a=sizeof(buf), foo(0)");
ASSERT_EQUALS("", errout_str());
check("template<class T>\n"
"struct A\n"
"{\n"
" static B f(const B &);\n"
" static A f(const A &);\n"
" static A &g();\n"
" static T &h();\n"
"\n"
" enum {\n"
" X = sizeof(f(g() >> h())) == sizeof(A),\n"
" Y = sizeof(f(g() << h())) == sizeof(A),\n"
" Z = X & Y\n"
" };\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void sizeofForArrayParameter() {
check("void f() {\n"
" int a[10];\n"
" std::cout << sizeof(a) / sizeof(int) << std::endl;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" unsigned int a = 2;\n"
" unsigned int b = 2;\n"
" int c[(a+b)];\n"
" std::cout << sizeof(c) / sizeof(int) << std::endl;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" unsigned int a = { 2 };\n"
" unsigned int b[] = { 0 };\n"
" int c[a[b[0]]];\n"
" std::cout << sizeof(c) / sizeof(int) << std::endl;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" unsigned int a[] = { 1 };\n"
" unsigned int b = 2;\n"
" int c[(a[0]+b)];\n"
" std::cout << sizeof(c) / sizeof(int) << std::endl;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int a[] = { 1, 2, 3 };\n"
" std::cout << sizeof(a) / sizeof(int) << std::endl;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int a[3] = { 1, 2, 3 };\n"
" std::cout << sizeof(a) / sizeof(int) << std::endl;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f( int a[]) {\n"
" std::cout << sizeof(a) / sizeof(int) << std::endl;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Using 'sizeof' on array given as "
"function argument returns size of a pointer.\n", errout_str());
check("void f( int a[]) {\n"
" std::cout << sizeof a / sizeof(int) << std::endl;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Using 'sizeof' on array given as "
"function argument returns size of a pointer.\n", errout_str());
check("void f( int a[3] ) {\n"
" std::cout << sizeof(a) / sizeof(int) << std::endl;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Using 'sizeof' on array given as "
"function argument returns size of a pointer.\n", errout_str());
check("typedef char Fixname[1000];\n"
"int f2(Fixname& f2v) {\n"
" int i = sizeof(f2v);\n"
" printf(\"sizeof f2v %d\", i);\n"
" }");
ASSERT_EQUALS("", errout_str());
check("void f(int *p) {\n"
" p[0] = 0;\n"
" int unused = sizeof(p);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" char p[] = \"test\";\n"
" int unused = sizeof(p);\n"
"}");
ASSERT_EQUALS("", errout_str());
// ticket #2495
check("void f() {\n"
" static float col[][3]={\n"
" {1,0,0},\n"
" {0,0,1},\n"
" {0,1,0},\n"
" {1,0,1},\n"
" {1,0,1},\n"
" {1,0,1},\n"
" };\n"
" const int COL_MAX=sizeof(col)/sizeof(col[0]);\n"
"}");
ASSERT_EQUALS("", errout_str());
// ticket #155
check("void f() {\n"
" char buff1[1024*64],buff2[sizeof(buff1)*2];\n"
"}");
ASSERT_EQUALS("", errout_str());
// ticket #2510
check("void f( int a[], int b) {\n"
" std::cout << sizeof(a) / sizeof(int) << std::endl;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Using 'sizeof' on array given as "
"function argument returns size of a pointer.\n", errout_str());
// ticket #2510
check("void f( int a[3] , int b[2] ) {\n"
" std::cout << sizeof(a) / sizeof(int) << std::endl;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Using 'sizeof' on array given as "
"function argument returns size of a pointer.\n", errout_str());
// ticket #2510
check("void f() {\n"
" char buff1[1024*64],buff2[sizeof(buff1)*(2+1)];\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void sizeofForNumericParameter() {
check("void f() {\n"
" std::cout << sizeof(10) << std::endl;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Suspicious usage of 'sizeof' with a numeric constant as parameter.\n", errout_str());
check("void f() {\n"
" std::cout << sizeof(-10) << std::endl;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Suspicious usage of 'sizeof' with a numeric constant as parameter.\n", errout_str());
check("void f() {\n"
" std::cout << sizeof 10 << std::endl;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Suspicious usage of 'sizeof' with a numeric constant as parameter.\n", errout_str());
check("void f() {\n"
" std::cout << sizeof -10 << std::endl;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Suspicious usage of 'sizeof' with a numeric constant as parameter.\n", errout_str());
}
void suspiciousSizeofCalculation() {
check("void f() {\n"
" int* p;\n"
" return sizeof(p)/5;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning, inconclusive) Division of result of sizeof() on pointer type.\n", errout_str());
check("void f() {\n"
" unknown p;\n"
" return sizeof(p)/5;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" return sizeof(unknown)/5;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int p;\n"
" return sizeof(p)/5;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int* p[5];\n"
" return sizeof(p)/5;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" return sizeof(foo)*sizeof(bar);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning, inconclusive) Multiplying sizeof() with sizeof() indicates a logic error.\n", errout_str());
check("void f() {\n"
" return (foo)*sizeof(bar);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" return sizeof(foo)*bar;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" return (end - source) / sizeof(encode_block_type) * sizeof(encode_block_type);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct S { T* t; };\n" // #10179
"int f(S* s) {\n"
" return g(sizeof(*s->t) / 4);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" const char* a[N];\n"
" for (int i = 0; i < (int)(sizeof(a) / sizeof(char*)); i++) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("int f(int** p) {\n"
" return sizeof(p[0]) / 4;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (warning, inconclusive) Division of result of sizeof() on pointer type.\n", errout_str());
check("struct S {\n"
" unsigned char* s;\n"
"};\n"
"struct T {\n"
" S s[38];\n"
"};\n"
"void f(T* t) {\n"
" for (size_t i = 0; i < sizeof(t->s) / sizeof(t->s[0]); i++) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct S {\n"
" struct T {\n"
" char* c[3];\n"
" } t[1];\n"
"};\n"
"void f(S* s) {\n"
" for (int i = 0; i != sizeof(s->t[0].c) / sizeof(char*); i++) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(int32_t* buf, size_t len) {\n"
" for (int i = 0; i < len / sizeof(buf[0]); i++) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(int32_t*** buf, size_t len) {\n"
" for (int i = 0; i < len / sizeof(**buf[0]); i++) {}\n"
" for (int i = 0; i < len / sizeof(*buf[0][0]); i++) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void checkPointerSizeof() {
check("void f() {\n"
" char *x = malloc(10);\n"
" free(x);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int *x = malloc(sizeof(*x));\n"
" free(x);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int *x = malloc(sizeof(int));\n"
" free(x);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int *x = malloc(sizeof(x));\n"
" free(x);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Size of pointer 'x' used instead of size of its data.\n", errout_str());
check("void f() {\n"
" int *x = (int*)malloc(sizeof(x));\n"
" free(x);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Size of pointer 'x' used instead of size of its data.\n", errout_str());
check("void f() {\n"
" int *x = static_cast<int*>(malloc(sizeof(x)));\n"
" free(x);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Size of pointer 'x' used instead of size of its data.\n", errout_str());
check("void f() {\n"
" int *x = malloc(sizeof(&x));\n"
" free(x);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Size of pointer 'x' used instead of size of its data.\n", errout_str());
check("void f() {\n"
" int *x = malloc(sizeof(int*));\n"
" free(x);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Size of pointer 'x' used instead of size of its data.\n", errout_str());
check("void f() {\n"
" int *x = malloc(sizeof(int));\n"
" free(x);\n"
" int **y = malloc(sizeof(int*));\n"
" free(y);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int *x = malloc(100 * sizeof(x));\n"
" free(x);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Size of pointer 'x' used instead of size of its data.\n", errout_str());
check("void f() {\n"
" int *x = malloc(sizeof(x) * 100);\n"
" free(x);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Size of pointer 'x' used instead of size of its data.\n", errout_str());
check("void f() {\n"
" int *x = malloc(sizeof *x);\n"
" free(x);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int *x = malloc(sizeof x);\n"
" free(x);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Size of pointer 'x' used instead of size of its data.\n", errout_str());
check("void f() {\n"
" int *x = malloc(100 * sizeof x);\n"
" free(x);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Size of pointer 'x' used instead of size of its data.\n", errout_str());
check("void f() {\n"
" int *x = calloc(1, sizeof(*x));\n"
" free(x);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int *x = calloc(1, sizeof *x);\n"
" free(x);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int *x = calloc(1, sizeof(x));\n"
" free(x);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Size of pointer 'x' used instead of size of its data.\n", errout_str());
check("void f() {\n"
" int *x = calloc(1, sizeof x);\n"
" free(x);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Size of pointer 'x' used instead of size of its data.\n", errout_str());
check("void f() {\n"
" int *x = calloc(1, sizeof(int));\n"
" free(x);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" char x[10];\n"
" memset(x, 0, sizeof(x));\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" char* x[10];\n"
" memset(x, 0, sizeof(x));\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" char x[10];\n"
" memset(x, 0, sizeof x);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int *x = malloc(sizeof(int));\n"
" memset(x, 0, sizeof(int));\n"
" free(x);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int *x = malloc(sizeof(int));\n"
" memset(x, 0, sizeof(*x));\n"
" free(x);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int *x = malloc(sizeof(int));\n"
" memset(x, 0, sizeof *x);\n"
" free(x);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int *x = malloc(sizeof(int));\n"
" memset(x, 0, sizeof x);\n"
" free(x);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Size of pointer 'x' used instead of size of its data.\n", errout_str());
check("void f() {\n"
" int *x = malloc(sizeof(int));\n"
" memset(x, 0, sizeof(x));\n"
" free(x);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Size of pointer 'x' used instead of size of its data.\n", errout_str());
check("void f() {\n"
" int *x = malloc(sizeof(int) * 10);\n"
" memset(x, 0, sizeof(x) * 10);\n"
" free(x);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Size of pointer 'x' used instead of size of its data.\n", errout_str());
check("void f() {\n"
" int *x = malloc(sizeof(int) * 10);\n"
" memset(x, 0, sizeof x * 10);\n"
" free(x);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Size of pointer 'x' used instead of size of its data.\n", errout_str());
check("void f() {\n"
" int *x = malloc(sizeof(int) * 10);\n"
" memset(x, 0, sizeof(*x) * 10);\n"
" free(x);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int *x = malloc(sizeof(int) * 10);\n"
" memset(x, 0, sizeof *x * 10);\n"
" free(x);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int *x = malloc(sizeof(int) * 10);\n"
" memset(x, 0, sizeof(int) * 10);\n"
" free(x);\n"
"}");
ASSERT_EQUALS("", errout_str());
check(
"int fun(const char *buf1)\n"
"{\n"
" const char *buf1_ex = \"foobarbaz\";\n"
" return strncmp(buf1, buf1_ex, sizeof(buf1_ex)) == 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (warning) Size of pointer 'buf1_ex' used instead of size of its data.\n", errout_str());
check(
"int fun(const char *buf1) {\n"
" return strncmp(buf1, foo(buf2), sizeof(buf1)) == 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Size of pointer 'buf1' used instead of size of its data.\n", errout_str());
check("int fun(const char *buf2) {\n"
" return strncmp(buf1, buf2, sizeof(char*)) == 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Size of pointer 'buf2' used instead of size of its data.\n", errout_str());
// #ticket 3874
check("void f()\n"
"{\n"
" int * pIntArray[10];\n"
" memset(pIntArray, 0, sizeof(pIntArray));\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void FreeFileName(const char *s) {\n"
" CxString tbuf;\n"
" const char *p;\n"
" memcpy(s, siezof(s));\n" // non-standard memcpy
"}");
ASSERT_EQUALS("", errout_str());
check("int f() {\n"
" module_config_t *tab = module;\n"
" memset(tab + confsize, 0, sizeof(tab[confsize]));\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int f(char* aug) {\n"
" memmove(aug + extra_string, aug, buf - (bfd_byte *)aug);\n" // #7100
"}");
ASSERT_EQUALS("", errout_str());
// #7518
check("bool create_iso_definition(cpp_reader *pfile, cpp_macro *macro) {\n"
" cpp_token *token;\n"
" cpp_hashnode **params = malloc(sizeof(cpp_hashnode *) * macro->paramc);\n"
" memcpy(params, macro->params, sizeof(cpp_hashnode *) * macro->paramc);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void* foo() {\n"
" void* AtomName = malloc(sizeof(char *) * 34);\n"
" return AtomName;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void checkPointerSizeofStruct() {
check("void f() {\n"
" struct foo *ptr;\n"
" memset( ptr->bar, 0, sizeof ptr->bar );\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" struct foo {\n"
" char bar[10];\n"
" }* ptr;\n"
" memset( ptr->bar, 0, sizeof ptr->bar );\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" struct foo {\n"
" char *bar;\n"
" }* ptr;\n"
" memset( ptr->bar, 0, sizeof ptr->bar );\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (warning) Size of pointer 'bar' used instead of size of its data.\n", errout_str());
}
void sizeofDivisionMemset() {
check("void foo(memoryMapEntry_t* entry, memoryMapEntry_t* memoryMapEnd) {\n"
" memmove(entry, entry + 1, (memoryMapEnd - entry) / sizeof(entry));\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning, inconclusive) Division of result of sizeof() on pointer type.\n"
"[test.cpp:2]: (warning) Division by result of sizeof(). memmove() expects a size in bytes, did you intend to multiply instead?\n",
errout_str());
check("Foo* allocFoo(int num) {\n"
" return malloc(num / sizeof(Foo));\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Division by result of sizeof(). malloc() expects a size in bytes, did you intend to multiply instead?\n", errout_str());
check("void f() {\n"
" char str[100];\n"
" strncpy(str, xyz, sizeof(str)/sizeof(str[0]));\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n" // #9648
" int a[5] = { 0 };\n"
" int b[5];\n"
" memcpy(b, a, ((sizeof(a) / sizeof(a[0])) - 1) * sizeof(a[0]));\n"
" memcpy(b, a, sizeof(a[0]) * ((sizeof(a) / sizeof(a[0])) - 1));\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void sizeofVoid() {
check("void f() {\n"
" int size = sizeof(void);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (portability) Behaviour of 'sizeof(void)' is not covered by the ISO C standard.\n", errout_str());
check("void f() {\n"
" void* p;\n"
" int size = sizeof(*p);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (portability) '*p' is of type 'void', the behaviour of 'sizeof(void)' is not covered by the ISO C standard.\n", errout_str());
check("void f() {\n"
" void* p = malloc(10);\n"
" int* p2 = p + 4;\n"
" int* p3 = p - 1;\n"
" int* p4 = 1 + p;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (portability) 'p' is of type 'void *'. When using void pointers in calculations, the behaviour is undefined.\n"
"[test.cpp:4]: (portability) 'p' is of type 'void *'. When using void pointers in calculations, the behaviour is undefined.\n"
"[test.cpp:5]: (portability) 'p' is of type 'void *'. When using void pointers in calculations, the behaviour is undefined.\n", errout_str());
check("void f() {\n"
" void* p1 = malloc(10);\n"
" void* p2 = malloc(5);\n"
" p1--;\n"
" p2++;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (portability) 'p1' is of type 'void *'. When using void pointers in calculations, the behaviour is undefined.\n"
"[test.cpp:5]: (portability) 'p2' is of type 'void *'. When using void pointers in calculations, the behaviour is undefined.\n", errout_str());
check("void f() {\n"
" void* p1 = malloc(10);\n"
" void* p2 = malloc(5);\n"
" p1-=4;\n"
" p2+=4;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (portability) 'p1' is of type 'void *'. When using void pointers in calculations, the behaviour is undefined.\n"
"[test.cpp:5]: (portability) 'p2' is of type 'void *'. When using void pointers in calculations, the behaviour is undefined.\n", errout_str());
check("void f() {\n"
" void* p = malloc(10);\n"
" int* p2 = &p + 4;\n"
" int* p3 = &p - 1;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" void** p1 = malloc(10);\n"
" p1--;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" void** p1;\n"
" int j = sizeof(*p1);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" void* p1[5];\n"
" int j = sizeof(*p1);\n"
"}");
ASSERT_EQUALS("", errout_str());
// Calculations on void* with casts
check("void f(void *data) {\n"
" *((unsigned char *)data + 1) = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(void *data) {\n"
" *((unsigned char *)(data) + 1) = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(void *data) {\n"
" unsigned char* c = (unsigned char *)(data + 1);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (portability) 'data' is of type 'void *'. When using void pointers in calculations, the behaviour is undefined.\n", errout_str());
check("void f(void *data) {\n"
" unsigned char* c = (unsigned char *)data++;\n"
" unsigned char* c2 = (unsigned char *)++data;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (portability) 'data' is of type 'void *'. When using void pointers in calculations, the behaviour is undefined.\n"
"[test.cpp:3]: (portability) 'data' is of type 'void *'. When using void pointers in calculations, the behaviour is undefined.\n", errout_str());
check("void f(void *data) {\n"
" void* data2 = data + 1;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (portability) 'data' is of type 'void *'. When using void pointers in calculations, the behaviour is undefined.\n", errout_str());
// #4908 (void pointer as a member of a struct/class)
check("struct FOO {\n"
" void *data;\n"
"};\n"
"char f(struct FOO foo) {\n"
" char x = *((char*)(foo.data+1));\n"
" foo.data++;\n"
" return x;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (portability) 'foo.data' is of type 'void *'. When using void pointers in calculations, the behaviour is undefined.\n"
"[test.cpp:6]: (portability) 'foo.data' is of type 'void *'. When using void pointers in calculations, the behaviour is undefined.\n", errout_str());
check("struct FOO {\n"
" void *data;\n"
"};\n"
"char f(struct FOO foo) {\n"
" char x = *((char*)foo.data+1);\n"
" return x;\n"
"}\n"
"char f2(struct FOO foo) {\n"
" char x = *((char*)((FOO)foo).data + 1);\n"
" return x;\n"
"}\n"
"char f3(struct FOO* foo) {\n"
" char x = *((char*)foo->data + 1);\n"
" return x;\n"
"}\n"
"struct BOO {\n"
" FOO data;\n"
"};\n"
"void f4(struct BOO* boo) {\n"
" char c = *((char*)boo->data.data + 1);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct FOO {\n"
" void *data;\n"
"};\n"
"char f(struct FOO* foo) {\n"
" *(foo[1].data + 1) = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (portability) 'foo[1].data' is of type 'void *'. When using void pointers in calculations, the behaviour is undefined.\n", errout_str());
check("struct FOO {\n"
" void *data;\n"
"};\n"
"void f2(struct FOO* foo) {\n"
" (foo[0]).data++;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (portability) '(foo[0]).data' is of type 'void *'. When using void pointers in calculations, the behaviour is undefined.\n", errout_str());
// #6050 arithmetic on void**
check("void* array[10];\n"
"void** b = array + 3;");
ASSERT_EQUALS("", errout_str());
}
void customStrncat() {
// Ensure we don't crash on custom-defined strncat, ticket #5875
check("char strncat ();\n"
"int main () {\n"
" return strncat ();\n"
"}");
}
};
REGISTER_TEST(TestSizeof)
| null |
1,023 | cpp | cppcheck | testpostfixoperator.cpp | test/testpostfixoperator.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#include "checkpostfixoperator.h"
#include "errortypes.h"
#include "fixture.h"
#include "helpers.h"
#include "settings.h"
#include <cstddef>
class TestPostfixOperator : public TestFixture {
public:
TestPostfixOperator() : TestFixture("TestPostfixOperator") {}
private:
const Settings settings = settingsBuilder().severity(Severity::performance).build();
#define check(code) check_(code, __FILE__, __LINE__)
template<size_t size>
void check_(const char (&code)[size], const char* file, int line) {
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
// Check for postfix operators..
CheckPostfixOperator checkPostfixOperator(&tokenizer, &settings, this);
checkPostfixOperator.postfixOperator();
}
void run() override {
TEST_CASE(testsimple);
TEST_CASE(testfor);
TEST_CASE(testvolatile);
TEST_CASE(testiterator);
TEST_CASE(test2168);
TEST_CASE(pointerSimplest);
TEST_CASE(pointer); // #2321 - postincrement of pointer is OK
TEST_CASE(testtemplate); // #4686
TEST_CASE(testmember);
TEST_CASE(testcomma);
TEST_CASE(testauto); // #8350
}
void testsimple() {
check("int main()\n"
"{\n"
" unsigned int k(0);\n"
" std::cout << k << std::endl;\n"
" k++;\n"
" std::cout << k << std::endl;\n"
" if(k) {\n"
" k++;\n"
" }\n"
" std::cout << k << std::endl;\n"
" k--;\n"
" std::cout << k << std::endl;\n"
" return 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("class K {};"
"int main()\n"
"{\n"
" K k(0);\n"
" std::cout << k << std::endl;\n"
" k++;\n"
" std::cout << k << std::endl;\n"
" return 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (performance) Prefer prefix ++/-- operators for non-primitive types.\n", errout_str());
check("struct K {};"
"void foo()\n"
"{\n"
" K k(0);\n"
" k++;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (performance) Prefer prefix ++/-- operators for non-primitive types.\n", errout_str());
check("struct K {};\n"
"void foo(K& k)\n"
"{\n"
" k++;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (performance) Prefer prefix ++/-- operators for non-primitive types.\n", errout_str());
check("union K {};"
"void foo()\n"
"{\n"
" K k(0);\n"
" k++;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (performance) Prefer prefix ++/-- operators for non-primitive types.\n", errout_str());
check("class K {};"
"int main()\n"
"{\n"
" K k(1);\n"
" std::cout << k << std::endl;\n"
" if(k) {\n"
" k++;\n"
" }\n"
" std::cout << k << std::endl;\n"
" return 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (performance) Prefer prefix ++/-- operators for non-primitive types.\n", errout_str());
check("class K {};"
"int main()\n"
"{\n"
" K k(1);\n"
" std::cout << k << std::endl;\n"
" if(k) {\n"
" ++k;\n"
" }\n"
" k++;\n"
" std::cout << k << std::endl;\n"
" return 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:8]: (performance) Prefer prefix ++/-- operators for non-primitive types.\n", errout_str());
check("class K {};"
"int main()\n"
"{\n"
" K k(0);\n"
" std::cout << k << std::endl;\n"
" k--;\n"
" std::cout << k << std::endl;\n"
" return 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (performance) Prefer prefix ++/-- operators for non-primitive types.\n", errout_str());
check("class K {};"
"int main()\n"
"{\n"
" K k(0);\n"
" std::cout << k << std::endl;\n"
" ++k;\n"
" std::cout << k << std::endl;\n"
" return 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("class K {};"
"int main()\n"
"{\n"
" K k(0);\n"
" std::cout << k << std::endl;\n"
" --k;\n"
" std::cout << k << std::endl;\n"
" return 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
// #9042
check("template <class T>\n"
"class c {\n"
" int i = 0;\n"
" c() { i--; }\n"
"};\n"
"template <class T>\n"
"class s {};\n"
"using BOOL = char;");
ASSERT_EQUALS("", errout_str());
}
void testfor() {
check("int main()\n"
"{\n"
" for ( unsigned int i=0; i <= 10; i++) {\n"
" std::cout << i << std::endl;\n"
" }\n"
" return 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("class K {};\n"
"int main()\n"
"{\n"
" for ( K i(0); i <= 10; i++) {\n"
" std::cout << i << std::endl;\n"
" }\n"
" return 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (performance) Prefer prefix ++/-- operators for non-primitive types.\n", errout_str());
check("class K {};\n"
"int main()\n"
"{\n"
" for ( K i(0); i <= 10; ++i) {\n"
" std::cout << i << std::endl;\n"
" }\n"
" return 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("class K {};\n"
"int main()\n"
"{\n"
" for ( K i(10); i > 1; i--) {\n"
" std::cout << i << std::endl;\n"
" }\n"
" return 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (performance) Prefer prefix ++/-- operators for non-primitive types.\n", errout_str());
check("class K {};\n"
"int main(int argc, char *argv[])\n"
"{\n"
" for ( K i=10; i > 1; --i) {\n"
" std::cout << i << std::endl;\n"
" }\n"
" return 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void testvolatile() {
check("class K {};\n"
"int main()\n"
"{\n"
" volatile K k(0);\n"
" std::cout << k << std::endl;\n"
" k++;\n"
" std::cout << k << std::endl;\n"
" return 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (performance) Prefer prefix ++/-- operators for non-primitive types.\n", errout_str());
}
void testiterator() {
check("class Base {};\n"
"int main() {\n"
" std::vector<Base*> v;\n"
" v.push_back(new Base());\n"
" v.push_back(new Base());\n"
" for (std::vector<Base*>::iterator i=v.begin(); i!=v.end(); i++) {\n"
" ;;\n"
" }\n"
" v.clear();\n"
" return 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (performance) Prefer prefix ++/-- operators for non-primitive types.\n", errout_str());
check("int main() {\n"
" std::vector<int> v;\n"
" std::vector<int>::iterator it;\n"
" for( int i=0; i < 10; ++i ) v.push_back(i);\n"
" unsigned int total = 0;\n"
" it = v.begin();\n"
" while( it != v.end() ) {\n"
" total += *it;\n"
" it++;\n"
" }\n"
" return 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:9]: (performance) Prefer prefix ++/-- operators for non-primitive types.\n", errout_str());
check("int main() {\n"
" std::vector<int> v;\n"
" std::vector<int>::const_iterator it;\n"
" for( int i=0; i < 10; ++i ) v.push_back(i);\n"
" unsigned int total = 0;\n"
" it = v.begin();\n"
" while( it != v.end() ) {\n"
" it++;\n"
" }\n"
" return 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:8]: (performance) Prefer prefix ++/-- operators for non-primitive types.\n", errout_str());
check("int main() {\n"
" std::vector<int> v;\n"
" std::vector<int>::iterator it;\n"
" for( int i=0; i < 10; ++i ) v.push_back(i);\n"
" unsigned int total = 0;\n"
" std::vector<int>::reverse_iterator rit;\n"
" rit= v.rend();\n"
" while( rit != v.rbegin() ) {\n"
" rit--;\n"
" }\n"
" return 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:9]: (performance) Prefer prefix ++/-- operators for non-primitive types.\n", errout_str());
}
void test2168() {
ASSERT_THROW_INTERNAL(check("--> declare allocator lock here\n"
"int main(){}"),
AST);
}
void pointerSimplest() {
check("void f(int* p){\n"
" p++;\n"
" std::cout << *p;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void pointer() {
check("static struct class * ab;\n"
"int * p;\n"
"\n"
"void f() {\n"
" p++;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void testtemplate() {
check("bool foo() {\n"
" std::vector<FilterConfigCacheEntry>::iterator aIter(aImport.begin());\n"
" aIter++;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (performance) Prefer prefix ++/-- operators for non-primitive types.\n", errout_str());
}
void testmember() {
check("bool foo() {\n"
" class A {}; class B {A a;};\n"
" B b;\n"
" b.a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (performance) Prefer prefix ++/-- operators for non-primitive types.\n", errout_str());
check("bool foo() {\n"
" class A {}; class B {A a;};\n"
" B b;\n"
" foo(b.a++);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void testcomma() {
check("bool foo(int i) {\n"
" class A {};\n"
" A a;\n"
" i++, a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (performance) Prefer prefix ++/-- operators for non-primitive types.\n", errout_str());
check("bool foo(int i) {\n"
" class A {};\n"
" A a;\n"
" foo(i, a++);\n"
" foo(a++, i);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void testauto() { // #8350
check("enum class Color { Red = 0, Green = 1, };\n"
"int fun(const Color color) {\n"
" auto a = 0;\n"
" for (auto i = static_cast<int>(color); i < 10; i++) {\n"
" a += i;\n"
" }\n"
" return a;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
};
REGISTER_TEST(TestPostfixOperator)
| null |
1,024 | cpp | cppcheck | testplatform.cpp | test/testplatform.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#include "platform.h"
#include "fixture.h"
#include "standards.h"
#include <string>
#include "xml.h"
class TestPlatform : public TestFixture {
public:
TestPlatform() : TestFixture("TestPlatform") {}
private:
void run() override {
TEST_CASE(empty);
TEST_CASE(valid_config_win32a);
TEST_CASE(valid_config_unix64);
TEST_CASE(valid_config_win32w);
TEST_CASE(valid_config_unix32);
TEST_CASE(valid_config_win64);
TEST_CASE(valid_config_file_1);
TEST_CASE(valid_config_file_2);
TEST_CASE(valid_config_file_3);
TEST_CASE(valid_config_file_4);
TEST_CASE(invalid_config_file_1);
TEST_CASE(empty_elements);
TEST_CASE(default_platform);
TEST_CASE(limitsDefines);
TEST_CASE(charMinMax);
TEST_CASE(no_root_node);
TEST_CASE(wrong_root_node);
}
static bool readPlatform(Platform& platform, const char* xmldata) {
tinyxml2::XMLDocument doc;
return (doc.Parse(xmldata) == tinyxml2::XML_SUCCESS) && platform.loadFromXmlDocument(&doc);
}
void empty() const {
// An empty platform file does not change values, only the type.
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n<platform/>";
Platform platform;
// TODO: this should fail - platform files need to be complete
TODO_ASSERT(!readPlatform(platform, xmldata));
}
void valid_config_win32a() const {
// Verify if native Win32A platform is loaded correctly
Platform platform;
PLATFORM(platform, Platform::Type::Win32A);
ASSERT_EQUALS(Platform::Type::Win32A, platform.type);
ASSERT(platform.isWindows());
ASSERT_EQUALS(1, platform.sizeof_bool);
ASSERT_EQUALS(2, platform.sizeof_short);
ASSERT_EQUALS(4, platform.sizeof_int);
ASSERT_EQUALS(4, platform.sizeof_long);
ASSERT_EQUALS(8, platform.sizeof_long_long);
ASSERT_EQUALS(4, platform.sizeof_float);
ASSERT_EQUALS(8, platform.sizeof_double);
ASSERT_EQUALS(8, platform.sizeof_long_double);
ASSERT_EQUALS(2, platform.sizeof_wchar_t);
ASSERT_EQUALS(4, platform.sizeof_size_t);
ASSERT_EQUALS(4, platform.sizeof_pointer);
ASSERT_EQUALS('\0', platform.defaultSign);
ASSERT_EQUALS(8, platform.char_bit);
ASSERT_EQUALS(16, platform.short_bit);
ASSERT_EQUALS(32, platform.int_bit);
ASSERT_EQUALS(32, platform.long_bit);
ASSERT_EQUALS(64, platform.long_long_bit);
}
void valid_config_unix64() const {
// Verify if native Unix64 platform is loaded correctly
Platform platform;
PLATFORM(platform, Platform::Type::Unix64);
ASSERT_EQUALS(Platform::Type::Unix64, platform.type);
ASSERT(!platform.isWindows());
ASSERT_EQUALS(1, platform.sizeof_bool);
ASSERT_EQUALS(2, platform.sizeof_short);
ASSERT_EQUALS(4, platform.sizeof_int);
ASSERT_EQUALS(8, platform.sizeof_long);
ASSERT_EQUALS(8, platform.sizeof_long_long);
ASSERT_EQUALS(4, platform.sizeof_float);
ASSERT_EQUALS(8, platform.sizeof_double);
ASSERT_EQUALS(16, platform.sizeof_long_double);
ASSERT_EQUALS(4, platform.sizeof_wchar_t);
ASSERT_EQUALS(8, platform.sizeof_size_t);
ASSERT_EQUALS(8, platform.sizeof_pointer);
ASSERT_EQUALS('\0', platform.defaultSign);
ASSERT_EQUALS(8, platform.char_bit);
ASSERT_EQUALS(16, platform.short_bit);
ASSERT_EQUALS(32, platform.int_bit);
ASSERT_EQUALS(64, platform.long_bit);
ASSERT_EQUALS(64, platform.long_long_bit);
}
void valid_config_win32w() const {
// Verify if native Win32W platform is loaded correctly
Platform platform;
PLATFORM(platform, Platform::Type::Win32W);
ASSERT_EQUALS(Platform::Type::Win32W, platform.type);
ASSERT(platform.isWindows());
ASSERT_EQUALS(1, platform.sizeof_bool);
ASSERT_EQUALS(2, platform.sizeof_short);
ASSERT_EQUALS(4, platform.sizeof_int);
ASSERT_EQUALS(4, platform.sizeof_long);
ASSERT_EQUALS(8, platform.sizeof_long_long);
ASSERT_EQUALS(4, platform.sizeof_float);
ASSERT_EQUALS(8, platform.sizeof_double);
ASSERT_EQUALS(8, platform.sizeof_long_double);
ASSERT_EQUALS(2, platform.sizeof_wchar_t);
ASSERT_EQUALS(4, platform.sizeof_size_t);
ASSERT_EQUALS(4, platform.sizeof_pointer);
ASSERT_EQUALS('\0', platform.defaultSign);
ASSERT_EQUALS(8, platform.char_bit);
ASSERT_EQUALS(16, platform.short_bit);
ASSERT_EQUALS(32, platform.int_bit);
ASSERT_EQUALS(32, platform.long_bit);
ASSERT_EQUALS(64, platform.long_long_bit);
}
void valid_config_unix32() const {
// Verify if native Unix32 platform is loaded correctly
Platform platform;
PLATFORM(platform, Platform::Type::Unix32);
ASSERT_EQUALS(Platform::Type::Unix32, platform.type);
ASSERT(!platform.isWindows());
ASSERT_EQUALS(1, platform.sizeof_bool);
ASSERT_EQUALS(2, platform.sizeof_short);
ASSERT_EQUALS(4, platform.sizeof_int);
ASSERT_EQUALS(4, platform.sizeof_long);
ASSERT_EQUALS(8, platform.sizeof_long_long);
ASSERT_EQUALS(4, platform.sizeof_float);
ASSERT_EQUALS(8, platform.sizeof_double);
ASSERT_EQUALS(12, platform.sizeof_long_double);
ASSERT_EQUALS(4, platform.sizeof_wchar_t);
ASSERT_EQUALS(4, platform.sizeof_size_t);
ASSERT_EQUALS(4, platform.sizeof_pointer);
ASSERT_EQUALS('\0', platform.defaultSign);
ASSERT_EQUALS(8, platform.char_bit);
ASSERT_EQUALS(16, platform.short_bit);
ASSERT_EQUALS(32, platform.int_bit);
ASSERT_EQUALS(32, platform.long_bit);
ASSERT_EQUALS(64, platform.long_long_bit);
}
void valid_config_win64() const {
// Verify if native Win64 platform is loaded correctly
Platform platform;
PLATFORM(platform, Platform::Type::Win64);
ASSERT_EQUALS(Platform::Type::Win64, platform.type);
ASSERT(platform.isWindows());
ASSERT_EQUALS(1, platform.sizeof_bool);
ASSERT_EQUALS(2, platform.sizeof_short);
ASSERT_EQUALS(4, platform.sizeof_int);
ASSERT_EQUALS(4, platform.sizeof_long);
ASSERT_EQUALS(8, platform.sizeof_long_long);
ASSERT_EQUALS(4, platform.sizeof_float);
ASSERT_EQUALS(8, platform.sizeof_double);
ASSERT_EQUALS(8, platform.sizeof_long_double);
ASSERT_EQUALS(2, platform.sizeof_wchar_t);
ASSERT_EQUALS(8, platform.sizeof_size_t);
ASSERT_EQUALS(8, platform.sizeof_pointer);
ASSERT_EQUALS('\0', platform.defaultSign);
ASSERT_EQUALS(8, platform.char_bit);
ASSERT_EQUALS(16, platform.short_bit);
ASSERT_EQUALS(32, platform.int_bit);
ASSERT_EQUALS(32, platform.long_bit);
ASSERT_EQUALS(64, platform.long_long_bit);
}
void valid_config_file_1() const {
// Valid platform configuration with all possible values specified.
// Similar to the avr8 platform file.
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<platform>\n"
" <char_bit>8</char_bit>\n"
" <default-sign>unsigned</default-sign>\n"
" <sizeof>\n"
" <bool>1</bool>\n"
" <short>2</short>\n"
" <int>2</int>\n"
" <long>4</long>\n"
" <long-long>8</long-long>\n"
" <float>4</float>\n"
" <double>4</double>\n"
" <long-double>4</long-double>\n"
" <pointer>2</pointer>\n"
" <size_t>2</size_t>\n"
" <wchar_t>2</wchar_t>\n"
" </sizeof>\n"
" </platform>";
Platform platform;
ASSERT(readPlatform(platform, xmldata));
ASSERT_EQUALS(Platform::Type::File, platform.type);
ASSERT(!platform.isWindows());
ASSERT_EQUALS(8, platform.char_bit);
ASSERT_EQUALS('u', platform.defaultSign);
ASSERT_EQUALS(1, platform.sizeof_bool);
ASSERT_EQUALS(2, platform.sizeof_short);
ASSERT_EQUALS(2, platform.sizeof_int);
ASSERT_EQUALS(4, platform.sizeof_long);
ASSERT_EQUALS(8, platform.sizeof_long_long);
ASSERT_EQUALS(4, platform.sizeof_float);
ASSERT_EQUALS(4, platform.sizeof_double);
ASSERT_EQUALS(4, platform.sizeof_long_double);
ASSERT_EQUALS(2, platform.sizeof_pointer);
ASSERT_EQUALS(2, platform.sizeof_size_t);
ASSERT_EQUALS(2, platform.sizeof_wchar_t);
ASSERT_EQUALS(16, platform.short_bit);
ASSERT_EQUALS(16, platform.int_bit);
ASSERT_EQUALS(32, platform.long_bit);
ASSERT_EQUALS(64, platform.long_long_bit);
}
void valid_config_file_2() const {
// Valid platform configuration with all possible values specified and
// char_bit > 8.
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<platform>\n"
" <char_bit>20</char_bit>\n"
" <default-sign>signed</default-sign>\n"
" <sizeof>\n"
" <bool>1</bool>\n"
" <short>2</short>\n"
" <int>3</int>\n"
" <long>4</long>\n"
" <long-long>5</long-long>\n"
" <float>6</float>\n"
" <double>7</double>\n"
" <long-double>8</long-double>\n"
" <pointer>9</pointer>\n"
" <size_t>10</size_t>\n"
" <wchar_t>11</wchar_t>\n"
" </sizeof>\n"
" </platform>";
Platform platform;
ASSERT(readPlatform(platform, xmldata));
ASSERT_EQUALS(Platform::Type::File, platform.type);
ASSERT(!platform.isWindows());
ASSERT_EQUALS(20, platform.char_bit);
ASSERT_EQUALS('s', platform.defaultSign);
ASSERT_EQUALS(1, platform.sizeof_bool);
ASSERT_EQUALS(2, platform.sizeof_short);
ASSERT_EQUALS(3, platform.sizeof_int);
ASSERT_EQUALS(4, platform.sizeof_long);
ASSERT_EQUALS(5, platform.sizeof_long_long);
ASSERT_EQUALS(6, platform.sizeof_float);
ASSERT_EQUALS(7, platform.sizeof_double);
ASSERT_EQUALS(8, platform.sizeof_long_double);
ASSERT_EQUALS(9, platform.sizeof_pointer);
ASSERT_EQUALS(10, platform.sizeof_size_t);
ASSERT_EQUALS(11, platform.sizeof_wchar_t);
ASSERT_EQUALS(40, platform.short_bit);
ASSERT_EQUALS(60, platform.int_bit);
ASSERT_EQUALS(80, platform.long_bit);
ASSERT_EQUALS(100, platform.long_long_bit);
}
void valid_config_file_3() const {
// Valid platform configuration without any usable information.
// Similar like an empty file.
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<platform>\n"
" <char_bit1>8</char_bit1>\n"
" <default-sign1>unsigned</default-sign1>\n"
" <sizeof1>\n"
" <bool1>1</bool1>\n"
" <short1>2</short1>\n"
" <int1>3</int1>\n"
" <long1>4</long1>\n"
" <long-long1>5</long-long1>\n"
" <float1>6</float1>\n"
" <double1>7</double1>\n"
" <long-double1>8</long-double1>\n"
" <pointer1>9</pointer1>\n"
" <size_t1>10</size_t1>\n"
" <wchar_t1>11</wchar_t1>\n"
" </sizeof1>\n"
" </platform>";
Platform platform;
// TODO: needs to fail - files need to be complete
TODO_ASSERT(!readPlatform(platform, xmldata));
}
void valid_config_file_4() const {
// Valid platform configuration with all possible values specified and
// set to 0.
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<platform>\n"
" <char_bit>0</char_bit>\n"
" <default-sign>z</default-sign>\n"
" <sizeof>\n"
" <bool>0</bool>\n"
" <short>0</short>\n"
" <int>0</int>\n"
" <long>0</long>\n"
" <long-long>0</long-long>\n"
" <float>0</float>\n"
" <double>0</double>\n"
" <long-double>0</long-double>\n"
" <pointer>0</pointer>\n"
" <size_t>0</size_t>\n"
" <wchar_t>0</wchar_t>\n"
" </sizeof>\n"
" </platform>";
Platform platform;
ASSERT(readPlatform(platform, xmldata));
ASSERT_EQUALS(Platform::Type::File, platform.type);
ASSERT(!platform.isWindows());
ASSERT_EQUALS(0, platform.char_bit);
ASSERT_EQUALS('z', platform.defaultSign);
ASSERT_EQUALS(0, platform.sizeof_bool);
ASSERT_EQUALS(0, platform.sizeof_short);
ASSERT_EQUALS(0, platform.sizeof_int);
ASSERT_EQUALS(0, platform.sizeof_long);
ASSERT_EQUALS(0, platform.sizeof_long_long);
ASSERT_EQUALS(0, platform.sizeof_float);
ASSERT_EQUALS(0, platform.sizeof_double);
ASSERT_EQUALS(0, platform.sizeof_long_double);
ASSERT_EQUALS(0, platform.sizeof_pointer);
ASSERT_EQUALS(0, platform.sizeof_size_t);
ASSERT_EQUALS(0, platform.sizeof_wchar_t);
ASSERT_EQUALS(0, platform.short_bit);
ASSERT_EQUALS(0, platform.int_bit);
ASSERT_EQUALS(0, platform.long_bit);
ASSERT_EQUALS(0, platform.long_long_bit);
}
void invalid_config_file_1() const {
// Invalid XML file: mismatching elements "boolt" vs "bool".
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<platform>\n"
" <char_bit>8</char_bit>\n"
" <default-sign>unsigned</default-sign>\n"
" <sizeof>\n"
" <boolt>1</bool>\n"
" <short>2</short>\n"
" <int>2</int>\n"
" <long>4</long>\n"
" <long-long>8</long-long>\n"
" <float>4</float>\n"
" <double>4</double>\n"
" <long-double>4</long-double>\n"
" <pointer>2</pointer>\n"
" <size_t>2</size_t>\n"
" <wchar_t>2</wchar_t>\n"
" </sizeof>\n"
" </platform>";
Platform platform;
ASSERT(!readPlatform(platform, xmldata));
}
void empty_elements() const {
// Valid platform configuration without any usable information.
// Similar like an empty file.
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<platform>\n"
" <char_bit></char_bit>\n"
" <default-sign></default-sign>\n"
" <sizeof>\n"
" <bool></bool>\n"
" <short></short>\n"
" <int></int>\n"
" <long></long>\n"
" <long-long></long-long>\n"
" <float></float>\n"
" <double></double>\n"
" <long-double></long-double>\n"
" <pointer></pointer>\n"
" <size_t></size_t>\n"
" <wchar_t></wchar_t>\n"
" </sizeof>\n"
" </platform>";
Platform platform;
ASSERT(!readPlatform(platform, xmldata));
}
void default_platform() const {
Platform platform;
ASSERT_EQUALS(Platform::Type::Native, platform.type);
}
void limitsDefines() const {
Platform platform;
ASSERT_EQUALS(true, platform.set(Platform::Unix64));
const std::string defs = "CHAR_BIT=8;SCHAR_MIN=-128;SCHAR_MAX=127;UCHAR_MAX=255;CHAR_MIN=0;CHAR_MAX=127;SHRT_MIN=-32768;SHRT_MAX=32767;USHRT_MAX=65535;INT_MIN=(-2147483647 - 1);INT_MAX=2147483647;UINT_MAX=4294967295;LONG_MIN=(-9223372036854775807L - 1L);LONG_MAX=9223372036854775807L;ULONG_MAX=18446744073709551615UL";
const std::string defs_c99 = "CHAR_BIT=8;SCHAR_MIN=-128;SCHAR_MAX=127;UCHAR_MAX=255;CHAR_MIN=0;CHAR_MAX=127;SHRT_MIN=-32768;SHRT_MAX=32767;USHRT_MAX=65535;INT_MIN=(-2147483647 - 1);INT_MAX=2147483647;UINT_MAX=4294967295;LONG_MIN=(-9223372036854775807L - 1L);LONG_MAX=9223372036854775807L;ULONG_MAX=18446744073709551615UL;LLONG_MIN=(-9223372036854775807LL - 1LL);LLONG_MAX=9223372036854775807LL;ULLONG_MAX=18446744073709551615ULL";
ASSERT_EQUALS(defs, platform.getLimitsDefines(Standards::cstd_t::C89));
ASSERT_EQUALS(defs_c99, platform.getLimitsDefines(Standards::cstd_t::C99));
ASSERT_EQUALS(defs_c99, platform.getLimitsDefines(Standards::cstd_t::CLatest));
ASSERT_EQUALS(defs, platform.getLimitsDefines(Standards::cppstd_t::CPP03));
ASSERT_EQUALS(defs_c99, platform.getLimitsDefines(Standards::cppstd_t::CPP11));
ASSERT_EQUALS(defs_c99, platform.getLimitsDefines(Standards::cppstd_t::CPPLatest));
}
void charMinMax() const {
Platform platform;
ASSERT_EQUALS(255, platform.unsignedCharMax());
ASSERT_EQUALS(127, platform.signedCharMax());
ASSERT_EQUALS(-128, platform.signedCharMin());
}
void no_root_node() const {
constexpr char xmldata[] = "<?xml version=\"1.0\"?>";
Platform platform;
ASSERT(!readPlatform(platform, xmldata));
}
void wrong_root_node() const {
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<platforms/>";
Platform platform;
ASSERT(!readPlatform(platform, xmldata));
}
};
REGISTER_TEST(TestPlatform)
| null |
1,025 | cpp | cppcheck | testlibrary.cpp | test/testlibrary.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#include "errortypes.h"
#include "fixture.h"
#include "helpers.h"
#include "library.h"
#include "settings.h"
#include "standards.h"
#include "token.h"
#include "tokenlist.h"
#include <cstddef>
#include <cstdint>
#include <map>
#include <sstream>
#include <string>
#include <unordered_map>
#include <vector>
#define ASSERT_EQ(expected, actual) ASSERT(expected == actual)
class TestLibrary : public TestFixture {
public:
TestLibrary() : TestFixture("TestLibrary") {}
private:
const Settings settings;
void run() override {
TEST_CASE(isCompliantValidationExpression);
TEST_CASE(empty);
TEST_CASE(function);
TEST_CASE(function_match_scope);
TEST_CASE(function_match_args);
TEST_CASE(function_match_args_default);
TEST_CASE(function_match_var);
TEST_CASE(function_arg);
TEST_CASE(function_arg_any);
TEST_CASE(function_arg_variadic);
TEST_CASE(function_arg_direction);
TEST_CASE(function_arg_valid);
TEST_CASE(function_arg_minsize);
TEST_CASE(function_namespace);
TEST_CASE(function_method);
TEST_CASE(function_baseClassMethod); // calling method in base class
TEST_CASE(function_warn);
TEST_CASE(memory);
TEST_CASE(memory2); // define extra "free" allocation functions
TEST_CASE(memory3);
TEST_CASE(resource);
TEST_CASE(podtype);
TEST_CASE(container);
TEST_CASE(version);
TEST_CASE(loadLibErrors);
TEST_CASE(loadLibCombinations);
}
void isCompliantValidationExpression() const {
ASSERT_EQUALS(true, Library::isCompliantValidationExpression("-1"));
ASSERT_EQUALS(true, Library::isCompliantValidationExpression("1"));
ASSERT_EQUALS(true, Library::isCompliantValidationExpression("1:"));
ASSERT_EQUALS(true, Library::isCompliantValidationExpression(":1"));
ASSERT_EQUALS(true, Library::isCompliantValidationExpression("-1,42"));
ASSERT_EQUALS(true, Library::isCompliantValidationExpression("-1,-42"));
ASSERT_EQUALS(true, Library::isCompliantValidationExpression("-1.0:42.0"));
ASSERT_EQUALS(true, Library::isCompliantValidationExpression("1.175494e-38:3.402823e+38"));
ASSERT_EQUALS(true, Library::isCompliantValidationExpression("1.175494e-38,3.402823e+38"));
ASSERT_EQUALS(true, Library::isCompliantValidationExpression("1.175494e-38:"));
ASSERT_EQUALS(true, Library::isCompliantValidationExpression(":1.175494e-38"));
ASSERT_EQUALS(true, Library::isCompliantValidationExpression(":42.0"));
ASSERT_EQUALS(true, Library::isCompliantValidationExpression("!42.0"));
// Robustness tests
ASSERT_EQUALS(false, Library::isCompliantValidationExpression(nullptr));
ASSERT_EQUALS(false, Library::isCompliantValidationExpression("x"));
ASSERT_EQUALS(false, Library::isCompliantValidationExpression("!"));
ASSERT_EQUALS(false, Library::isCompliantValidationExpression(""));
}
void empty() const {
// Reading an empty library file is considered to be OK
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n<def/>";
Library library;
ASSERT(LibraryHelper::loadxmldata(library, xmldata, sizeof(xmldata)));
ASSERT(library.functions().empty());
}
void function() const {
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <function name=\"foo\">\n"
" <noreturn>false</noreturn>\n"
" </function>\n"
"</def>";
const char code[] = "foo();";
SimpleTokenList tokenList(code);
tokenList.front()->next()->astOperand1(tokenList.front());
Library library;
ASSERT(LibraryHelper::loadxmldata(library, xmldata, sizeof(xmldata)));
ASSERT_EQUALS(library.functions().size(), 1U);
ASSERT(library.functions().at("foo").argumentChecks.empty());
ASSERT(library.isnotnoreturn(tokenList.front()));
}
void function_match_scope() const {
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <function name=\"foo\">\n"
" <arg nr=\"1\"/>"
" </function>\n"
"</def>";
Library library;
ASSERT(LibraryHelper::loadxmldata(library, xmldata, sizeof(xmldata)));
{
const char code[] = "fred.foo(123);"; // <- wrong scope, not library function
const SimpleTokenList tokenList(code);
ASSERT(library.isNotLibraryFunction(tokenList.front()->tokAt(2)));
}
{
const char code[] = "Fred::foo(123);"; // <- wrong scope, not library function
const SimpleTokenList tokenList(code);
ASSERT(library.isNotLibraryFunction(tokenList.front()->tokAt(2)));
}
}
void function_match_args() const {
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <function name=\"foo\">\n"
" <arg nr=\"1\"/>"
" </function>\n"
"</def>";
TokenList tokenList(&settings);
std::istringstream istr("foo();"); // <- too few arguments, not library function
ASSERT(tokenList.createTokens(istr, Standards::Language::CPP));
Token::createMutualLinks(tokenList.front()->next(), tokenList.back()->previous());
tokenList.createAst();
Library library;
ASSERT(LibraryHelper::loadxmldata(library, xmldata, sizeof(xmldata)));
ASSERT(library.isNotLibraryFunction(tokenList.front()));
}
void function_match_args_default() const {
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <function name=\"foo\">\n"
" <arg nr=\"1\"/>"
" <arg nr=\"2\" default=\"0\"/>"
" </function>\n"
"</def>";
Library library;
ASSERT(LibraryHelper::loadxmldata(library, xmldata, sizeof(xmldata)));
{
TokenList tokenList(&settings);
std::istringstream istr("foo();"); // <- too few arguments, not library function
ASSERT(tokenList.createTokens(istr, Standards::Language::CPP));
Token::createMutualLinks(tokenList.front()->next(), tokenList.back()->previous());
tokenList.createAst();
ASSERT(library.isNotLibraryFunction(tokenList.front()));
}
{
TokenList tokenList(&settings);
std::istringstream istr("foo(a);"); // <- library function
ASSERT(tokenList.createTokens(istr, Standards::Language::CPP));
Token::createMutualLinks(tokenList.front()->next(), tokenList.back()->previous());
tokenList.createAst();
const Library::Function* func = nullptr;
ASSERT(!library.isNotLibraryFunction(tokenList.front(), &func));
ASSERT(func);
}
{
TokenList tokenList(&settings);
std::istringstream istr("foo(a, b);"); // <- library function
ASSERT(tokenList.createTokens(istr, Standards::Language::CPP));
Token::createMutualLinks(tokenList.front()->next(), tokenList.back()->previous());
tokenList.createAst();
const Library::Function* func = nullptr;
ASSERT(!library.isNotLibraryFunction(tokenList.front(), &func));
ASSERT(func);
}
{
TokenList tokenList(&settings);
std::istringstream istr("foo(a, b, c);"); // <- too much arguments, not library function
ASSERT(tokenList.createTokens(istr, Standards::Language::CPP));
Token::createMutualLinks(tokenList.front()->next(), tokenList.back()->previous());
tokenList.createAst();
ASSERT(library.isNotLibraryFunction(tokenList.front()));
}
}
void function_match_var() const {
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <function name=\"foo\">\n"
" <arg nr=\"1\"/>"
" </function>\n"
"</def>";
const char code[] = "Fred foo(123);"; // <- Variable declaration, not library function
SimpleTokenList tokenList(code);
tokenList.front()->next()->astOperand1(tokenList.front());
tokenList.front()->next()->varId(1);
Library library;
ASSERT(LibraryHelper::loadxmldata(library, xmldata, sizeof(xmldata)));
ASSERT(library.isNotLibraryFunction(tokenList.front()->next()));
}
void function_arg() const {
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <function name=\"foo\">\n"
" <arg nr=\"1\"><not-uninit/></arg>\n"
" <arg nr=\"2\"><not-null/></arg>\n"
" <arg nr=\"3\"><formatstr/></arg>\n"
" <arg nr=\"4\"><strz/></arg>\n"
" <arg nr=\"5\" default=\"0\"><not-bool/></arg>\n"
" </function>\n"
"</def>";
Library library;
ASSERT(LibraryHelper::loadxmldata(library, xmldata, sizeof(xmldata)));
const auto& foo_fn_args = library.functions().at("foo").argumentChecks;
ASSERT_EQUALS(0, foo_fn_args.at(1).notuninit);
ASSERT_EQUALS(true, foo_fn_args.at(2).notnull);
ASSERT_EQUALS(true, foo_fn_args.at(3).formatstr);
ASSERT_EQUALS(true, foo_fn_args.at(4).strz);
ASSERT_EQUALS(false, foo_fn_args.at(4).optional);
ASSERT_EQUALS(true, foo_fn_args.at(5).notbool);
ASSERT_EQUALS(true, foo_fn_args.at(5).optional);
}
void function_arg_any() const {
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
"<function name=\"foo\">\n"
" <arg nr=\"any\"><not-uninit/></arg>\n"
"</function>\n"
"</def>";
Library library;
ASSERT(LibraryHelper::loadxmldata(library, xmldata, sizeof(xmldata)));
ASSERT_EQUALS(0, library.functions().at("foo").argumentChecks.at(-1).notuninit);
}
void function_arg_variadic() const {
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
"<function name=\"foo\">\n"
" <arg nr=\"1\"></arg>\n"
" <arg nr=\"variadic\"><not-uninit/></arg>\n"
"</function>\n"
"</def>";
Library library;
ASSERT(LibraryHelper::loadxmldata(library, xmldata, sizeof(xmldata)));
ASSERT_EQUALS(0, library.functions().at("foo").argumentChecks.at(-1).notuninit);
const char code[] = "foo(a,b,c,d,e);";
SimpleTokenList tokenList(code);
tokenList.front()->next()->astOperand1(tokenList.front());
ASSERT_EQUALS(false, library.isuninitargbad(tokenList.front(), 1));
ASSERT_EQUALS(true, library.isuninitargbad(tokenList.front(), 2));
ASSERT_EQUALS(true, library.isuninitargbad(tokenList.front(), 3));
ASSERT_EQUALS(true, library.isuninitargbad(tokenList.front(), 4));
}
void function_arg_direction() const {
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
"<function name=\"foo\">\n"
" <arg nr=\"1\" direction=\"in\"></arg>\n"
" <arg nr=\"2\" direction=\"out\"></arg>\n"
" <arg nr=\"3\" direction=\"inout\"></arg>\n"
" <arg nr=\"4\"></arg>\n"
"</function>\n"
"</def>";
Library library;
ASSERT(LibraryHelper::loadxmldata(library, xmldata, sizeof(xmldata)));
const char code[] = "foo(a,b,c,d);";
SimpleTokenList tokenList(code);
tokenList.front()->next()->astOperand1(tokenList.front());
ASSERT(Library::ArgumentChecks::Direction::DIR_IN == library.getArgDirection(tokenList.front(), 1));
ASSERT(Library::ArgumentChecks::Direction::DIR_OUT == library.getArgDirection(tokenList.front(), 2));
ASSERT(Library::ArgumentChecks::Direction::DIR_INOUT == library.getArgDirection(tokenList.front(), 3));
ASSERT(Library::ArgumentChecks::Direction::DIR_UNKNOWN == library.getArgDirection(tokenList.front(), 4));
}
void function_arg_valid() const {
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <function name=\"foo\">\n"
" <arg nr=\"1\"><valid>1:</valid></arg>\n"
" <arg nr=\"2\"><valid>-7:0</valid></arg>\n"
" <arg nr=\"3\"><valid>1:5,8</valid></arg>\n"
" <arg nr=\"4\"><valid>-1,5</valid></arg>\n"
" <arg nr=\"5\"><valid>:1,5</valid></arg>\n"
" <arg nr=\"6\"><valid>1.5:</valid></arg>\n"
" <arg nr=\"7\"><valid>-6.7:-5.5,-3.3:-2.7</valid></arg>\n"
" <arg nr=\"8\"><valid>0.0:</valid></arg>\n"
" <arg nr=\"9\"><valid>:2.0</valid></arg>\n"
" <arg nr=\"10\"><valid>0.0</valid></arg>\n"
" <arg nr=\"11\"><valid>!0.0</valid></arg>\n"
" </function>\n"
"</def>";
Library library;
ASSERT(LibraryHelper::loadxmldata(library, xmldata, sizeof(xmldata)));
const char code[] = "foo(a,b,c,d,e,f,g,h,i,j,k);";
SimpleTokenList tokenList(code);
tokenList.front()->next()->astOperand1(tokenList.front());
// 1-
ASSERT_EQUALS(false, library.isIntArgValid(tokenList.front(), 1, -10));
ASSERT_EQUALS(false, library.isFloatArgValid(tokenList.front(), 1, -10.0));
ASSERT_EQUALS(false, library.isIntArgValid(tokenList.front(), 1, 0));
ASSERT_EQUALS(false, library.isFloatArgValid(tokenList.front(), 1, 0.0));
ASSERT_EQUALS(true, library.isIntArgValid(tokenList.front(), 1, 1));
ASSERT_EQUALS(true, library.isFloatArgValid(tokenList.front(), 1, 1.0));
ASSERT_EQUALS(true, library.isIntArgValid(tokenList.front(), 1, 10));
ASSERT_EQUALS(true, library.isFloatArgValid(tokenList.front(), 1, 10.0));
// -7-0
ASSERT_EQUALS(false, library.isIntArgValid(tokenList.front(), 2, -10));
ASSERT_EQUALS(false, library.isFloatArgValid(tokenList.front(), 2, -10.0));
ASSERT_EQUALS(false, library.isFloatArgValid(tokenList.front(), 2, -7.5));
ASSERT_EQUALS(false, library.isFloatArgValid(tokenList.front(), 2, -7.1));
ASSERT_EQUALS(true, library.isIntArgValid(tokenList.front(), 2, -7));
ASSERT_EQUALS(true, library.isFloatArgValid(tokenList.front(), 2, -7.0));
ASSERT_EQUALS(true, library.isIntArgValid(tokenList.front(), 2, -3));
ASSERT_EQUALS(true, library.isFloatArgValid(tokenList.front(), 2, -3.0));
ASSERT_EQUALS(true, library.isFloatArgValid(tokenList.front(), 2, -3.5));
ASSERT_EQUALS(true, library.isIntArgValid(tokenList.front(), 2, 0));
ASSERT_EQUALS(true, library.isFloatArgValid(tokenList.front(), 2, 0.0));
ASSERT_EQUALS(false, library.isFloatArgValid(tokenList.front(), 2, 0.5));
ASSERT_EQUALS(false, library.isIntArgValid(tokenList.front(), 2, 1));
ASSERT_EQUALS(false, library.isFloatArgValid(tokenList.front(), 2, 1.0));
// 1-5,8
ASSERT_EQUALS(false, library.isIntArgValid(tokenList.front(), 3, 0));
ASSERT_EQUALS(false, library.isFloatArgValid(tokenList.front(), 3, 0.0));
ASSERT_EQUALS(true, library.isIntArgValid(tokenList.front(), 3, 1));
ASSERT_EQUALS(true, library.isFloatArgValid(tokenList.front(), 3, 1.0));
ASSERT_EQUALS(true, library.isIntArgValid(tokenList.front(), 3, 3));
ASSERT_EQUALS(true, library.isFloatArgValid(tokenList.front(), 3, 3.0));
ASSERT_EQUALS(true, library.isIntArgValid(tokenList.front(), 3, 5));
ASSERT_EQUALS(true, library.isFloatArgValid(tokenList.front(), 3, 5.0));
ASSERT_EQUALS(false, library.isIntArgValid(tokenList.front(), 3, 6));
ASSERT_EQUALS(false, library.isFloatArgValid(tokenList.front(), 3, 6.0));
ASSERT_EQUALS(false, library.isIntArgValid(tokenList.front(), 3, 7));
ASSERT_EQUALS(false, library.isFloatArgValid(tokenList.front(), 3, 7.0));
ASSERT_EQUALS(true, library.isIntArgValid(tokenList.front(), 3, 8));
ASSERT_EQUALS(false, library.isFloatArgValid(tokenList.front(), 3, 8.0));
ASSERT_EQUALS(false, library.isIntArgValid(tokenList.front(), 3, 9));
ASSERT_EQUALS(false, library.isFloatArgValid(tokenList.front(), 3, 9.0));
// -1,5
ASSERT_EQUALS(false, library.isIntArgValid(tokenList.front(), 4, -10));
ASSERT_EQUALS(false, library.isFloatArgValid(tokenList.front(), 4, -10.0));
ASSERT_EQUALS(true, library.isIntArgValid(tokenList.front(), 4, -1));
ASSERT_EQUALS(false, library.isFloatArgValid(tokenList.front(), 4, -1.0));
ASSERT_EQUALS(false, library.isFloatArgValid(tokenList.front(), 4, 5.000001));
ASSERT_EQUALS(false, library.isFloatArgValid(tokenList.front(), 4, 5.5));
// :1,5
ASSERT_EQUALS(true, library.isIntArgValid(tokenList.front(), 5, -10));
ASSERT_EQUALS(true, library.isFloatArgValid(tokenList.front(), 5, -10.0));
ASSERT_EQUALS(true, library.isIntArgValid(tokenList.front(), 5, 1));
ASSERT_EQUALS(true, library.isFloatArgValid(tokenList.front(), 5, 1.0));
ASSERT_EQUALS(false, library.isIntArgValid(tokenList.front(), 5, 2));
ASSERT_EQUALS(false, library.isFloatArgValid(tokenList.front(), 5, 2.0));
// 1.5:
ASSERT_EQUALS(false, library.isIntArgValid(tokenList.front(), 6, 0));
ASSERT_EQUALS(false, library.isFloatArgValid(tokenList.front(), 6, 0.0));
ASSERT_EQUALS(false, library.isIntArgValid(tokenList.front(), 6, 1));
ASSERT_EQUALS(false, library.isFloatArgValid(tokenList.front(), 6, 1.499999));
ASSERT_EQUALS(true, library.isFloatArgValid(tokenList.front(), 6, 1.5));
ASSERT_EQUALS(true, library.isIntArgValid(tokenList.front(), 6, 2));
ASSERT_EQUALS(true, library.isIntArgValid(tokenList.front(), 6, 10));
// -6.7:-5.5,-3.3:-2.7
ASSERT_EQUALS(false, library.isIntArgValid(tokenList.front(), 7, -7));
ASSERT_EQUALS(false, library.isFloatArgValid(tokenList.front(), 7, -7.0));
ASSERT_EQUALS(false, library.isFloatArgValid(tokenList.front(), 7, -6.7000001));
ASSERT_EQUALS(true, library.isFloatArgValid(tokenList.front(), 7, -6.7));
ASSERT_EQUALS(true, library.isIntArgValid(tokenList.front(), 7, -6));
ASSERT_EQUALS(true, library.isFloatArgValid(tokenList.front(), 7, -6.0));
ASSERT_EQUALS(true, library.isFloatArgValid(tokenList.front(), 7, -5.5));
ASSERT_EQUALS(false, library.isFloatArgValid(tokenList.front(), 7, -5.4999999));
ASSERT_EQUALS(false, library.isFloatArgValid(tokenList.front(), 7, -3.3000001));
ASSERT_EQUALS(true, library.isFloatArgValid(tokenList.front(), 7, -3.3));
ASSERT_EQUALS(true, library.isIntArgValid(tokenList.front(), 7, -3));
ASSERT_EQUALS(true, library.isFloatArgValid(tokenList.front(), 7, -3.0));
ASSERT_EQUALS(true, library.isFloatArgValid(tokenList.front(), 7, -2.7));
ASSERT_EQUALS(false, library.isFloatArgValid(tokenList.front(), 7, -2.6999999));
ASSERT_EQUALS(false, library.isIntArgValid(tokenList.front(), 7, -2));
ASSERT_EQUALS(false, library.isFloatArgValid(tokenList.front(), 7, -2.0));
ASSERT_EQUALS(false, library.isIntArgValid(tokenList.front(), 7, 0));
ASSERT_EQUALS(false, library.isFloatArgValid(tokenList.front(), 7, 0.0));
ASSERT_EQUALS(false, library.isIntArgValid(tokenList.front(), 7, 3));
ASSERT_EQUALS(false, library.isFloatArgValid(tokenList.front(), 7, 3.0));
ASSERT_EQUALS(false, library.isIntArgValid(tokenList.front(), 7, 6));
ASSERT_EQUALS(false, library.isFloatArgValid(tokenList.front(), 7, 6.0));
// 0.0:
ASSERT_EQUALS(false, library.isIntArgValid(tokenList.front(), 8, -1));
ASSERT_EQUALS(false, library.isFloatArgValid(tokenList.front(), 8, -1.0));
ASSERT_EQUALS(false, library.isFloatArgValid(tokenList.front(), 8, -0.00000001));
ASSERT_EQUALS(true, library.isIntArgValid(tokenList.front(), 8, 0));
ASSERT_EQUALS(true, library.isFloatArgValid(tokenList.front(), 8, 0.0));
ASSERT_EQUALS(true, library.isFloatArgValid(tokenList.front(), 8, 0.000000001));
ASSERT_EQUALS(true, library.isIntArgValid(tokenList.front(), 8, 1));
ASSERT_EQUALS(true, library.isFloatArgValid(tokenList.front(), 8, 1.0));
// :2.0
ASSERT_EQUALS(true, library.isIntArgValid(tokenList.front(), 9, -1));
ASSERT_EQUALS(true, library.isFloatArgValid(tokenList.front(), 9, -1.0));
ASSERT_EQUALS(true, library.isIntArgValid(tokenList.front(), 9, 2));
ASSERT_EQUALS(true, library.isFloatArgValid(tokenList.front(), 9, 2.0));
ASSERT_EQUALS(false, library.isFloatArgValid(tokenList.front(), 9, 2.00000001));
ASSERT_EQUALS(false, library.isIntArgValid(tokenList.front(), 9, 200));
ASSERT_EQUALS(false, library.isFloatArgValid(tokenList.front(), 9, 200.0));
// 0.0
ASSERT_EQUALS(true, library.isIntArgValid(tokenList.front(), 10, 0));
ASSERT_EQUALS(true, library.isFloatArgValid(tokenList.front(), 10, 0.0));
// ! 0.0
ASSERT_EQUALS(true, library.isFloatArgValid(tokenList.front(), 11, -0.42));
ASSERT_EQUALS(false, library.isFloatArgValid(tokenList.front(), 11, 0.0));
ASSERT_EQUALS(true, library.isFloatArgValid(tokenList.front(), 11, 0.42));
}
void function_arg_minsize() const {
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <function name=\"foo\">\n"
" <arg nr=\"1\"><minsize type=\"strlen\" arg=\"2\"/></arg>\n"
" <arg nr=\"2\"><minsize type=\"argvalue\" arg=\"3\"/></arg>\n"
" <arg nr=\"3\"/>\n"
" <arg nr=\"4\"><minsize type=\"value\" value=\"500\"/></arg>\n"
" <arg nr=\"5\"><minsize type=\"value\" value=\"4\" baseType=\"int\"/></arg>\n"
" </function>\n"
"</def>";
Library library;
ASSERT(LibraryHelper::loadxmldata(library, xmldata, sizeof(xmldata)));
const char code[] = "foo(a,b,c,d,e);";
SimpleTokenList tokenList(code);
tokenList.front()->next()->astOperand1(tokenList.front());
// arg1: type=strlen arg2
const std::vector<Library::ArgumentChecks::MinSize> *minsizes = library.argminsizes(tokenList.front(),1);
ASSERT_EQUALS(true, minsizes != nullptr);
ASSERT_EQUALS(1U, minsizes ? minsizes->size() : 1U);
if (minsizes && minsizes->size() == 1U) {
const Library::ArgumentChecks::MinSize &m = minsizes->front();
ASSERT_EQUALS(true, Library::ArgumentChecks::MinSize::Type::STRLEN == m.type);
ASSERT_EQUALS(2, m.arg);
}
// arg2: type=argvalue arg3
minsizes = library.argminsizes(tokenList.front(), 2);
ASSERT_EQUALS(true, minsizes != nullptr);
ASSERT_EQUALS(1U, minsizes ? minsizes->size() : 1U);
if (minsizes && minsizes->size() == 1U) {
const Library::ArgumentChecks::MinSize &m = minsizes->front();
ASSERT_EQUALS(true, Library::ArgumentChecks::MinSize::Type::ARGVALUE == m.type);
ASSERT_EQUALS(3, m.arg);
}
// arg4: type=value
minsizes = library.argminsizes(tokenList.front(), 4);
ASSERT_EQUALS(true, minsizes != nullptr);
ASSERT_EQUALS(1U, minsizes ? minsizes->size() : 1U);
if (minsizes && minsizes->size() == 1U) {
const Library::ArgumentChecks::MinSize &m = minsizes->front();
ASSERT(Library::ArgumentChecks::MinSize::Type::VALUE == m.type);
ASSERT_EQUALS(500, m.value);
ASSERT_EQUALS("", m.baseType);
}
// arg5: type=value
minsizes = library.argminsizes(tokenList.front(), 5);
ASSERT_EQUALS(true, minsizes != nullptr);
ASSERT_EQUALS(1U, minsizes ? minsizes->size() : 1U);
if (minsizes && minsizes->size() == 1U) {
const Library::ArgumentChecks::MinSize& m = minsizes->front();
ASSERT(Library::ArgumentChecks::MinSize::Type::VALUE == m.type);
ASSERT_EQUALS(4, m.value);
ASSERT_EQUALS("int", m.baseType);
}
}
void function_namespace() const {
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <function name=\"Foo::foo,bar\">\n"
" <noreturn>false</noreturn>\n"
" </function>\n"
"</def>";
Library library;
ASSERT(LibraryHelper::loadxmldata(library, xmldata, sizeof(xmldata)));
ASSERT_EQUALS(library.functions().size(), 2U);
ASSERT(library.functions().at("Foo::foo").argumentChecks.empty());
ASSERT(library.functions().at("bar").argumentChecks.empty());
{
const char code[] = "Foo::foo();";
const SimpleTokenList tokenList(code);
ASSERT(library.isnotnoreturn(tokenList.front()->tokAt(2)));
}
{
const char code[] = "bar();";
const SimpleTokenList tokenList(code);
ASSERT(library.isnotnoreturn(tokenList.front()));
}
}
void function_method() {
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <function name=\"CString::Format\">\n"
" <noreturn>false</noreturn>\n"
" </function>\n"
"</def>";
Library library;
ASSERT(LibraryHelper::loadxmldata(library, xmldata, sizeof(xmldata)));
ASSERT_EQUALS(library.functions().size(), 1U);
{
SimpleTokenizer tokenizer(settings, *this);
const char code[] = "CString str; str.Format();";
ASSERT(tokenizer.tokenize(code));
ASSERT(library.isnotnoreturn(Token::findsimplematch(tokenizer.tokens(), "Format")));
}
{
SimpleTokenizer tokenizer(settings, *this);
const char code[] = "HardDrive hd; hd.Format();";
ASSERT(tokenizer.tokenize(code));
ASSERT(!library.isnotnoreturn(Token::findsimplematch(tokenizer.tokens(), "Format")));
}
}
void function_baseClassMethod() {
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <function name=\"Base::f\">\n"
" <arg nr=\"1\"><not-null/></arg>\n"
" </function>\n"
"</def>";
Library library;
ASSERT(LibraryHelper::loadxmldata(library, xmldata, sizeof(xmldata)));
{
SimpleTokenizer tokenizer(settings, *this);
const char code[] = "struct X : public Base { void dostuff() { f(0); } };";
ASSERT(tokenizer.tokenize(code));
ASSERT(library.isnullargbad(Token::findsimplematch(tokenizer.tokens(), "f"),1));
}
{
SimpleTokenizer tokenizer(settings, *this);
const char code[] = "struct X : public Base { void dostuff() { f(1,2); } };";
ASSERT(tokenizer.tokenize(code));
ASSERT(!library.isnullargbad(Token::findsimplematch(tokenizer.tokens(), "f"),1));
}
}
void function_warn() const {
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <function name=\"a\">\n"
" <warn severity=\"style\" cstd=\"c99\">Message</warn>\n"
" </function>\n"
" <function name=\"b\">\n"
" <warn severity=\"performance\" cppstd=\"c++11\" reason=\"Obsolescent\" alternatives=\"c,d,e\"/>\n"
" </function>\n"
"</def>";
Library library;
ASSERT(LibraryHelper::loadxmldata(library, xmldata, sizeof(xmldata)));
const char code[] = "a(); b();";
const SimpleTokenList tokenList(code);
const Library::WarnInfo* a = library.getWarnInfo(tokenList.front());
const Library::WarnInfo* b = library.getWarnInfo(tokenList.front()->tokAt(4));
ASSERT_EQUALS(2, library.functionwarn().size());
ASSERT(a && b);
if (a && b) {
ASSERT_EQUALS("Message", a->message);
ASSERT_EQUALS_ENUM(Severity::style, a->severity);
ASSERT_EQUALS(Standards::C99, a->standards.c);
ASSERT_EQUALS(Standards::CPP03, a->standards.cpp);
ASSERT_EQUALS("Obsolescent function 'b' called. It is recommended to use 'c', 'd' or 'e' instead.", b->message);
ASSERT_EQUALS_ENUM(Severity::performance, b->severity);
ASSERT_EQUALS(Standards::C89, b->standards.c);
ASSERT_EQUALS(Standards::CPP11, b->standards.cpp);
}
}
void memory() const {
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <memory>\n"
" <alloc>CreateX</alloc>\n"
" <dealloc>DeleteX</dealloc>\n"
" </memory>\n"
"</def>";
Library library;
ASSERT(LibraryHelper::loadxmldata(library, xmldata, sizeof(xmldata)));
ASSERT(library.functions().empty());
const Library::AllocFunc* af = library.getAllocFuncInfo("CreateX");
ASSERT(af && af->arg == -1);
ASSERT(Library::ismemory(af));
ASSERT_EQUALS(library.allocId("CreateX"), library.deallocId("DeleteX"));
const Library::AllocFunc* df = library.getDeallocFuncInfo("DeleteX");
ASSERT(df && df->arg == 1);
}
void memory2() const {
constexpr char xmldata1[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <memory>\n"
" <alloc>malloc</alloc>\n"
" <dealloc>free</dealloc>\n"
" </memory>\n"
"</def>";
constexpr char xmldata2[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <memory>\n"
" <alloc>foo</alloc>\n"
" <dealloc>free</dealloc>\n"
" </memory>\n"
"</def>";
Library library;
ASSERT_EQUALS(true, LibraryHelper::loadxmldata(library, xmldata1, sizeof(xmldata1)));
ASSERT_EQUALS(true, LibraryHelper::loadxmldata(library, xmldata2, sizeof(xmldata2)));
ASSERT_EQUALS(library.deallocId("free"), library.allocId("malloc"));
ASSERT_EQUALS(library.deallocId("free"), library.allocId("foo"));
}
void memory3() const {
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <memory>\n"
" <alloc arg=\"5\" init=\"false\">CreateX</alloc>\n"
" <dealloc arg=\"2\">DeleteX</dealloc>\n"
" </memory>\n"
"</def>";
Library library;
ASSERT(LibraryHelper::loadxmldata(library, xmldata, sizeof(xmldata)));
ASSERT(library.functions().empty());
const Library::AllocFunc* af = library.getAllocFuncInfo("CreateX");
ASSERT(af && af->arg == 5 && !af->initData);
const Library::AllocFunc* df = library.getDeallocFuncInfo("DeleteX");
ASSERT(df && df->arg == 2);
}
void resource() const {
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <resource>\n"
" <alloc>CreateX</alloc>\n"
" <dealloc>DeleteX</dealloc>\n"
" </resource>\n"
"</def>";
Library library;
ASSERT(LibraryHelper::loadxmldata(library, xmldata, sizeof(xmldata)));
ASSERT(library.functions().empty());
ASSERT(Library::isresource(library.allocId("CreateX")));
ASSERT_EQUALS(library.allocId("CreateX"), library.deallocId("DeleteX"));
}
void podtype() const {
{
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <podtype name=\"s8\" sign=\"s\" size=\"1\"/>\n"
" <podtype name=\"u8\" sign=\"u\" size=\"1\"/>\n"
" <podtype name=\"u16\" sign=\"u\" size=\"2\"/>\n"
" <podtype name=\"s16\" sign=\"s\" size=\"2\"/>\n"
"</def>";
Library library;
ASSERT(LibraryHelper::loadxmldata(library, xmldata, sizeof(xmldata)));
// s8
{
const Library::PodType * const type = library.podtype("s8");
ASSERT_EQUALS(true, type != nullptr);
if (type) {
ASSERT_EQUALS(1U, type->size);
ASSERT_EQUALS('s', type->sign);
}
}
// u8
{
const Library::PodType * const type = library.podtype("u8");
ASSERT_EQUALS(true, type != nullptr);
if (type) {
ASSERT_EQUALS(1U, type->size);
ASSERT_EQUALS('u', type->sign);
}
}
// u16
{
const Library::PodType * const type = library.podtype("u16");
ASSERT_EQUALS(true, type != nullptr);
if (type) {
ASSERT_EQUALS(2U, type->size);
ASSERT_EQUALS('u', type->sign);
}
}
// s16
{
const Library::PodType * const type = library.podtype("s16");
ASSERT_EQUALS(true, type != nullptr);
if (type) {
ASSERT_EQUALS(2U, type->size);
ASSERT_EQUALS('s', type->sign);
}
}
// robustness test: provide cfg without PodType
{
const Library::PodType * const type = library.podtype("nonExistingPodType");
ASSERT_EQUALS(true, type == nullptr);
}
}
}
void container() {
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <container id=\"A\" startPattern=\"std :: A <\" endPattern=\"> !!::\" itEndPattern=\"> :: iterator\">\n"
" <type templateParameter=\"1\"/>\n"
" <size templateParameter=\"4\">\n"
" <function name=\"resize\" action=\"resize\"/>\n"
" <function name=\"clear\" action=\"clear\"/>\n"
" <function name=\"size\" yields=\"size\"/>\n"
" <function name=\"empty\" yields=\"empty\"/>\n"
" <function name=\"push_back\" action=\"push\"/>\n"
" <function name=\"pop_back\" action=\"pop\"/>\n"
" </size>\n"
" <access>\n"
" <function name=\"at\" yields=\"at_index\"/>\n"
" <function name=\"begin\" yields=\"start-iterator\"/>\n"
" <function name=\"end\" yields=\"end-iterator\"/>\n"
" <function name=\"data\" yields=\"buffer\"/>\n"
" <function name=\"c_str\" yields=\"buffer-nt\"/>\n"
" <function name=\"front\" yields=\"item\"/>\n"
" <function name=\"find\" action=\"find\"/>\n"
" <function name=\"cfind\" action=\"find-const\"/>\n"
" </access>\n"
" </container>\n"
" <container id=\"B\" startPattern=\"std :: B <\" inherits=\"A\" opLessAllowed=\"false\">\n"
" <size templateParameter=\"3\"/>\n" // Inherits all but templateParameter
" </container>\n"
" <container id=\"C\">\n"
" <type string=\"std-like\"/>\n"
" <access indexOperator=\"array-like\"/>\n"
" </container>\n"
" <container id=\"E\" startPattern=\"std :: E\"/>\n"
" <container id=\"F\" startPattern=\"std :: F\" itEndPattern=\":: iterator\"/>\n"
"</def>";
Library library;
ASSERT(LibraryHelper::loadxmldata(library, xmldata, sizeof(xmldata)));
const Library::Container& A = library.containers().at("A");
const Library::Container& B = library.containers().at("B");
const Library::Container& C = library.containers().at("C");
const Library::Container& E = library.containers().at("E");
const Library::Container& F = library.containers().at("F");
ASSERT_EQUALS(A.type_templateArgNo, 1);
ASSERT_EQUALS(A.size_templateArgNo, 4);
ASSERT_EQUALS(A.startPattern, "std :: A <");
ASSERT_EQUALS(A.endPattern, "> !!::");
ASSERT_EQUALS(A.itEndPattern, "> :: iterator");
ASSERT_EQUALS(A.stdStringLike, false);
ASSERT_EQUALS(A.arrayLike_indexOp, false);
ASSERT_EQUALS(A.opLessAllowed, true);
ASSERT_EQ(Library::Container::Yield::SIZE, A.getYield("size"));
ASSERT_EQ(Library::Container::Yield::EMPTY, A.getYield("empty"));
ASSERT_EQ(Library::Container::Yield::AT_INDEX, A.getYield("at"));
ASSERT_EQ(Library::Container::Yield::START_ITERATOR, A.getYield("begin"));
ASSERT_EQ(Library::Container::Yield::END_ITERATOR, A.getYield("end"));
ASSERT_EQ(Library::Container::Yield::BUFFER, A.getYield("data"));
ASSERT_EQ(Library::Container::Yield::BUFFER_NT, A.getYield("c_str"));
ASSERT_EQ(Library::Container::Yield::ITEM, A.getYield("front"));
ASSERT_EQ(Library::Container::Yield::NO_YIELD, A.getYield("foo"));
ASSERT_EQ(Library::Container::Action::RESIZE, A.getAction("resize"));
ASSERT_EQ(Library::Container::Action::CLEAR, A.getAction("clear"));
ASSERT_EQ(Library::Container::Action::PUSH, A.getAction("push_back"));
ASSERT_EQ(Library::Container::Action::POP, A.getAction("pop_back"));
ASSERT_EQ(Library::Container::Action::FIND, A.getAction("find"));
ASSERT_EQ(Library::Container::Action::FIND_CONST, A.getAction("cfind"));
ASSERT_EQ(Library::Container::Action::NO_ACTION, A.getAction("foo"));
ASSERT_EQUALS(B.type_templateArgNo, 1);
ASSERT_EQUALS(B.size_templateArgNo, 3);
ASSERT_EQUALS(B.startPattern, "std :: B <");
ASSERT_EQUALS(B.endPattern, "> !!::");
ASSERT_EQUALS(B.itEndPattern, "> :: iterator");
ASSERT_EQUALS(B.functions.size(), A.functions.size());
ASSERT_EQUALS(B.opLessAllowed, false);
ASSERT(C.functions.empty());
ASSERT_EQUALS(C.type_templateArgNo, -1);
ASSERT_EQUALS(C.size_templateArgNo, -1);
ASSERT_EQUALS(C.stdStringLike, true);
ASSERT_EQUALS(C.arrayLike_indexOp, true);
ASSERT_EQUALS(E.startPattern, "std :: E");
ASSERT_EQUALS(E.endPattern, "");
ASSERT_EQUALS(E.itEndPattern, "");
ASSERT_EQUALS(F.startPattern, "std :: F");
ASSERT_EQUALS(F.endPattern, "");
ASSERT_EQUALS(F.itEndPattern, ":: iterator");
{
const SimpleTokenizer var(*this, "std::A<int> a;");
ASSERT_EQUALS(&A, library.detectContainer(var.tokens()));
ASSERT(!library.detectIterator(var.tokens()));
bool isIterator;
ASSERT_EQUALS(&A, library.detectContainerOrIterator(var.tokens(), &isIterator));
ASSERT(!isIterator);
}
{
const SimpleTokenizer var(*this, "std::A<int>::size_type a_s;");
ASSERT(!library.detectContainer(var.tokens()));
ASSERT(!library.detectIterator(var.tokens()));
ASSERT(!library.detectContainerOrIterator(var.tokens()));
}
{
const SimpleTokenizer var(*this, "std::A<int>::iterator a_it;");
ASSERT(!library.detectContainer(var.tokens()));
ASSERT_EQUALS(&A, library.detectIterator(var.tokens()));
bool isIterator;
ASSERT_EQUALS(&A, library.detectContainerOrIterator(var.tokens(), &isIterator));
ASSERT(isIterator);
}
{
const SimpleTokenizer var(*this, "std::B<int> b;");
ASSERT_EQUALS(&B, library.detectContainer(var.tokens()));
ASSERT(!library.detectIterator(var.tokens()));
bool isIterator;
ASSERT_EQUALS(&B, library.detectContainerOrIterator(var.tokens(), &isIterator));
ASSERT(!isIterator);
}
{
const SimpleTokenizer var(*this, "std::B<int>::size_type b_s;");
ASSERT(!library.detectContainer(var.tokens()));
ASSERT(!library.detectIterator(var.tokens()));
ASSERT(!library.detectContainerOrIterator(var.tokens()));
}
{
const SimpleTokenizer var(*this, "std::B<int>::iterator b_it;");
ASSERT(!library.detectContainer(var.tokens()));
ASSERT_EQUALS(&B, library.detectIterator(var.tokens()));
bool isIterator;
ASSERT_EQUALS(&B, library.detectContainerOrIterator(var.tokens(), &isIterator));
ASSERT(isIterator);
}
{
const SimpleTokenizer var(*this, "C c;");
ASSERT(!library.detectContainer(var.tokens()));
ASSERT(!library.detectIterator(var.tokens()));
ASSERT(!library.detectContainerOrIterator(var.tokens()));
}
{
const SimpleTokenizer var(*this, "D d;");
ASSERT(!library.detectContainer(var.tokens()));
ASSERT(!library.detectIterator(var.tokens()));
ASSERT(!library.detectContainerOrIterator(var.tokens()));
}
{
const SimpleTokenizer var(*this, "std::E e;");
ASSERT(library.detectContainer(var.tokens()));
ASSERT(!library.detectIterator(var.tokens()));
bool isIterator;
ASSERT_EQUALS(&E, library.detectContainerOrIterator(var.tokens(), &isIterator));
ASSERT(!isIterator);
ASSERT(!library.detectContainerOrIterator(var.tokens(), nullptr, true));
}
{
const SimpleTokenizer var(*this, "E e;");
ASSERT(!library.detectContainer(var.tokens()));
ASSERT(!library.detectIterator(var.tokens()));
ASSERT(!library.detectContainerOrIterator(var.tokens()));
ASSERT_EQUALS(&E, library.detectContainerOrIterator(var.tokens(), nullptr, true));
}
{
const SimpleTokenizer var(*this, "std::E::iterator I;");
ASSERT(!library.detectContainer(var.tokens()));
ASSERT(!library.detectIterator(var.tokens()));
ASSERT(!library.detectContainerOrIterator(var.tokens()));
ASSERT(!library.detectContainerOrIterator(var.tokens(), nullptr, true));
}
{
const SimpleTokenizer var(*this, "std::E::size_type p;");
ASSERT(!library.detectContainer(var.tokens()));
ASSERT(!library.detectIterator(var.tokens()));
ASSERT(!library.detectContainerOrIterator(var.tokens()));
ASSERT(!library.detectContainerOrIterator(var.tokens(), nullptr, true));
}
{
const SimpleTokenizer var(*this, "std::F f;");
ASSERT(library.detectContainer(var.tokens()));
ASSERT(!library.detectIterator(var.tokens()));
bool isIterator;
ASSERT_EQUALS(&F, library.detectContainerOrIterator(var.tokens(), &isIterator));
ASSERT(!isIterator);
}
{
const SimpleTokenizer var(*this, "std::F::iterator I;");
ASSERT(!library.detectContainer(var.tokens()));
TODO_ASSERT(library.detectIterator(var.tokens()));
bool isIterator = false;
TODO_ASSERT_EQUALS((intptr_t)&F, 0, (intptr_t)library.detectContainerOrIterator(var.tokens(), &isIterator));
TODO_ASSERT(isIterator);
}
{
const SimpleTokenizer var(*this, "F::iterator I;");
ASSERT(!library.detectContainer(var.tokens()));
ASSERT(!library.detectIterator(var.tokens()));
ASSERT(!library.detectContainerOrIterator(var.tokens()));
bool isIterator = false;
TODO_ASSERT_EQUALS((intptr_t)&F, 0, (intptr_t)library.detectContainerOrIterator(var.tokens(), &isIterator, true));
TODO_ASSERT(isIterator);
}
}
#define LOADLIBERROR(xmldata, errorcode) loadLibError(xmldata, errorcode, __FILE__, __LINE__)
void version() const {
{
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
"</def>";
Library library;
ASSERT(LibraryHelper::loadxmldata(library, xmldata, sizeof(xmldata)));
}
{
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def format=\"1\">\n"
"</def>";
Library library;
ASSERT(LibraryHelper::loadxmldata(library, xmldata, sizeof(xmldata)));
}
{
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def format=\"42\">\n"
"</def>";
LOADLIBERROR(xmldata, Library::ErrorCode::UNSUPPORTED_FORMAT);
}
}
template<std::size_t size>
void loadLibError(const char (&xmldata)[size], Library::ErrorCode errorcode, const char* file, unsigned line) const {
Library library;
Library::Error liberr;
assertEquals(file, line, true, LibraryHelper::loadxmldata(library, liberr, xmldata, size-1));
assertEquals(file, line, true, errorcode == liberr.errorcode);
}
#define LOADLIB_ERROR_INVALID_RANGE(valid) LOADLIBERROR("<?xml version=\"1.0\"?>\n" \
"<def>\n" \
"<function name=\"f\">\n" \
"<arg nr=\"1\">\n" \
"<valid>" valid "</valid>\n" \
"</arg>\n" \
"</function>\n" \
"</def>", \
Library::ErrorCode::BAD_ATTRIBUTE_VALUE)
void loadLibErrors() const {
LOADLIBERROR("<?xml version=\"1.0\"?>",
Library::ErrorCode::BAD_XML);
LOADLIBERROR("<?xml version=\"1.0\"?>\n"
"<def>\n"
" <X name=\"uint8_t,std::uint8_t\" size=\"1\"/>\n"
"</def>",
Library::ErrorCode::UNKNOWN_ELEMENT);
// #define without attributes
LOADLIBERROR("<?xml version=\"1.0\"?>\n"
"<def>\n"
" <define />\n" // no attributes provided at all
"</def>",
Library::ErrorCode::MISSING_ATTRIBUTE);
// #define with name but without value
LOADLIBERROR("<?xml version=\"1.0\"?>\n"
"<def>\n"
" <define name=\"foo\" />\n" // no value provided
"</def>",
Library::ErrorCode::MISSING_ATTRIBUTE);
LOADLIBERROR("<?xml version=\"1.0\"?>\n"
"<def>\n"
" <define value=\"1\" />\n" // no name provided
"</def>",
Library::ErrorCode::MISSING_ATTRIBUTE);
LOADLIBERROR("<?xml version=\"1.0\"?>\n"
"<X>\n"
"</X>",
Library::ErrorCode::UNSUPPORTED_FORMAT);
// empty range
LOADLIB_ERROR_INVALID_RANGE("");
// letter as range
LOADLIB_ERROR_INVALID_RANGE("a");
// letter and number as range
LOADLIB_ERROR_INVALID_RANGE("1a");
// digit followed by dash
LOADLIB_ERROR_INVALID_RANGE("0:2-1");
// single dash
LOADLIB_ERROR_INVALID_RANGE("-");
// range with multiple colons
LOADLIB_ERROR_INVALID_RANGE("1:2:3");
// extra dot
LOADLIB_ERROR_INVALID_RANGE("1.0.0:10");
// consecutive dots
LOADLIB_ERROR_INVALID_RANGE("1..0:10");
// dot followed by dash
LOADLIB_ERROR_INVALID_RANGE("1.-0:10");
// dot without preceding number
LOADLIB_ERROR_INVALID_RANGE(".5:10");
// dash followed by dot
LOADLIB_ERROR_INVALID_RANGE("-.5:10");
// colon followed by dot without preceding number
LOADLIB_ERROR_INVALID_RANGE("0:.5");
// colon followed by dash followed by dot
LOADLIB_ERROR_INVALID_RANGE("-10:-.5");
// dot not followed by number
LOADLIB_ERROR_INVALID_RANGE("1:5.");
// dot not followed by number
LOADLIB_ERROR_INVALID_RANGE("1.:5");
// dot followed by comma
LOADLIB_ERROR_INVALID_RANGE("1:5.,6:10");
// comma followed by dot
LOADLIB_ERROR_INVALID_RANGE("-10:0,.5:");
}
void loadLibCombinations() const {
{
const Settings s = settingsBuilder().library("std.cfg").library("gnu.cfg").library("bsd.cfg").build();
ASSERT_EQUALS(s.library.defines().empty(), false);
}
{
const Settings s = settingsBuilder().library("std.cfg").library("microsoft_sal.cfg").build();
ASSERT_EQUALS(s.library.defines().empty(), false);
}
{
const Settings s = settingsBuilder().library("std.cfg").library("windows.cfg").library("mfc.cfg").build();
ASSERT_EQUALS(s.library.defines().empty(), false);
}
}
};
REGISTER_TEST(TestLibrary)
| null |
1,026 | cpp | cppcheck | testtokenize.cpp | test/testtokenize.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#include "config.h"
#include "errortypes.h"
#include "fixture.h"
#include "helpers.h"
#include "platform.h"
#include "preprocessor.h" // usually tests here should not use preprocessor...
#include "settings.h"
#include "standards.h"
#include "token.h"
#include "tokenize.h"
#include "tokenlist.h"
#include <cstdint>
#include <cstring>
#include <list>
#include <set>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
#include <simplecpp.h>
class TestTokenizer : public TestFixture {
public:
TestTokenizer() : TestFixture("TestTokenizer") {}
private:
const Settings settings0 = settingsBuilder().library("qt.cfg").build();
const Settings settings1 = settingsBuilder().library("qt.cfg").library("std.cfg").build();
const Settings settings_windows = settingsBuilder().library("windows.cfg").build();
void run() override {
TEST_CASE(tokenize1);
TEST_CASE(tokenize2);
TEST_CASE(tokenize4);
TEST_CASE(tokenize5);
TEST_CASE(tokenize7);
TEST_CASE(tokenize8);
TEST_CASE(tokenize9);
TEST_CASE(tokenize11);
TEST_CASE(tokenize13); // bailout if the code contains "@" - that is not handled well.
TEST_CASE(tokenize14); // tokenize "0X10" => 16
TEST_CASE(tokenizeHexWithSuffix); // tokenize 0xFFFFFFul
TEST_CASE(tokenize15); // tokenize ".123"
TEST_CASE(tokenize17); // #2759
TEST_CASE(tokenize18); // tokenize "(X&&Y)" into "( X && Y )" instead of "( X & & Y )"
TEST_CASE(tokenize19); // #3006 (segmentation fault)
TEST_CASE(tokenize21); // tokenize 0x0E-7
TEST_CASE(tokenize22); // special marker $ from preprocessor
TEST_CASE(tokenize25); // #4239 (segmentation fault)
TEST_CASE(tokenize26); // #4245 (segmentation fault)
TEST_CASE(tokenize27); // #4525 (segmentation fault)
TEST_CASE(tokenize31); // #3503 (Wrong handling of member function taking function pointer as argument)
TEST_CASE(tokenize32); // #5884 (fsanitize=undefined: left shift of negative value -10000 in lib/templatesimplifier.cpp:852:46)
TEST_CASE(tokenize33); // #5780 Various crashes on valid template code
TEST_CASE(tokenize34); // #8031
TEST_CASE(tokenize35); // #8361
TEST_CASE(tokenize36); // #8436
TEST_CASE(tokenize37); // #8550
TEST_CASE(tokenize38); // #9569
TEST_CASE(tokenize39); // #9771
TEST_CASE(validate);
TEST_CASE(objectiveC); // Syntax error should be written for objective C/C++ code.
TEST_CASE(syntax_case_default);
TEST_CASE(removePragma);
TEST_CASE(foreach); // #3690
TEST_CASE(ifconstexpr);
TEST_CASE(combineOperators);
TEST_CASE(concatenateNegativeNumber);
TEST_CASE(longtok);
TEST_CASE(simplifyHeadersAndUnusedTemplates1);
TEST_CASE(simplifyHeadersAndUnusedTemplates2);
TEST_CASE(simplifyAt);
TEST_CASE(inlineasm);
TEST_CASE(simplifyAsm2); // #4725 (writing asm() around "^{}")
TEST_CASE(ifAddBraces1);
TEST_CASE(ifAddBraces2);
TEST_CASE(ifAddBraces3);
TEST_CASE(ifAddBraces4);
TEST_CASE(ifAddBraces5);
TEST_CASE(ifAddBraces7);
TEST_CASE(ifAddBraces9);
TEST_CASE(ifAddBraces11);
TEST_CASE(ifAddBraces12);
TEST_CASE(ifAddBraces13);
TEST_CASE(ifAddBraces15); // #2616 - unknown macro before if
TEST_CASE(ifAddBraces16);
TEST_CASE(ifAddBraces17); // '} else' should be in the same line
TEST_CASE(ifAddBraces18); // #3424 - if if { } else else
TEST_CASE(ifAddBraces19); // #3928 - if for if else
TEST_CASE(ifAddBraces20); // #5012 - syntax error 'else }'
TEST_CASE(ifAddBracesLabels); // #5332 - if (x) label: {} ..
TEST_CASE(switchAddBracesLabels);
TEST_CASE(whileAddBraces);
TEST_CASE(whileAddBracesLabels);
TEST_CASE(doWhileAddBraces);
TEST_CASE(doWhileAddBracesLabels);
TEST_CASE(forAddBraces1);
TEST_CASE(forAddBraces2); // #5088
TEST_CASE(forAddBracesLabels);
TEST_CASE(simplifyExternC);
TEST_CASE(simplifyKeyword); // #5842 - remove C99 static keyword between []
TEST_CASE(isOneNumber);
TEST_CASE(simplifyFunctionParameters);
TEST_CASE(simplifyFunctionParameters1); // #3721
TEST_CASE(simplifyFunctionParameters2); // #4430
TEST_CASE(simplifyFunctionParameters3); // #4436
TEST_CASE(simplifyFunctionParameters4); // #9421
TEST_CASE(simplifyFunctionParametersMultiTemplate);
TEST_CASE(simplifyFunctionParametersErrors);
TEST_CASE(simplifyFunctionTryCatch);
TEST_CASE(removeParentheses1); // Ticket #61
TEST_CASE(removeParentheses3);
TEST_CASE(removeParentheses4); // Ticket #390
TEST_CASE(removeParentheses5); // Ticket #392
TEST_CASE(removeParentheses6);
TEST_CASE(removeParentheses7);
TEST_CASE(removeParentheses8); // Ticket #1865
TEST_CASE(removeParentheses9); // Ticket #1962
TEST_CASE(removeParentheses10); // Ticket #2320
TEST_CASE(removeParentheses11); // Ticket #2505
TEST_CASE(removeParentheses12); // Ticket #2760 ',(b)='
TEST_CASE(removeParentheses13);
TEST_CASE(removeParentheses14); // Ticket #3309
TEST_CASE(removeParentheses15); // Ticket #4142
TEST_CASE(removeParentheses16); // Ticket #4423 '*(x.y)='
TEST_CASE(removeParentheses17); // Don't remove parentheses in 'a ? b : (c>0 ? d : e);'
TEST_CASE(removeParentheses18); // 'float(*a)[2]' => 'float *a[2]'
TEST_CASE(removeParentheses19); // ((typeof(x) *)0)
TEST_CASE(removeParentheses20); // Ticket #5479: a<b<int>>(2);
TEST_CASE(removeParentheses21); // Don't "simplify" casts
TEST_CASE(removeParentheses22);
TEST_CASE(removeParentheses23); // Ticket #6103 - Infinite loop upon valid input
TEST_CASE(removeParentheses24); // Ticket #7040
TEST_CASE(removeParentheses25); // daca@home - a=(b,c)
TEST_CASE(removeParentheses26); // Ticket #8875 a[0](0)
TEST_CASE(removeParentheses27);
TEST_CASE(removeParentheses28); // #12164 - don't remove parentheses in '(expr1) ? (expr2) : (expr3);'
TEST_CASE(tokenize_double);
TEST_CASE(tokenize_strings);
TEST_CASE(simplifyStructDecl);
TEST_CASE(vardecl1);
TEST_CASE(vardecl2);
TEST_CASE(vardecl3);
TEST_CASE(vardecl4);
TEST_CASE(vardecl5); // #7048
TEST_CASE(vardec_static);
TEST_CASE(vardecl6);
TEST_CASE(vardecl7);
TEST_CASE(vardecl8);
TEST_CASE(vardecl9);
TEST_CASE(vardecl10);
TEST_CASE(vardecl11);
TEST_CASE(vardecl12);
TEST_CASE(vardecl13);
TEST_CASE(vardecl14);
TEST_CASE(vardecl15);
TEST_CASE(vardecl16);
TEST_CASE(vardecl17);
TEST_CASE(vardecl18);
TEST_CASE(vardecl19);
TEST_CASE(vardecl20); // #3700 - register const int H = 0;
TEST_CASE(vardecl21); // #4042 - a::b const *p = 0;
TEST_CASE(vardecl22); // #4211 - segmentation fault
TEST_CASE(vardecl23); // #4276 - segmentation fault
TEST_CASE(vardecl24); // #4187 - variable declaration within lambda function
TEST_CASE(vardecl25); // #4799 - segmentation fault
TEST_CASE(vardecl26); // #5907 - incorrect handling of extern declarations
TEST_CASE(vardecl27); // #7850 - crash on valid C code
TEST_CASE(vardecl28);
TEST_CASE(vardecl29); // #9282
TEST_CASE(vardecl30);
TEST_CASE(vardecl31); // function pointer init
TEST_CASE(vardecl_stl_1);
TEST_CASE(vardecl_stl_2);
TEST_CASE(vardecl_stl_3);
TEST_CASE(vardecl_template_1);
TEST_CASE(vardecl_template_2);
TEST_CASE(vardecl_union);
TEST_CASE(vardecl_par); // #2743 - set links if variable type contains parentheses
TEST_CASE(vardecl_par2); // #3912 - set correct links
TEST_CASE(vardecl_par3); // #6556 - Fred x1(a), x2(b);
TEST_CASE(vardecl_class_ref);
TEST_CASE(volatile_variables);
// unsigned i; => unsigned int i;
TEST_CASE(implicitIntConst);
TEST_CASE(implicitIntExtern);
TEST_CASE(implicitIntSigned1);
TEST_CASE(implicitIntUnsigned1);
TEST_CASE(implicitIntUnsigned2);
TEST_CASE(implicitIntUnsigned3); // template arguments
TEST_CASE(simplifyStdType); // #4947, #4950, #4951
TEST_CASE(createLinks);
TEST_CASE(createLinks2);
TEST_CASE(simplifyString);
TEST_CASE(simplifyConst);
TEST_CASE(switchCase);
TEST_CASE(simplifyPointerToStandardType);
TEST_CASE(simplifyFunctionPointers1);
TEST_CASE(simplifyFunctionPointers2);
TEST_CASE(simplifyFunctionPointers3);
TEST_CASE(simplifyFunctionPointers4);
TEST_CASE(simplifyFunctionPointers5);
TEST_CASE(simplifyFunctionPointers6);
TEST_CASE(simplifyFunctionPointers7);
TEST_CASE(simplifyFunctionPointers8); // #7410 - throw
TEST_CASE(simplifyFunctionPointers9); // #6113 - function call with function pointer
TEST_CASE(removedeclspec);
TEST_CASE(removeattribute);
TEST_CASE(functionAttributeBefore1);
TEST_CASE(functionAttributeBefore2);
TEST_CASE(functionAttributeBefore3);
TEST_CASE(functionAttributeBefore4);
TEST_CASE(functionAttributeBefore5); // __declspec(dllexport)
TEST_CASE(functionAttributeAfter1);
TEST_CASE(functionAttributeAfter2);
TEST_CASE(functionAttributeListBefore);
TEST_CASE(functionAttributeListAfter);
TEST_CASE(splitTemplateRightAngleBrackets);
TEST_CASE(cpp03template1);
TEST_CASE(cpp0xtemplate1);
TEST_CASE(cpp0xtemplate2);
TEST_CASE(cpp0xtemplate3);
TEST_CASE(cpp0xtemplate4); // Ticket #6181: Mishandled C++11 syntax
TEST_CASE(cpp0xtemplate5); // Ticket #9154 change >> to > >
TEST_CASE(cpp14template); // Ticket #6708
TEST_CASE(arraySize);
TEST_CASE(arraySizeAfterValueFlow);
TEST_CASE(labels);
TEST_CASE(simplifyInitVar);
TEST_CASE(simplifyInitVar2);
TEST_CASE(simplifyInitVar3);
TEST_CASE(bitfields1);
TEST_CASE(bitfields2);
TEST_CASE(bitfields3);
TEST_CASE(bitfields4); // ticket #1956
TEST_CASE(bitfields5); // ticket #1956
TEST_CASE(bitfields6); // ticket #2595
TEST_CASE(bitfields7); // ticket #1987
TEST_CASE(bitfields8);
TEST_CASE(bitfields9); // ticket #2706
TEST_CASE(bitfields10);
TEST_CASE(bitfields12); // ticket #3485 (segmentation fault)
TEST_CASE(bitfields13); // ticket #3502 (segmentation fault)
TEST_CASE(bitfields15); // ticket #7747 (enum Foo {A,B}:4;)
TEST_CASE(bitfields16); // Save bitfield bit count
TEST_CASE(simplifyNamespaceStd);
TEST_CASE(microsoftMemory);
TEST_CASE(microsoftString);
TEST_CASE(borland);
TEST_CASE(simplifySQL);
TEST_CASE(simplifyCAlternativeTokens);
// x = ({ 123; }); => { x = 123; }
TEST_CASE(simplifyCompoundStatements);
TEST_CASE(simplifyOperatorName1);
TEST_CASE(simplifyOperatorName2);
TEST_CASE(simplifyOperatorName3);
TEST_CASE(simplifyOperatorName4);
TEST_CASE(simplifyOperatorName5);
TEST_CASE(simplifyOperatorName6); // ticket #3194
TEST_CASE(simplifyOperatorName7); // ticket #4619
TEST_CASE(simplifyOperatorName8); // ticket #5706
TEST_CASE(simplifyOperatorName9); // ticket #5709 - comma operator not properly tokenized
TEST_CASE(simplifyOperatorName10); // #8746 - using a::operator=
TEST_CASE(simplifyOperatorName11); // #8889
TEST_CASE(simplifyOperatorName12); // #9110
TEST_CASE(simplifyOperatorName13); // user defined literal
TEST_CASE(simplifyOperatorName14); // std::complex operator "" if
TEST_CASE(simplifyOperatorName15); // ticket #9468 syntaxError
TEST_CASE(simplifyOperatorName16); // ticket #9472
TEST_CASE(simplifyOperatorName17);
TEST_CASE(simplifyOperatorName18); // global namespace
TEST_CASE(simplifyOperatorName19);
TEST_CASE(simplifyOperatorName20);
TEST_CASE(simplifyOperatorName21);
TEST_CASE(simplifyOperatorName22);
TEST_CASE(simplifyOperatorName23);
TEST_CASE(simplifyOperatorName24);
TEST_CASE(simplifyOperatorName25);
TEST_CASE(simplifyOperatorName26);
TEST_CASE(simplifyOperatorName27);
TEST_CASE(simplifyOperatorName28);
TEST_CASE(simplifyOperatorName29); // spaceship operator
TEST_CASE(simplifyOperatorName31); // #6342
TEST_CASE(simplifyOperatorName32); // #10256
TEST_CASE(simplifyOperatorName33); // #10138
TEST_CASE(simplifyOverloadedOperators1);
TEST_CASE(simplifyOverloadedOperators2); // (*this)(123)
TEST_CASE(simplifyOverloadedOperators3); // #9881 - hang
TEST_CASE(simplifyNullArray);
// Some simple cleanups of unhandled macros in the global scope
TEST_CASE(removeMacrosInGlobalScope);
TEST_CASE(addSemicolonAfterUnknownMacro);
// a = b = 0;
TEST_CASE(multipleAssignment);
TEST_CASE(platformWin);
TEST_CASE(platformWin32A);
TEST_CASE(platformWin32W);
TEST_CASE(platformWin32AStringCat); // ticket #5015
TEST_CASE(platformWin32WStringCat); // ticket #5015
TEST_CASE(platformWinWithNamespace);
TEST_CASE(simplifyStaticConst);
TEST_CASE(simplifyCPPAttribute);
TEST_CASE(simplifyCaseRange);
TEST_CASE(simplifyEmptyNamespaces);
TEST_CASE(prepareTernaryOpForAST);
// AST data
TEST_CASE(astexpr);
TEST_CASE(astexpr2); // limit large expressions
TEST_CASE(astpar);
TEST_CASE(astnewdelete);
TEST_CASE(astbrackets);
TEST_CASE(astunaryop);
TEST_CASE(astfunction);
TEST_CASE(asttemplate);
TEST_CASE(astrequires);
TEST_CASE(astcast);
TEST_CASE(astlambda);
TEST_CASE(astcase);
TEST_CASE(astrefqualifier);
TEST_CASE(astvardecl);
TEST_CASE(astnewscoped);
TEST_CASE(startOfExecutableScope);
TEST_CASE(removeMacroInClassDef); // #6058
TEST_CASE(sizeofAddParentheses);
TEST_CASE(reportUnknownMacros);
// Make sure the Tokenizer::findGarbageCode() does not have false positives
// The TestGarbage ensures that there are true positives
TEST_CASE(findGarbageCode);
TEST_CASE(checkEnableIf);
TEST_CASE(checkTemplates);
TEST_CASE(checkNamespaces);
TEST_CASE(checkLambdas);
TEST_CASE(checkIfCppCast);
TEST_CASE(checkRefQualifiers);
TEST_CASE(checkConditionBlock);
TEST_CASE(checkUnknownCircularVar);
TEST_CASE(checkRequires);
// #9052
TEST_CASE(noCrash1);
TEST_CASE(noCrash2);
TEST_CASE(noCrash3);
TEST_CASE(noCrash4);
TEST_CASE(noCrash5); // #10603
TEST_CASE(noCrash6); // #10212
TEST_CASE(noCrash7);
// --check-config
TEST_CASE(checkConfiguration);
TEST_CASE(unknownType); // #8952
TEST_CASE(unknownMacroBeforeReturn);
TEST_CASE(cppcast);
TEST_CASE(checkHeader1);
TEST_CASE(removeExtraTemplateKeywords);
TEST_CASE(removeAlignas1);
TEST_CASE(removeAlignas2); // Do not remove alignof in the same way
TEST_CASE(removeAlignas3); // remove alignas in C11 code
TEST_CASE(dumpAlignas);
TEST_CASE(simplifyCoroutines);
TEST_CASE(simplifySpaceshipOperator);
TEST_CASE(simplifyIfSwitchForInit1);
TEST_CASE(simplifyIfSwitchForInit2);
TEST_CASE(simplifyIfSwitchForInit3);
TEST_CASE(simplifyIfSwitchForInit4);
TEST_CASE(simplifyIfSwitchForInit5);
TEST_CASE(cpp20_default_bitfield_initializer);
TEST_CASE(cpp11init);
TEST_CASE(testDirectiveIncludeTypes);
TEST_CASE(testDirectiveIncludeLocations);
TEST_CASE(testDirectiveIncludeComments);
TEST_CASE(testDirectiveRelativePath);
}
#define tokenizeAndStringify(...) tokenizeAndStringify_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
std::string tokenizeAndStringify_(const char* file, int linenr, const char (&code)[size], bool expand = true, Platform::Type platform = Platform::Type::Native,
bool cpp = true, Standards::cppstd_t cppstd = Standards::CPP11, Standards::cstd_t cstd = Standards::C11) {
const Settings settings = settingsBuilder(settings1).debugwarnings().cpp(cppstd).c(cstd).platform(platform).build();
// tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code, cpp), file, linenr);
if (tokenizer.tokens())
return tokenizer.tokens()->stringifyList(false, expand, false, true, false, nullptr, nullptr);
return "";
}
// TODO: get rid of this
std::string tokenizeAndStringify_(const char* file, int linenr, const std::string& code) {
const Settings settings = settingsBuilder(settings1).debugwarnings().cpp(Standards::CPP11).c(Standards::C11).build();
// tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, linenr);
if (tokenizer.tokens())
return tokenizer.tokens()->stringifyList(false, true, false, true, false, nullptr, nullptr);
return "";
}
#define tokenizeAndStringifyWindows(...) tokenizeAndStringifyWindows_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
std::string tokenizeAndStringifyWindows_(const char* file, int linenr, const char (&code)[size], bool expand = true, Platform::Type platform = Platform::Type::Native, bool cpp = true, bool cpp11 = true) {
const Settings settings = settingsBuilder(settings_windows).debugwarnings().cpp(cpp11 ? Standards::CPP11 : Standards::CPP03).platform(platform).build();
// tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code, cpp), file, linenr);
if (tokenizer.tokens())
return tokenizer.tokens()->stringifyList(false, expand, false, true, false, nullptr, nullptr);
return "";
}
template<size_t size>
std::string tokenizeAndStringify_(const char* file, int line, const char (&code)[size], const Settings &settings, bool cpp = true) {
// tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code, cpp), file, line);
if (!tokenizer.tokens())
return "";
return tokenizer.tokens()->stringifyList(false, true, false, true, false, nullptr, nullptr);
}
#define tokenizeDebugListing(...) tokenizeDebugListing_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
std::string tokenizeDebugListing_(const char* file, int line, const char (&code)[size], bool cpp = true) {
const Settings settings = settingsBuilder(settings0).c(Standards::C89).cpp(Standards::CPP03).build();
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code, cpp), file, line);
// result..
return tokenizer.tokens()->stringifyList(true,true,true,true,false);
}
void directiveDump(const char filedata[], std::ostream& ostr) {
directiveDump(filedata, "test.c", settingsDefault, ostr);
}
void directiveDump(const char filedata[], const char filename[], const Settings& settings, std::ostream& ostr) {
Preprocessor preprocessor(settings, *this);
std::istringstream istr(filedata);
simplecpp::OutputList outputList;
std::vector<std::string> files{filename};
const simplecpp::TokenList tokens1(istr, files, filename, &outputList);
std::list<Directive> directives = preprocessor.createDirectives(tokens1);
Tokenizer tokenizer(settings, *this);
tokenizer.setDirectives(std::move(directives));
tokenizer.dump(ostr);
}
void tokenize1() {
const char code[] = "void f ( )\n"
"{ if ( p . y ( ) > yof ) { } }";
ASSERT_EQUALS(code, tokenizeAndStringify(code));
ASSERT_EQUALS(
"[test.cpp:2]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable yof\n",
errout_str());
}
void tokenize2() {
const char code[] = "{ sizeof a, sizeof b }";
ASSERT_EQUALS("{ sizeof ( a ) , sizeof ( b ) }", tokenizeAndStringify(code));
}
void tokenize4() {
const char code[] = "class foo\n"
"{\n"
"public:\n"
" const int i;\n"
"}";
ASSERT_EQUALS("class foo\n"
"{\n"
"public:\n"
"const int i ;\n"
"}", tokenizeAndStringify(code));
ASSERT_EQUALS("", errout_str());
}
void tokenize5() {
// Tokenize values
ASSERT_EQUALS("; + 1E3 ;", tokenizeAndStringify("; +1E3 ;"));
ASSERT_EQUALS("; 1E-2 ;", tokenizeAndStringify("; 1E-2 ;"));
}
void tokenize7() {
const char code[] = "void f() {\n"
" int x1 = 1;\n"
" int x2(x1);\n"
"}\n";
ASSERT_EQUALS("void f ( ) {\nint x1 ; x1 = 1 ;\nint x2 ; x2 = x1 ;\n}",
tokenizeAndStringify(code));
}
void tokenize8() {
const char code[] = "void f() {\n"
" int x1(g());\n"
" int x2(x1);\n"
"}\n";
ASSERT_EQUALS("1: void f ( ) {\n"
"2: int x1@1 ; x1@1 = g ( ) ;\n"
"3: int x2@2 ; x2@2 = x1@1 ;\n"
"4: }\n",
tokenizeDebugListing(code));
}
void tokenize9() {
const char code[] = "typedef void (*fp)();\n"
"typedef fp (*fpp)();\n"
"void f() {\n"
" fpp x = (fpp)f();\n"
"}";
(void)tokenizeAndStringify(code);
ASSERT_EQUALS("", errout_str());
}
void tokenize11() {
ASSERT_EQUALS("X * sizeof ( Y ( ) ) ;", tokenizeAndStringify("X * sizeof(Y());"));
}
// bailout if there is "@" - it is not handled well
void tokenize13() {
const char code[] = "@implementation\n"
"-(Foo *)foo: (Bar *)bar\n"
"{ }\n"
"@end\n";
ASSERT_THROW_INTERNAL(tokenizeAndStringify(code), SYNTAX);
}
// Ticket #2361: 0X10 => 16
void tokenize14() {
ASSERT_EQUALS("; 0x10 ;", tokenizeAndStringify(";0x10;"));
ASSERT_EQUALS("; 0X10 ;", tokenizeAndStringify(";0X10;"));
ASSERT_EQUALS("; 0444 ;", tokenizeAndStringify(";0444;"));
}
// Ticket #8050
void tokenizeHexWithSuffix() {
ASSERT_EQUALS("; 0xFFFFFF ;", tokenizeAndStringify(";0xFFFFFF;"));
ASSERT_EQUALS("; 0xFFFFFFu ;", tokenizeAndStringify(";0xFFFFFFu;"));
ASSERT_EQUALS("; 0xFFFFFFul ;", tokenizeAndStringify(";0xFFFFFFul;"));
// Number of digits decides about internal representation...
ASSERT_EQUALS("; 0xFFFFFFFF ;", tokenizeAndStringify(";0xFFFFFFFF;"));
ASSERT_EQUALS("; 0xFFFFFFFFu ;", tokenizeAndStringify(";0xFFFFFFFFu;"));
ASSERT_EQUALS("; 0xFFFFFFFFul ;", tokenizeAndStringify(";0xFFFFFFFFul;"));
}
// Ticket #2429: 0.125
void tokenize15() {
ASSERT_EQUALS("0.125 ;", tokenizeAndStringify(".125;"));
ASSERT_EQUALS("005.125 ;", tokenizeAndStringify("005.125;")); // Don't confuse with octal values
}
void tokenize17() { // #2759
ASSERT_EQUALS("class B : private :: A { } ;", tokenizeAndStringify("class B : private ::A { };"));
}
void tokenize18() { // tokenize "(X&&Y)" into "( X && Y )" instead of "( X & & Y )"
ASSERT_EQUALS("( X && Y ) ;", tokenizeAndStringify("(X&&Y);"));
}
void tokenize19() {
// #3006 - added hasComplicatedSyntaxErrorsInTemplates to avoid segmentation fault
ASSERT_THROW_INTERNAL(tokenizeAndStringify("x < () <"), SYNTAX);
// #3496 - make sure hasComplicatedSyntaxErrorsInTemplates works
ASSERT_EQUALS("void a ( Fred * f ) { for ( ; n < f . x ( ) ; ) { } }",
tokenizeAndStringify("void a(Fred* f) MACRO { for (;n < f->x();) {} }"));
// #6216 - make sure hasComplicatedSyntaxErrorsInTemplates works
ASSERT_EQUALS("C :: C ( )\n"
": v { }\n"
"{\n"
"for ( int dim = 0 ; dim < v . size ( ) ; ++ dim ) {\n"
"v [ dim ] . f ( ) ;\n"
"}\n"
"} ;",
tokenizeAndStringify("C::C()\n"
":v{}\n"
"{\n"
" for (int dim = 0; dim < v.size(); ++dim) {\n"
" v[dim]->f();\n"
" }\n"
"};"));
ignore_errout(); // we do not care about the output
}
void tokenize21() { // tokenize 0x0E-7
ASSERT_EQUALS("0x0E - 7 ;", tokenizeAndStringify("0x0E-7;"));
}
void tokenize22() { // tokenize special marker $ from preprocessor
ASSERT_EQUALS("a$b", tokenizeAndStringify("a$b"));
ASSERT_EQUALS("a $b\nc", tokenizeAndStringify("a $b\nc"));
ASSERT_EQUALS("a = $0 ;", tokenizeAndStringify("a = $0;"));
ASSERT_EQUALS("a$ ++ ;", tokenizeAndStringify("a$++;"));
ASSERT_EQUALS("$if ( ! p )", tokenizeAndStringify("$if(!p)"));
}
// #4239 - segfault for "f ( struct { int typedef T x ; } ) { }"
void tokenize25() {
ASSERT_THROW_INTERNAL(tokenizeAndStringify("f ( struct { int typedef T x ; } ) { }"), SYNTAX);
}
// #4245 - segfault
void tokenize26() {
ASSERT_THROW_INTERNAL(tokenizeAndStringify("class x { protected : template < int y = } ;"), SYNTAX); // Garbage code
}
void tokenize27() {
// #4525 - segfault
(void)tokenizeAndStringify("struct except_spec_d_good : except_spec_a, except_spec_b {\n"
"~except_spec_d_good();\n"
"};\n"
"struct S { S(); };\n"
"S::S() __attribute((pure)) = default;"
);
// original code: glibc-2.18/posix/bug-regex20.c
(void)tokenizeAndStringify("static unsigned int re_string_context_at (const re_string_t *input, int idx, int eflags) internal_function __attribute__ ((pure));");
}
// #3503 - don't "simplify" SetFunction member function to a variable
void tokenize31() {
ASSERT_EQUALS("struct TTestClass { TTestClass ( ) { }\n"
"void SetFunction ( Other ( * m_f ) ( ) ) { }\n"
"} ;",
tokenizeAndStringify("struct TTestClass { TTestClass() { }\n"
" void SetFunction(Other(*m_f)()) { }\n"
"};"));
ASSERT_EQUALS("struct TTestClass { TTestClass ( ) { }\n"
"void SetFunction ( Other ( * m_f ) ( ) ) ;\n"
"} ;",
tokenizeAndStringify("struct TTestClass { TTestClass() { }\n"
" void SetFunction(Other(*m_f)());\n"
"};"));
}
// #5884 - Avoid left shift of negative integer value.
void tokenize32() {
// Do not simplify negative integer left shifts.
const char code[] = "void f ( ) { int max_x ; max_x = -10000 << 16 ; }";
ASSERT_EQUALS(code, tokenizeAndStringify(code));
}
// #5780 Various crashes on valid template code in Tokenizer::setVarId()
void tokenize33() {
const char code[] = "template<typename T, typename A = Alloc<T>> struct vector {};\n"
"void z() {\n"
" vector<int> VI;\n"
"}\n";
(void)tokenizeAndStringify(code);
}
void tokenize34() { // #8031
{
const char code[] = "struct Container {\n"
" Container();\n"
" int* mElements;\n"
"};\n"
"Container::Container() : mElements(nullptr) {}\n"
"Container intContainer;";
const char exp[] = "1: struct Container {\n"
"2: Container ( ) ;\n"
"3: int * mElements@1 ;\n"
"4: } ;\n"
"5: Container :: Container ( ) : mElements@1 ( nullptr ) { }\n"
"6: Container intContainer@2 ;\n";
ASSERT_EQUALS(exp, tokenizeDebugListing(code));
}
{
const char code[] = "template<class T> struct Container {\n"
" Container();\n"
" int* mElements;\n"
"};\n"
"template <class T> Container<T>::Container() : mElements(nullptr) {}\n"
"Container<int> intContainer;";
const char exp[] = "1: struct Container<int> ;\n"
"2:\n"
"|\n"
"5:\n"
"6: Container<int> intContainer@1 ;\n"
"1: struct Container<int> {\n"
"2: Container<int> ( ) ;\n"
"3: int * mElements@2 ;\n"
"4: } ;\n"
"5: Container<int> :: Container<int> ( ) : mElements@2 ( nullptr ) { }\n";
ASSERT_EQUALS(exp, tokenizeDebugListing(code));
}
}
void tokenize35() { // #8361
ASSERT_NO_THROW(tokenizeAndStringify("typedef int CRCWord; "
"template<typename T> ::CRCWord const Compute(T const t) { return 0; }"));
}
void tokenize36() { // #8436
const char code[] = "int foo ( int i ) { return i ? * new int { 5 } : int { i ? 0 : 1 } ; }";
ASSERT_EQUALS(code, tokenizeAndStringify(code));
}
void tokenize37() { // #8550
const char codeC[] = "class name { public: static void init ( ) {} } ; "
"typedef class name N; "
"void foo ( ) { return N :: init ( ) ; }";
const char expC[] = "class name { public: static void init ( ) { } } ; "
"void foo ( ) { return name :: init ( ) ; }";
ASSERT_EQUALS(expC, tokenizeAndStringify(codeC));
const char codeS[] = "class name { public: static void init ( ) {} } ; "
"typedef struct name N; "
"void foo ( ) { return N :: init ( ) ; }";
const char expS[] = "class name { public: static void init ( ) { } } ; "
"void foo ( ) { return name :: init ( ) ; }";
ASSERT_EQUALS(expS, tokenizeAndStringify(codeS));
}
void tokenize38() { // #9569
const char code[] = "using Binary = std::vector<char>; enum Type { Binary };";
const char exp[] = "enum Type { Binary } ;";
ASSERT_EQUALS(exp, tokenizeAndStringify(code));
}
void tokenize39() { // #9771
const char code[] = "template <typename T> class Foo;"
"template <typename T> bool operator!=(const Foo<T> &, const Foo<T> &);"
"template <typename T> class Foo { friend bool operator!= <> (const Foo<T> &, const Foo<T> &); };";
const char exp[] = "template < typename T > class Foo ; "
"template < typename T > bool operator!= ( const Foo < T > & , const Foo < T > & ) ; "
"template < typename T > class Foo { friend bool operator!= < > ( const Foo < T > & , const Foo < T > & ) ; } ;";
ASSERT_EQUALS(exp, tokenizeAndStringify(code));
}
void validate() {
// C++ code in C file
ASSERT_THROW_INTERNAL(tokenizeAndStringify(";using namespace std;",false,Platform::Type::Native,false), SYNTAX);
ASSERT_THROW_INTERNAL(tokenizeAndStringify(";std::map<int,int> m;",false,Platform::Type::Native,false), SYNTAX);
ASSERT_THROW_INTERNAL(tokenizeAndStringify(";template<class T> class X { };",false,Platform::Type::Native,false), SYNTAX);
ASSERT_THROW_INTERNAL(tokenizeAndStringify("int X<Y>() {};",false,Platform::Type::Native,false), SYNTAX);
{
Tokenizer tokenizer(settings1, *this);
const char code[] = "void foo(int i) { reinterpret_cast<char>(i) };";
std::istringstream istr(code);
ASSERT(tokenizer.list.createTokens(istr, "test.h"));
ASSERT_THROW_INTERNAL(tokenizer.simplifyTokens1(""), SYNTAX);
}
}
void objectiveC() {
ASSERT_THROW_INTERNAL(tokenizeAndStringify("void f() { [foo bar]; }"), SYNTAX);
}
void syntax_case_default() { // correct syntax
ASSERT_NO_THROW(tokenizeAndStringify("void f(int n) {switch (n) { case 0: z(); break;}}"));
ASSERT_EQUALS("", errout_str());
(void)tokenizeAndStringify("void f(int n) {switch (n) { case 0:; break;}}");
ASSERT_EQUALS("", errout_str());
// TODO: Do not throw AST validation exception
TODO_ASSERT_THROW(tokenizeAndStringify("void f(int n) {switch (n) { case 0?1:2 : z(); break;}}"), InternalError);
//ASSERT_EQUALS("", errout_str());
// TODO: Do not throw AST validation exception
TODO_ASSERT_THROW(tokenizeAndStringify("void f(int n) {switch (n) { case 0?(1?3:4):2 : z(); break;}}"), InternalError);
ASSERT_EQUALS("", errout_str());
//allow GCC '({ %name%|%num%|%bool% ; })' statement expression extension
// TODO: Do not throw AST validation exception
TODO_ASSERT_THROW(tokenizeAndStringify("void f(int n) {switch (n) { case 0?({0;}):1: z(); break;}}"), InternalError);
ASSERT_EQUALS("", errout_str());
//'b' can be or a macro or an undefined enum
ASSERT_NO_THROW(tokenizeAndStringify("void f(int n) {switch (n) { case b: z(); break;}}"));
ASSERT_EQUALS("", errout_str());
//valid, when there's this declaration: 'constexpr int g() { return 2; }'
ASSERT_NO_THROW(tokenizeAndStringify("void f(int n) {switch (n) { case g(): z(); break;}}"));
ASSERT_EQUALS("", errout_str());
//valid, when there's also this declaration: 'constexpr int g[1] = {0};'
ASSERT_NO_THROW(tokenizeAndStringify("void f(int n) {switch (n) { case g[0]: z(); break;}}"));
ASSERT_EQUALS(
"[test.cpp:1]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable g\n",
errout_str());
//valid, similar to above case
ASSERT_NO_THROW(tokenizeAndStringify("void f(int n) {switch (n) { case *g: z(); break;}}"));
ASSERT_EQUALS("", errout_str());
//valid, when 'x' and 'y' are constexpr.
ASSERT_NO_THROW(tokenizeAndStringify("void f(int n) {switch (n) { case sqrt(x+y): z(); break;}}"));
ASSERT_EQUALS(
"[test.cpp:1]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable x\n",
errout_str());
}
void removePragma() {
const char code[] = "_Pragma(\"abc\") int x;";
const Settings s_c89 = settingsBuilder().c(Standards::C89).build();
ASSERT_EQUALS("_Pragma ( \"abc\" ) int x ;", tokenizeAndStringify(code, s_c89, false));
const Settings s_clatest;
ASSERT_EQUALS("int x ;", tokenizeAndStringify(code, s_clatest, false));
const Settings s_cpp03 = settingsBuilder().cpp(Standards::CPP03).build();
ASSERT_EQUALS("_Pragma ( \"abc\" ) int x ;", tokenizeAndStringify(code, s_cpp03, true));
const Settings s_cpplatest;
ASSERT_EQUALS("int x ;", tokenizeAndStringify(code, s_cpplatest, true));
}
void foreach () {
// #3690,#5154
const char code[] ="void f() { for each ( char c in MyString ) { Console::Write(c); } }";
ASSERT_EQUALS("void f ( ) { asm ( \"char c in MyString\" ) { Console :: Write ( c ) ; } }", tokenizeAndStringify(code));
ASSERT_EQUALS(
"[test.cpp:1]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable c\n",
errout_str());
}
void ifconstexpr() {
ASSERT_EQUALS("void f ( ) { if ( FOO ) { bar ( c ) ; } }", tokenizeAndStringify("void f() { if constexpr ( FOO ) { bar(c); } }"));
ASSERT_EQUALS(
"[test.cpp:1]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable FOO\n",
filter_valueflow(errout_str()));
}
void combineOperators() {
ASSERT_EQUALS("; private: ;", tokenizeAndStringify(";private:;"));
ASSERT_EQUALS("; protected: ;", tokenizeAndStringify(";protected:;"));
ASSERT_EQUALS("; public: ;", tokenizeAndStringify(";public:;"));
ASSERT_EQUALS("; __published: ;", tokenizeAndStringify(";__published:;"));
ASSERT_EQUALS("a . public : ;", tokenizeAndStringify("a.public:;"));
ASSERT_EQUALS("void f ( x & = 2 ) ;", tokenizeAndStringify("void f(x &= 2);"));
ASSERT_EQUALS("const_cast < a * > ( & e )", tokenizeAndStringify("const_cast<a*>(&e)"));
}
void concatenateNegativeNumber() {
ASSERT_EQUALS("i = -12 ;", tokenizeAndStringify("i = -12;"));
ASSERT_EQUALS("1 - 2 ;", tokenizeAndStringify("1-2;"));
ASSERT_EQUALS("foo ( -1 ) - 2 ;", tokenizeAndStringify("foo(-1)-2;"));
ASSERT_EQUALS("int f ( ) { return -2 ; }", tokenizeAndStringify("int f(){return -2;}"));
ASSERT_EQUALS("int x [ 2 ] = { -2 , 1 }", tokenizeAndStringify("int x[2] = {-2,1}"));
ASSERT_EQUALS("f ( 123 )", tokenizeAndStringify("f(+123)"));
}
void longtok() {
const std::string filedata(10000, 'a');
ASSERT_EQUALS(filedata, tokenizeAndStringify(filedata));
}
void simplifyHeadersAndUnusedTemplates1() {
const Settings s = settingsBuilder().checkUnusedTemplates(false).build();
ASSERT_EQUALS(";",
tokenizeAndStringify("; template <typename... a> uint8_t b(std::tuple<uint8_t> d) {\n"
" std::tuple<a...> c{std::move(d)};\n"
" return std::get<0>(c);\n"
"}", s));
ASSERT_EQUALS("int g ( int ) ;",
tokenizeAndStringify("int g(int);\n"
"template <class F, class... Ts> auto h(F f, Ts... xs) {\n"
" auto e = f(g(xs)...);\n"
" return e;\n"
"}", s));
}
void simplifyHeadersAndUnusedTemplates2() {
const char code[] = "; template< typename T, u_int uBAR = 0 >\n"
"class Foo {\n"
"public:\n"
" void FooBar() {\n"
" new ( (uBAR ? uBAR : sizeof(T))) T;\n"
" }\n"
"};";
{
const Settings s = settingsBuilder().checkUnusedTemplates(false).build();
ASSERT_EQUALS(";", tokenizeAndStringify(code, s));
}
{
ASSERT_EQUALS("; template < typename T , u_int uBAR = 0 >\n"
"class Foo {\n"
"public:\n"
"void FooBar ( ) {\n"
"new ( uBAR ? uBAR : sizeof ( T ) ) T ;\n"
"}\n"
"} ;", tokenizeAndStringify(code, settingsDefault));
}
}
void simplifyAt() {
ASSERT_EQUALS("int x ;", tokenizeAndStringify("int x@123;"));
ASSERT_EQUALS("bool x ;", tokenizeAndStringify("bool x@123:1;"));
ASSERT_EQUALS("char PORTB ; bool PB3 ;", tokenizeAndStringify("char PORTB @ 0x10; bool PB3 @ PORTB:3;\n"));
ASSERT_EQUALS("int x ;", tokenizeAndStringify("int x @ (0x1000 + 18);"));
ASSERT_EQUALS("int x [ 10 ] ;", tokenizeAndStringify("int x[10]@0x100;"));
ASSERT_EQUALS("void ( * f [ ] ) ( void ) ;", tokenizeAndStringify("void (*f[])(void)@0x100;")); // #13458
ASSERT_EQUALS("interrupt@ f ( ) { }", tokenizeAndStringify("@interrupt f() {}"));
ASSERT_EQUALS("const short MyVariable = 0xF0F0 ;", tokenizeAndStringify("const short MyVariable @ \"MYOWNSECTION\" = 0xF0F0; ")); // #12602
}
void inlineasm() {
ASSERT_EQUALS("asm ( \"mov ax , bx\" ) ;", tokenizeAndStringify("asm { mov ax,bx };"));
ASSERT_EQUALS("asm ( \"mov ax , bx\" ) ;", tokenizeAndStringify("_asm { mov ax,bx };"));
ASSERT_EQUALS("asm ( \"mov ax , bx\" ) ;", tokenizeAndStringify("_asm mov ax,bx"));
ASSERT_EQUALS("asm ( \"mov ax , bx\" ) ;", tokenizeAndStringify("__asm { mov ax,bx };"));
ASSERT_EQUALS("asm ( \"\"mov ax,bx\"\" ) ;", tokenizeAndStringify("__asm__ __volatile__ ( \"mov ax,bx\" );"));
ASSERT_EQUALS("asm ( \"_emit 12h\" ) ;", tokenizeAndStringify("__asm _emit 12h ;"));
ASSERT_EQUALS("asm ( \"mov a , b\" ) ;", tokenizeAndStringify("__asm mov a, b ;"));
ASSERT_EQUALS("asm ( \"\"fnstcw %0\" : \"= m\" ( old_cw )\" ) ;", tokenizeAndStringify("asm volatile (\"fnstcw %0\" : \"= m\" (old_cw));"));
ASSERT_EQUALS("asm ( \"\"fnstcw %0\" : \"= m\" ( old_cw )\" ) ;", tokenizeAndStringify(" __asm__ (\"fnstcw %0\" : \"= m\" (old_cw));"));
ASSERT_EQUALS("asm ( \"\"ddd\"\" ) ;", tokenizeAndStringify(" __asm __volatile__ (\"ddd\") ;"));
ASSERT_EQUALS("asm ( \"\"ddd\"\" ) ;", tokenizeAndStringify(" __asm __volatile (\"ddd\") ;"));
ASSERT_EQUALS("asm ( \"\"mov ax,bx\"\" ) ;", tokenizeAndStringify("__asm__ volatile ( \"mov ax,bx\" );"));
ASSERT_EQUALS("asm ( \"mov ax , bx\" ) ; int a ;", tokenizeAndStringify("asm { mov ax,bx } int a;"));
ASSERT_EQUALS("asm\n\n( \"mov ax , bx\" ) ;", tokenizeAndStringify("__asm\nmov ax,bx\n__endasm;"));
ASSERT_EQUALS("asm\n\n( \"push b ; for if\" ) ;", tokenizeAndStringify("__asm\npush b ; for if\n__endasm;"));
// 'asm ( ) ;' should be in the same line
ASSERT_EQUALS(";\n\nasm ( \"\"mov ax,bx\"\" ) ;", tokenizeAndStringify(";\n\n__asm__ volatile ( \"mov ax,bx\" );"));
ASSERT_EQUALS("void func1 ( ) ;", tokenizeAndStringify("void func1() __asm__(\"...\") __attribute__();"));
}
// #4725 - ^{}
void simplifyAsm2() {
ASSERT_THROW_INTERNAL_EQUALS(tokenizeAndStringify("void f() { ^{} }"), SYNTAX, "syntax error");
ASSERT_THROW_INTERNAL_EQUALS(tokenizeAndStringify("void f() { x(^{}); }"), SYNTAX, "syntax error");
ASSERT_THROW_INTERNAL_EQUALS(tokenizeAndStringify("void f() { foo(A(), ^{ bar(); }); }"), SYNTAX, "syntax error");
ASSERT_THROW_INTERNAL_EQUALS(tokenizeAndStringify("int f0(Args args) {\n"
" return ^{\n"
" return sizeof...(Args);\n"
" }() + ^ {\n"
" return sizeof...(args);\n"
" }();\n"
"};"), SYNTAX, "syntax error");
ASSERT_THROW_INTERNAL_EQUALS(tokenizeAndStringify("int(^block)(void) = ^{\n"
" static int test = 0;\n"
" return test;\n"
"};"), SYNTAX, "syntax error");
ASSERT_THROW_INTERNAL_EQUALS(tokenizeAndStringify("; return f(a[b=c],^{});"), SYNTAX, "syntax error: keyword 'return' is not allowed in global scope"); // #7185
ASSERT_EQUALS("{ return f ( asm ( \"^(void){somecode}\" ) ) ; }",
tokenizeAndStringify("{ return f(^(void){somecode}); }"));
ASSERT_THROW_INTERNAL_EQUALS(tokenizeAndStringify(";a?(b?(c,^{}):0):^{};"), SYNTAX, "syntax error");
ASSERT_EQUALS("template < typename T > "
"CImg < T > operator| ( const char * const expression , const CImg < T > & img ) { "
"return img | expression ; "
"} "
"template < typename T > "
"CImg < T > operator^ ( const char * const expression , const CImg < T > & img ) { "
"return img ^ expression ; "
"} "
"template < typename T > "
"CImg < T > operator== ( const char * const expression , const CImg < T > & img ) { "
"return img == expression ; "
"}",
tokenizeAndStringify("template < typename T >"
"inline CImg<T> operator|(const char *const expression, const CImg<T>& img) {"
" return img | expression ;"
"}"
"template<typename T>"
"inline CImg<T> operator^(const char *const expression, const CImg<T>& img) {"
" return img ^ expression;"
"}"
"template<typename T>"
"inline CImg<T> operator==(const char *const expression, const CImg<T>& img) {"
" return img == expression;"
"}"));
}
void ifAddBraces1() {
const char code[] = "void f()\n"
"{\n"
" if (a);\n"
" else ;\n"
"}\n";
ASSERT_EQUALS("void f ( )\n"
"{\n"
"if ( a ) { ; }\n"
"else { ; }\n"
"}", tokenizeAndStringify(code));
ASSERT_EQUALS(
"[test.cpp:3]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable a\n",
filter_valueflow(errout_str()));
}
void ifAddBraces2() {
const char code[] = "void f()\n"
"{\n"
" if (a) if (b) { }\n"
"}\n";
ASSERT_EQUALS("void f ( )\n"
"{\n"
"if ( a ) { if ( b ) { } }\n"
"}", tokenizeAndStringify(code));
ASSERT_EQUALS(
"[test.cpp:3]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable a\n",
filter_valueflow(errout_str()));
}
void ifAddBraces3() {
const char code[] = "void f()\n"
"{\n"
" if (a) for (;;) { }\n"
"}\n";
ASSERT_EQUALS("void f ( )\n"
"{\n"
"if ( a ) { for ( ; ; ) { } }\n"
"}", tokenizeAndStringify(code));
ASSERT_EQUALS(
"[test.cpp:3]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable a\n",
filter_valueflow(errout_str()));
}
void ifAddBraces4() {
const char code[] = "char * foo ()\n"
"{\n"
" char *str = malloc(10);\n"
" if (somecondition)\n"
" for ( ; ; )\n"
" { }\n"
" return str;\n"
"}\n";
ASSERT_EQUALS("char * foo ( )\n"
"{\n"
"char * str ; str = malloc ( 10 ) ;\n"
"if ( somecondition ) {\n"
"for ( ; ; )\n"
"{ } }\n"
"return str ;\n"
"}", tokenizeAndStringify(code));
ASSERT_EQUALS(
"[test.cpp:4]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable somecondition\n",
filter_valueflow(errout_str()));
}
void ifAddBraces5() {
const char code[] = "void f()\n"
"{\n"
"for(int i = 0; i < 2; i++)\n"
"if(true)\n"
"return;\n"
"\n"
"return;\n"
"}\n";
ASSERT_EQUALS("void f ( )\n"
"{\n"
"for ( int i = 0 ; i < 2 ; i ++ ) {\n"
"if ( true ) {\n"
"return ; } }\n\n"
"return ;\n"
"}", tokenizeAndStringify(code));
}
void ifAddBraces7() {
const char code[] = "void f()\n"
"{\n"
"int a;\n"
"if( a )\n"
" ({a=4;}),({a=5;});\n"
"}\n";
ASSERT_EQUALS("void f ( )\n"
"{\n"
"int a ;\n"
"if ( a ) {\n"
"( { a = 4 ; } ) , ( { a = 5 ; } ) ; }\n"
"}", tokenizeAndStringify(code));
ASSERT_EQUALS("", filter_valueflow(errout_str()));
}
void ifAddBraces9() {
// ticket #990
const char code[] =
"void f() {"
" for (int k=0; k<VectorSize; k++)"
" LOG_OUT(ID_Vector[k])"
"}";
ASSERT_THROW_INTERNAL(tokenizeAndStringify(code), UNKNOWN_MACRO);
}
void ifAddBraces11() {
const char code[] = "{ if (x) if (y) ; else ; }";
const char expected[] = "{ if ( x ) { if ( y ) { ; } else { ; } } }";
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
}
void ifAddBraces12() {
// ticket #1424
const char code[] = "{ if (x) do { } while(x); }";
const char expected[] = "{ if ( x ) { do { } while ( x ) ; } }";
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
}
void ifAddBraces13() {
// ticket #1809
const char code[] = "{ if (x) if (y) { } else { } else { } }";
const char expected[] = "{ if ( x ) { if ( y ) { } else { } } else { } }";
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
// ticket #1809
const char code2[] = "{ if (x) while (y) { } else { } }";
const char expected2[] = "{ if ( x ) { while ( y ) { } } else { } }";
ASSERT_EQUALS(expected2, tokenizeAndStringify(code2));
}
void ifAddBraces15() {
// ticket #2616 - unknown macro before if
// TODO: Remove "A" or change it to ";A;". Then cleanup Tokenizer::ifAddBraces().
ASSERT_EQUALS("{ A if ( x ) { y ( ) ; } }", tokenizeAndStringify("{A if(x)y();}"));
}
void ifAddBraces16() {
// ticket #2873 - the fix is not needed anymore.
{
const char code[] = "void f() { "
"(void) ( { if(*p) (*p) = x(); } ) "
"}";
ASSERT_EQUALS("void f ( ) { ( void ) ( { if ( * p ) { ( * p ) = x ( ) ; } } ) }",
tokenizeAndStringify(code));
ASSERT_EQUALS(
"[test.cpp:1]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable p\n",
filter_valueflow(errout_str()));
}
}
void ifAddBraces17() {
const char code[] = "void f()\n"
"{\n"
" if (a)\n"
" bar1 ();\n"
"\n"
" else\n"
" bar2 ();\n"
"}\n";
ASSERT_EQUALS("void f ( )\n"
"{\n"
"if ( a ) {\n"
"bar1 ( ) ; }\n"
"\n"
"else {\n"
"bar2 ( ) ; }\n"
"}", tokenizeAndStringify(code));
ASSERT_EQUALS(
"[test.cpp:3]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable a\n",
filter_valueflow(errout_str()));
}
void ifAddBraces18() {
// ticket #3424 - if if { } else else
ASSERT_EQUALS("{ if ( x ) { if ( y ) { } else { ; } } else { ; } }",
tokenizeAndStringify("{ if(x) if(y){}else;else;}"));
ASSERT_EQUALS("{ if ( x ) { if ( y ) { if ( z ) { } else { ; } } else { ; } } else { ; } }",
tokenizeAndStringify("{ if(x) if(y) if(z){}else;else;else;}"));
}
void ifAddBraces19() {
// #3928 - if for if else
const char code[] = "void f()\n"
"{\n"
" if (a)\n"
" for (;;)\n"
" if (b)\n"
" bar1();\n"
" else\n"
" bar2();\n"
"}\n";
ASSERT_EQUALS("void f ( )\n"
"{\n"
"if ( a ) {\n"
"for ( ; ; ) {\n"
"if ( b ) {\n"
"bar1 ( ) ; }\n"
"else {\n"
"bar2 ( ) ; } } }\n"
"}", tokenizeAndStringify(code));
ASSERT_EQUALS(
"[test.cpp:3]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable a\n",
filter_valueflow(errout_str()));
}
void ifAddBraces20() { // #5012 - syntax error 'else }'
const char code[] = "void f() { if(x) {} else }";
ASSERT_THROW_INTERNAL(tokenizeAndStringify(code), SYNTAX);
}
void ifAddBracesLabels() {
// Labels before statement
ASSERT_EQUALS("int f ( int x ) {\n"
"if ( x ) {\n"
"l1 : ; l2 : ; return x ; }\n"
"}",
tokenizeAndStringify("int f(int x) {\n"
" if (x)\n"
" l1: l2: return x;\n"
"}"));
ASSERT_EQUALS("", filter_valueflow(errout_str()));
// Labels before {
ASSERT_EQUALS("int f ( int x ) {\n"
"if ( x )\n"
"{ l1 : ; l2 : ; return x ; }\n"
"}",
tokenizeAndStringify("int f(int x) {\n"
" if (x)\n"
" l1: l2: { return x; }\n"
"}"));
ASSERT_EQUALS("", filter_valueflow(errout_str()));
// Labels before try/catch
ASSERT_EQUALS("int f ( int x ) {\n"
"if ( x ) {\n"
"l1 : ; l2 : ;\n"
"try { throw 1 ; }\n"
"catch ( ... ) { return x ; } }\n"
"}",
tokenizeAndStringify("int f(int x) {\n"
" if (x)\n"
" l1: l2:\n"
" try { throw 1; }\n"
" catch(...) { return x; }\n"
"}"));
ASSERT_EQUALS("", filter_valueflow(errout_str()));
}
void switchAddBracesLabels() {
// Labels before statement
ASSERT_EQUALS("int f ( int x ) {\n"
"switch ( x ) {\n"
"l1 : ; case 0 : ; l2 : ; case ( 1 ) : ; return x ; }\n"
"}",
tokenizeAndStringify("int f(int x) {\n"
" switch (x)\n"
" l1: case 0: l2: case (1): return x;\n"
"}"));
// Labels before {
ASSERT_EQUALS("int f ( int x ) {\n"
"switch ( x )\n"
"{ l1 : ; case 0 : ; l2 : ; case ( 1 ) : ; return x ; }\n"
"}",
tokenizeAndStringify("int f(int x) {\n"
" switch (x)\n"
" l1: case 0: l2: case (1): { return x; }\n"
"}"));
// Labels before try/catch
ASSERT_EQUALS("int f ( int x ) {\n"
"switch ( x ) {\n"
"l1 : ; case 0 : ; l2 : ; case ( 1 ) : ;\n"
"try { throw 1 ; }\n"
"catch ( ... ) { return x ; } }\n"
"}",
tokenizeAndStringify("int f(int x) {\n"
" switch (x)\n"
" l1: case 0: l2: case (1):\n"
" try { throw 1; }\n"
" catch(...) { return x; }\n"
"}"));
}
void whileAddBraces() {
const char code[] = "{while(a);}";
ASSERT_EQUALS("{ while ( a ) { ; } }", tokenizeAndStringify(code));
}
void whileAddBracesLabels() {
// Labels before statement
ASSERT_EQUALS("void f ( int x ) {\n"
"while ( x ) {\n"
"l1 : ; l2 : ; -- x ; }\n"
"}",
tokenizeAndStringify("void f(int x) {\n"
" while (x)\n"
" l1: l2: --x;\n"
"}"));
ASSERT_EQUALS("", filter_valueflow(errout_str()));
// Labels before {
ASSERT_EQUALS("void f ( int x ) {\n"
"while ( x )\n"
"{ l1 : ; l2 : ; -- x ; }\n"
"}",
tokenizeAndStringify("void f(int x) {\n"
" while (x)\n"
" l1: l2: { -- x; }\n"
"}"));
ASSERT_EQUALS("", filter_valueflow(errout_str()));
// Labels before try/catch
ASSERT_EQUALS("void f ( int x ) {\n"
"while ( x ) {\n"
"l1 : ; l2 : ;\n"
"try { throw 1 ; }\n"
"catch ( ... ) { -- x ; } }\n"
"}",
tokenizeAndStringify("void f(int x) {\n"
" while (x)\n"
" l1: l2:\n"
" try { throw 1; }\n"
" catch(...) { --x; }\n"
"}"));
ASSERT_EQUALS("", filter_valueflow(errout_str()));
}
void doWhileAddBraces() {
{
const char code[] = "{do ; while (0);}";
const char result[] = "{ do { ; } while ( 0 ) ; }";
ASSERT_EQUALS(result, tokenizeAndStringify(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "{ UNKNOWN_MACRO ( do ) ; while ( a -- ) ; }";
ASSERT_THROW_INTERNAL(tokenizeAndStringify(code), SYNTAX);
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "{ UNKNOWN_MACRO ( do , foo ) ; while ( a -- ) ; }";
ASSERT_THROW_INTERNAL(tokenizeAndStringify(code), SYNTAX);
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "void foo ( int c , int d ) {\n"
" do\n"
" if ( c ) {\n"
" while ( c ) { c -- ; }\n"
" }\n"
" while ( -- d > 0 ) ;\n"
" return 0 ;\n"
"}\n";
const char result[] = "void foo ( int c , int d ) {\n"
"do {\n"
"if ( c ) {\n"
"while ( c ) { c -- ; }\n"
"} }\n"
"while ( -- d > 0 ) ;\n"
"return 0 ;\n"
"}";
ASSERT_EQUALS(result, tokenizeAndStringify(code));
ASSERT_EQUALS("", filter_valueflow(errout_str()));
}
{
const char code[] = "void foo ( int c , int d ) {\n"
" do\n"
" do c -- ; while ( c ) ;\n"
" while ( -- d > 0 ) ;\n"
" return 0 ;\n"
"}\n";
const char result[] = "void foo ( int c , int d ) {\n"
"do {\n"
"do { c -- ; } while ( c ) ; }\n"
"while ( -- d > 0 ) ;\n"
"return 0 ;\n"
"}";
ASSERT_EQUALS(result, tokenizeAndStringify(code));
ASSERT_EQUALS("", errout_str());
}
{
// #8148 - while inside the do-while body
const char code[] = "void foo() {\n"
" do { while (x) f(); } while (y);\n"
"}";
const char result[] = "void foo ( ) {\n"
"do { while ( x ) { f ( ) ; } } while ( y ) ;\n"
"}";
ASSERT_EQUALS(result, tokenizeAndStringify(code));
ASSERT_EQUALS(
"[test.cpp:2]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable x\n",
filter_valueflow(errout_str()));
}
}
void doWhileAddBracesLabels() {
// Labels before statement
ASSERT_EQUALS("void f ( int x ) {\n"
"do {\n"
"l1 : ; l2 : ; -- x ; }\n"
"while ( x ) ;\n"
"}",
tokenizeAndStringify("void f(int x) {\n"
" do\n"
" l1: l2: --x;\n"
" while (x);\n"
"}"));
// Labels before {
ASSERT_EQUALS("void f ( int x ) {\n"
"do\n"
"{ l1 : ; l2 : ; -- x ; }\n"
"while ( x ) ;\n"
"}",
tokenizeAndStringify("void f(int x) {\n"
" do\n"
" l1: l2: { -- x; }\n"
" while (x);\n"
"}"));
// Labels before try/catch
ASSERT_EQUALS("void f ( int x ) {\n"
"do {\n"
"l1 : ; l2 : ;\n"
"try { throw 1 ; }\n"
"catch ( ... ) { -- x ; } }\n"
"while ( x ) ;\n"
"}",
tokenizeAndStringify("void f(int x) {\n"
" do\n"
" l1: l2:\n"
" try { throw 1; }\n"
" catch(...) { --x; }\n"
" while (x);\n"
"}"));
}
void forAddBraces1() {
{
const char code[] = "void f() {\n"
" for(;;)\n"
" if (a) { }\n"
" else { }\n"
"}";
const char expected[] = "void f ( ) {\n"
"for ( ; ; ) {\n"
"if ( a ) { }\n"
"else { } }\n"
"}";
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
ASSERT_EQUALS(
"[test.cpp:3]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable a\n",
filter_valueflow(errout_str()));
}
{
const char code[] = "void f() {\n"
" for(;;)\n"
" if (a) { }\n"
" else if (b) { }\n"
" else { }\n"
"}";
const char expected[] = "void f ( ) {\n"
"for ( ; ; ) {\n"
"if ( a ) { }\n"
"else { if ( b ) { }\n"
"else { } } }\n"
"}";
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
ASSERT_EQUALS(
"[test.cpp:3]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable a\n",
filter_valueflow(errout_str()));
}
}
void forAddBraces2() { // #5088
const char code[] = "void f() {\n"
" for(;;) try { } catch (...) { }\n"
"}";
const char expected[] = "void f ( ) {\n"
"for ( ; ; ) { try { } catch ( ... ) { } }\n"
"}";
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
}
void forAddBracesLabels() {
// Labels before statement
ASSERT_EQUALS("void f ( int x ) {\n"
"for ( ; x ; ) {\n"
"l1 : ; l2 : ; -- x ; }\n"
"}",
tokenizeAndStringify("void f(int x) {\n"
" for ( ; x; )\n"
" l1: l2: --x;\n"
"}"));
// Labels before {
ASSERT_EQUALS("void f ( int x ) {\n"
"for ( ; x ; )\n"
"{ l1 : ; l2 : ; -- x ; }\n"
"}",
tokenizeAndStringify("void f(int x) {\n"
" for ( ; x; )\n"
" l1: l2: { -- x; }\n"
"}"));
// Labels before try/catch
ASSERT_EQUALS("void f ( int x ) {\n"
"for ( ; x ; ) {\n"
"l1 : ; l2 : ;\n"
"try { throw 1 ; }\n"
"catch ( ... ) { -- x ; } }\n"
"}",
tokenizeAndStringify("void f(int x) {\n"
" for ( ; x; )\n"
" l1: l2:\n"
" try { throw 1; }\n"
" catch(...) { --x; }\n"
"}"));
}
void simplifyExternC() {
const char expected[] = "int foo ( ) ;";
{
const char code[] = "extern \"C\" int foo();";
// tokenize..
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
// Expected result..
ASSERT_EQUALS(expected, tokenizer.tokens()->stringifyList(nullptr, false));
ASSERT(tokenizer.tokens()->next()->isExternC());
}
{
const char code[] = "extern \"C\" { int foo(); }";
// tokenize..
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
// Expected result..
ASSERT_EQUALS(expected, tokenizer.tokens()->stringifyList(nullptr, false));
ASSERT(tokenizer.tokens()->next()->isExternC());
}
{
const char code[] = "extern \"C++\" int foo();";
// tokenize..
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
// Expected result..
ASSERT_EQUALS(expected, tokenizer.tokens()->stringifyList(nullptr, false));
ASSERT(!tokenizer.tokens()->next()->isExternC());
}
{
const char code[] = "extern \"C++\" { int foo(); }";
// tokenize..
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
// Expected result..
ASSERT_EQUALS(expected, tokenizer.tokens()->stringifyList(nullptr, false));
ASSERT(!tokenizer.tokens()->next()->isExternC());
}
}
void simplifyFunctionParameters() {
{
const char code[] = "char a [ ABC ( DEF ) ] ;";
ASSERT_EQUALS(code, tokenizeAndStringify(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "module ( a , a , sizeof ( a ) , 0444 ) ;";
ASSERT_EQUALS("module ( a , a , sizeof ( a ) , 0444 ) ;", tokenizeAndStringify(code));
ASSERT_EQUALS("", errout_str());
}
ASSERT_EQUALS("void f ( int x ) { }", tokenizeAndStringify("void f(x) int x; { }"));
ASSERT_EQUALS("", errout_str());
ASSERT_EQUALS("void f ( int x , char y ) { }", tokenizeAndStringify("void f(x,y) int x; char y; { }"));
ASSERT_EQUALS("", errout_str());
ASSERT_EQUALS("int main ( int argc , char * argv [ ] ) { }", tokenizeAndStringify("int main(argc,argv) int argc; char *argv[]; { }"));
ASSERT_EQUALS("", errout_str());
ASSERT_EQUALS("int f ( int p , int w , float d ) { }", tokenizeAndStringify("int f(p,w,d) float d; { }"));
ASSERT_EQUALS("", errout_str());
// #1067 - Not simplified. Feel free to fix so it is simplified correctly but this syntax is obsolescent.
ASSERT_EQUALS("int ( * d ( a , b , c ) ) ( ) int a ; int b ; int c ; { }", tokenizeAndStringify("int (*d(a,b,c))()int a,b,c; { }"));
ASSERT_EQUALS("", errout_str());
{
// This is not a function but the pattern is similar..
const char code[] = "void foo()"
"{"
" if (x)"
" int x;"
" { }"
"}";
ASSERT_EQUALS("void foo ( ) { if ( x ) { int x ; } { } }", tokenizeAndStringify(code));
ASSERT_EQUALS(
"[test.cpp:1]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable x\n",
filter_valueflow(errout_str()));
}
}
void simplifyFunctionParameters1() { // ticket #3721
const char code[] = "typedef float ufloat;\n"
"typedef short ftnlen;\n"
"int f(p,w,d,e,len) ufloat *p; ftnlen len;\n"
"{\n"
"}\n";
ASSERT_EQUALS("int f ( float * p , int w , int d , int e , short len )\n"
"{\n"
"}", tokenizeAndStringify(code));
}
void simplifyFunctionParameters2() { // #4430
const char code[] = "class Item { "
"int i ; "
"public: "
"Item ( int i ) ; "
"} ; "
"Item :: Item ( int i ) : i ( i ) { }";
ASSERT_EQUALS(code, tokenizeAndStringify(code));
}
void simplifyFunctionParameters3() { // #4436
const char code[] = "class Item { "
"int i ; "
"int j ; "
"public: "
"Item ( int i , int j ) ; "
"} ; "
"Item :: Item ( int i , int j ) : i ( i ) , j ( j ) { }";
ASSERT_EQUALS(code, tokenizeAndStringify(code));
}
void simplifyFunctionParameters4() { // #9421
const char code[] = "int foo :: bar ( int , int ) const ;";
ASSERT_EQUALS(code, tokenizeAndStringify(code));
}
void simplifyFunctionParametersMultiTemplate() {
const char code[] = "template < typename T1 > template < typename T2 > "
"void A < T1 > :: foo ( T2 ) { }";
ASSERT_EQUALS(code, tokenizeAndStringify(code));
ASSERT_EQUALS("[test.cpp:1]: (debug) Executable scope 'foo' with unknown function.\n", errout_str());
}
void simplifyFunctionParametersErrors() {
//same parameters...
ASSERT_THROW_INTERNAL(tokenizeAndStringify("void foo(x, x)\n"
" int x;\n"
" int x;\n"
"{}\n"), SYNTAX);
ASSERT_THROW_INTERNAL(tokenizeAndStringify("void foo(x, y)\n"
" int x;\n"
" int x;\n"
"{}\n"), SYNTAX);
ASSERT_NO_THROW(tokenizeAndStringify("void foo(int, int)\n"
"{}"));
ASSERT_EQUALS("", errout_str());
// #3848 - Don't hang
(void)tokenizeAndStringify("sal_Bool ShapeHasText(sal_uLong, sal_uLong) const {\n"
" return sal_True;\n"
"}\n"
"void CreateSdrOLEFromStorage() {\n"
" comphelper::EmbeddedObjectContainer aCnt( xDestStorage );\n"
" { }\n"
"}");
ignore_errout();
}
void simplifyFunctionTryCatch() {
ASSERT_EQUALS("void foo ( ) { try {\n"
"} catch ( int ) {\n"
"} catch ( char ) {\n"
"} }",
tokenizeAndStringify("void foo() try {\n"
"} catch (int) {\n"
"} catch (char) {\n"
"}"));
ASSERT_EQUALS("void foo ( ) { try {\n"
"struct S {\n"
"void bar ( ) { try {\n"
"} catch ( int ) {\n"
"} catch ( char ) {\n"
"} }\n"
"} ;\n"
"} catch ( long ) {\n"
"} }",
tokenizeAndStringify("void foo() try {\n"
" struct S {\n"
" void bar() try {\n"
" } catch (int) {\n"
" } catch (char) {\n"
" }\n"
" };\n"
"} catch (long) {\n"
"}"));
}
// Simplify "((..))" into "(..)"
void removeParentheses1() {
const char code[] = "void foo()"
"{"
" free(((void*)p));"
"}";
ASSERT_EQUALS("void foo ( ) { free ( ( void * ) p ) ; }", tokenizeAndStringify(code));
ASSERT_EQUALS(
"[test.cpp:1]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable p\n",
errout_str());
}
void removeParentheses3() {
{
const char code[] = "void foo()"
"{"
" if (( true )==(true)){}"
"}";
ASSERT_EQUALS("void foo ( ) { if ( true == true ) { } }", tokenizeAndStringify(code));
}
{
const char code[] = "void foo()"
"{"
" if (( 2 )==(2)){}"
"}";
ASSERT_EQUALS("void foo ( ) { if ( 2 == 2 ) { } }", tokenizeAndStringify(code));
}
{
const char code[] = "void foo()"
"{"
" if( g(10)){}"
"}";
ASSERT_EQUALS("void foo ( ) { if ( g ( 10 ) ) { } }", tokenizeAndStringify(code));
}
}
// Simplify "( function (..))" into "function (..)"
void removeParentheses4() {
const char code[] = "void foo()"
"{"
" (free(p));"
"}";
ASSERT_EQUALS("void foo ( ) { free ( p ) ; }", tokenizeAndStringify(code));
ASSERT_EQUALS(
"[test.cpp:1]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable p\n",
errout_str());
}
void removeParentheses5() {
// Simplify "( delete x )" into "delete x"
{
const char code[] = "void foo()"
"{"
" (delete p);"
"}";
ASSERT_EQUALS("void foo ( ) { delete p ; }", tokenizeAndStringify(code));
ASSERT_EQUALS(
"[test.cpp:1]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable p\n",
errout_str());
}
// Simplify "( delete [] x )" into "delete [] x"
{
const char code[] = "void foo()"
"{"
" (delete [] p);"
"}";
ASSERT_EQUALS("void foo ( ) { delete [ ] p ; }", tokenizeAndStringify(code));
ASSERT_EQUALS(
"[test.cpp:1]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable p\n",
errout_str());
}
}
// "!(abc.a)" => "!abc.a"
void removeParentheses6() {
{
const char code[] = "(!(abc.a));";
ASSERT_EQUALS("( ! abc . a ) ;", tokenizeAndStringify(code));
}
//handle more complex member selections
{
const char code[] = "(!(a.b.c.d));";
ASSERT_EQUALS("( ! a . b . c . d ) ;", tokenizeAndStringify(code));
}
}
void removeParentheses7() {
const char code[] = ";char *p; (delete(p), (p)=0);";
ASSERT_EQUALS("; char * p ; delete ( p ) , p = 0 ;", tokenizeAndStringify(code));
}
void removeParentheses8() {
const char code[] = "struct foo {\n"
" void operator delete(void *obj, size_t sz);\n"
"}\n";
const std::string actual(tokenizeAndStringify(code, true, Platform::Type::Win32A));
const char expected[] = "struct foo {\n"
"void operatordelete ( void * obj , unsigned long sz ) ;\n"
"}";
ASSERT_EQUALS(expected, actual);
}
void removeParentheses9() {
ASSERT_EQUALS("void delete ( double num ) ;", tokenizeAndStringify("void delete(double num);"));
}
void removeParentheses10() {
ASSERT_EQUALS("p = buf + 8 ;", tokenizeAndStringify("p = (buf + 8);"));
}
void removeParentheses11() {
// #2502
ASSERT_EQUALS("{ } x ( ) ;", tokenizeAndStringify("{}(x());"));
}
void removeParentheses12() {
// #2760
ASSERT_EQUALS(", x = 0 ;", tokenizeAndStringify(",(x)=0;"));
}
void removeParentheses13() {
ASSERT_EQUALS("; f ( a + b , c ) ;", tokenizeAndStringify(";f((a+b),c);"));
ASSERT_EQUALS("; x = y [ a + b ] ;", tokenizeAndStringify(";x=y[(a+b)];"));
}
void removeParentheses14() {
ASSERT_EQUALS("{ if ( ( i & 1 ) == 0 ) { ; } }", tokenizeAndStringify("{ if ( (i & 1) == 0 ); }"));
}
void removeParentheses15() {
ASSERT_EQUALS("a = b ? c : 123 ;", tokenizeAndStringify("a = b ? c : (123);"));
ASSERT_EQUALS("a = b ? c : ( 123 + 456 ) ;", tokenizeAndStringify("a = b ? c : ((123)+(456));"));
ASSERT_EQUALS("a = b ? ( 123 ) : c ;", tokenizeAndStringify("a = b ? (123) : c;"));
// #4316
ASSERT_EQUALS("a = b ? c : ( d = 1 , 0 ) ;", tokenizeAndStringify("a = b ? c : (d=1,0);"));
}
void removeParentheses16() { // *(x.y)=
// #4423
ASSERT_EQUALS("; * x = 0 ;", tokenizeAndStringify(";*(x)=0;"));
ASSERT_EQUALS("; * x . y = 0 ;", tokenizeAndStringify(";*(x.y)=0;"));
}
void removeParentheses17() { // a ? b : (c > 0 ? d : e)
ASSERT_EQUALS("a ? b : ( c > 0 ? d : e ) ;", tokenizeAndStringify("a?b:(c>0?d:e);"));
}
void removeParentheses18() {
ASSERT_EQUALS("float ( * a ) [ 2 ] ;", tokenizeAndStringify("float(*a)[2];"));
}
void removeParentheses19() {
ASSERT_EQUALS("( ( ( typeof ( X ) ) * ) 0 ) ;", tokenizeAndStringify("(((typeof(X))*)0);"));
}
void removeParentheses20() {
ASSERT_EQUALS("a < b < int > > ( 2 ) ;", tokenizeAndStringify("a<b<int>>(2);"));
}
void removeParentheses21() {
ASSERT_EQUALS("a = ( int ) - b ;", tokenizeAndStringify("a = ((int)-b);"));
}
void removeParentheses22() {
static char code[] = "struct S { "
"char *(a); "
"char &(b); "
"const static char *(c); "
"} ;";
static const char exp[] = "struct S { "
"char * a ; "
"char & b ; "
"static const char * c ; "
"} ;";
ASSERT_EQUALS(exp, tokenizeAndStringify(code));
}
void removeParentheses23() { // Ticket #6103
// Reported case
{
static char code[] = "; * * p f ( ) int = { new int ( * [ 2 ] ) ; void }";
static const char exp[] = "; * * p f ( ) int = { new int ( * [ 2 ] ) ; void }";
ASSERT_EQUALS(exp, tokenizeAndStringify(code));
}
// Various valid cases
{
static char code[] = "int * f [ 1 ] = { new ( int ) } ;";
static const char exp[] = "int * f [ 1 ] = { new int } ;";
ASSERT_EQUALS(exp, tokenizeAndStringify(code));
}
{
static char code[] = "int * * f [ 1 ] = { new ( int ) [ 1 ] } ;";
static const char exp[] = "int * * f [ 1 ] = { new int [ 1 ] } ;";
ASSERT_EQUALS(exp, tokenizeAndStringify(code));
}
{
static char code[] = "list < int > * f [ 1 ] = { new ( list < int > ) } ;";
static const char exp[] = "list < int > * f [ 1 ] = { new list < int > } ;";
ASSERT_EQUALS(exp, tokenizeAndStringify(code));
}
// don't remove parentheses in operator new overload
{
static char code[] = "void *operator new(__SIZE_TYPE__, int);";
static const char exp[] = "void * operatornew ( __SIZE_TYPE__ , int ) ;";
ASSERT_EQUALS(exp, tokenizeAndStringify(code));
}
}
void removeParentheses24() { // Ticket #7040
static char code[] = "std::hash<decltype(t._data)>()(t._data);";
static const char exp[] = "std :: hash < decltype ( t . _data ) > ( ) ( t . _data ) ;";
ASSERT_EQUALS(exp, tokenizeAndStringify(code));
}
void removeParentheses25() { // daca@home - a=(b,c)
static char code[] = "a=(b,c);";
static const char exp[] = "a = ( b , c ) ;";
ASSERT_EQUALS(exp, tokenizeAndStringify(code));
}
void removeParentheses26() { // Ticket #8875 a[0](0)
static char code[] = "a[0](0);";
static const char exp[] = "a [ 0 ] ( 0 ) ;";
ASSERT_EQUALS(exp, tokenizeAndStringify(code));
}
void removeParentheses27() {
static char code[] = "struct S { int i; };\n"
"void g(int, int);\n"
"void f(S s, int j) {\n"
" g(j, (decltype(s.i))j * s.i);\n"
"}\n";
static const char exp[] = "struct S { int i ; } ;\n"
"void g ( int , int ) ;\n"
"void f ( S s , int j ) {\n"
"g ( j , ( decltype ( s . i ) ) j * s . i ) ;\n"
"}";
ASSERT_EQUALS(exp, tokenizeAndStringify(code));
}
void removeParentheses28() { // Ticket #12164
static char code[] = "temp1 = (value > 100U) ? (value+100U) : (value-50U);";
static const char exp[] = "temp1 = ( value > 100U ) ? ( value + 100U ) : ( value - 50U ) ;";
ASSERT_EQUALS(exp, tokenizeAndStringify(code));
}
void tokenize_double() {
const char code[] = "void f() {\n"
" double a = 4.2;\n"
" float b = 4.2f;\n"
" double c = 4.2e+10;\n"
" double d = 4.2e-10;\n"
" int e = 4+2;\n"
"}";
ASSERT_EQUALS("void f ( ) {\n"
"double a ; a = 4.2 ;\n"
"float b ; b = 4.2f ;\n"
"double c ; c = 4.2e+10 ;\n"
"double d ; d = 4.2e-10 ;\n"
"int e ; e = 4 + 2 ;\n"
"}", tokenizeAndStringify(code));
}
void tokenize_strings() {
const char code[] = "void f() {\n"
"const char *a =\n"
"{\n"
"\"hello \"\n"
"\"more \"\n"
"\"world\"\n"
"};\n"
"}";
ASSERT_EQUALS("void f ( ) {\n"
"const char * a ; a =\n"
"{\n"
"\"hello more world\"\n"
"\n"
"\n"
"} ;\n"
"}", tokenizeAndStringify(code));
}
void simplifyStructDecl() {
const char code[] = "const struct A { int a; int b; } a;";
ASSERT_EQUALS("struct A { int a ; int b ; } ; const struct A a ;", tokenizeAndStringify(code));
// #9519
const char code2[] = "enum A {} (a);";
const char expected2[] = "enum A { } ; enum A a ;";
ASSERT_EQUALS(expected2, tokenizeAndStringify(code2));
// #11052
const char code3[] = "struct a { int b; } static e[1];";
const char expected3[] = "struct a { int b ; } ; struct a static e [ 1 ] ;";
ASSERT_EQUALS(expected3, tokenizeAndStringify(code3));
// #11013 - Do not remove unnamed struct in union
const char code4[] = "union U { struct { int a; int b; }; int ab[2]; };";
const char expected4[] = "union U { struct { int a ; int b ; } ; int ab [ 2 ] ; } ;";
ASSERT_EQUALS(expected4, tokenizeAndStringify(code4));
}
void vardecl1() {
const char code[] = "unsigned int a, b;";
const std::string actual(tokenizeAndStringify(code));
ASSERT_EQUALS("unsigned int a ; unsigned int b ;", actual);
}
void vardecl2() {
const char code[] = "void foo(a,b) unsigned int a, b; { }";
const std::string actual(tokenizeAndStringify(code));
ASSERT_EQUALS("void foo ( unsigned int a , unsigned int b ) { }", actual);
}
void vardecl3() {
const char code[] = "void f() { char * p = foo<10,char>(); }";
const std::string actual(tokenizeAndStringify(code));
ASSERT_EQUALS("void f ( ) { char * p ; p = foo < 10 , char > ( ) ; }", actual);
}
void vardecl4() {
// ticket #346
const char code1[] = "void *p = NULL;";
const char res1[] = "void * p ; p = NULL ;";
ASSERT_EQUALS(res1, tokenizeAndStringify(code1));
const char code2[] = "const void *p = NULL;";
const char res2[] = "const void * p ; p = NULL ;";
ASSERT_EQUALS(res2, tokenizeAndStringify(code2));
const char code3[] = "void * const p = NULL;";
const char res3[] = "void * const p ; p = NULL ;";
ASSERT_EQUALS(res3, tokenizeAndStringify(code3));
const char code4[] = "const void * const p = NULL;";
const char res4[] = "const void * const p ; p = NULL ;";
ASSERT_EQUALS(res4, tokenizeAndStringify(code4));
const char code5[] = "const void * volatile p = NULL;";
const char res5[] = "const void * volatile p ; p = NULL ;";
ASSERT_EQUALS(res5, tokenizeAndStringify(code5));
}
void vardecl5() {
ASSERT_EQUALS("void foo ( int nX ) {\n"
"int addI ; addI = frontPoint == 2 || frontPoint == 1 ? ( i = 0 , 1 ) : ( i = nX - 2 , -1 ) ;\n"
"}", tokenizeAndStringify("void foo(int nX) {\n"
" int addI = frontPoint == 2 || frontPoint == 1 ? i = 0, 1 : (i = nX - 2, -1);\n"
"}"));
ASSERT_EQUALS(
"[test.cpp:2]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable frontPoint\n",
errout_str());
}
void vardecl_stl_1() {
// ticket #520
const char code1[] = "std::vector<std::string>a, b;";
const char res1[] = "std :: vector < std :: string > a ; std :: vector < std :: string > b ;";
ASSERT_EQUALS(res1, tokenizeAndStringify(code1));
const char code2[] = "std::vector<std::string>::const_iterator it, cit;";
const char res2[] = "std :: vector < std :: string > :: const_iterator it ; std :: vector < std :: string > :: const_iterator cit ;";
ASSERT_EQUALS(res2, tokenizeAndStringify(code2));
const char code3[] = "std::vector<std::pair<std::string, std::string > > *c, d;";
const char res3[] = "std :: vector < std :: pair < std :: string , std :: string > > * c ; std :: vector < std :: pair < std :: string , std :: string > > d ;";
ASSERT_EQUALS(res3, tokenizeAndStringify(code3));
}
void vardecl_stl_2() {
const char code1[] = "{ std::string x = \"abc\"; }";
ASSERT_EQUALS("{ std :: string x ; x = \"abc\" ; }", tokenizeAndStringify(code1));
const char code2[] = "{ std::vector<int> x = y; }";
ASSERT_EQUALS("{ std :: vector < int > x ; x = y ; }", tokenizeAndStringify(code2));
}
void vardecl_stl_3()
{
const char code1[] = "{ std::string const x = \"abc\"; }";
ASSERT_EQUALS("{ const std :: string x = \"abc\" ; }", tokenizeAndStringify(code1));
const char code2[] = "{ std::vector<int> const x = y; }";
ASSERT_EQUALS("{ const std :: vector < int > x = y ; }", tokenizeAndStringify(code2));
}
void vardecl_template_1() {
// ticket #1046
const char code1[] = "b<(1<<24),10,24> u, v;";
const char res1[] = "b < 16777216 , 10 , 24 > u ; b < 16777216 , 10 , 24 > v ;";
ASSERT_EQUALS(res1, tokenizeAndStringify(code1));
// ticket #3571 (segmentation fault)
(void)tokenizeAndStringify("template <int i = (3>4) > class X4 {};");
}
void vardecl_template_2() {
// ticket #3650
const char code[] = "const string str = x<8,int>();";
const char expected[] = "const string str = x < 8 , int > ( ) ;";
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
}
void vardecl_union() {
// ticket #1976
const char code1[] = "class Fred { public: union { int a ; int b ; } ; } ;";
ASSERT_EQUALS(code1, tokenizeAndStringify(code1));
// ticket #2039
const char code2[] = "void f() {\n"
" union {\n"
" int x;\n"
" long y;\n"
" };\n"
"}";
ASSERT_EQUALS("void f ( ) {\nunion {\nint x ;\nlong y ;\n} ;\n}", tokenizeAndStringify(code2));
// ticket #3927
const char code3[] = "union xy *p = NULL;";
ASSERT_EQUALS("union xy * p ; p = NULL ;", tokenizeAndStringify(code3));
}
void vardecl_par() {
// ticket #2743 - set links if variable type contains parentheses
const char code[] = "Fred<int(*)()> fred1=a, fred2=b;";
ASSERT_EQUALS("Fred < int ( * ) ( ) > fred1 ; fred1 = a ; Fred < int ( * ) ( ) > fred2 ; fred2 = b ;", tokenizeAndStringify(code));
}
void vardecl_par2() {
// ticket #3912 - set correct links
const char code[] = "function<void (shared_ptr<MyClass>)> v;";
ASSERT_EQUALS("function < void ( shared_ptr < MyClass > ) > v ;", tokenizeAndStringify(code));
}
void vardecl_par3() {
// ticket #6556- Fred x1(a), x2(b);
const char code[] = "Fred x1(a), x2(b);";
ASSERT_EQUALS("Fred x1 ( a ) ; Fred x2 ( b ) ;", tokenizeAndStringify(code));
}
void vardecl_class_ref() {
const char code[] = "class A { B &b1,&b2; };";
ASSERT_EQUALS("class A { B & b1 ; B & b2 ; } ;", tokenizeAndStringify(code));
}
void vardec_static() {
{
// don't simplify declarations of static variables
// "static int i = 0;" is not the same as "static int i; i = 0;"
const char code[] = "static int i = 0 ;";
ASSERT_EQUALS(code, tokenizeAndStringify(code));
}
{
const char code[] = "static int a, b;";
ASSERT_EQUALS("static int a ; static int b ;", tokenizeAndStringify(code));
}
{
const char code[] = "static unsigned int a, b;";
ASSERT_EQUALS("static unsigned int a ; static unsigned int b ;", tokenizeAndStringify(code));
}
{
const char code[] = "static int a=1, b=1;";
ASSERT_EQUALS("static int a = 1 ; static int b = 1 ;", tokenizeAndStringify(code));
}
{
const char code[] = "static int *a, *b;";
ASSERT_EQUALS("static int * a ; static int * b ;", tokenizeAndStringify(code));
}
{
const char code[] = "static unsigned int *a=0, *b=0;";
ASSERT_EQUALS("static unsigned int * a = 0 ; static unsigned int * b = 0 ;", tokenizeAndStringify(code));
}
{
// Ticket #4450
const char code[] = "static int large_eeprom_type = (13 | (5)), "
"default_flash_type = 42;";
ASSERT_EQUALS("static int large_eeprom_type = 13 | 5 ; static int default_flash_type = 42 ;",
tokenizeAndStringify(code));
}
{
// Ticket #5121
const char code[] = "unsigned int x;"
"static const unsigned int A = 1, B = A, C = 0, D = (A), E = 0;"
"void f() {"
" unsigned int *foo = &x;"
"}";
ASSERT_EQUALS("unsigned int x ; "
"static const unsigned int A = 1 ; "
"static const unsigned int B = A ; "
"static const unsigned int C = 0 ; "
"static const unsigned int D = A ; "
"static const unsigned int E = 0 ; "
"void f ( ) { "
"unsigned int * foo ; "
"foo = & x ; "
"}",
tokenizeAndStringify(code));
}
{
// Ticket #5266
const char code[] = "class Machine {\n"
" static int const STACK_ORDER = 10, STACK_MAX = 1 << STACK_ORDER,"
" STACK_GUARD = 2;\n"
"};";
ASSERT_EQUALS("class Machine {\n"
"static const int STACK_ORDER = 10 ; static const int STACK_MAX = 1 << STACK_ORDER ; "
"static const int STACK_GUARD = 2 ;\n"
"} ;",
tokenizeAndStringify(code));
}
{
// Ticket #9515
const char code[] = "void(a)(void) {\n"
" static int b;\n"
" if (b) {}\n"
"}\n";
ASSERT_EQUALS("void ( a ) ( void ) {\n"
"static int b ;\n"
"if ( b ) { }\n"
"}",
tokenizeAndStringify(code));
}
}
void vardecl6() {
// ticket #565
const char code1[] = "int z = x >> 16;";
const char res1[] = "int z ; z = x >> 16 ;";
ASSERT_EQUALS(res1, tokenizeAndStringify(code1));
}
void vardecl7() {
// ticket #603
const char code[] = "void f() {\n"
" for (int c = 0; c < 0; ++c) {}\n"
" int t;\n"
" D(3 > t, \"T\");\n"
"}";
const char res[] = "void f ( ) {\n"
"for ( int c = 0 ; c < 0 ; ++ c ) { }\n"
"int t ;\n"
"D ( 3 > t , \"T\" ) ;\n"
"}";
ASSERT_EQUALS(res, tokenizeAndStringify(code));
}
void vardecl8() {
// ticket #696
const char code[] = "char a[10]={'\\0'}, b[10]={'\\0'};";
const char res[] = "char a [ 10 ] = { '\\0' } ; char b [ 10 ] = { '\\0' } ;";
ASSERT_EQUALS(res, tokenizeAndStringify(code));
}
void vardecl9() {
const char code[] = "char a[2] = {'A', '\\0'}, b[2] = {'B', '\\0'};";
const char res[] = "char a [ 2 ] = { 'A' , '\\0' } ; char b [ 2 ] = { 'B' , '\\0' } ;";
ASSERT_EQUALS(res, tokenizeAndStringify(code));
}
void vardecl10() {
// ticket #732
const char code[] = "char a [ 2 ] = { '-' } ; memset ( a , '-' , sizeof ( a ) ) ;";
ASSERT_EQUALS(code, tokenizeAndStringify(code));
}
void vardecl11() {
// ticket #1684
const char code[] = "char a[5][8], b[5][8];";
ASSERT_EQUALS("char a [ 5 ] [ 8 ] ; char b [ 5 ] [ 8 ] ;", tokenizeAndStringify(code));
}
void vardecl12() {
const char code[] = "struct A { public: B a, b, c, d; };";
ASSERT_EQUALS("struct A { public: B a ; B b ; B c ; B d ; } ;", tokenizeAndStringify(code));
}
void vardecl13() {
const char code[] = "void f() {\n"
" int a = (x < y) ? 1 : 0;\n"
"}";
ASSERT_EQUALS("void f ( ) {\nint a ; a = ( x < y ) ? 1 : 0 ;\n}", tokenizeAndStringify(code));
ASSERT_EQUALS(
"[test.cpp:2]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable x\n",
errout_str());
}
void vardecl14() {
const char code[] = "::std::tr1::shared_ptr<int> pNum1, pNum2;\n";
ASSERT_EQUALS(":: std :: tr1 :: shared_ptr < int > pNum1 ; :: std :: tr1 :: shared_ptr < int > pNum2 ;", tokenizeAndStringify(code, false, Platform::Type::Native, true, Standards::CPP03));
}
void vardecl15() {
const char code[] = "const char x[] = \"foo\", y[] = \"bar\";\n";
ASSERT_EQUALS("const char x [ 4 ] = \"foo\" ; const char y [ 4 ] = \"bar\" ;", tokenizeAndStringify(code));
}
void vardecl16() {
{
const char code[] = "const a::b<c,d(e),f>::g::h<i>::l *x [] = foo(),y [][] = bar();\n";
ASSERT_EQUALS("const a :: b < c , d ( e ) , f > :: g :: h < i > :: l * x [ ] = foo ( ) ; "
"const a :: b < c , d ( e ) , f > :: g :: h < i > :: l y [ ] [ ] = bar ( ) ;", tokenizeAndStringify(code));
}
{
const char code[] = "const ::b<c,d(e),f>::g::h<i>::l *x [] = foo(),y [][] = bar();\n";
ASSERT_EQUALS("const :: b < c , d ( e ) , f > :: g :: h < i > :: l * x [ ] = foo ( ) ; "
"const :: b < c , d ( e ) , f > :: g :: h < i > :: l y [ ] [ ] = bar ( ) ;", tokenizeAndStringify(code));
}
}
void vardecl17() {
const char code[] = "a < b > :: c :: d :: e < f > x = foo(), y = bar();\n";
ASSERT_EQUALS("a < b > :: c :: d :: e < f > x ; x = foo ( ) ; "
"a < b > :: c :: d :: e < f > y ; y = bar ( ) ;", tokenizeAndStringify(code));
}
void vardecl18() {
const char code[] = "void f() {\n"
" g((double)v1*v2, v3, v4);\n"
"}\n";
ASSERT_EQUALS("void f ( ) {\n"
"g ( ( double ) v1 * v2 , v3 , v4 ) ;\n"
"}", tokenizeAndStringify(code));
ASSERT_EQUALS(
"[test.cpp:2]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable v1\n",
errout_str());
}
void vardecl19() {
{
const char code[] = "void func(in, r, m)\n"
"int in;"
"int r,m;"
"{\n"
"}\n";
ASSERT_EQUALS("void func (\n"
"int in , int r , int m\n"
")\n"
"{\n"
"}", tokenizeAndStringify(code));
}
{
const char code[] = "void f(r,f)\n"
"char *r;\n"
"{\n"
"}\n";
ASSERT_EQUALS("void f (\n"
"char * r\n"
")\n"
"\n"
"{\n"
"}", tokenizeAndStringify(code));
}
{
const char code[] = "void f(f)\n"
"{\n"
"}\n";
ASSERT_EQUALS("void f ( )\n"
"{\n"
"}", tokenizeAndStringify(code));
}
{
const char code[] = "void f(f,r)\n"
"char *r;\n"
"{\n"
"}\n";
ASSERT_EQUALS("void f (\n"
"char * r\n"
")\n"
"\n"
"{\n"
"}", tokenizeAndStringify(code));
}
{
const char code[] = "void f(r,f,s)\n"
"char *r;\n"
"char *s;\n"
"{\n"
"}\n";
ASSERT_EQUALS("void f (\n"
"char * r ,\n"
"char * s\n"
")\n"
"\n"
"\n"
"{\n"
"}", tokenizeAndStringify(code));
}
{
const char code[] = "void f(r,s,t)\n"
"char *r,*s,*t;\n"
"{\n"
"}\n";
ASSERT_EQUALS("void f (\n"
"char * r , char * s , char * t\n"
")\n"
"\n"
"{\n"
"}", tokenizeAndStringify(code));
}
{
const char code[] = "void f(a, b) register char *a, *b;\n"
"{\n"
"}\n";
ASSERT_EQUALS("void f ( char * a , char * b )\n"
"{\n"
"}", tokenizeAndStringify(code));
}
}
void vardecl20() {
// #3700
const char code[] = "void a::b() const\n"
"{\n"
" register const int X = 0;\n"
"}\n";
ASSERT_EQUALS("void a :: b ( ) const\n"
"{\n"
"const int X = 0 ;\n"
"}", tokenizeAndStringify(code));
ASSERT_EQUALS("[test.cpp:1]: (debug) Executable scope 'b' with unknown function.\n", errout_str());
}
void vardecl21() { // type in namespace
// #4042 - a::b const *p = 0;
const char code1[] = "void f() {\n"
" a::b const *p = 0;\n"
"}\n";
ASSERT_EQUALS("void f ( ) {\n"
"const a :: b * p ; p = 0 ;\n"
"}"
, tokenizeAndStringify(code1));
// #4226 - ::a::b const *p = 0;
const char code2[] = "void f() {\n"
" ::a::b const *p = 0;\n"
"}\n";
ASSERT_EQUALS("void f ( ) {\n"
"const :: a :: b * p ; p = 0 ;\n"
"}"
, tokenizeAndStringify(code2));
}
void vardecl22() { // #4211 - segmentation fault
(void)tokenizeAndStringify("A<B<C<int>> >* p = 0;");
}
void vardecl23() { // #4276 - segmentation fault
ASSERT_THROW_INTERNAL(tokenizeAndStringify("class a { protected : template < class int x = 1 ; public : int f ( ) ; }"), SYNTAX);
}
void vardecl24() { // #4187 - variable declaration within lambda function
const char code1[] = "void f() {\n"
" std::for_each(ints.begin(), ints.end(), [](int val)\n"
" {\n"
" int temp = 0;\n"
" });\n"
"}";
const char expected1[] = "void f ( ) {\n"
"std :: for_each ( ints . begin ( ) , ints . end ( ) , [ ] ( int val )\n"
"{\n"
"int temp ; temp = 0 ;\n"
"} ) ;\n"
"}";
ASSERT_EQUALS(expected1, tokenizeAndStringify(code1));
const char code2[] = "void f(int j) {\n"
" g( [](){int temp = 0;} , j );\n"
"}";
const char expected2[] = "void f ( int j ) {\n"
"g ( [ ] ( ) { int temp ; temp = 0 ; } , j ) ;\n"
"}";
ASSERT_EQUALS(expected2, tokenizeAndStringify(code2));
}
void vardecl25() { // #4799 - segmentation fault
(void)tokenizeAndStringify("void A::func(P g) const {}\n"
"void A::a() {\n"
" b = new d( [this]( const P & p) -> double { return this->func(p);} );\n"
"}");
ignore_errout();
}
void vardecl26() { // #5907
const char code[] = "extern int *new, obj, player;";
const char expected[] = "extern int * new ; extern int obj ; extern int player ;";
ASSERT_EQUALS(expected, tokenizeAndStringify(code, true, Platform::Type::Native, false));
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
ASSERT_EQUALS("[test.cpp:1]: (debug) Scope::checkVariable found variable 'new' with varid 0.\n", errout_str());
}
void vardecl27() { // #7850 (segmentation fault)
const char code[] = "extern int foo(char);\n"
"void* class(char c) {\n"
" if (foo(c))\n"
" return 0;\n"
" return 0;\n"
"}";
(void)tokenizeAndStringify(code, /*expand=*/ true, Platform::Type::Native, false);
}
void vardecl28() {
const char code[] = "unsigned short f(void) {\n"
" unsigned short const int x = 1;\n"
" return x;\n"
"}";
ASSERT_EQUALS("unsigned short f ( ) {\n"
"const unsigned short x ; x = 1 ;\n"
"return x ;\n"
"}",
tokenizeAndStringify(code, /*expand=*/ true, Platform::Type::Native, false));
}
void vardecl29() { // #9282
{
const char code[] = "double f1() noexcept, f2(double) noexcept;";
ASSERT_EQUALS("double f1 ( ) noexcept ( true ) ; double f2 ( double ) noexcept ( true ) ;",
tokenizeAndStringify(code));
}
{
const char code[] = "class C {\n"
" double f1() const noexcept, f2 (double) const noexcept;\n"
"};\n";
ASSERT_EQUALS("class C {\n"
"double f1 ( ) const noexcept ( true ) ; double f2 ( double ) const noexcept ( true ) ;\n"
"} ;",
tokenizeAndStringify(code));
}
}
void vardecl30() {
const char code[] = "struct D {} const d;";
ASSERT_EQUALS("struct D { } ; struct D const d ;",
tokenizeAndStringify(code, true, Platform::Type::Native, true));
ASSERT_EQUALS("struct D { } ; struct D const d ;",
tokenizeAndStringify(code, true, Platform::Type::Native, false));
}
void vardecl31() {
{
const char code[] = "void foo() { int (*fptr)() = 0; }";
ASSERT_EQUALS("void foo ( ) { int ( * fptr ) ( ) ; fptr = 0 ; }", tokenizeAndStringify(code));
}
{
const char code[] = "void foo() { int (*fptr)(int) = 0; }";
ASSERT_EQUALS("void foo ( ) { int ( * fptr ) ( int ) ; fptr = 0 ; }", tokenizeAndStringify(code));
}
}
void volatile_variables() {
{
const char code[] = "volatile int a=0;\n"
"volatile int b=0;\n"
"volatile int c=0;\n";
const std::string actual(tokenizeAndStringify(code));
ASSERT_EQUALS("volatile int a ; a = 0 ;\nvolatile int b ; b = 0 ;\nvolatile int c ; c = 0 ;", actual);
}
{
const char code[] = "char *volatile s1, *volatile s2;\n"; // #11004
const std::string actual(tokenizeAndStringify(code));
ASSERT_EQUALS("char * volatile s1 ; char * volatile s2 ;", actual);
}
}
void simplifyKeyword() {
{
const char code[] = "void f (int a [ static 5] );";
ASSERT_EQUALS("void f ( int a [ 5 ] ) ;", tokenizeAndStringify(code));
}
{
const char in4[] = "struct B final : A { void foo(); };";
const char out4[] = "struct B : A { void foo ( ) ; } ;";
ASSERT_EQUALS(out4, tokenizeAndStringify(in4));
const char in5[] = "struct ArrayItemsValidator final {\n"
" SchemaError validate() const override {\n"
" for (; pos < value.size(); ++pos) {\n"
" }\n"
" return none;\n"
" }\n"
"};\n";
const char out5[] =
"struct ArrayItemsValidator {\n"
"SchemaError validate ( ) const override {\n"
"for ( ; pos < value . size ( ) ; ++ pos ) {\n"
"}\n"
"return none ;\n"
"}\n"
"} ;";
ASSERT_EQUALS(out5, tokenizeAndStringify(in5));
ASSERT_EQUALS(
"[test.cpp:3]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable pos\n",
errout_str());
}
{
// Ticket #8679
const char code[] = "thread_local void *thread_local_var; "
"__thread void *thread_local_var_2;";
ASSERT_EQUALS("static void * thread_local_var ; "
"void * thread_local_var_2 ;", tokenizeAndStringify(code));
}
ASSERT_EQUALS("class Fred { } ;", tokenizeAndStringify("class DLLEXPORT Fred final { };"));
}
void implicitIntConst() {
ASSERT_EQUALS("const int x ;", tokenizeAndStringify("const x;", true, Platform::Type::Native, false));
ASSERT_EQUALS("const int * x ;", tokenizeAndStringify("const *x;", true, Platform::Type::Native, false));
ASSERT_EQUALS("const int * f ( ) ;", tokenizeAndStringify("const *f();", true, Platform::Type::Native, false));
}
void implicitIntExtern() {
ASSERT_EQUALS("extern int x ;", tokenizeAndStringify("extern x;", true, Platform::Type::Native, false));
ASSERT_EQUALS("extern int * x ;", tokenizeAndStringify("extern *x;", true, Platform::Type::Native, false));
ASSERT_EQUALS("const int * f ( ) ;", tokenizeAndStringify("const *f();", true, Platform::Type::Native, false));
}
/**
* tokenize "signed i" => "signed int i"
*/
void implicitIntSigned1() {
{
const char code1[] = "void foo ( signed int , float ) ;";
ASSERT_EQUALS(code1, tokenizeAndStringify(code1));
}
{
const char code1[] = "signed i ;";
const char code2[] = "signed int i ;";
ASSERT_EQUALS(code2, tokenizeAndStringify(code1));
}
{
const char code1[] = "signed int i ;";
ASSERT_EQUALS(code1, tokenizeAndStringify(code1));
}
{
const char code1[] = "int signed i ;";
const char code2[] = "signed int i ;";
ASSERT_EQUALS(code2, tokenizeAndStringify(code1));
}
{
const char code1[] = "void f() { for (signed i=0; i<10; i++) {} }";
const char code2[] = "void f ( ) { for ( signed int i = 0 ; i < 10 ; i ++ ) { } }";
ASSERT_EQUALS(code2, tokenizeAndStringify(code1));
}
}
/**
* tokenize "unsigned i" => "unsigned int i"
* tokenize "unsigned" => "unsigned int"
*/
void implicitIntUnsigned1() {
// No changes..
{
const char code[] = "void foo ( unsigned int , float ) ;";
ASSERT_EQUALS(code, tokenizeAndStringify(code));
}
// insert "int" after "unsigned"..
{
const char code1[] = "unsigned i ;";
const char code2[] = "unsigned int i ;";
ASSERT_EQUALS(code2, tokenizeAndStringify(code1));
}
{
const char code1[] = "int unsigned i ;";
const char code2[] = "unsigned int i ;";
ASSERT_EQUALS(code2, tokenizeAndStringify(code1));
}
// insert "int" after "unsigned"..
{
const char code1[] = "void f() { for (unsigned i=0; i<10; i++) {} }";
const char code2[] = "void f ( ) { for ( unsigned int i = 0 ; i < 10 ; i ++ ) { } }";
ASSERT_EQUALS(code2, tokenizeAndStringify(code1));
}
// "extern unsigned x;" => "extern int x;"
{
const char code1[] = "; extern unsigned x;";
const char code2[] = "; extern unsigned int x ;";
ASSERT_EQUALS(code2, tokenizeAndStringify(code1));
}
}
void implicitIntUnsigned2() {
const char code[] = "i = (unsigned)j;";
const char expected[] = "i = ( unsigned int ) j ;";
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
}
// simplify "unsigned" when using templates..
void implicitIntUnsigned3() {
{
const char code[] = "; foo<unsigned>();";
const char expected[] = "; foo < unsigned int > ( ) ;";
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
}
{
const char code[] = "; foo<unsigned int>();";
const char expected[] = "; foo < unsigned int > ( ) ;";
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
}
}
void simplifyStdType() { // #4947, #4950, #4951
// unsigned long long
{
const char code[] = "long long unsigned int x;";
const char expected[] = "unsigned long long x ;";
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
}
{
const char code[] = "long long int unsigned x;";
const char expected[] = "unsigned long long x ;";
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
}
{
const char code[] = "unsigned long long int x;";
const char expected[] = "unsigned long long x ;";
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
}
{
const char code[] = "unsigned int long long x;";
const char expected[] = "unsigned long long x ;";
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
}
{
const char code[] = "int unsigned long long x;";
const char expected[] = "unsigned long long x ;";
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
}
{
const char code[] = "int long long unsigned x;";
const char expected[] = "unsigned long long x ;";
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
}
// signed long long
{
const char code[] = "long long signed int x;";
const char expected[] = "signed long long x ;";
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
}
{
const char code[] = "long long int signed x;";
const char expected[] = "signed long long x ;";
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
}
{
const char code[] = "signed long long int x;";
const char expected[] = "signed long long x ;";
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
}
{
const char code[] = "signed int long long x;";
const char expected[] = "signed long long x ;";
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
}
{
const char code[] = "int signed long long x;";
const char expected[] = "signed long long x ;";
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
}
{
const char code[] = "int long long signed x;";
const char expected[] = "signed long long x ;";
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
}
// unsigned short
{
const char code[] = "short unsigned int x;";
const char expected[] = "unsigned short x ;";
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
}
{
const char code[] = "short int unsigned x;";
const char expected[] = "unsigned short x ;";
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
}
{
const char code[] = "unsigned short int x;";
const char expected[] = "unsigned short x ;";
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
}
{
const char code[] = "unsigned int short x;";
const char expected[] = "unsigned short x ;";
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
}
{
const char code[] = "int unsigned short x;";
const char expected[] = "unsigned short x ;";
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
}
{
const char code[] = "int short unsigned x;";
const char expected[] = "unsigned short x ;";
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
}
// signed short
{
const char code[] = "short signed int x;";
const char expected[] = "signed short x ;";
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
}
{
const char code[] = "short int signed x;";
const char expected[] = "signed short x ;";
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
}
{
const char code[] = "signed short int x;";
const char expected[] = "signed short x ;";
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
}
{
const char code[] = "signed int short x;";
const char expected[] = "signed short x ;";
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
}
{
const char code[] = "int signed short x;";
const char expected[] = "signed short x ;";
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
}
{
const char code[] = "int short signed x;";
const char expected[] = "signed short x ;";
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
}
{
const char code[] = "unsigned static short const int i;";
const char expected[] = "static const unsigned short i ;";
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
}
{
const char code[] = "float complex x;";
const char expected[] = "float complex x ;";
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
}
{
const char code[] = "float complex x;";
const char expected[] = "_Complex float x ;";
ASSERT_EQUALS(expected, tokenizeAndStringify(code, true, Platform::Native, false));
}
{
const char code[] = "complex float x;";
const char expected[] = "_Complex float x ;";
ASSERT_EQUALS(expected, tokenizeAndStringify(code, true, Platform::Native, false));
}
{
const char code[] = "complex long double x;";
const char expected[] = "_Complex long double x ;";
ASSERT_EQUALS(expected, tokenizeAndStringify(code, true, Platform::Native, false));
}
{
const char code[] = "long double complex x;";
const char expected[] = "_Complex long double x ;";
ASSERT_EQUALS(expected, tokenizeAndStringify(code, true, Platform::Native, false));
}
{
const char code[] = "double complex;";
const char expected[] = "double complex ;";
ASSERT_EQUALS(expected, tokenizeAndStringify(code, true, Platform::Native, false));
}
}
void createLinks() {
{
const char code[] = "class A{\n"
" void f() {}\n"
"};";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
const Token *tok = tokenizer.tokens();
// A body {}
ASSERT_EQUALS(true, tok->linkAt(2) == tok->tokAt(9));
ASSERT_EQUALS(true, tok->linkAt(9) == tok->tokAt(2));
// f body {}
ASSERT_EQUALS(true, tok->linkAt(7) == tok->tokAt(8));
ASSERT_EQUALS(true, tok->linkAt(8) == tok->tokAt(7));
// f ()
ASSERT_EQUALS(true, tok->linkAt(5) == tok->tokAt(6));
ASSERT_EQUALS(true, tok->linkAt(6) == tok->tokAt(5));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "void f(){\n"
" char a[10];\n"
" char *b ; b = new char[a[0]];\n"
"};";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
const Token *tok = tokenizer.tokens();
// a[10]
ASSERT_EQUALS(true, tok->linkAt(7) == tok->tokAt(9));
ASSERT_EQUALS(true, tok->linkAt(9) == tok->tokAt(7));
// new char[]
ASSERT_EQUALS(true, tok->linkAt(19) == tok->tokAt(24));
ASSERT_EQUALS(true, tok->linkAt(24) == tok->tokAt(19));
// a[0]
ASSERT_EQUALS(true, tok->linkAt(21) == tok->tokAt(23));
ASSERT_EQUALS(true, tok->linkAt(23) == tok->tokAt(21));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "void f(){\n"
" foo(g());\n"
"};";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
const Token *tok = tokenizer.tokens();
// foo(
ASSERT_EQUALS(true, tok->linkAt(6) == tok->tokAt(10));
ASSERT_EQUALS(true, tok->linkAt(10) == tok->tokAt(6));
// g(
ASSERT_EQUALS(true, tok->linkAt(8) == tok->tokAt(9));
ASSERT_EQUALS(true, tok->linkAt(9) == tok->tokAt(8));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "bool foo(C<z> a, bar<int, x<float>>& f, int b) {\n"
" return(a<b && b>f);\n"
"}";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
const Token *tok = tokenizer.tokens();
// template<
ASSERT_EQUALS(true, tok->tokAt(6) == tok->linkAt(4));
ASSERT_EQUALS(true, tok->tokAt(4) == tok->linkAt(6));
// bar<
ASSERT_EQUALS(true, tok->tokAt(17) == tok->linkAt(10));
ASSERT_EQUALS(true, tok->tokAt(10) == tok->linkAt(17));
// x<
ASSERT_EQUALS(true, tok->tokAt(16) == tok->linkAt(14));
ASSERT_EQUALS(true, tok->tokAt(14) == tok->linkAt(16));
// a<b && b>f
ASSERT_EQUALS(true, nullptr == tok->linkAt(28));
ASSERT_EQUALS(true, nullptr == tok->linkAt(32));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "void foo() {\n"
" return static_cast<bar>(a);\n"
"}";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
const Token *tok = tokenizer.tokens();
// static_cast<
ASSERT_EQUALS(true, tok->tokAt(9) == tok->linkAt(7));
ASSERT_EQUALS(true, tok->tokAt(7) == tok->linkAt(9));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "void foo() {\n"
" nvwa<(x > y)> ERROR_nnn;\n"
"}";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
const Token *tok = tokenizer.tokens();
// nvwa<(x > y)>
ASSERT_EQUALS(true, tok->tokAt(12) == tok->linkAt(6));
ASSERT_EQUALS(true, tok->tokAt(6) == tok->linkAt(12));
ASSERT_EQUALS("", errout_str());
}
{
// #4860
const char code[] = "class A : public B<int> {};";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
const Token *tok = tokenizer.tokens();
// B<..>
ASSERT_EQUALS(true, tok->tokAt(5) == tok->linkAt(7));
ASSERT_EQUALS(true, tok->linkAt(5) == tok->tokAt(7));
ASSERT_EQUALS("", errout_str());
}
{
// #4860
const char code[] = "Bar<Typelist< int, Typelist< int, Typelist< int, FooNullType>>>>::set(1, 2, 3);";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
const Token *tok = tokenizer.tokens();
ASSERT_EQUALS(true, tok->tokAt(1) == tok->linkAt(18));
ASSERT_EQUALS(true, tok->tokAt(3) == tok->linkAt(17));
ASSERT_EQUALS(true, tok->tokAt(7) == tok->linkAt(16));
ASSERT_EQUALS(true, tok->tokAt(11) == tok->linkAt(15));
ASSERT_EQUALS("", errout_str());
}
{
// #5627
const char code[] = "new Foo<Bar>[10];";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
const Token *tok = tokenizer.tokens();
ASSERT_EQUALS(true, tok->tokAt(2) == tok->linkAt(4));
ASSERT_EQUALS(true, tok->tokAt(4) == tok->linkAt(2));
ASSERT_EQUALS(true, tok->tokAt(5) == tok->linkAt(7));
ASSERT_EQUALS(true, tok->tokAt(7) == tok->linkAt(5));
ASSERT_EQUALS("", errout_str());
}
{
// #6242
const char code[] = "func = integral_<uchar, int, double>;";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
const Token *tok = tokenizer.tokens();
ASSERT_EQUALS(true, tok->tokAt(3) == tok->linkAt(9));
ASSERT_EQUALS(true, tok->linkAt(3) == tok->tokAt(9));
ASSERT_EQUALS("", errout_str());
}
{
// if (a < b || c > d) { }
const char code[] = "{ if (a < b || c > d); }";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
const Token *tok = tokenizer.tokens();
ASSERT_EQUALS(true, tok->linkAt(3) == nullptr);
}
{
// bool f = a < b || c > d
const char code[] = "bool f = a < b || c > d;";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
const Token *tok = tokenizer.tokens();
ASSERT_EQUALS(true, tok->linkAt(4) == nullptr);
}
{
// template
const char code[] = "a < b || c > d;";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
const Token *tok = tokenizer.tokens();
ASSERT_EQUALS(true, tok->linkAt(1) == tok->tokAt(5));
}
{
// if (a < ... > d) { }
const char code[] = "{ if (a < b || c == 3 || d > e); }";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
const Token *tok = tokenizer.tokens();
ASSERT_EQUALS(true, tok->linkAt(3) == nullptr);
}
{
// template
const char code[] = "a<b==3 || c> d;";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
const Token *tok = tokenizer.tokens();
ASSERT_EQUALS(true, tok->linkAt(1) == tok->tokAt(7));
}
{
// template
const char code[] = "a<b || c==4> d;";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
const Token *tok = tokenizer.tokens();
ASSERT_EQUALS(true, tok->linkAt(1) == tok->tokAt(7));
}
{
const char code[] = "template < f = b || c > struct S;";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
const Token *tok = tokenizer.tokens();
ASSERT_EQUALS(true, tok->linkAt(1) == tok->tokAt(7));
ASSERT_EQUALS(true, tok->tokAt(1) == tok->linkAt(7));
}
{
const char code[] = "struct A : B<c&&d> {};";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
const Token *tok = tokenizer.tokens();
ASSERT_EQUALS(true, tok->linkAt(4) == tok->tokAt(8));
ASSERT_EQUALS(true, tok->tokAt(4) == tok->linkAt(8));
}
{
const char code[] = "Data<T&&>;";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
const Token *tok = tokenizer.tokens();
ASSERT_EQUALS(true, tok->linkAt(1) == tok->tokAt(4));
ASSERT_EQUALS(true, tok->tokAt(1) == tok->linkAt(4));
}
{
// #6601
const char code[] = "template<class R> struct FuncType<R(&)()> : FuncType<R()> { };";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
const Token *tok = tokenizer.tokens();
ASSERT_EQUALS(true, tok->linkAt(1) == tok->tokAt(4)); // <class R>
ASSERT_EQUALS(true, tok->linkAt(7) == tok->tokAt(14)); // <R(&)()>
ASSERT_EQUALS(true, tok->linkAt(9) == tok->tokAt(11)); // (&)
ASSERT_EQUALS(true, tok->linkAt(12) == tok->tokAt(13)); // ()
ASSERT_EQUALS(true, tok->linkAt(17) == tok->tokAt(21)); // <R()>
ASSERT_EQUALS(true, tok->linkAt(19) == tok->tokAt(20)); // ()
ASSERT_EQUALS(true, tok->linkAt(22) == tok->tokAt(23)); // {}
}
}
void createLinks2() {
{
// #7158
const char code[] = "enum { value = boost::mpl::at_c<B, C> };";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
const Token *tok = Token::findsimplematch(tokenizer.tokens(), "<");
ASSERT_EQUALS(true, tok->link() == tok->tokAt(4));
ASSERT_EQUALS(true, tok->linkAt(4) == tok);
}
{
// #7865
const char code[] = "template <typename T, typename U>\n"
"struct CheckedDivOp< T, U, typename std::enable_if<std::is_floating_point<T>::value || std::is_floating_point<U>::value>::type> {\n"
"};\n";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
const Token *tok1 = Token::findsimplematch(tokenizer.tokens(), "struct")->tokAt(2);
const Token *tok2 = Token::findsimplematch(tokenizer.tokens(), "{")->previous();
ASSERT_EQUALS(true, tok1->link() == tok2);
ASSERT_EQUALS(true, tok2->link() == tok1);
}
{
// #7975
const char code[] = "template <class C> X<Y&&Z, C*> copy() {};\n";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
const Token *tok1 = Token::findsimplematch(tokenizer.tokens(), "< Y");
const Token *tok2 = Token::findsimplematch(tok1, "> copy");
ASSERT_EQUALS(true, tok1->link() == tok2);
ASSERT_EQUALS(true, tok2->link() == tok1);
}
{
// #8006
const char code[] = "C<int> && a = b;";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
const Token *tok1 = tokenizer.tokens()->next();
const Token *tok2 = tok1->tokAt(2);
ASSERT_EQUALS(true, tok1->link() == tok2);
ASSERT_EQUALS(true, tok2->link() == tok1);
}
{
// #8115
const char code[] = "void Test(C<int> && c);";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
const Token *tok1 = Token::findsimplematch(tokenizer.tokens(), "<");
const Token *tok2 = tok1->tokAt(2);
ASSERT_EQUALS(true, tok1->link() == tok2);
ASSERT_EQUALS(true, tok2->link() == tok1);
}
{
// #8654
const char code[] = "template<int N> struct A {}; "
"template<int... Ns> struct foo : A<Ns>... {};";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
const Token *A = Token::findsimplematch(tokenizer.tokens(), "A <");
ASSERT_EQUALS(true, A->linkAt(1) == A->tokAt(3));
}
{
// #8851
const char code[] = "template<typename std::enable_if<!(std::value1) && std::value2>::type>"
"void basic_json() {}";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
ASSERT_EQUALS(true, Token::simpleMatch(tokenizer.tokens()->linkAt(1), "> void"));
}
{
// #9094 - template usage or comparison?
const char code[] = "a = f(x%x<--a==x>x);";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
ASSERT(nullptr == Token::findsimplematch(tokenizer.tokens(), "<")->link());
}
{
// #11319
const char code[] = "using std::same_as;\n"
"template<same_as<int> T>\n"
"void f();";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
const Token *tok1 = Token::findsimplematch(tokenizer.tokens(), "template <");
const Token *tok2 = Token ::findsimplematch(tokenizer.tokens(), "same_as <");
ASSERT(tok1->linkAt(1) == tok1->tokAt(7));
ASSERT(tok2->linkAt(1) == tok2->tokAt(3));
}
{
// #9131 - template usage or comparison?
const char code[] = "using std::list; list<t *> l;";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
ASSERT(nullptr != Token::findsimplematch(tokenizer.tokens(), "<")->link());
}
{
const char code[] = "using std::set;\n"
"void foo()\n"
"{\n"
" for (set<ParticleSource*>::iterator i = sources.begin(); i != sources.end(); ++i) {}\n"
"}";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
ASSERT(nullptr != Token::findsimplematch(tokenizer.tokens(), "<")->link());
}
{
// #8890
const char code[] = "void f() {\n"
" a<> b;\n"
" b.a<>::c();\n"
"}\n";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
ASSERT(nullptr != Token::findsimplematch(tokenizer.tokens(), "> ::")->link());
}
{
// #9136
const char code[] = "template <char> char * a;\n"
"template <char... b> struct c {\n"
" void d() { a<b...>[0]; }\n"
"};\n";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
ASSERT(nullptr != Token::findsimplematch(tokenizer.tokens(), "> [")->link());
}
{
// #9057
const char code[] = "template <bool> struct a;\n"
"template <bool b, typename> using c = typename a<b>::d;\n"
"template <typename e> using f = c<e() && sizeof(int), int>;\n"
"template <typename e, typename = f<e>> struct g {};\n"
"template <typename e> using baz = g<e>;\n";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
ASSERT(nullptr != Token::findsimplematch(tokenizer.tokens(), "> ;")->link());
}
{
// #9141
const char code[] = "struct a {\n"
" typedef int b;\n"
" operator b();\n"
"};\n"
"template <int> using c = a;\n"
"template <int d> c<d> e;\n"
"auto f = -e<1> == 0;\n";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
ASSERT(nullptr != Token::findsimplematch(tokenizer.tokens(), "> ==")->link());
}
{
// #9145
const char code[] = "template <typename a, a> struct b {\n"
" template <typename c> constexpr void operator()(c &&) const;\n"
"};\n"
"template <int d> struct e { b<int, d> f; };\n"
"template <int g> using h = e<g>;\n"
"template <int g> h<g> i;\n"
"template <typename a, a d>\n"
"template <typename c>\n"
"constexpr void b<a, d>::operator()(c &&) const {\n"
" i<3>.f([] {});\n"
"}\n";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
ASSERT(nullptr != Token::findsimplematch(tokenizer.tokens(), "> . f (")->link());
}
{
// #10491
const char code[] = "template <template <class> class> struct a;\n";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
const Token* tok1 = Token::findsimplematch(tokenizer.tokens(), "< class");
const Token* tok2 = Token::findsimplematch(tok1, "> class");
ASSERT_EQUALS(true, tok1->link() == tok2);
ASSERT_EQUALS(true, tok2->link() == tok1);
}
{
// #10491
const char code[] = "template <template <class> class> struct a;\n";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
const Token* tok1 = Token::findsimplematch(tokenizer.tokens(), "< template");
const Token* tok2 = Token::findsimplematch(tok1, "> struct");
ASSERT_EQUALS(true, tok1->link() == tok2);
ASSERT_EQUALS(true, tok2->link() == tok1);
}
{
// #10552
const char code[] = "v.value<QPair<int, int>>()\n";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
const Token* tok1 = Token::findsimplematch(tokenizer.tokens(), "< QPair");
const Token* tok2 = Token::findsimplematch(tok1, "> (");
ASSERT_EQUALS(true, tok1->link() == tok2);
ASSERT_EQUALS(true, tok2->link() == tok1);
}
{
// #10552
const char code[] = "v.value<QPair<int, int>>()\n";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
const Token* tok1 = Token::findsimplematch(tokenizer.tokens(), "< int");
const Token* tok2 = Token::findsimplematch(tok1, "> > (");
ASSERT_EQUALS(true, tok1->link() == tok2);
ASSERT_EQUALS(true, tok2->link() == tok1);
}
{
// #10615
const char code[] = "struct A : public B<__is_constructible()>{};\n";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
const Token* tok1 = Token::findsimplematch(tokenizer.tokens(), "< >");
const Token* tok2 = Token::findsimplematch(tok1, "> { } >");
ASSERT_EQUALS(true, tok1->link() == tok2);
ASSERT_EQUALS(true, tok2->link() == tok1);
}
{
// #10664
const char code[] = "class C1 : public T1<D2<C2>const> {};\n";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
const Token* tok1 = Token::findsimplematch(tokenizer.tokens(), "< C2");
const Token* tok2 = Token::findsimplematch(tok1, "> const");
ASSERT_EQUALS(true, tok1->link() == tok2);
ASSERT_EQUALS(true, tok2->link() == tok1);
}
{
// #11453
const char code[] = "template<typename T>\n"
"std::array<T, 1> a{};\n"
"void f() {\n"
" if (a<int>[0]) {}\n"
"}\n";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
const Token* tok1 = Token::findsimplematch(tokenizer.tokens(), "< int");
const Token* tok2 = Token::findsimplematch(tok1, "> [");
ASSERT_EQUALS(true, tok1->link() == tok2);
ASSERT_EQUALS(true, tok2->link() == tok1);
}
{
// #11490
const char code[] = "void g() {\n"
" int b[2] = {};\n"
" if (b[idx<1>]) {}\n"
"}\n";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
const Token* tok1 = Token::findsimplematch(tokenizer.tokens(), "< 1");
const Token* tok2 = Token::findsimplematch(tok1, "> ]");
ASSERT_EQUALS(true, tok1->link() == tok2);
ASSERT_EQUALS(true, tok2->link() == tok1);
}
{ // #11275
const char code[] = "void f() {\n"
" []<typename T>() {};\n"
"}\n";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
const Token* tok1 = Token::findsimplematch(tokenizer.tokens(), "< T");
const Token* tok2 = Token::findsimplematch(tok1, "> (");
ASSERT_EQUALS(true, tok1->link() == tok2);
ASSERT_EQUALS(true, tok2->link() == tok1);
}
{ // #11810
const char code[] = "void f() {\n"
" auto g = [] <typename A, typename B> (A a, B&& b) { return a < b; };\n"
"}\n";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
const Token* tok1 = Token::findsimplematch(tokenizer.tokens(), "< A");
const Token* tok2 = Token::findsimplematch(tok1, "> (");
ASSERT_EQUALS(true, tok1->link() == tok2);
ASSERT_EQUALS(true, tok2->link() == tok1);
}
{
const char code[] = "void f() {\n"
" auto g = [] <typename U> () {\n"
" return [] <typename T> () {};\n"
" };\n"
"}\n";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
const Token* tok1 = Token::findsimplematch(tokenizer.tokens(), "< T");
const Token* tok2 = Token::findsimplematch(tok1, "> (");
ASSERT_EQUALS(true, tok1->link() == tok2);
ASSERT_EQUALS(true, tok2->link() == tok1);
}
{
const char code[] = "struct S {\n" // #11840
" template<typename T, typename U>\n"
" void operator() (int);\n"
"};\n"
"void f() {\n"
" S s;\n"
" s.operator()<int, int>(1);\n"
"}\n";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
const Token* tok1 = Token::findsimplematch(tokenizer.tokens(), "< int");
const Token* tok2 = Token::findsimplematch(tok1, "> (");
ASSERT_EQUALS(true, tok1->link() == tok2);
ASSERT_EQUALS(true, tok2->link() == tok1);
}
{
const char code[] = "template<typename T>\n"
"auto f() {\n"
" return std::integral_constant<\n"
" bool,\n"
" std::is_same<typename T::size_type, std::size_t>::value && std::is_same<typename T::size_type, std::size_t>::value\n"
" >();\n"
"}\n";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
const Token* tok1 = Token::findsimplematch(tokenizer.tokens(), "< bool");
const Token* tok2 = Token::findsimplematch(tok1, "> (");
ASSERT_EQUALS(true, tok1->link() == tok2);
ASSERT_EQUALS(true, tok2->link() == tok1);
}
{
const char code[] = "double f() {\n"
" return std::is_same_v<int, double> ? 1e-7 : 1e-3;\n"
"}\n";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
const Token* tok1 = Token::findsimplematch(tokenizer.tokens(), "< int");
const Token* tok2 = Token::findsimplematch(tok1, "> ?");
ASSERT_EQUALS(true, tok1->link() == tok2);
ASSERT_EQUALS(true, tok2->link() == tok1);
}
}
void simplifyString() {
Tokenizer tokenizer(settings0, *this);
ASSERT_EQUALS("\"abc\"", tokenizer.simplifyString("\"abc\""));
ASSERT_EQUALS("\"\n\"", tokenizer.simplifyString("\"\\xa\""));
ASSERT_EQUALS("\"3\"", tokenizer.simplifyString("\"\\x33\""));
ASSERT_EQUALS("\"33\"", tokenizer.simplifyString("\"\\x333\""));
ASSERT_EQUALS("\"a\"", tokenizer.simplifyString("\"\\x61\""));
ASSERT_EQUALS("\"\n1\"", tokenizer.simplifyString("\"\\0121\""));
ASSERT_EQUALS("\"3\"", tokenizer.simplifyString("\"\\x33\""));
ASSERT_EQUALS("\" 0\"", tokenizer.simplifyString("\"\\0400\""));
ASSERT_EQUALS("\"\\nhello\"", tokenizer.simplifyString("\"\\nhello\""));
ASSERT_EQUALS("\"aaa\"", tokenizer.simplifyString("\"\\x61\\x61\\x61\""));
ASSERT_EQUALS("\"\n1\n1\n1\"", tokenizer.simplifyString("\"\\0121\\0121\\0121\""));
ASSERT_EQUALS("\"\\\\x61\"", tokenizer.simplifyString("\"\\\\x61\""));
ASSERT_EQUALS("\"b\"", tokenizer.simplifyString("\"\\x62\""));
ASSERT_EQUALS("\" 7\"", tokenizer.simplifyString("\"\\0407\""));
// terminate a string at null character.
ASSERT_EQUALS(std::string("\"a") + '\0' + "\"", tokenizer.simplifyString("\"a\\0\""));
}
void simplifyConst() {
ASSERT_EQUALS("void foo ( ) { const int x ; }",
tokenizeAndStringify("void foo(){ int const x;}"));
ASSERT_EQUALS("void foo ( ) { { } const long x ; }",
tokenizeAndStringify("void foo(){ {} long const x;}"));
ASSERT_EQUALS("void foo ( int b , const unsigned int x ) { }",
tokenizeAndStringify("void foo(int b,unsigned const x){}"));
ASSERT_EQUALS("void foo ( ) { bar ( ) ; const char x ; }",
tokenizeAndStringify("void foo(){ bar(); char const x;}"));
ASSERT_EQUALS("void foo ( const char x ) { }",
tokenizeAndStringify("void foo(char const x){}"));
ASSERT_EQUALS("void foo ( int b , const char x ) { }",
tokenizeAndStringify("void foo(int b,char const x){}"));
ASSERT_EQUALS("void foo ( ) { int * const x ; }",
tokenizeAndStringify("void foo(){ int * const x;}"));
ASSERT_EQUALS("const int foo ( ) ;", tokenizeAndStringify("int const foo ();"));
ASSERT_EQUALS("const int x ;", tokenizeAndStringify("int const x;"));
ASSERT_EQUALS("const unsigned int x ;", tokenizeAndStringify("unsigned const x;"));
ASSERT_EQUALS("const struct X x ;", tokenizeAndStringify("struct X const x;"));
}
void switchCase() {
ASSERT_EQUALS("void foo ( int i ) { switch ( i ) { case -1 : ; break ; } }",
tokenizeAndStringify("void foo (int i) { switch(i) { case -1: break; } }"));
//ticket #3227
ASSERT_EQUALS("void foo ( int n ) { switch ( n ) { label : ; case 1 : ; label1 : ; label2 : ; break ; } }",
tokenizeAndStringify("void foo(int n){ switch (n){ label: case 1: label1: label2: break; }}"));
//ticket #8345
ASSERT_EQUALS("void foo ( ) { switch ( 0 ) { case 0 : ; default : ; } }",
tokenizeAndStringify("void foo () { switch(0) case 0 : default : ; }"));
//ticket #8477
ASSERT_EQUALS("void foo ( ) { enum Anonymous0 : int { Six = 6 } ; return Six ; }",
tokenizeAndStringify("void foo () { enum : int { Six = 6 } ; return Six ; }"));
// ticket #8281
ASSERT_NO_THROW(tokenizeAndStringify("void lzma_decode(int i) { "
" bool state; "
" switch (i) "
" while (true) { "
" state=false; "
" case 1: "
" ; "
" }"
"}"));
// ticket #8417
ASSERT_NO_THROW(tokenizeAndStringify("void printOwnedAttributes(int mode) { "
" switch(mode) case 0: { break; } "
"}"));
ASSERT_THROW_INTERNAL(tokenizeAndStringify("void printOwnedAttributes(int mode) { "
" switch(mode) case 0: { break; } case 1: ; "
"}"),
SYNTAX);
}
void simplifyPointerToStandardType() {
// Pointer to standard type
ASSERT_EQUALS("char buf [ 100 ] ; readlink ( path , buf , 99 ) ;",
tokenizeAndStringify("char buf[100] ; readlink(path, &buf[0], 99);",
true, Platform::Type::Native, false));
ASSERT_EQUALS("", errout_str());
ASSERT_EQUALS("void foo ( char * c ) { if ( 1 == ( 1 & c [ 0 ] ) ) { } }",
tokenizeAndStringify("void foo(char *c) { if (1==(1 & c[0])) {} }",
true, Platform::Type::Native, false));
ASSERT_EQUALS("", filter_valueflow(errout_str()));
// Simplification of unknown type - C only
ASSERT_EQUALS("foo data [ 100 ] ; something ( foo ) ;",
tokenizeAndStringify("foo data[100]; something(&foo[0]);", true, Platform::Type::Native, false));
ASSERT_EQUALS("", errout_str());
// C++: No pointer simplification
ASSERT_EQUALS("foo data [ 100 ] ; something ( & foo [ 0 ] ) ;",
tokenizeAndStringify("foo data[100]; something(&foo[0]);"));
ASSERT_EQUALS("", errout_str());
}
void simplifyFunctionPointers1() {
ASSERT_EQUALS("void ( * f ) ( ) ;", tokenizeAndStringify("void (*f)();"));
ASSERT_EQUALS("void * ( * f ) ( ) ;", tokenizeAndStringify("void *(*f)();"));
ASSERT_EQUALS("unsigned int ( * f ) ( ) ;", tokenizeAndStringify("unsigned int (*f)();"));
ASSERT_EQUALS("unsigned int * ( * f ) ( ) ;", tokenizeAndStringify("unsigned int * (*f)();"));
ASSERT_EQUALS("void ( * f [ 2 ] ) ( ) ;", tokenizeAndStringify("void (*f[2])();"));
ASSERT_EQUALS("void ( * f [ 2 ] ) ( void ) ;", tokenizeAndStringify("typedef void func_t(void); func_t *f[2];"));
}
void simplifyFunctionPointers2() {
const char code[] = "typedef void (* PF)();"
"void f1 ( ) { }"
"PF pf = &f1;"
"PF pfs[] = { &f1, &f1 };";
const char expected[] = "void f1 ( ) { } "
"void ( * pf ) ( ) ; pf = & f1 ; "
"void ( * pfs [ ] ) ( ) = { & f1 , & f1 } ;";
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
}
void simplifyFunctionPointers3() {
// Related with ticket #2873
const char code[] = "void f() {\n"
"(void)(xy(*p)(0));"
"\n}";
const char expected[] = "void f ( ) {\n"
"( void ) ( xy ( * p ) ( 0 ) ) ;\n"
"}";
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
ASSERT_EQUALS(
"[test.cpp:2]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable p\n",
errout_str());
}
void simplifyFunctionPointers4() {
const char code[] = "struct S\n"
"{\n"
" typedef void (*FP)();\n"
" virtual FP getFP();\n"
"};";
const char expected[] = "1: struct S\n"
"2: {\n"
"3:\n"
"4: virtual void * getFP ( ) ;\n"
"5: } ;\n";
ASSERT_EQUALS(expected, tokenizeDebugListing(code));
}
void simplifyFunctionPointers5() {
const char code[] = ";void (*fp[])(int a) = {0,0,0};";
const char expected[] = "1: ; void ( * fp@1 [ ] ) ( int ) = { 0 , 0 , 0 } ;\n"; // TODO: Array dimension
ASSERT_EQUALS(expected, tokenizeDebugListing(code));
}
void simplifyFunctionPointers6() {
const char code1[] = "void (*fp(void))(int) {}";
const char expected1[] = "1: void * fp ( ) { }\n";
ASSERT_EQUALS(expected1, tokenizeDebugListing(code1));
const char code2[] = "std::string (*fp(void))(int);";
const char expected2[] = "1: std :: string * fp ( ) ;\n";
ASSERT_EQUALS(expected2, tokenizeDebugListing(code2));
}
void simplifyFunctionPointers7() {
const char code1[] = "void (X::*y)();";
const char expected1[] = "1: void ( * y@1 ) ( ) ;\n";
ASSERT_EQUALS(expected1, tokenizeDebugListing(code1));
}
void simplifyFunctionPointers8() {
const char code1[] = "int (*f)() throw(int);";
const char expected1[] = "1: int ( * f@1 ) ( ) ;\n";
ASSERT_EQUALS(expected1, tokenizeDebugListing(code1));
}
void simplifyFunctionPointers9() { // function call with function pointer
const char code1[] = "int f() { (*f)(); }";
const char expected1[] = "1: int f ( ) { ( * f ) ( ) ; }\n";
ASSERT_EQUALS(expected1, tokenizeDebugListing(code1));
const char code2[] = "int f() { return (*f)(); }";
const char expected2[] = "1: int f ( ) { return ( * f ) ( ) ; }\n";
ASSERT_EQUALS(expected2, tokenizeDebugListing(code2));
const char code3[] = "int f() { throw (*f)(); }";
const char expected3[] = "1: int f ( ) { throw ( * f ) ( ) ; }\n";
ASSERT_EQUALS(expected3, tokenizeDebugListing(code3));
}
void removedeclspec() {
ASSERT_EQUALS("a b", tokenizeAndStringify("a __declspec ( dllexport ) b"));
ASSERT_EQUALS("a b", tokenizeAndStringify("a _declspec ( dllexport ) b"));
ASSERT_EQUALS("int a ;", tokenizeAndStringify("__declspec(thread) __declspec(align(32)) int a;"));
ASSERT_EQUALS("int i ;", tokenizeAndStringify("__declspec(allocate(\"mycode\")) int i;"));
ASSERT_EQUALS("struct IUnknown ;", tokenizeAndStringify("struct __declspec(uuid(\"00000000-0000-0000-c000-000000000046\")) IUnknown;"));
ASSERT_EQUALS("__property int x [ ] ;", tokenizeAndStringify("__declspec(property(get=GetX, put=PutX)) int x[];"));
}
void removeattribute() {
ASSERT_EQUALS("short array [ 3 ] ;", tokenizeAndStringify("short array[3] __attribute__ ((aligned));"));
ASSERT_EQUALS("int x [ 2 ] ;", tokenizeAndStringify("int x[2] __attribute__ ((packed));"));
ASSERT_EQUALS("int vecint ;", tokenizeAndStringify("int __attribute__((mode(SI))) __attribute__((vector_size (16))) vecint;"));
// alternate spelling #5328
ASSERT_EQUALS("short array [ 3 ] ;", tokenizeAndStringify("short array[3] __attribute ((aligned));"));
ASSERT_EQUALS("int x [ 2 ] ;", tokenizeAndStringify("int x[2] __attribute ((packed));"));
ASSERT_EQUALS("int vecint ;", tokenizeAndStringify("int __attribute((mode(SI))) __attribute((vector_size (16))) vecint;"));
ASSERT_EQUALS("struct Payload_IR_config { uint8_t tap [ 16 ] ; } ;", tokenizeAndStringify("struct __attribute__((packed, gcc_struct)) Payload_IR_config { uint8_t tap[16]; };"));
}
void functionAttributeBefore1() {
const char code[] = "void __attribute__((pure)) __attribute__((nothrow)) __attribute__((const)) func1();\n"
"void __attribute__((__pure__)) __attribute__((__nothrow__)) __attribute__((__const__)) func2();\n"
"void __attribute__((nothrow)) __attribute__((pure)) __attribute__((const)) func3();\n"
"void __attribute__((__nothrow__)) __attribute__((__pure__)) __attribute__((__const__)) func4();\n"
"void __attribute__((noreturn)) func5();\n"
"void __attribute__((__visibility__(\"default\"))) func6();";
const char expected[] = "void func1 ( ) ; void func2 ( ) ; void func3 ( ) ; void func4 ( ) ; void func5 ( ) ; void func6 ( ) ;";
// tokenize..
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
// Expected result..
ASSERT_EQUALS(expected, tokenizer.tokens()->stringifyList(nullptr, false));
const Token * func1 = Token::findsimplematch(tokenizer.tokens(), "func1");
const Token * func2 = Token::findsimplematch(tokenizer.tokens(), "func2");
const Token * func3 = Token::findsimplematch(tokenizer.tokens(), "func3");
const Token * func4 = Token::findsimplematch(tokenizer.tokens(), "func4");
const Token * func5 = Token::findsimplematch(tokenizer.tokens(), "func5");
const Token * func6 = Token::findsimplematch(tokenizer.tokens(), "func6");
ASSERT(func1 && func1->isAttributePure() && func1->isAttributeNothrow() && func1->isAttributeConst() && !func1->isAttributeExport());
ASSERT(func2 && func2->isAttributePure() && func2->isAttributeNothrow() && func2->isAttributeConst() && !func2->isAttributeExport());
ASSERT(func3 && func3->isAttributePure() && func3->isAttributeNothrow() && func3->isAttributeConst() && !func3->isAttributeExport());
ASSERT(func4 && func4->isAttributePure() && func4->isAttributeNothrow() && func4->isAttributeConst() && !func4->isAttributeExport());
ASSERT(func5 && func5->isAttributeNoreturn());
ASSERT(func6 && func6->isAttributeExport());
}
void functionAttributeBefore2() {
const char code[] = "extern vas_f *VAS_Fail __attribute__((__noreturn__));";
const char expected[] = "extern vas_f * VAS_Fail ;";
// tokenize..
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
ASSERT_EQUALS(expected, tokenizer.tokens()->stringifyList(nullptr, false));
const Token * VAS_Fail = Token::findsimplematch(tokenizer.tokens(), "VAS_Fail");
ASSERT(VAS_Fail && VAS_Fail->isAttributeNoreturn());
}
void functionAttributeBefore3() { // #10978
const char code[] = "void __attribute__((__noreturn__)) (*func_notret)(void);";
const char expected[] = "void ( * func_notret ) ( void ) ;";
// tokenize..
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
ASSERT_EQUALS(expected, tokenizer.tokens()->stringifyList(nullptr, false));
const Token* func_notret = Token::findsimplematch(tokenizer.tokens(), "func_notret");
ASSERT(func_notret && func_notret->isAttributeNoreturn());
}
void functionAttributeBefore4() {
const char code[] = "__attribute__((const)) int& foo();";
const char expected[] = "int & foo ( ) ;";
// tokenize..
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
ASSERT_EQUALS(expected, tokenizer.tokens()->stringifyList(nullptr, false));
const Token* foo = Token::findsimplematch(tokenizer.tokens(), "foo");
ASSERT(foo && foo->isAttributeConst());
}
void functionAttributeBefore5() { // __declspec(dllexport)
const char code[] = "void __declspec(dllexport) func1();\n";
const char expected[] = "void func1 ( ) ;";
// tokenize..
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
// Expected result..
ASSERT_EQUALS(expected, tokenizer.tokens()->stringifyList(nullptr, false));
const Token * func1 = Token::findsimplematch(tokenizer.tokens(), "func1");
ASSERT(func1 && func1->isAttributeExport());
}
void functionAttributeAfter1() {
const char code[] = "void func1() __attribute__((pure)) __attribute__((nothrow)) __attribute__((const));\n"
"void func2() __attribute__((__pure__)) __attribute__((__nothrow__)) __attribute__((__const__));\n"
"void func3() __attribute__((nothrow)) __attribute__((pure)) __attribute__((const));\n"
"void func4() __attribute__((__nothrow__)) __attribute__((__pure__)) __attribute__((__const__));"
"void func5() __attribute__((noreturn));";
const char expected[] = "void func1 ( ) ; void func2 ( ) ; void func3 ( ) ; void func4 ( ) ; void func5 ( ) ;";
// tokenize..
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
// Expected result..
ASSERT_EQUALS(expected, tokenizer.tokens()->stringifyList(nullptr, false));
const Token * func1 = Token::findsimplematch(tokenizer.tokens(), "func1");
const Token * func2 = Token::findsimplematch(tokenizer.tokens(), "func2");
const Token * func3 = Token::findsimplematch(tokenizer.tokens(), "func3");
const Token * func4 = Token::findsimplematch(tokenizer.tokens(), "func4");
const Token * func5 = Token::findsimplematch(tokenizer.tokens(), "func5");
ASSERT(func1 && func1->isAttributePure() && func1->isAttributeNothrow() && func1->isAttributeConst());
ASSERT(func2 && func2->isAttributePure() && func2->isAttributeNothrow() && func2->isAttributeConst());
ASSERT(func3 && func3->isAttributePure() && func3->isAttributeNothrow() && func3->isAttributeConst());
ASSERT(func4 && func4->isAttributePure() && func4->isAttributeNothrow() && func4->isAttributeConst());
ASSERT(func5 && func5->isAttributeNoreturn());
}
void functionAttributeAfter2() {
const char code[] = "class foo {\n"
"public:\n"
" bool operator==(const foo &) __attribute__((__pure__));\n"
"};";
const char expected[] = "class foo { public: bool operator== ( const foo & ) ; } ;";
// tokenize..
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
// Expected result..
ASSERT_EQUALS(expected, tokenizer.tokens()->stringifyList(nullptr, false));
const Token *tok = Token::findsimplematch(tokenizer.tokens(), "operator==");
ASSERT(tok && tok->isAttributePure());
}
void functionAttributeListBefore() {
const char code[] = "void __attribute__((pure,nothrow,const)) func1();\n"
"void __attribute__((__pure__,__nothrow__,__const__)) func2();\n"
"void __attribute__((nothrow,pure,const)) func3();\n"
"void __attribute__((__nothrow__,__pure__,__const__)) func4();\n"
"void __attribute__((noreturn,format(printf,1,2))) func5();\n"
"void __attribute__((__nothrow__)) __attribute__((__pure__,__const__)) func6();\n"
"void __attribute__((__nothrow__,__pure__)) __attribute__((__const__)) func7();\n"
"void __attribute__((noreturn)) __attribute__(()) __attribute__((nothrow,pure,const)) func8();";
const char expected[] = "void func1 ( ) ; void func2 ( ) ; void func3 ( ) ; void func4 ( ) ; void func5 ( ) ; "
"void func6 ( ) ; void func7 ( ) ; void func8 ( ) ;";
// tokenize..
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
// Expected result..
ASSERT_EQUALS(expected, tokenizer.tokens()->stringifyList(nullptr, false));
const Token * func1 = Token::findsimplematch(tokenizer.tokens(), "func1");
const Token * func2 = Token::findsimplematch(tokenizer.tokens(), "func2");
const Token * func3 = Token::findsimplematch(tokenizer.tokens(), "func3");
const Token * func4 = Token::findsimplematch(tokenizer.tokens(), "func4");
const Token * func5 = Token::findsimplematch(tokenizer.tokens(), "func5");
const Token * func6 = Token::findsimplematch(tokenizer.tokens(), "func6");
const Token * func7 = Token::findsimplematch(tokenizer.tokens(), "func7");
const Token * func8 = Token::findsimplematch(tokenizer.tokens(), "func8");
ASSERT(func1 && func1->isAttributePure() && func1->isAttributeNothrow() && func1->isAttributeConst());
ASSERT(func2 && func2->isAttributePure() && func2->isAttributeNothrow() && func2->isAttributeConst());
ASSERT(func3 && func3->isAttributePure() && func3->isAttributeNothrow() && func3->isAttributeConst());
ASSERT(func4 && func4->isAttributePure() && func4->isAttributeNothrow() && func4->isAttributeConst());
ASSERT(func5 && func5->isAttributeNoreturn());
ASSERT(func6 && func6->isAttributePure() && func6->isAttributeNothrow() && func6->isAttributeConst());
ASSERT(func7 && func7->isAttributePure() && func7->isAttributeNothrow() && func7->isAttributeConst());
ASSERT(func8 && func8->isAttributeNoreturn() && func8->isAttributePure() && func8->isAttributeNothrow() && func8->isAttributeConst());
}
void functionAttributeListAfter() {
const char code[] = "void func1() __attribute__((pure,nothrow,const));\n"
"void func2() __attribute__((__pure__,__nothrow__,__const__));\n"
"void func3() __attribute__((nothrow,pure,const));\n"
"void func4() __attribute__((__nothrow__,__pure__,__const__));\n"
"void func5() __attribute__((noreturn,format(printf,1,2)));\n"
"void func6() __attribute__((__nothrow__)) __attribute__((__pure__,__const__));\n"
"void func7() __attribute__((__nothrow__,__pure__)) __attribute__((__const__));\n"
"void func8() __attribute__((noreturn)) __attribute__(()) __attribute__((nothrow,pure,const));";
const char expected[] = "void func1 ( ) ; void func2 ( ) ; void func3 ( ) ; void func4 ( ) ; void func5 ( ) ; "
"void func6 ( ) ; void func7 ( ) ; void func8 ( ) ;";
// tokenize..
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
// Expected result..
ASSERT_EQUALS(expected, tokenizer.tokens()->stringifyList(nullptr, false));
const Token * func1 = Token::findsimplematch(tokenizer.tokens(), "func1");
const Token * func2 = Token::findsimplematch(tokenizer.tokens(), "func2");
const Token * func3 = Token::findsimplematch(tokenizer.tokens(), "func3");
const Token * func4 = Token::findsimplematch(tokenizer.tokens(), "func4");
const Token * func5 = Token::findsimplematch(tokenizer.tokens(), "func5");
const Token * func6 = Token::findsimplematch(tokenizer.tokens(), "func6");
const Token * func7 = Token::findsimplematch(tokenizer.tokens(), "func7");
const Token * func8 = Token::findsimplematch(tokenizer.tokens(), "func8");
ASSERT(func1 && func1->isAttributePure() && func1->isAttributeNothrow() && func1->isAttributeConst());
ASSERT(func2 && func2->isAttributePure() && func2->isAttributeNothrow() && func2->isAttributeConst());
ASSERT(func3 && func3->isAttributePure() && func3->isAttributeNothrow() && func3->isAttributeConst());
ASSERT(func4 && func4->isAttributePure() && func4->isAttributeNothrow() && func4->isAttributeConst());
ASSERT(func5 && func5->isAttributeNoreturn());
ASSERT(func6 && func6->isAttributePure() && func6->isAttributeNothrow() && func6->isAttributeConst());
ASSERT(func7 && func7->isAttributePure() && func7->isAttributeNothrow() && func7->isAttributeConst());
ASSERT(func8 && func8->isAttributeNoreturn() && func8->isAttributePure() && func8->isAttributeNothrow() && func8->isAttributeConst());
}
void splitTemplateRightAngleBrackets() {
{
const char code[] = "; z = x < 0 ? x >> y : x >> y;";
ASSERT_EQUALS("; z = x < 0 ? x >> y : x >> y ;", tokenizeAndStringify(code));
}
{
// ftp://ftp.de.debian.org/debian/pool/main/f/ffmpeg/ffmpeg_4.3.1.orig.tar.xz
// ffmpeg-4.3.1/libavcodec/mpeg4videodec.c:376
const char code[] = "void f ( ) {\n"
" int shift_y = ctx->sprite_shift[0];\n"
" int shift_c = ctx->sprite_shift[1];\n"
" if ( shift_c < 0 || shift_y < 0 ||\n"
" FFABS ( sprite_offset [ 0 ] [ i ] ) >= INT_MAX >> shift_y ||\n"
" FFABS ( sprite_offset [ 1 ] [ i ] ) >= INT_MAX >> shift_c ||\n"
" FFABS ( sprite_delta [ 0 ] [ i ] ) >= INT_MAX >> shift_y ||\n"
" FFABS ( sprite_delta [ 1 ] [ i ] ) >= INT_MAX >> shift_y ) ;\n"
"}";
ASSERT_EQUALS(std::string::npos, tokenizeAndStringify(code).find("> >"));
ASSERT_EQUALS(
"[test.cpp:2]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable sprite_shift\n",
errout_str());
}
{
const char code[] = "struct S { bool vector; };\n"
"struct T { std::vector<std::shared_ptr<int>> v; };\n";
ASSERT_EQUALS("struct S { bool vector ; } ;\n"
"struct T { std :: vector < std :: shared_ptr < int > > v ; } ;",
tokenizeAndStringify(code));
ASSERT_EQUALS("", errout_str());
}
}
void cpp03template1() {
{
const char code[] = "template<typename> struct extent {};";
ASSERT_EQUALS("template < typename > struct extent { } ;", tokenizeAndStringify(code));
}
{
const char code[] = "template<typename> struct extent;";
ASSERT_EQUALS("template < typename > struct extent ;", tokenizeAndStringify(code));
}
{
const char code[] = "template<typename, unsigned = 0> struct extent;";
ASSERT_EQUALS("template < typename , unsigned int = 0 > struct extent ;", tokenizeAndStringify(code));
}
}
void cpp0xtemplate1() {
const char code[] = "template <class T>\n"
"void fn2 (T t = []{return 1;}())\n"
"{}\n"
"int main()\n"
"{\n"
" fn2<int>();\n"
"}\n";
ASSERT_EQUALS("void fn2<int> ( int t = [ ] { return 1 ; } ( ) ) ;\n"
"\n"
"int main ( )\n"
"{\n"
"fn2<int> ( ) ;\n"
"}\n"
"void fn2<int> ( int t = [ ] { return 1 ; } ( ) )\n"
"{ }", tokenizeAndStringify(code));
}
void cpp0xtemplate2() {
// tokenize ">>" into "> >"
const char code[] = "list<list<int>> ints;\n";
ASSERT_EQUALS("list < list < int > > ints ;", tokenizeAndStringify(code));
}
void cpp0xtemplate3() {
// #2549
const char code[] = "template<class T, T t = (T)0>\n"
"struct S\n"
"{};\n"
"S<int> s;\n";
ASSERT_EQUALS("struct S<int,(int)0> ;\n"
"\n"
"\n"
"S<int,(int)0> s ;\n"
"struct S<int,(int)0>\n"
"{ } ;",
tokenizeAndStringify(code));
}
void cpp0xtemplate4() { // #6181, #6354, #6414
// #6181
ASSERT_NO_THROW(tokenizeAndStringify("class A; "
"template <class T> class Disposer; "
"template <typename T, class D = Disposer<T>> class Shim {}; "
"class B : public Shim<A> {};"));
// #6354 (segmentation fault)
(void)tokenizeAndStringify("template <class ELFT> class ELFObjectImage {}; "
"ObjectImage *createObjectImage() { "
" return new ELFObjectImage<ELFType<little>>(Obj); "
"} "
"void resolveX86_64Relocation() { "
" reinterpret_cast<int>(0); "
"}");
// #6414
ASSERT_NO_THROW(tokenizeAndStringify("template<typename value_type, typename function_type> "
"value_type Base(const value_type x, const value_type dx, function_type func, int type_deriv) { "
" return 0.0; "
"}; "
"namespace { "
" template<class DC> class C { "
" void Fun(int G, const double x); "
" }; "
" template<class DC> void C<DC>::Fun(int G, const double x) {"
" Base<double, CDFFunctor<DC>>(2, 2, f, 0); "
" }; "
" template<class DC> class C2 {}; "
"}"));
ignore_errout();
}
void cpp0xtemplate5() { // #9154
{
const char code[] = "struct s<x<u...>>;";
ASSERT_EQUALS("struct s < x < u ... > > ;",
tokenizeAndStringify(code));
}
{
const char code[] = "template <class f> using c = e<i<q<f,r>,b...>>;";
ASSERT_EQUALS("template < class f > using c = e < i < q < f , r > , b ... > > ;",
tokenizeAndStringify(code));
}
{
const char code[] = "struct s<x<u...>> { };";
ASSERT_EQUALS("struct s < x < u ... > > { } ;",
tokenizeAndStringify(code));
}
{
const char code[] = "struct q : s<x<u...>> { };";
ASSERT_EQUALS("struct q : s < x < u ... > > { } ;",
tokenizeAndStringify(code));
}
{
const char code[] = "struct q : private s<x<u...>> { };";
ASSERT_EQUALS("struct q : private s < x < u ... > > { } ;",
tokenizeAndStringify(code));
}
}
void cpp14template() { // Ticket #6708
(void)tokenizeAndStringify("template <typename T> "
"decltype(auto) forward(T& t) { return 0; }");
ASSERT_EQUALS("[test.cpp:1]: (debug) auto token with no type.\n", errout_str());
}
void arraySize() {
ASSERT_EQUALS("; int a [ 3 ] = { 1 , 2 , 3 } ;", tokenizeAndStringify(";int a[]={1,2,3};"));
ASSERT_EQUALS("; int a [ 3 ] = { 1 , 2 , 3 } ;", tokenizeAndStringify(";int a[]={1,2,3,};"));
ASSERT_EQUALS("; foo a [ 3 ] = { { 1 , 2 } , { 3 , 4 } , { 5 , 6 } } ;", tokenizeAndStringify(";foo a[]={{1,2},{3,4},{5,6}};"));
ASSERT_EQUALS("; int a [ 1 ] = { foo < bar1 , bar2 > ( 123 , 4 ) } ;", tokenizeAndStringify(";int a[]={foo<bar1,bar2>(123,4)};"));
ASSERT_EQUALS("; int a [ 2 ] = { b > c ? 1 : 2 , 3 } ;", tokenizeAndStringify(";int a[]={ b>c?1:2,3};"));
ASSERT_EQUALS("int main ( ) { int a [ 2 ] = { b < c ? 1 : 2 , 3 } }", tokenizeAndStringify("int main(){int a[]={b<c?1:2,3}}"));
ASSERT_EQUALS(
"[test.cpp:1]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable b\n",
errout_str());
ASSERT_EQUALS("; int a [ 3 ] = { ABC , 2 , 3 } ;", tokenizeAndStringify(";int a[]={ABC,2,3};"));
ASSERT_EQUALS("; int a [ 3 ] = { [ 2 ] = 5 } ;", tokenizeAndStringify(";int a[]={ [2] = 5 };"));
ASSERT_EQUALS("; int a [ 5 ] = { 1 , 2 , [ 2 ] = 5 , 3 , 4 } ;", tokenizeAndStringify(";int a[]={ 1, 2, [2] = 5, 3, 4 };"));
ASSERT_EQUALS("; int a [ ] = { 1 , 2 , [ x ] = 5 , 3 , 4 } ;", tokenizeAndStringify(";int a[]={ 1, 2, [x] = 5, 3, 4 };"));
ASSERT_EQUALS("; const char c [ 4 ] = \"abc\" ;", tokenizeAndStringify(";const char c[] = { \"abc\" };"));
}
void arraySizeAfterValueFlow() {
const char code[] = "enum {X=10}; int a[] = {[X]=1};";
ASSERT_EQUALS("enum Anonymous0 { X = 10 } ; int a [ 11 ] = { [ X ] = 1 } ;", tokenizeAndStringify(code));
}
void labels() {
ASSERT_EQUALS("void f ( ) { ab : ; a = 0 ; }", tokenizeAndStringify("void f() { ab: a=0; }"));
//ticket #3176
ASSERT_EQUALS("void f ( ) { ab : ; ( * func ) ( ) ; }", tokenizeAndStringify("void f() { ab: (*func)(); }"));
//with '*' operator
ASSERT_EQUALS("void f ( ) { ab : ; * b = 0 ; }", tokenizeAndStringify("void f() { ab: *b=0; }"));
ASSERT_EQUALS("void f ( ) { ab : ; * * b = 0 ; }", tokenizeAndStringify("void f() { ab: **b=0; }"));
//with '&' operator
ASSERT_EQUALS("void f ( ) { ab : ; & b = 0 ; }", tokenizeAndStringify("void f() { ab: &b=0; }"));
ASSERT_EQUALS("void f ( ) { ab : ; & ( b . x ) = 0 ; }", tokenizeAndStringify("void f() { ab: &(b->x)=0; }"));
//with '(' parentheses
ASSERT_EQUALS("void f ( ) { ab : ; * ( * b ) . x = 0 ; }", tokenizeAndStringify("void f() { ab: *(* b)->x=0; }"));
ASSERT_EQUALS("void f ( ) { ab : ; ( * * b ) . x = 0 ; }", tokenizeAndStringify("void f() { ab: (** b).x=0; }"));
ASSERT_EQUALS("void f ( ) { ab : ; & ( * b . x ) = 0 ; }", tokenizeAndStringify("void f() { ab: &(*b.x)=0; }"));
//with '{' parentheses
ASSERT_EQUALS("void f ( ) { ab : ; { b = 0 ; } }", tokenizeAndStringify("void f() { ab: {b=0;} }"));
ASSERT_EQUALS("void f ( ) { ab : ; { * b = 0 ; } }", tokenizeAndStringify("void f() { ab: { *b=0;} }"));
ASSERT_EQUALS("void f ( ) { ab : ; { & b = 0 ; } }", tokenizeAndStringify("void f() { ab: { &b=0;} }"));
ASSERT_EQUALS("void f ( ) { ab : ; { & ( * b . x ) = 0 ; } }", tokenizeAndStringify("void f() { ab: {&(*b.x)=0;} }"));
//with unhandled MACRO() code
ASSERT_THROW_INTERNAL(tokenizeAndStringify("void f() { MACRO(ab: b=0;, foo)}"), UNKNOWN_MACRO);
ASSERT_EQUALS("void f ( ) { MACRO ( bar , ab : { & ( * b . x ) = 0 ; } ) }", tokenizeAndStringify("void f() { MACRO(bar, ab: {&(*b.x)=0;})}"));
ignore_errout();
}
void simplifyInitVar() {
{
const char code[] = "int i ; int p(0);";
ASSERT_EQUALS("int i ; int p ; p = 0 ;", tokenizeAndStringify(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "int i; int *p(0);";
ASSERT_EQUALS("int i ; int * p ; p = 0 ;", tokenizeAndStringify(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "int p(0);";
ASSERT_EQUALS("int p ; p = 0 ;", tokenizeAndStringify(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "int *p(0);";
ASSERT_EQUALS("int * p ; p = 0 ;", tokenizeAndStringify(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "int i ; int p(i);";
ASSERT_EQUALS("int i ; int p ; p = i ;", tokenizeAndStringify(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "int i; int *p(&i);";
ASSERT_EQUALS("int i ; int * p ; p = & i ;", tokenizeAndStringify(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "int i; void *p(&i);";
ASSERT_EQUALS("int i ; void * p ; p = & i ;", tokenizeAndStringify(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "struct S { }; struct S s; struct S *p(&s);";
ASSERT_EQUALS("struct S { } ; struct S s ; struct S * p ; p = & s ;", tokenizeAndStringify(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "struct S { }; S s; S *p(&s);";
ASSERT_EQUALS("struct S { } ; S s ; S * p ; p = & s ;", tokenizeAndStringify(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "union S { int i; float f; }; union S s; union S *p(&s);";
ASSERT_EQUALS("union S { int i ; float f ; } ; union S s ; union S * p ; p = & s ;", tokenizeAndStringify(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "union S { int i; float f; }; S s; S *p(&s);";
ASSERT_EQUALS("union S { int i ; float f ; } ; S s ; S * p ; p = & s ;", tokenizeAndStringify(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "class C { }; class C c; class C *p(&c);";
ASSERT_EQUALS("class C { } ; class C c ; class C * p ; p = & c ;", tokenizeAndStringify(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "class C { }; C c; C *p(&c);";
ASSERT_EQUALS("class C { } ; C c ; C * p ; p = & c ;", tokenizeAndStringify(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "struct S { }; struct S s; struct S s1(s);";
ASSERT_EQUALS("struct S { } ; struct S s ; struct S s1 ( s ) ;", tokenizeAndStringify(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "struct S { }; S s; S s1(s);";
ASSERT_EQUALS("struct S { } ; S s ; S s1 ( s ) ;", tokenizeAndStringify(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "struct S { }; struct S s; struct S s1(&s);";
ASSERT_EQUALS("struct S { } ; struct S s ; struct S s1 ( & s ) ;", tokenizeAndStringify(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "struct S { }; S s; S s1(&s);";
ASSERT_EQUALS("struct S { } ; S s ; S s1 ( & s ) ;", tokenizeAndStringify(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "class S { int function(); };";
ASSERT_EQUALS("class S { int function ( ) ; } ;", tokenizeAndStringify(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "class S { int function(void); };";
ASSERT_EQUALS("class S { int function ( ) ; } ;", tokenizeAndStringify(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "class S { int function(int); };";
ASSERT_EQUALS("class S { int function ( int ) ; } ;", tokenizeAndStringify(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "int function(void);";
ASSERT_EQUALS("int function ( ) ;", tokenizeAndStringify(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "int function(int);";
ASSERT_EQUALS("int function ( int ) ;", tokenizeAndStringify(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "extern int function(void);";
ASSERT_EQUALS("extern int function ( ) ;", tokenizeAndStringify(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "int function1(void); int function2(void);";
ASSERT_EQUALS("int function1 ( ) ; int function2 ( ) ;", tokenizeAndStringify(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "int function(A);";
// We can't tell if this a function prototype or a variable without knowing
// what A is. Since A is undefined, just leave it alone.
ASSERT_EQUALS("int function ( A ) ;", tokenizeAndStringify(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "int i; int function(A);";
ASSERT_EQUALS("int i ; int function ( A ) ;", tokenizeAndStringify(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "class A { } ; int foo(A);";
ASSERT_EQUALS("class A { } ; int foo ( A ) ;", tokenizeAndStringify(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "class A { } ; A a; int foo(a);";
ASSERT_EQUALS("class A { } ; A a ; int foo ; foo = a ;", tokenizeAndStringify(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "int x(f());";
ASSERT_EQUALS("int x ; x = f ( ) ;", tokenizeAndStringify(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "{ return doSomething(X), 0; }";
ASSERT_EQUALS("{ return doSomething ( X ) , 0 ; }", tokenizeAndStringify(code));
ASSERT_EQUALS("", errout_str());
}
}
void simplifyInitVar2() {
// ticket #5131 - unsigned
const char code[] = "void f() {\n"
" unsigned int a(0),b(0);\n"
"}";
ASSERT_EQUALS("void f ( ) {\n"
"unsigned int a ; a = 0 ; unsigned int b ; b = 0 ;\n"
"}", tokenizeAndStringify(code));
}
void simplifyInitVar3() {
const char code[] = "void f() {\n"
" int *a(0),b(0);\n"
"}";
ASSERT_EQUALS("void f ( ) {\n"
"int * a ; a = 0 ; int b ; b = 0 ;\n"
"}", tokenizeAndStringify(code));
}
void bitfields1() {
const char code1[] = "struct A { bool x : 1; };";
ASSERT_EQUALS("struct A { bool x ; } ;", tokenizeAndStringify(code1));
const char code2[] = "struct A { char x : 3; };";
ASSERT_EQUALS("struct A { char x ; } ;", tokenizeAndStringify(code2));
const char code3[] = "struct A { short x : 3; };";
ASSERT_EQUALS("struct A { short x ; } ;", tokenizeAndStringify(code3));
const char code4[] = "struct A { int x : 3; };";
ASSERT_EQUALS("struct A { int x ; } ;", tokenizeAndStringify(code4));
const char code5[] = "struct A { long x : 3; };";
ASSERT_EQUALS("struct A { long x ; } ;", tokenizeAndStringify(code5));
const char code6[] = "struct A { __int8 x : 3; };";
ASSERT_EQUALS("struct A { char x ; } ;", tokenizeAndStringifyWindows(code6, true, Platform::Type::Win32A));
const char code7[] = "struct A { __int16 x : 3; };";
ASSERT_EQUALS("struct A { short x ; } ;", tokenizeAndStringifyWindows(code7, true, Platform::Type::Win32A));
const char code8[] = "struct A { __int32 x : 3; };";
ASSERT_EQUALS("struct A { int x ; } ;", tokenizeAndStringifyWindows(code8, true, Platform::Type::Win32A));
const char code9[] = "struct A { __int64 x : 3; };";
ASSERT_EQUALS("struct A { long long x ; } ;", tokenizeAndStringifyWindows(code9, true, Platform::Type::Win32A));
const char code10[] = "struct A { unsigned char x : 3; };";
ASSERT_EQUALS("struct A { unsigned char x ; } ;", tokenizeAndStringify(code10));
const char code11[] = "struct A { unsigned short x : 3; };";
ASSERT_EQUALS("struct A { unsigned short x ; } ;", tokenizeAndStringify(code11));
const char code12[] = "struct A { unsigned int x : 3; };";
ASSERT_EQUALS("struct A { unsigned int x ; } ;", tokenizeAndStringify(code12));
const char code13[] = "struct A { unsigned long x : 3; };";
ASSERT_EQUALS("struct A { unsigned long x ; } ;", tokenizeAndStringify(code13));
const char code14[] = "struct A { unsigned __int8 x : 3; };";
ASSERT_EQUALS("struct A { unsigned char x ; } ;", tokenizeAndStringifyWindows(code14, true, Platform::Type::Win32A));
const char code15[] = "struct A { unsigned __int16 x : 3; };";
ASSERT_EQUALS("struct A { unsigned short x ; } ;", tokenizeAndStringifyWindows(code15, true, Platform::Type::Win32A));
const char code16[] = "struct A { unsigned __int32 x : 3; };";
ASSERT_EQUALS("struct A { unsigned int x ; } ;", tokenizeAndStringifyWindows(code16, true, Platform::Type::Win32A));
const char code17[] = "struct A { unsigned __int64 x : 3; };";
ASSERT_EQUALS("struct A { unsigned long long x ; } ;", tokenizeAndStringifyWindows(code17, true, Platform::Type::Win32A));
const char code18[] = "struct A { signed char x : 3; };";
ASSERT_EQUALS("struct A { signed char x ; } ;", tokenizeAndStringify(code18));
const char code19[] = "struct A { signed short x : 3; };";
ASSERT_EQUALS("struct A { signed short x ; } ;", tokenizeAndStringify(code19));
const char code20[] = "struct A { signed int x : 3; };";
ASSERT_EQUALS("struct A { signed int x ; } ;", tokenizeAndStringify(code20));
const char code21[] = "struct A { signed long x : 3; };";
ASSERT_EQUALS("struct A { signed long x ; } ;", tokenizeAndStringifyWindows(code21));
const char code22[] = "struct A { signed __int8 x : 3; };";
ASSERT_EQUALS("struct A { signed char x ; } ;", tokenizeAndStringifyWindows(code22, true, Platform::Type::Win32A));
const char code23[] = "struct A { signed __int16 x : 3; };";
ASSERT_EQUALS("struct A { signed short x ; } ;", tokenizeAndStringifyWindows(code23, true, Platform::Type::Win32A));
const char code24[] = "struct A { signed __int32 x : 3; };";
ASSERT_EQUALS("struct A { signed int x ; } ;", tokenizeAndStringifyWindows(code24, true, Platform::Type::Win32A));
const char code25[] = "struct A { signed __int64 x : 3; };";
ASSERT_EQUALS("struct A { signed long long x ; } ;", tokenizeAndStringifyWindows(code25, true, Platform::Type::Win32A));
}
void bitfields2() {
const char code1[] = "struct A { public: int x : 3; };";
ASSERT_EQUALS("struct A { public: int x ; } ;", tokenizeAndStringify(code1));
const char code2[] = "struct A { public: unsigned long x : 3; };";
ASSERT_EQUALS("struct A { public: unsigned long x ; } ;", tokenizeAndStringify(code2));
const char code3[] = "struct A { protected: int x : 3; };";
ASSERT_EQUALS("struct A { protected: int x ; } ;", tokenizeAndStringify(code3));
const char code4[] = "struct A { protected: unsigned long x : 3; };";
ASSERT_EQUALS("struct A { protected: unsigned long x ; } ;", tokenizeAndStringify(code4));
const char code5[] = "struct A { private: int x : 3; };";
ASSERT_EQUALS("struct A { private: int x ; } ;", tokenizeAndStringify(code5));
const char code6[] = "struct A { private: unsigned long x : 3; };";
ASSERT_EQUALS("struct A { private: unsigned long x ; } ;", tokenizeAndStringify(code6));
}
void bitfields3() {
const char code1[] = "struct A { const int x : 3; };";
ASSERT_EQUALS("struct A { const int x ; } ;", tokenizeAndStringify(code1));
const char code2[] = "struct A { const unsigned long x : 3; };";
ASSERT_EQUALS("struct A { const unsigned long x ; } ;", tokenizeAndStringify(code2));
const char code3[] = "struct A { public: const int x : 3; };";
ASSERT_EQUALS("struct A { public: const int x ; } ;", tokenizeAndStringify(code3));
const char code4[] = "struct A { public: const unsigned long x : 3; };";
ASSERT_EQUALS("struct A { public: const unsigned long x ; } ;", tokenizeAndStringify(code4));
}
void bitfields4() { // ticket #1956
const char code1[] = "struct A { CHAR x : 3; };";
ASSERT_EQUALS("struct A { CHAR x ; } ;", tokenizeAndStringify(code1));
const char code2[] = "struct A { UCHAR x : 3; };";
ASSERT_EQUALS("struct A { UCHAR x ; } ;", tokenizeAndStringify(code2));
const char code3[] = "struct A { BYTE x : 3; };";
ASSERT_EQUALS("struct A { BYTE x ; } ;", tokenizeAndStringify(code3));
const char code4[] = "struct A { WORD x : 3; };";
ASSERT_EQUALS("struct A { WORD x ; } ;", tokenizeAndStringify(code4));
const char code5[] = "struct A { DWORD x : 3; };";
ASSERT_EQUALS("struct A { DWORD x ; } ;", tokenizeAndStringify(code5));
const char code6[] = "struct A { LONG x : 3; };";
ASSERT_EQUALS("struct A { LONG x ; } ;", tokenizeAndStringify(code6));
const char code7[] = "struct A { UINT8 x : 3; };";
ASSERT_EQUALS("struct A { UINT8 x ; } ;", tokenizeAndStringify(code7));
const char code8[] = "struct A { UINT16 x : 3; };";
ASSERT_EQUALS("struct A { UINT16 x ; } ;", tokenizeAndStringify(code8));
const char code9[] = "struct A { UINT32 x : 3; };";
ASSERT_EQUALS("struct A { UINT32 x ; } ;", tokenizeAndStringify(code9));
const char code10[] = "struct A { UINT64 x : 3; };";
ASSERT_EQUALS("struct A { UINT64 x ; } ;", tokenizeAndStringify(code10));
}
void bitfields5() { // ticket #1956
const char code1[] = "struct RGB { unsigned int r : 3, g : 3, b : 2; };";
ASSERT_EQUALS("struct RGB { unsigned int r ; unsigned int g ; unsigned int b ; } ;", tokenizeAndStringify(code1));
const char code2[] = "struct A { int a : 3; int : 3; int c : 3; };";
ASSERT_EQUALS("struct A { int a ; int c ; } ;", tokenizeAndStringify(code2));
const char code3[] = "struct A { virtual void f() {} int f1 : 1; };";
ASSERT_EQUALS("struct A { virtual void f ( ) { } int f1 ; } ;", tokenizeAndStringify(code3));
}
void bitfields6() { // ticket #2595
const char code1[] = "struct A { bool b : true; };";
ASSERT_EQUALS("struct A { bool b ; } ;", tokenizeAndStringify(code1));
const char code2[] = "struct A { bool b : true, c : true; };";
ASSERT_EQUALS("struct A { bool b ; bool c ; } ;", tokenizeAndStringify(code2));
const char code3[] = "struct A { bool : true; };";
ASSERT_EQUALS("struct A { } ;", tokenizeAndStringify(code3));
}
void bitfields7() { // ticket #1987
const char code[] = "typedef struct Descriptor {"
" unsigned element_size: 8* sizeof( unsigned );"
"} Descriptor;";
const char expected[] = "struct Descriptor { "
"unsigned int element_size ; "
"} ;";
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
ASSERT_EQUALS("", errout_str());
}
void bitfields8() {
const char code[] = "struct A;"
"class B : virtual public C"
"{"
" int f();"
"};";
const char expected[] = "struct A ; "
"class B : virtual public C "
"{ "
"int f ( ) ; "
"} ;";
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
ASSERT_EQUALS("", errout_str());
}
void bitfields9() { // ticket #2706
const char code[] = "void f() {\n"
" goto half;\n"
"half:\n"
" {\n"
" ;\n"
" }\n"
"};";
(void)tokenizeAndStringify(code);
ASSERT_EQUALS("", errout_str());
}
void bitfields10() { // ticket #2737
const char code[] = "{}"
"MACRO "
"default: { }"
";";
ASSERT_EQUALS("{ } MACRO default : { } ;", tokenizeAndStringify(code));
}
void bitfields12() { // ticket #3485 (segmentation fault)
const char code[] = "{a:1;};\n";
ASSERT_EQUALS("{ } ;", tokenizeAndStringify(code));
}
void bitfields13() { // ticket #3502 (segmentation fault)
ASSERT_NO_THROW(tokenizeAndStringify("struct{x y:};\n"));
}
void bitfields15() { // #7747 - enum Foo {A,B}:4;
ASSERT_EQUALS("struct AB {\n"
"enum Foo { A , B } ; enum Foo Anonymous ;\n"
"} ;",
tokenizeAndStringify("struct AB {\n"
" enum Foo {A,B} : 4;\n"
"};"));
ASSERT_EQUALS("struct AB {\n"
"enum Foo { A , B } ; enum Foo foo ;\n"
"} ;",
tokenizeAndStringify("struct AB {\n"
" enum Foo {A,B} foo : 4;\n"
"};"));
}
void bitfields16() {
const char code[] = "struct A { unsigned int x : 1; };";
SimpleTokenizer tokenizer(settings0, *this);
ASSERT(tokenizer.tokenize(code));
const Token *x = Token::findsimplematch(tokenizer.tokens(), "x");
ASSERT_EQUALS(1, x->bits());
}
void simplifyNamespaceStd() {
const char *expected;
{
const char code[] = "map<foo, bar> m;"; // namespace std is not used
ASSERT_EQUALS("map < foo , bar > m ;", tokenizeAndStringify(code));
}
{
const char code[] = "using namespace std;\n"
"map<foo, bar> m;";
ASSERT_EQUALS("std :: map < foo , bar > m ;", tokenizeAndStringify(code));
}
{
const char code[] = "using namespace std;\n"
"string s;";
ASSERT_EQUALS("std :: string s ;", tokenizeAndStringify(code));
}
{
const char code[] = "using namespace std;\n"
"void foo() {swap(a, b); }";
ASSERT_EQUALS("void foo ( ) { std :: swap ( a , b ) ; }", tokenizeAndStringify(code));
}
{
const char code[] = "using namespace std;\n"
"void search() {}";
ASSERT_EQUALS("void search ( ) { }", tokenizeAndStringify(code));
}
{
const char code[] = "using namespace std;\n"
"void search();\n"
"void dostuff() { search(); }";
ASSERT_EQUALS("void search ( ) ;\nvoid dostuff ( ) { search ( ) ; }", tokenizeAndStringify(code));
}
{
const char code[] = "using namespace std;\n"
"void foo() {map(a, b); }"; // That's obviously not std::map<>
ASSERT_EQUALS("void foo ( ) { map ( a , b ) ; }", tokenizeAndStringify(code));
}
{
const char code[] = "using namespace std;\n"
"string<wchar_t> s;"; // That's obviously not std::string
TODO_ASSERT_EQUALS("string < wchar_t > s ;", "std :: string < wchar_t > s ;", tokenizeAndStringify(code));
}
{
const char code[] = "using namespace std;\n"
"swap s;"; // That's obviously not std::swap
ASSERT_EQUALS("swap s ;", tokenizeAndStringify(code));
}
{
const char code[] = "using namespace std;\n"
"std::string s;";
ASSERT_EQUALS("std :: string s ;", tokenizeAndStringify(code));
}
{ // #4042 (Do not add 'std ::' to variables)
const char code[] = "using namespace std;\n"
"const char * string = \"Hi\";";
ASSERT_EQUALS("const char * string ; string = \"Hi\" ;", tokenizeAndStringify(code));
}
{
const char code[] = "using namespace std;\n"
"string f(const char * string) {\n"
" cout << string << endl;\n"
" return string;\n"
"}";
expected = "std :: string f ( const char * string ) {\n"
"std :: cout << string << std :: endl ;\n"
"return string ;\n"
"}";
TODO_ASSERT_EQUALS(expected,
"std :: string f ( const char * string ) {\n"
"cout << string << endl ;\n"
"return string ;\n"
"}",
tokenizeAndStringify(code));
ASSERT_EQUALS(
"[test.cpp:3]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable cout\n",
errout_str());
}
{
const char code[] = "using namespace std;\n"
"void f() {\n"
" try { }\n"
" catch(std::exception &exception) { }\n"
"}";
expected = "void f ( ) {\n"
"try { }\n"
"catch ( std :: exception & exception ) { }\n"
"}";
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
}
{ // #5773 (Don't prepend 'std ::' to function definitions)
const char code[] = "using namespace std;\n"
"class C {\n"
" void search() {}\n"
" void search() const {}\n"
" void search() THROW_MACRO {}\n"
"};";
expected = "class C {\n"
"void search ( ) { }\n"
"void search ( ) const { }\n"
"void search ( ) { }\n"
"} ;";
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
}
// Ticket #8091
ASSERT_EQUALS("enum Anonymous0 { string } ;",
tokenizeAndStringify("using namespace std; "
"enum { string };"));
ASSERT_EQUALS("enum Type { string } ;",
tokenizeAndStringify("using namespace std; "
"enum Type { string } ;"));
ASSERT_EQUALS("enum class Type { string } ;",
tokenizeAndStringify("using namespace std; "
"enum class Type { string } ;"));
ASSERT_EQUALS("enum struct Type { string } ;",
tokenizeAndStringify("using namespace std; "
"enum struct Type { string } ;"));
ASSERT_EQUALS("enum struct Type : int { f = 0 , string } ;",
tokenizeAndStringify("using namespace std; "
"enum struct Type : int { f = 0 , string } ;"));
ASSERT_EQUALS("enum Type { a , b } ; void foo ( enum Type , std :: string ) { }",
tokenizeAndStringify("using namespace std; "
"enum Type { a , b } ; void foo ( enum Type , string) {}"));
ASSERT_EQUALS("struct T { } ; enum struct Type : int { f = 0 , string } ;",
tokenizeAndStringify("using namespace std; "
"struct T { typedef int type; } ; "
"enum struct Type : T :: type { f = 0 , string } ;"));
// Handle garbage enum code "well"
ASSERT_EQUALS("enum E : int ; void foo ( ) { std :: string s ; }",
tokenizeAndStringify("using namespace std; enum E : int ; void foo ( ) { string s ; }"));
ASSERT_NO_THROW(tokenizeAndStringify("NS_BEGIN(IMAGEIO_2D_DICOM) using namespace std; NS_END")); // #11045
{
const char code[] = "using namespace std;\n"
"void f(const unique_ptr<int>& p) {\n"
" if (!p)\n"
" throw runtime_error(\"abc\");\n"
"}";
expected = "void f ( const std :: unique_ptr < int > & p ) {\n"
"if ( ! p ) {\n"
"throw std :: runtime_error ( \"abc\" ) ; }\n"
"}";
TODO_ASSERT_EQUALS(expected,
"void f ( const std :: unique_ptr < int > & p ) {\n"
"if ( ! p ) {\n"
"throw runtime_error ( \"abc\" ) ; }\n"
"}",
tokenizeAndStringify(code));
}
{
const char code[] = "using namespace std;\n" // #8454
"void f() { string str = to_string(1); }\n";
expected = "void f ( ) { std :: string str ; str = std :: to_string ( 1 ) ; }";
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
}
{
const char code[] = "using namespace std;\n"
"vector<int>&& f(vector<int>& v) {\n"
" v.push_back(1);\n"
" return move(v);\n"
"}\n";
expected = "std :: vector < int > && f ( std :: vector < int > & v ) {\n"
"v . push_back ( 1 ) ;\n"
"return std :: move ( v ) ;\n"
"}";
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
}
}
void microsoftMemory() {
const char code1a[] = "void foo() { int a[10], b[10]; CopyMemory(a, b, sizeof(a)); }";
ASSERT_EQUALS("void foo ( ) { int a [ 10 ] ; int b [ 10 ] ; memcpy ( a , b , sizeof ( a ) ) ; }", tokenizeAndStringify(code1a,true,Platform::Type::Win32A));
const char code1b[] = "void foo() { int a[10], b[10]; RtlCopyMemory(a, b, sizeof(a)); }";
ASSERT_EQUALS("void foo ( ) { int a [ 10 ] ; int b [ 10 ] ; memcpy ( a , b , sizeof ( a ) ) ; }", tokenizeAndStringify(code1b,true,Platform::Type::Win32A));
const char code1c[] = "void foo() { int a[10], b[10]; RtlCopyBytes(a, b, sizeof(a)); }";
ASSERT_EQUALS("void foo ( ) { int a [ 10 ] ; int b [ 10 ] ; memcpy ( a , b , sizeof ( a ) ) ; }", tokenizeAndStringify(code1c,true,Platform::Type::Win32A));
const char code2a[] = "void foo() { int a[10]; FillMemory(a, sizeof(a), 255); }";
ASSERT_EQUALS("void foo ( ) { int a [ 10 ] ; memset ( a , 255 , sizeof ( a ) ) ; }", tokenizeAndStringify(code2a,true,Platform::Type::Win32A));
const char code2b[] = "void foo() { int a[10]; RtlFillMemory(a, sizeof(a), 255); }";
ASSERT_EQUALS("void foo ( ) { int a [ 10 ] ; memset ( a , 255 , sizeof ( a ) ) ; }", tokenizeAndStringify(code2b,true,Platform::Type::Win32A));
const char code2c[] = "void foo() { int a[10]; RtlFillBytes(a, sizeof(a), 255); }";
ASSERT_EQUALS("void foo ( ) { int a [ 10 ] ; memset ( a , 255 , sizeof ( a ) ) ; }", tokenizeAndStringify(code2c,true,Platform::Type::Win32A));
const char code3a[] = "void foo() { int a[10], b[10]; MoveMemory(a, b, sizeof(a)); }";
ASSERT_EQUALS("void foo ( ) { int a [ 10 ] ; int b [ 10 ] ; memmove ( a , b , sizeof ( a ) ) ; }", tokenizeAndStringify(code3a,true,Platform::Type::Win32A));
const char code3b[] = "void foo() { int a[10], b[10]; RtlMoveMemory(a, b, sizeof(a)); }";
ASSERT_EQUALS("void foo ( ) { int a [ 10 ] ; int b [ 10 ] ; memmove ( a , b , sizeof ( a ) ) ; }", tokenizeAndStringify(code3b,true,Platform::Type::Win32A));
const char code4a[] = "void foo() { int a[10]; ZeroMemory(a, sizeof(a)); }";
ASSERT_EQUALS("void foo ( ) { int a [ 10 ] ; memset ( a , 0 , sizeof ( a ) ) ; }", tokenizeAndStringify(code4a,true,Platform::Type::Win32A));
const char code4b[] = "void foo() { int a[10]; RtlZeroMemory(a, sizeof(a)); }";
ASSERT_EQUALS("void foo ( ) { int a [ 10 ] ; memset ( a , 0 , sizeof ( a ) ) ; }", tokenizeAndStringify(code4b,true,Platform::Type::Win32A));
const char code4c[] = "void foo() { int a[10]; RtlZeroBytes(a, sizeof(a)); }";
ASSERT_EQUALS("void foo ( ) { int a [ 10 ] ; memset ( a , 0 , sizeof ( a ) ) ; }", tokenizeAndStringify(code4c,true,Platform::Type::Win32A));
const char code4d[] = "void foo() { int a[10]; RtlSecureZeroMemory(a, sizeof(a)); }";
ASSERT_EQUALS("void foo ( ) { int a [ 10 ] ; memset ( a , 0 , sizeof ( a ) ) ; }", tokenizeAndStringify(code4d,true,Platform::Type::Win32A));
const char code5[] = "void foo() { int a[10], b[10]; RtlCompareMemory(a, b, sizeof(a)); }";
ASSERT_EQUALS("void foo ( ) { int a [ 10 ] ; int b [ 10 ] ; memcmp ( a , b , sizeof ( a ) ) ; }", tokenizeAndStringify(code5,true,Platform::Type::Win32A));
const char code6[] = "void foo() { ZeroMemory(f(1, g(a, b)), h(i, j(0, 1))); }";
ASSERT_EQUALS("void foo ( ) { memset ( f ( 1 , g ( a , b ) ) , 0 , h ( i , j ( 0 , 1 ) ) ) ; }", tokenizeAndStringify(code6,true,Platform::Type::Win32A));
const char code7[] = "void foo() { FillMemory(f(1, g(a, b)), h(i, j(0, 1)), 255); }";
ASSERT_EQUALS("void foo ( ) { memset ( f ( 1 , g ( a , b ) ) , 255 , h ( i , j ( 0 , 1 ) ) ) ; }", tokenizeAndStringify(code7,true,Platform::Type::Win32A));
}
void microsoftString() {
const char code1a[] = "void foo() { _tprintf (_T(\"test\") _T(\"1\")); }";
ASSERT_EQUALS("void foo ( ) { printf ( \"test1\" ) ; }", tokenizeAndStringify(code1a, true, Platform::Type::Win32A));
const char code1b[] = "void foo() { _tprintf (_TEXT(\"test\") _TEXT(\"2\")); }";
ASSERT_EQUALS("void foo ( ) { printf ( \"test2\" ) ; }", tokenizeAndStringify(code1b, true, Platform::Type::Win32A));
const char code1c[] = "void foo() { _tprintf (TEXT(\"test\") TEXT(\"3\")); }";
ASSERT_EQUALS("void foo ( ) { printf ( \"test3\" ) ; }", tokenizeAndStringify(code1c, true, Platform::Type::Win32A));
const char code2a[] = "void foo() { _tprintf (_T(\"test\") _T(\"1\")); }";
ASSERT_EQUALS("void foo ( ) { wprintf ( L\"test1\" ) ; }", tokenizeAndStringify(code2a, true, Platform::Type::Win32W));
ASSERT_EQUALS("void foo ( ) { wprintf ( L\"test1\" ) ; }", tokenizeAndStringify(code2a, true, Platform::Type::Win64));
const char code2b[] = "void foo() { _tprintf (_TEXT(\"test\") _TEXT(\"2\")); }";
ASSERT_EQUALS("void foo ( ) { wprintf ( L\"test2\" ) ; }", tokenizeAndStringify(code2b, true, Platform::Type::Win32W));
ASSERT_EQUALS("void foo ( ) { wprintf ( L\"test2\" ) ; }", tokenizeAndStringify(code2b, true, Platform::Type::Win64));
const char code2c[] = "void foo() { _tprintf (TEXT(\"test\") TEXT(\"3\")); }";
ASSERT_EQUALS("void foo ( ) { wprintf ( L\"test3\" ) ; }", tokenizeAndStringify(code2c, true, Platform::Type::Win32W));
ASSERT_EQUALS("void foo ( ) { wprintf ( L\"test3\" ) ; }", tokenizeAndStringify(code2c, true, Platform::Type::Win64));
}
void borland() {
// __closure
ASSERT_EQUALS("int ( * a ) ( ) ;", // TODO VarId
tokenizeAndStringify("int (__closure *a)();", true, Platform::Type::Win32A));
// __property
ASSERT_EQUALS("class Fred { ; __property ; } ;",
tokenizeAndStringify("class Fred { __property int x = { } };", true, Platform::Type::Win32A));
}
void simplifySQL() {
// Oracle PRO*C extensions for inline SQL. Just replace the SQL with "asm()" to fix wrong error messages
// ticket: #1959
ASSERT_EQUALS("asm ( \"\"__CPPCHECK_EMBEDDED_SQL_EXEC__ SQL SELECT A FROM B\"\" ) ;", tokenizeAndStringify("__CPPCHECK_EMBEDDED_SQL_EXEC__ SQL SELECT A FROM B;"));
ASSERT_THROW_INTERNAL(tokenizeAndStringify("__CPPCHECK_EMBEDDED_SQL_EXEC__ SQL"), SYNTAX);
ASSERT_EQUALS("asm ( \"\"__CPPCHECK_EMBEDDED_SQL_EXEC__ SQL EXECUTE BEGIN Proc1 ( A ) ; END ; END - __CPPCHECK_EMBEDDED_SQL_EXEC__\"\" ) ; asm ( \"\"__CPPCHECK_EMBEDDED_SQL_EXEC__ SQL COMMIT\"\" ) ;",
tokenizeAndStringify("__CPPCHECK_EMBEDDED_SQL_EXEC__ SQL EXECUTE BEGIN Proc1(A); END; END-__CPPCHECK_EMBEDDED_SQL_EXEC__; __CPPCHECK_EMBEDDED_SQL_EXEC__ SQL COMMIT;"));
ASSERT_EQUALS("asm ( \"\"__CPPCHECK_EMBEDDED_SQL_EXEC__ SQL UPDATE A SET B = C\"\" ) ; asm ( \"\"__CPPCHECK_EMBEDDED_SQL_EXEC__ SQL COMMIT\"\" ) ;",
tokenizeAndStringify("__CPPCHECK_EMBEDDED_SQL_EXEC__ SQL UPDATE A SET B = C; __CPPCHECK_EMBEDDED_SQL_EXEC__ SQL COMMIT;"));
ASSERT_EQUALS("asm ( \"\"__CPPCHECK_EMBEDDED_SQL_EXEC__ SQL COMMIT\"\" ) ; asm ( \"\"__CPPCHECK_EMBEDDED_SQL_EXEC__ SQL EXECUTE BEGIN Proc1 ( A ) ; END ; END - __CPPCHECK_EMBEDDED_SQL_EXEC__\"\" ) ;",
tokenizeAndStringify("__CPPCHECK_EMBEDDED_SQL_EXEC__ SQL COMMIT; __CPPCHECK_EMBEDDED_SQL_EXEC__ SQL EXECUTE BEGIN Proc1(A); END; END-__CPPCHECK_EMBEDDED_SQL_EXEC__;"));
ASSERT_THROW_INTERNAL(tokenizeAndStringify("int f(){ __CPPCHECK_EMBEDDED_SQL_EXEC__ SQL } int a;"), SYNTAX);
ASSERT_THROW_INTERNAL(tokenizeAndStringify("__CPPCHECK_EMBEDDED_SQL_EXEC__ SQL int f(){"), SYNTAX);
ASSERT_THROW_INTERNAL(tokenizeAndStringify("__CPPCHECK_EMBEDDED_SQL_EXEC__ SQL END-__CPPCHECK_EMBEDDED_SQL_EXEC__ int a;"), SYNTAX);
ASSERT_NO_THROW(tokenizeAndStringify("__CPPCHECK_EMBEDDED_SQL_EXEC__ SQL UPDATE A SET B = :&b->b1, C = :c::c1;"));
}
void simplifyCAlternativeTokens() {
ASSERT_EQUALS("void or ( ) ;", tokenizeAndStringify("void or(void);", true, Platform::Type::Native, false));
ASSERT_EQUALS("void f ( ) { if ( a && b ) { ; } }", tokenizeAndStringify("void f() { if (a and b); }", true, Platform::Type::Native, false));
ASSERT_EQUALS("void f ( ) { if ( a && b ) { ; } }", tokenizeAndStringify("void f() { if (a and b); }", true, Platform::Type::Native, true));
ASSERT_EQUALS("void f ( ) { if ( a || b ) { ; } }", tokenizeAndStringify("void f() { if (a or b); }", true, Platform::Type::Native, false));
ASSERT_EQUALS("void f ( ) { if ( a || b ) { ; } }", tokenizeAndStringify("void f() { if (a or b); }", true, Platform::Type::Native, true));
ASSERT_EQUALS("void f ( ) { if ( a & b ) { ; } }", tokenizeAndStringify("void f() { if (a bitand b); }", true, Platform::Type::Native, false));
ASSERT_EQUALS("void f ( ) { if ( a & b ) { ; } }", tokenizeAndStringify("void f() { if (a bitand b); }", true, Platform::Type::Native, true));
ASSERT_EQUALS("void f ( ) { if ( a | b ) { ; } }", tokenizeAndStringify("void f() { if (a bitor b); }", true, Platform::Type::Native, false));
ASSERT_EQUALS("void f ( ) { if ( a | b ) { ; } }", tokenizeAndStringify("void f() { if (a bitor b); }", true, Platform::Type::Native, true));
ASSERT_EQUALS("void f ( ) { if ( a ^ b ) { ; } }", tokenizeAndStringify("void f() { if (a xor b); }", true, Platform::Type::Native, false));
ASSERT_EQUALS("void f ( ) { if ( a ^ b ) { ; } }", tokenizeAndStringify("void f() { if (a xor b); }", true, Platform::Type::Native, true));
ASSERT_EQUALS("void f ( ) { if ( ~ b ) { ; } }", tokenizeAndStringify("void f() { if (compl b); }", true, Platform::Type::Native, false));
ASSERT_EQUALS("void f ( ) { if ( ~ b ) { ; } }", tokenizeAndStringify("void f() { if (compl b); }", true, Platform::Type::Native, true));
ASSERT_EQUALS("void f ( ) { if ( ! b ) { ; } }", tokenizeAndStringify("void f() { if (not b); }", true, Platform::Type::Native, false));
ASSERT_EQUALS("void f ( ) { if ( ! b ) { ; } }", tokenizeAndStringify("void f() { if (not b); }", true, Platform::Type::Native, true));
ASSERT_EQUALS("void f ( ) const { if ( ! b ) { ; } }", tokenizeAndStringify("void f() const { if (not b); }", true, Platform::Type::Native, true));
ASSERT_EQUALS("void f ( ) { if ( a != b ) { ; } }", tokenizeAndStringify("void f() { if (a not_eq b); }", true, Platform::Type::Native, false));
ASSERT_EQUALS("void f ( ) { if ( a != b ) { ; } }", tokenizeAndStringify("void f() { if (a not_eq b); }", true, Platform::Type::Native, true));
// #6201
ASSERT_EQUALS("void f ( ) { if ( ! c || ! memcmp ( a , b , s ) ) { ; } }", tokenizeAndStringify("void f() { if (!c or !memcmp(a, b, s)); }", true, Platform::Type::Native, false));
ASSERT_EQUALS("void f ( ) { if ( ! c || ! memcmp ( a , b , s ) ) { ; } }", tokenizeAndStringify("void f() { if (!c or !memcmp(a, b, s)); }", true, Platform::Type::Native, true));
// #6029
ASSERT_EQUALS("void f ( ) { if ( ! b ) { } }", tokenizeAndStringify("void f() { if (not b){} }", true, Platform::Type::Native, false));
ASSERT_EQUALS("void f ( ) { if ( ! b ) { } }", tokenizeAndStringify("void f() { if (not b){} }", true, Platform::Type::Native, true));
// #6207
ASSERT_EQUALS("void f ( ) { if ( not = x ) { } }", tokenizeAndStringify("void f() { if (not=x){} }", true, Platform::Type::Native, false));
ASSERT_EQUALS("void f ( ) { if ( not = x ) { } }", tokenizeAndStringify("void f() { if (not=x){} }", true, Platform::Type::Native, true));
// #8029
ASSERT_EQUALS("void f ( struct S * s ) { x = s . and + 1 ; }", tokenizeAndStringify("void f(struct S *s) { x = s->and + 1; }", true, Platform::Type::Native, false));
// #8745
ASSERT_EQUALS("void f ( ) { if ( x ) { or = 0 ; } }", tokenizeAndStringify("void f() { if (x) or = 0; }"));
// #9324
ASSERT_EQUALS("void f ( const char * str ) { while ( * str == '!' || * str == '[' ) { } }",
tokenizeAndStringify("void f(const char *str) { while (*str=='!' or *str=='['){} }"));
// #9920
ASSERT_EQUALS("result = ch != s . end ( ) && * ch == ':' ;", tokenizeAndStringify("result = ch != s.end() and *ch == ':';", true, Platform::Type::Native, false));
// #8975
ASSERT_EQUALS("void foo ( ) {\n"
"char * or ;\n"
"while ( ( * or != 0 ) && ( * or != '|' ) ) { or ++ ; }\n"
"}",
tokenizeAndStringify(
"void foo() {\n"
" char *or;\n"
" while ((*or != 0) && (*or != '|')) or++;\n"
"}", true, Platform::Type::Native, false));
// #10013
ASSERT_EQUALS("void f ( ) { x = ! 123 ; }", tokenizeAndStringify("void f() { x = not 123; }", true, Platform::Type::Native, true));
{ // #12476
const char code[] = "struct S { int a, b; };"
"void f(struct S* compl) {"
" compl->a = compl->b;"
"}";
const char exp[] = "struct S { int a ; int b ; } ; void f ( struct S * compl ) { compl . a = compl . b ; }";
ASSERT_EQUALS(exp, tokenizeAndStringify(code, true, Platform::Type::Native, false));
}
//ASSERT_EQUALS("", filter_valueflow(errout_str()));
ignore_errout();
}
void simplifyCompoundStatements() {
ASSERT_EQUALS("; x = 123 ;", tokenizeAndStringify(";x=({123;});"));
ASSERT_EQUALS("; x = y ;", tokenizeAndStringify(";x=({y;});"));
// #13419: Do not simplify compound statements in for loop
ASSERT_EQUALS("void foo ( int x ) { for ( ; ( { { } ; x < 1 ; } ) ; ) }",
tokenizeAndStringify("void foo(int x) { for (;({ {}; x<1; });) }"));
}
void simplifyOperatorName1() {
// make sure C code doesn't get changed
const char code[] = "void operator () {}"
"int main()"
"{"
" operator();"
"}";
const char result[] = "void operator ( ) { } "
"int main ( ) "
"{ "
"operator ( ) ; "
"}";
ASSERT_EQUALS(result, tokenizeAndStringify(code, /*expand=*/ true, /*platform=*/ Platform::Type::Native, false));
}
void simplifyOperatorName2() {
const char code[] = "class Fred"
"{"
" Fred(const Fred & f) { operator = (f); }"
" operator = ();"
"}";
const char result[] = "class Fred "
"{ "
"Fred ( const Fred & f ) { operator= ( f ) ; } "
"operator= ( ) ; "
"}";
ASSERT_EQUALS(result, tokenizeAndStringify(code));
}
void simplifyOperatorName3() {
// #2615
const char code[] = "void f() {"
"static_cast<ScToken*>(xResult.operator->())->GetMatrix();"
"}";
const char result[] = "void f ( ) { static_cast < ScToken * > ( xResult . operator-> ( ) ) . GetMatrix ( ) ; }";
ASSERT_EQUALS(result, tokenizeAndStringify(code));
}
void simplifyOperatorName4() {
const char code[] = "void operator==() { }";
const char result[] = "void operator== ( ) { }";
ASSERT_EQUALS(result, tokenizeAndStringify(code));
}
void simplifyOperatorName5() {
const char code1[] = "std::istream & operator >> (std::istream & s, Fred &f);";
const char result1[] = "std :: istream & operator>> ( std :: istream & s , Fred & f ) ;";
ASSERT_EQUALS(result1, tokenizeAndStringify(code1));
const char code2[] = "std::ostream & operator << (std::ostream & s, const Fred &f);";
const char result2[] = "std :: ostream & operator<< ( std :: ostream & s , const Fred & f ) ;";
ASSERT_EQUALS(result2, tokenizeAndStringify(code2));
}
void simplifyOperatorName6() { // ticket #3195
const char code1[] = "value_type * operator ++ (int);";
const char result1[] = "value_type * operator++ ( int ) ;";
ASSERT_EQUALS(result1, tokenizeAndStringify(code1));
const char code2[] = "value_type * operator -- (int);";
const char result2[] = "value_type * operator-- ( int ) ;";
ASSERT_EQUALS(result2, tokenizeAndStringify(code2));
}
void simplifyOperatorName7() { // ticket #4619
const char code1[] = "value_type * operator += (int);";
const char result1[] = "value_type * operator+= ( int ) ;";
ASSERT_EQUALS(result1, tokenizeAndStringify(code1));
}
void simplifyOperatorName8() { // ticket #5706
const char code1[] = "value_type * operator += (int) noexcept ;";
const char result1[] = "value_type * operator+= ( int ) noexcept ( true ) ;";
ASSERT_EQUALS(result1, tokenizeAndStringify(code1));
const char code2[] = "value_type * operator += (int) noexcept ( true ) ;";
const char result2[] = "value_type * operator+= ( int ) noexcept ( true ) ;";
ASSERT_EQUALS(result2, tokenizeAndStringify(code2));
const char code3[] = "value_type * operator += (int) throw ( ) ;";
const char result3[] = "value_type * operator+= ( int ) throw ( ) ;";
ASSERT_EQUALS(result3, tokenizeAndStringify(code3));
const char code4[] = "value_type * operator += (int) const noexcept ;";
const char result4[] = "value_type * operator+= ( int ) const noexcept ( true ) ;";
ASSERT_EQUALS(result4, tokenizeAndStringify(code4));
const char code5[] = "value_type * operator += (int) const noexcept ( true ) ;";
const char result5[] = "value_type * operator+= ( int ) const noexcept ( true ) ;";
ASSERT_EQUALS(result5, tokenizeAndStringify(code5));
const char code6[] = "value_type * operator += (int) const throw ( ) ;";
const char result6[] = "value_type * operator+= ( int ) const throw ( ) ;";
ASSERT_EQUALS(result6, tokenizeAndStringify(code6));
const char code7[] = "value_type * operator += (int) const noexcept ( false ) ;";
const char result7[] = "value_type * operator+= ( int ) const noexcept ( false ) ;";
ASSERT_EQUALS(result7, tokenizeAndStringify(code7));
}
void simplifyOperatorName9() { // Ticket #5709
const char code[] = "struct R { R operator, ( R b ) ; } ;";
ASSERT_EQUALS(code, tokenizeAndStringify(code));
}
void simplifyOperatorName31() { // #6342
const char code[] = "template <typename T>\n"
"struct B {\n"
" typedef T A[3];\n"
" operator A& () { return x_; }\n"
" A x_;\n"
"};";
ASSERT_EQUALS("template < typename T >\nstruct B {\n\nT ( & operatorT ( ) ) [ 3 ] { return x_ ; }\nT x_ [ 3 ] ;\n} ;", tokenizeAndStringify(code));
ASSERT_EQUALS("", errout_str());
}
void simplifyOperatorName32() { // #10256
const char code[] = "void f(int* = nullptr) {}\n";
ASSERT_EQUALS("void f ( int * = nullptr ) { }", tokenizeAndStringify(code));
ASSERT_EQUALS("", errout_str());
}
void simplifyOperatorName33() { // #10138
const char code[] = "int (operator\"\" _ii)(unsigned long long v) { return v; }\n";
ASSERT_EQUALS("int operator\"\"_ii ( unsigned long long v ) { return v ; }", tokenizeAndStringify(code));
ASSERT_EQUALS("", errout_str());
}
void simplifyOperatorName10() { // #8746
const char code1[] = "using a::operator=;";
ASSERT_EQUALS("using a :: operator= ;", tokenizeAndStringify(code1));
const char code2[] = "{ return &Fred::operator!=; }";
ASSERT_EQUALS("{ return & Fred :: operator!= ; }", tokenizeAndStringify(code2));
}
void simplifyOperatorName11() { // #8889
const char code[] = "auto operator = (const Fred & other) -> Fred & ;";
ASSERT_EQUALS("auto operator= ( const Fred & other ) . Fred & ;", tokenizeAndStringify(code));
ASSERT_EQUALS("[test.cpp:1]: (debug) auto token with no type.\n", errout_str());
const char code1[] = "auto operator = (const Fred & other) -> Fred & { }";
ASSERT_EQUALS("auto operator= ( const Fred & other ) . Fred & { }", tokenizeAndStringify(code1));
ASSERT_EQUALS("[test.cpp:1]: (debug) auto token with no type.\n", errout_str());
const char code2[] = "template <typename T> void g(S<&T::operator+ >) {}";
ASSERT_EQUALS("template < typename T > void g ( S < & T :: operator+ > ) { }", tokenizeAndStringify(code2));
ASSERT_EQUALS("", errout_str());
const char code3[] = "template <typename T> void g(S<&T::operator int>) {}";
ASSERT_EQUALS("template < typename T > void g ( S < & T :: operatorint > ) { }", tokenizeAndStringify(code3));
ASSERT_EQUALS("", errout_str());
const char code4[] = "template <typename T> void g(S<&T::template operator- <double> >) {}";
ASSERT_EQUALS("template < typename T > void g ( S < & T :: operator- < double > > ) { }", tokenizeAndStringify(code4));
ASSERT_EQUALS("", errout_str());
}
void simplifyOperatorName12() { // #9110
const char code[] = "namespace a {"
"template <typename b> void operator+(b);"
"}"
"using a::operator+;";
ASSERT_EQUALS("namespace a { "
"template < typename b > void operator+ ( b ) ; "
"} "
"using a :: operator+ ;",
tokenizeAndStringify(code));
}
void simplifyOperatorName13() { // user defined literal
const char code[] = "unsigned long operator\"\"_numch(const char *ch, unsigned long size);";
ASSERT_EQUALS("unsigned long operator\"\"_numch ( const char * ch , unsigned long size ) ;",
tokenizeAndStringify(code));
}
void simplifyOperatorName14() { // std::complex operator "" if
{
const char code[] = "constexpr std::complex<float> operator\"\"if(long double __num);";
ASSERT_EQUALS("constexpr std :: complex < float > operator\"\"if ( long double __num ) ;",
tokenizeAndStringify(code));
}
{
const char code[] = "constexpr std::complex<float> operator\"\"if(long double __num) { }";
ASSERT_EQUALS("constexpr std :: complex < float > operator\"\"if ( long double __num ) { }",
tokenizeAndStringify(code));
}
}
void simplifyOperatorName15() { // ticket #9468 syntaxError
const char code[] = "template <typename> struct a;"
"template <typename> struct b {"
" typedef char c;"
" operator c();"
"};"
"template <> struct a<char> : b<char> { using b::operator char; };";
ASSERT_EQUALS("struct a<char> ; template < typename > struct a ; "
"struct b<char> ; "
"struct a<char> : b<char> { using b :: operatorchar ; } ; struct b<char> { "
"operatorchar ( ) ; "
"} ;",
tokenizeAndStringify(code));
}
void simplifyOperatorName16() { // ticket #9472
{
const char code[] = "class I : public A { iterator& operator++() override; };";
ASSERT_EQUALS("class I : public A { iterator & operator++ ( ) override ; } ;",
tokenizeAndStringify(code));
}
{
const char code[] = "class I : public A { iterator& operator++() override { } };";
ASSERT_EQUALS("class I : public A { iterator & operator++ ( ) override { } } ;",
tokenizeAndStringify(code));
}
}
void simplifyOperatorName17() {
{
const char code[] = "template <class a> void b(a c, a d) { c.operator>() == d; }";
ASSERT_EQUALS("template < class a > void b ( a c , a d ) { c . operator> ( ) == d ; }",
tokenizeAndStringify(code));
}
{
const char code[] = "template <class a> void b(a c, a d) { c.operator>() == (d + 1); }";
ASSERT_EQUALS("template < class a > void b ( a c , a d ) { c . operator> ( ) == ( d + 1 ) ; }",
tokenizeAndStringify(code));
}
{
const char code[] = "template <class a> void b(a c, a d) { c.operator<() == d; }";
ASSERT_EQUALS("template < class a > void b ( a c , a d ) { c . operator< ( ) == d ; }",
tokenizeAndStringify(code));
}
{
const char code[] = "template <class a> void b(a c, a d) { c.operator>() == (d + 1); }";
ASSERT_EQUALS("template < class a > void b ( a c , a d ) { c . operator> ( ) == ( d + 1 ) ; }",
tokenizeAndStringify(code));
}
{
const char code[] = "template <class a> void b(a c, a d) { c.operator++() == d; }";
ASSERT_EQUALS("template < class a > void b ( a c , a d ) { c . operator++ ( ) == d ; }",
tokenizeAndStringify(code));
}
{
const char code[] = "template <class a> void b(a c, a d) { c.operator++() == (d + 1); }";
ASSERT_EQUALS("template < class a > void b ( a c , a d ) { c . operator++ ( ) == ( d + 1 ) ; }",
tokenizeAndStringify(code));
}
}
void simplifyOperatorName18() { // global namespace
{
const char code[] = "struct Fred { operator std::string() const { return std::string(\"Fred\"); } };";
ASSERT_EQUALS("struct Fred { operatorstd::string ( ) const { return std :: string ( \"Fred\" ) ; } } ;",
tokenizeAndStringify(code));
}
{
const char code[] = "struct Fred { operator ::std::string() const { return ::std::string(\"Fred\"); } };";
ASSERT_EQUALS("struct Fred { operator::std::string ( ) const { return :: std :: string ( \"Fred\" ) ; } } ;",
tokenizeAndStringify(code));
}
}
void simplifyOperatorName19() {
const char code[] = "struct v {};"
"enum E { e };"
"struct s {"
" operator struct v() { return v(); };"
" operator enum E() { return e; }"
"};"
"void f() {"
" (void)&s::operator struct v;"
" (void)&s::operator enum E;"
"}";
ASSERT_EQUALS("struct v { } ; "
"enum E { e } ; "
"struct s { "
"operatorstructv ( ) { return v ( ) ; } ; "
"operatorenumE ( ) { return e ; } "
"} ; "
"void f ( ) { "
"( void ) & s :: operatorstructv ; "
"( void ) & s :: operatorenumE ; "
"}",
tokenizeAndStringify(code));
}
void simplifyOperatorName20() {
const char code[] = "void operator \"\" _a(const char *);"
"namespace N {"
" using ::operator \"\" _a;"
" void operator \"\" _b(const char *);"
"}";
ASSERT_EQUALS("void operator\"\"_a ( const char * ) ; "
"namespace N { "
"using :: operator\"\"_a ; "
"void operator\"\"_b ( const char * ) ; "
"}",
tokenizeAndStringify(code));
}
void simplifyOperatorName21() {
const char code[] = "template<char...> void operator \"\" _h() {}"
"template<> void operator \"\" _h<'a', 'b', 'c'>() {}"
"template void operator \"\" _h<'a', 'b', 'c', 'd'>();";
ASSERT_EQUALS("void operator\"\"_h<'a','b','c'> ( ) ; "
"void operator\"\"_h<'a','b','c','d'> ( ) ; "
"void operator\"\"_h<'a','b','c'> ( ) { } "
"void operator\"\"_h<'a','b','c','d'> ( ) { }",
tokenizeAndStringify(code));
}
void simplifyOperatorName22() {
const char code[] = "static RSLRelOp convertOperator(const Software::ComparisonOperator& op) {"
" if (op == &Software::operator==) return RSLEqual;"
"return RSLNotEqual;"
"}";
ASSERT_EQUALS("static RSLRelOp convertOperator ( const Software :: ComparisonOperator & op ) { "
"if ( op == & Software :: operator== ) { return RSLEqual ; } "
"return RSLNotEqual ; "
"}",
tokenizeAndStringify(code));
ASSERT_EQUALS(
"[test.cpp:1]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable RSLEqual\n",
filter_valueflow(errout_str()));
}
void simplifyOperatorName23() {
{
const char code[] = "double *vtkMatrix3x3::operator[](const unsigned int i) {"
" VTK_LEGACY_BODY(vtkMatrix3x3::operator[], \"VTK 7.0\");"
" return &(this->Element[i][0]);"
"}";
ASSERT_EQUALS("double * vtkMatrix3x3 :: operator[] ( const unsigned int i ) { "
"VTK_LEGACY_BODY ( vtkMatrix3x3 :: operator[] , \"VTK 7.0\" ) ; "
"return & ( this . Element [ i ] [ 0 ] ) ; "
"}",
tokenizeAndStringify(code));
ignore_errout();
}
{
const char code[] = "double *vtkMatrix3x3::operator,(const unsigned int i) {"
" VTK_LEGACY_BODY(vtkMatrix3x3::operator,, \"VTK 7.0\");"
" return &(this->Element[i][0]);"
"}";
ASSERT_EQUALS("double * vtkMatrix3x3 :: operator, ( const unsigned int i ) { "
"VTK_LEGACY_BODY ( vtkMatrix3x3 :: operator, , \"VTK 7.0\" ) ; "
"return & ( this . Element [ i ] [ 0 ] ) ; "
"}",
tokenizeAndStringify(code));
ignore_errout();
}
}
void simplifyOperatorName24() {
{
const char code[] = "void foo() { int i = a.operator++() ? a.operator--() : 0; }";
ASSERT_EQUALS("void foo ( ) { int i ; i = a . operator++ ( ) ? a . operator-- ( ) : 0 ; }",
tokenizeAndStringify(code));
}
{
const char code[] = "void foo() { int i = a.operator++(0) ? a.operator--(0) : 0; }";
ASSERT_EQUALS("void foo ( ) { int i ; i = a . operator++ ( 0 ) ? a . operator-- ( 0 ) : 0 ; }",
tokenizeAndStringify(code));
}
}
void simplifyOperatorName25() {
const char code[] = "bool negative(const Number &num) { return num.operator std::string()[0] == '-'; }";
ASSERT_EQUALS("bool negative ( const Number & num ) { return num . operatorstd::string ( ) [ 0 ] == '-' ; }",
tokenizeAndStringify(code));
}
void simplifyOperatorName26() {
const char code[] = "void foo() {"
" x = y.operator *().z[123];"
"}";
ASSERT_EQUALS("void foo ( ) { x = y . operator* ( ) . z [ 123 ] ; }",
tokenizeAndStringify(code));
ignore_errout();
}
void simplifyOperatorName27() {
const char code[] = "int operator \"\" i (const char *, int);\n"
"x = \"abc\"i;";
ASSERT_EQUALS("int operator\"\"i ( const char * , int ) ;\n"
"x = operator\"\"i ( \"abc\" , 3 ) ;",
tokenizeAndStringify(code));
}
void simplifyOperatorName28() {
const char code[] = "template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };\n"
"int main() { }";
ASSERT_EQUALS("template < class ... Ts > struct overloaded : Ts ... { using Ts :: operator ( ) ... ; } ;\n"
"int main ( ) { }",
tokenizeAndStringify(code));
ASSERT_EQUALS("[test.cpp:1]: (debug) simplifyOperatorName: found unsimplified operator name\n", errout_str());
}
void simplifyOperatorName29() {
const Settings settings = settingsBuilder().cpp(Standards::CPP20).build();
ASSERT_EQUALS("auto operator<=> ( ) ;", tokenizeAndStringify("auto operator<=>();", settings));
}
void simplifyOverloadedOperators1() {
const char code[] = "struct S { void operator()(int); };\n"
"\n"
"void foo(S x) {\n"
" x(123);\n"
"}";
ASSERT_EQUALS("struct S { void operator() ( int ) ; } ;\n"
"\n"
"void foo ( S x ) {\n"
"x . operator() ( 123 ) ;\n"
"}",
tokenizeAndStringify(code));
}
void simplifyOverloadedOperators2() { // #9879 - (*this)(123);
const char code[] = "struct S {\n"
" void operator()(int);\n"
" void foo() { (*this)(123); }\n"
"};\n";
ASSERT_EQUALS("struct S {\n"
"void operator() ( int ) ;\n"
"void foo ( ) { ( * this ) . operator() ( 123 ) ; }\n"
"} ;",
tokenizeAndStringify(code));
}
void simplifyOverloadedOperators3() { // #9881
const char code[] = "struct Func { double operator()(double x) const; };\n"
"void foo(double, double);\n"
"void test() {\n"
" Func max;\n"
" double y = 0;\n"
" foo(0, max(y));\n"
"}";
ASSERT_EQUALS("struct Func { double operator() ( double x ) const ; } ;\n"
"void foo ( double , double ) ;\n"
"void test ( ) {\n"
"Func max ;\n"
"double y ; y = 0 ;\n"
"foo ( 0 , max . operator() ( y ) ) ;\n"
"}",
tokenizeAndStringify(code));
}
void simplifyNullArray() {
ASSERT_EQUALS("* ( foo . bar [ 5 ] ) = x ;", tokenizeAndStringify("0[foo.bar[5]] = x;"));
}
void removeMacrosInGlobalScope() {
// remove some unhandled macros in the global scope.
ASSERT_EQUALS("void f ( ) { }", tokenizeAndStringify("void f() NOTHROW { }"));
ASSERT_EQUALS("struct Foo { } ;", tokenizeAndStringify("struct __declspec(dllexport) Foo {};"));
ASSERT_THROW_INTERNAL(tokenizeAndStringify("ABA() namespace { int a ; }"), UNKNOWN_MACRO);
// #3750
ASSERT_THROW_INTERNAL(tokenizeAndStringify("; AB(foo*) foo::foo() { }"), UNKNOWN_MACRO);
// #4834 - syntax error
ASSERT_THROW_INTERNAL(tokenizeAndStringify("A(B) foo() {}"), UNKNOWN_MACRO);
// #3855
ASSERT_EQUALS("; class foo { }",
tokenizeAndStringify("; AB class foo { }"));
ASSERT_EQUALS("; CONST struct ABC abc ;",
tokenizeAndStringify("; CONST struct ABC abc ;"));
ASSERT_NO_THROW(tokenizeAndStringify("class A {\n"
" UNKNOWN_MACRO(A)\n" // <- this macro is ignored
"private:\n"
" int x;\n"
"};"));
ASSERT_THROW_INTERNAL(tokenizeAndStringify("MACRO(test) void test() { }"), UNKNOWN_MACRO); // #7931
ASSERT_THROW_INTERNAL(tokenizeAndStringify("BEGIN_MESSAGE_MAP(CSetProgsAdvDlg, CResizableStandAloneDialog)\n"
" ON_BN_CLICKED(IDC_ADDTOOL, OnBnClickedAddtool)\n"
"END_MESSAGE_MAP()\n"
"\n"
"BOOL CSetProgsAdvDlg::OnInitDialog() {}"),
UNKNOWN_MACRO);
ASSERT_EQUALS("struct S {\n"
"S ( ) : p { new ( malloc ( 4 ) ) int { } } { }\n"
"int * p ;\n"
"} ;",
tokenizeAndStringify("struct S {\n"
" S() : p{new (malloc(4)) int{}} {}\n"
" int* p;\n"
"};\n"));
}
void addSemicolonAfterUnknownMacro() {
// #6975
ASSERT_EQUALS("void f ( ) { MACRO ( ) ; try { } }", tokenizeAndStringify("void f() { MACRO() try {} }"));
// #9376
ASSERT_EQUALS("MACRO ( ) ; using namespace foo ;", tokenizeAndStringify("MACRO() using namespace foo;"));
}
void multipleAssignment() {
ASSERT_EQUALS("a = b = 0 ;", tokenizeAndStringify("a=b=0;"));
}
void platformWin() {
const char code[] = "BOOL f;"
"BOOLEAN g;"
"BYTE h;"
"CHAR i;"
"DWORD j;"
"FLOAT k;"
"INT l;"
"INT32 m;"
"INT64 n;"
"LONG o;"
"SHORT p;"
"UCHAR q;"
"UINT r;"
"ULONG s;"
"USHORT t;"
"WORD u;"
"VOID *v;"
"LPBOOL w;"
"PBOOL x;"
"LPBYTE y;"
"PBOOLEAN z;"
"PBYTE A;"
"LPCSTR B;"
"PCSTR C;"
"LPCVOID D;"
"LPDWORD E;"
"LPINT F;"
"PINT G;"
"LPLONG H;"
"PLONG I;"
"LPSTR J;"
"PSTR K;"
"PCHAR L;"
"LPVOID M;"
"PVOID N;"
"BOOL _bool;"
"HFILE hfile;"
"LONG32 long32;"
"LCID lcid;"
"LCTYPE lctype;"
"LGRPID lgrpid;"
"LONG64 long64;"
"PUCHAR puchar;"
"LPCOLORREF lpcolorref;"
"PDWORD pdword;"
"PULONG pulong;"
"SERVICE_STATUS_HANDLE service_status_hanlde;"
"SC_LOCK sc_lock;"
"SC_HANDLE sc_handle;"
"HACCEL haccel;"
"HCONV hconv;"
"HCONVLIST hconvlist;"
"HDDEDATA hddedata;"
"HDESK hdesk;"
"HDROP hdrop;"
"HDWP hdwp;"
"HENHMETAFILE henhmetafile;"
"HHOOK hhook;"
"HKL hkl;"
"HMONITOR hmonitor;"
"HSZ hsz;"
"HWINSTA hwinsta;"
"PWCHAR pwchar;"
"PUSHORT pushort;"
"LANGID langid;"
"DWORD64 dword64;"
"ULONG64 ulong64;"
"LPWSTR lpcwstr;"
"LPCWSTR lpcwstr;"
"LPHANDLE lpHandle;"
"PCWSTR pcwStr;"
"PDWORDLONG pdWordLong;"
"PDWORD_PTR pdWordPtr;"
"PDWORD32 pdWord32;"
"PDWORD64 pdWord64;"
"LONGLONG ll;"
"USN usn;"
"PULONG64 puLong64;"
"PULONG32 puLong32;"
"PFLOAT ptrToFloat;";
const char expected[] = "int f ; "
"unsigned char g ; "
"unsigned char h ; "
"char i ; "
"unsigned long j ; "
"float k ; "
"int l ; "
"int m ; "
"long long n ; "
"long o ; "
"short p ; "
"unsigned char q ; "
"unsigned int r ; "
"unsigned long s ; "
"unsigned short t ; "
"unsigned short u ; "
"void * v ; "
"int * w ; "
"int * x ; "
"unsigned char * y ; "
"unsigned char * z ; "
"unsigned char * A ; "
"const char * B ; "
"const char * C ; "
"const void * D ; "
"unsigned long * E ; "
"int * F ; "
"int * G ; "
"long * H ; "
"long * I ; "
"char * J ; "
"char * K ; "
"char * L ; "
"void * M ; "
"void * N ; "
"int _bool ; "
"int hfile ; "
"int long32 ; "
"unsigned long lcid ; "
"unsigned long lctype ; "
"unsigned long lgrpid ; "
"long long long64 ; "
"unsigned char * puchar ; "
"unsigned long * lpcolorref ; "
"unsigned long * pdword ; "
"unsigned long * pulong ; "
"void * service_status_hanlde ; "
"void * sc_lock ; "
"void * sc_handle ; "
"void * haccel ; "
"void * hconv ; "
"void * hconvlist ; "
"void * hddedata ; "
"void * hdesk ; "
"void * hdrop ; "
"void * hdwp ; "
"void * henhmetafile ; "
"void * hhook ; "
"void * hkl ; "
"void * hmonitor ; "
"void * hsz ; "
"void * hwinsta ; "
"wchar_t * pwchar ; "
"unsigned short * pushort ; "
"unsigned short langid ; "
"unsigned long long dword64 ; "
"unsigned long long ulong64 ; "
"wchar_t * lpcwstr ; "
"const wchar_t * lpcwstr ; "
"void * lpHandle ; "
"const wchar_t * pcwStr ; "
"long * pdWordLong ; "
"long * pdWordPtr ; "
"unsigned int * pdWord32 ; "
"unsigned long * pdWord64 ; "
"long long ll ; "
"long long usn ; "
"unsigned long long * puLong64 ; "
"unsigned int * puLong32 ; "
"float * ptrToFloat ;";
// These types should be defined the same on all Windows platforms
const std::string win32A = tokenizeAndStringifyWindows(code, true, Platform::Type::Win32A);
ASSERT_EQUALS(expected, win32A);
ASSERT_EQUALS(win32A, tokenizeAndStringifyWindows(code, true, Platform::Type::Win32W));
ASSERT_EQUALS(win32A, tokenizeAndStringifyWindows(code, true, Platform::Type::Win64));
}
void platformWin32A() {
const char code[] = "wchar_t wc;"
"TCHAR c;"
"PTSTR ptstr;"
"LPTSTR lptstr;"
"PCTSTR pctstr;"
"LPCTSTR lpctstr;"
"void foo() {"
" TCHAR tc = _T(\'c\'); "
" TCHAR src[10] = _T(\"123456789\");"
" TCHAR dst[10];"
" _tcscpy(dst, src);"
" dst[0] = 0;"
" _tcscat(dst, src);"
" LPTSTR d = _tcsdup(src);"
" _tprintf(_T(\"Hello world!\"));"
" _stprintf(dst, _T(\"Hello!\"));"
" _sntprintf(dst, sizeof(dst) / sizeof(TCHAR), _T(\"Hello world!\"));"
" _tscanf(_T(\"%s\"), dst);"
" _stscanf(dst, _T(\"%s\"), dst);"
"}"
"TBYTE tbyte;";
const char expected[] = "wchar_t wc ; "
"char c ; "
"char * ptstr ; "
"char * lptstr ; "
"const char * pctstr ; "
"const char * lpctstr ; "
"void foo ( ) { "
"char tc ; tc = \'c\' ; "
"char src [ 10 ] = \"123456789\" ; "
"char dst [ 10 ] ; "
"strcpy ( dst , src ) ; "
"dst [ 0 ] = 0 ; "
"strcat ( dst , src ) ; "
"char * d ; d = strdup ( src ) ; "
"printf ( \"Hello world!\" ) ; "
"sprintf ( dst , \"Hello!\" ) ; "
"_snprintf ( dst , sizeof ( dst ) / sizeof ( char ) , \"Hello world!\" ) ; "
"scanf ( \"%s\" , dst ) ; "
"sscanf ( dst , \"%s\" , dst ) ; "
"} "
"unsigned char tbyte ;";
ASSERT_EQUALS(expected, tokenizeAndStringifyWindows(code, true, Platform::Type::Win32A));
const char code2[] = "LPCTSTR f(void* p) { return LPCTSTR(p); }\n" // #11430
"LPCTSTR g() { return LPCTSTR{}; }";
const char expected2[] = "const char * f ( void * p ) { return ( const char * ) ( p ) ; }\n"
"const char * g ( ) { return ( const char * ) ( 0 ) ; }";
ASSERT_EQUALS(expected2, tokenizeAndStringifyWindows(code2, true, Platform::Type::Win32A));
}
void platformWin32W() {
const char code[] = "wchar_t wc;"
"TCHAR c;"
"PTSTR ptstr;"
"LPTSTR lptstr;"
"PCTSTR pctstr;"
"LPCTSTR lpctstr;"
"TBYTE tbyte;"
"void foo() {"
" TCHAR tc = _T(\'c\');"
" TCHAR src[10] = _T(\"123456789\");"
" TCHAR dst[10];"
" _tcscpy(dst, src);"
" dst[0] = 0;"
" _tcscat(dst, src);"
" LPTSTR d = _tcsdup(src);"
" _tprintf(_T(\"Hello world!\"));"
" _stprintf(dst, _T(\"Hello!\"));"
" _sntprintf(dst, sizeof(dst) / sizeof(TCHAR), _T(\"Hello world!\"));"
" _tscanf(_T(\"%s\"), dst);"
" _stscanf(dst, _T(\"%s\"), dst);"
"}";
const char expected[] = "wchar_t wc ; "
"wchar_t c ; "
"wchar_t * ptstr ; "
"wchar_t * lptstr ; "
"const wchar_t * pctstr ; "
"const wchar_t * lpctstr ; "
"unsigned wchar_t tbyte ; "
"void foo ( ) { "
"wchar_t tc ; tc = L\'c\' ; "
"wchar_t src [ 10 ] = L\"123456789\" ; "
"wchar_t dst [ 10 ] ; "
"wcscpy ( dst , src ) ; "
"dst [ 0 ] = 0 ; "
"wcscat ( dst , src ) ; "
"wchar_t * d ; d = wcsdup ( src ) ; "
"wprintf ( L\"Hello world!\" ) ; "
"swprintf ( dst , L\"Hello!\" ) ; "
"_snwprintf ( dst , sizeof ( dst ) / sizeof ( wchar_t ) , L\"Hello world!\" ) ; "
"wscanf ( L\"%s\" , dst ) ; "
"swscanf ( dst , L\"%s\" , dst ) ; "
"}";
ASSERT_EQUALS(expected, tokenizeAndStringifyWindows(code, true, Platform::Type::Win32W));
}
void platformWin32AStringCat() { //#5150
const char code[] = "TCHAR text[] = _T(\"123\") _T(\"456\") _T(\"789\");";
const char expected[] = "char text [ 10 ] = \"123456789\" ;";
ASSERT_EQUALS(expected, tokenizeAndStringifyWindows(code, true, Platform::Type::Win32A));
}
void platformWin32WStringCat() { //#5150
const char code[] = "TCHAR text[] = _T(\"123\") _T(\"456\") _T(\"789\");";
const char expected[] = "wchar_t text [ 10 ] = L\"123456789\" ;";
ASSERT_EQUALS(expected, tokenizeAndStringifyWindows(code, true, Platform::Type::Win32W));
}
void platformWinWithNamespace() {
const char code1[] = "UINT32 a; ::UINT32 b; foo::UINT32 c;";
const char expected1[] = "unsigned int a ; unsigned int b ; foo :: UINT32 c ;";
ASSERT_EQUALS(expected1, tokenizeAndStringifyWindows(code1, true, Platform::Type::Win32A));
const char code2[] = "LPCVOID a; ::LPCVOID b; foo::LPCVOID c;";
const char expected2[] = "const void * a ; const void * b ; foo :: LPCVOID c ;";
ASSERT_EQUALS(expected2, tokenizeAndStringifyWindows(code2, true, Platform::Type::Win32A));
}
void isOneNumber() const {
ASSERT_EQUALS(true, Tokenizer::isOneNumber("1.0"));
ASSERT_EQUALS(true, Tokenizer::isOneNumber("+1.0"));
ASSERT_EQUALS(true, Tokenizer::isOneNumber("1.0e+0"));
ASSERT_EQUALS(true, Tokenizer::isOneNumber("+1L"));
ASSERT_EQUALS(true, Tokenizer::isOneNumber("+1"));
ASSERT_EQUALS(true, Tokenizer::isOneNumber("1"));
ASSERT_EQUALS(true, Tokenizer::isOneNumber("+1E+0"));
ASSERT_EQUALS(false, Tokenizer::isOneNumber("0.0"));
ASSERT_EQUALS(false, Tokenizer::isOneNumber("+0.0"));
ASSERT_EQUALS(false, Tokenizer::isOneNumber("-0"));
ASSERT_EQUALS(false, Tokenizer::isOneNumber(""));
ASSERT_EQUALS(false, Tokenizer::isOneNumber("garbage"));
}
void simplifyStaticConst() {
const char code1[] = "class foo { public: bool const static c ; }";
const char expected1[] = "class foo { public: static const bool c ; }";
ASSERT_EQUALS(expected1, tokenizeAndStringify(code1));
const char code2[] =
"int long long f()\n"
"{\n"
"static const long long signed int i1;\n"
"static const long long int signed i2;\n"
"static const signed long long int i3;\n"
"static const signed int long long i4;\n"
"static const int signed long long i5;\n"
"static const int long long signed i6;\n"
"long long static const signed int i7;\n"
"long long static const int signed i8;\n"
"signed static const long long int i9;\n"
"signed static const int long long i10;\n"
"int static const signed long long i11;\n"
"int static const long long signed i12;\n"
"long long signed int static const i13;\n"
"long long int signed static const i14;\n"
"signed long long int static const i15;\n"
"signed int long long static const i16;\n"
"int signed long long static const i17;\n"
"int long long signed static const i18;\n"
"return i1 + i2 + i3 + i4 + i5 + i6 + i7 + i8 + i9 + i10 + i11 + i12\n"
"+ i13 + i14 + i15 + i16 + i17 + i18;\n"
"}";
const char expected2[] =
"long long f ( )\n"
"{\n"
"static const signed long long i1 ;\n"
"static const signed long long i2 ;\n"
"static const signed long long i3 ;\n"
"static const signed long long i4 ;\n"
"static const signed long long i5 ;\n"
"static const signed long long i6 ;\n"
"static const signed long long i7 ;\n"
"static const signed long long i8 ;\n"
"static const signed long long i9 ;\n"
"static const signed long long i10 ;\n"
"static const signed long long i11 ;\n"
"static const signed long long i12 ;\n"
"static const signed long long i13 ;\n"
"static const signed long long i14 ;\n"
"static const signed long long i15 ;\n"
"static const signed long long i16 ;\n"
"static const signed long long i17 ;\n"
"static const signed long long i18 ;\n"
"return i1 + i2 + i3 + i4 + i5 + i6 + i7 + i8 + i9 + i10 + i11 + i12\n"
"+ i13 + i14 + i15 + i16 + i17 + i18 ;\n"
"}";
ASSERT_EQUALS(expected2, tokenizeAndStringify(code2));
const char code3[] = "const unsigned long extern int i;";
const char expected3[] = "extern const unsigned long i ;";
ASSERT_EQUALS(expected3, tokenizeAndStringify(code3));
}
void simplifyCPPAttribute() {
ASSERT_EQUALS("int f ( ) ;",
tokenizeAndStringify("[[deprecated]] int f();"));
ASSERT_THROW_INTERNAL(tokenizeAndStringify("[[deprecated]] int f();", true, Platform::Type::Native, false), SYNTAX);
ASSERT_EQUALS("template < class T > int f ( ) { }",
tokenizeAndStringify("template <class T> [[noreturn]] int f(){}"));
ASSERT_EQUALS("int f ( int i ) ;",
tokenizeAndStringify("[[maybe_unused]] int f([[maybe_unused]] int i);"));
ASSERT_EQUALS("struct a ;",
tokenizeAndStringify("struct [[]] a;"));
ASSERT_EQUALS("struct a ;",
tokenizeAndStringify("struct [[,]] a;"));
ASSERT_EQUALS("struct a ;",
tokenizeAndStringify("struct [[deprecated,]] a;"));
ASSERT_EQUALS("struct a ;",
tokenizeAndStringify("struct [[,,]] a;"));
ASSERT_EQUALS("struct a ;",
tokenizeAndStringify("struct [[deprecated,,]] a;"));
ASSERT_EQUALS("struct a ;",
tokenizeAndStringify("struct [[deprecated,maybe_unused,]] a;"));
ASSERT_EQUALS("struct a ;",
tokenizeAndStringify("struct [[,,,]] a;"));
ASSERT_EQUALS("struct a ;",
tokenizeAndStringify("struct alignas(int) a;"));
ASSERT_EQUALS("struct a ;",
tokenizeAndStringify("struct alignas ( alignof ( float ) ) a;"));
ASSERT_EQUALS("char a [ 256 ] ;",
tokenizeAndStringify("alignas(256) char a[256];"));
ASSERT_EQUALS("struct a ;",
tokenizeAndStringify("struct alignas(float) [[deprecated(reason)]] a;"));
ASSERT_EQUALS("struct a ;",
tokenizeAndStringify("struct [[deprecated,maybe_unused]] alignas(double) [[trivial_abi]] a;"));
ASSERT_EQUALS("void func5 ( const char * , ... ) ;",
tokenizeAndStringify("[[noreturn]] void func5(const char*, ...);"));
ASSERT_EQUALS("void func5 ( const char * , ... ) ;",
tokenizeAndStringify("[[noreturn]] [[gnu::format(printf, 1, 2)]] void func5(const char*, ...);"));
ASSERT_EQUALS("void func5 ( const char * , ... ) ;",
tokenizeAndStringify("[[gnu::format(printf, 1, 2)]] [[noreturn]] void func5(const char*, ...);"));
ASSERT_EQUALS("int func1 ( ) ;",
tokenizeAndStringify("[[nodiscard]] int func1();"));
ASSERT_EQUALS("int func1 ( ) ;",
tokenizeAndStringify("[[nodiscard]] [[clang::optnone]] int func1();"));
ASSERT_EQUALS("int func1 ( ) ;",
tokenizeAndStringify("[[clang::optnone]] [[nodiscard]] int func1();"));
ASSERT_EQUALS("void f ( int i ) { exit ( i ) ; }",
tokenizeAndStringify("[[noreturn]] void f(int i) { exit(i); }", /*expand*/ true, Platform::Type::Native, /*cpp*/ false, Standards::CPP11, Standards::C23));
}
void simplifyCaseRange() {
ASSERT_EQUALS("void f ( int x ) { switch ( x ) { case 1 : case 2 : case 3 : case 4 : ; } }", tokenizeAndStringify("void f(int x) { switch(x) { case 1 ... 4: } }"));
ASSERT_EQUALS("void f ( int x ) { switch ( x ) { case 4 ... 1 : ; } }", tokenizeAndStringify("void f(int x) { switch(x) { case 4 ... 1: } }"));
(void)tokenizeAndStringify("void f(int x) { switch(x) { case 1 ... 1000000: } }"); // Do not run out of memory
ASSERT_EQUALS("void f ( int x ) { switch ( x ) { case 'a' : case 98 : case 'c' : ; } }", tokenizeAndStringify("void f(int x) { switch(x) { case 'a' ... 'c': } }"));
ASSERT_EQUALS("void f ( int x ) { switch ( x ) { case 'c' ... 'a' : ; } }", tokenizeAndStringify("void f(int x) { switch(x) { case 'c' ... 'a': } }"));
ASSERT_EQUALS("void f ( int x ) { switch ( x ) { case '[' : case 92 : case ']' : ; } }", tokenizeAndStringify("void f(int x) { switch(x) { case '[' ... ']': } }"));
ASSERT_EQUALS("void f ( int x ) { switch ( x ) { case '&' : case 39 : case '(' : ; } }", tokenizeAndStringify("void f(int x) { switch(x) { case '&' ... '(': } }"));
ASSERT_EQUALS("void f ( int x ) { switch ( x ) { case '\\x61' : case 98 : case '\\x63' : ; } }", tokenizeAndStringify("void f(int x) { switch(x) { case '\\x61' ... '\\x63': } }"));
}
void simplifyEmptyNamespaces() {
ASSERT_EQUALS(";", tokenizeAndStringify("namespace { }"));
ASSERT_EQUALS(";", tokenizeAndStringify("namespace foo { }"));
ASSERT_EQUALS(";", tokenizeAndStringify("namespace foo { namespace { } }"));
ASSERT_EQUALS(";", tokenizeAndStringify("namespace { namespace { } }")); // Ticket #9512
ASSERT_EQUALS(";", tokenizeAndStringify("namespace foo { namespace bar { } }"));
}
void prepareTernaryOpForAST() {
ASSERT_EQUALS("a ? b : c ;", tokenizeAndStringify("a ? b : c;"));
ASSERT_EQUALS("a ? ( b , c ) : d ;", tokenizeAndStringify("a ? b , c : d;"));
ASSERT_EQUALS("a ? ( b , c ) : d ;", tokenizeAndStringify("a ? (b , c) : d;"));
ASSERT_EQUALS("a ? ( 1 ? ( a , b ) : 3 ) : d ;", tokenizeAndStringify("a ? 1 ? a, b : 3 : d;"));
ASSERT_EQUALS("a ? ( std :: map < int , int > ( ) ) : 0 ;", tokenizeAndStringify("typedef std::map<int,int> mymap; a ? mymap() : 0;"));
ASSERT_EQUALS("a ? ( b < c ) : d > e", tokenizeAndStringify("a ? b < c : d > e"));
}
enum class AstStyle : std :: uint8_t {
Simple,
Z3
};
std::string testAst(const char code[], AstStyle style = AstStyle::Simple) {
// tokenize given code..
Tokenizer tokenizer(settings0, *this);
std::istringstream istr(code);
if (!tokenizer.list.createTokens(istr,"test.cpp"))
return "ERROR";
tokenizer.combineStringAndCharLiterals();
tokenizer.combineOperators();
tokenizer.simplifySpaceshipOperator();
tokenizer.createLinks();
tokenizer.createLinks2();
tokenizer.list.front()->assignIndexes();
// set varid..
for (Token *tok = tokenizer.list.front(); tok; tok = tok->next()) {
if (tok->str() == "var")
tok->varId(1);
}
// Create AST..
tokenizer.prepareTernaryOpForAST();
tokenizer.list.createAst();
tokenizer.list.validateAst(false);
// Basic AST validation
for (const Token *tok = tokenizer.list.front(); tok; tok = tok->next()) {
if (tok->astOperand2() && !tok->astOperand1() && tok->str() != ";" && tok->str() != ":")
return "Op2 but no Op1 for token: " + tok->str();
}
// Return stringified AST
if (style == AstStyle::Z3)
return tokenizer.list.front()->astTop()->astStringZ3();
std::string ret;
std::set<const Token *> astTop;
for (const Token *tok = tokenizer.list.front(); tok; tok = tok->next()) {
if (tok->astOperand1() && astTop.find(tok->astTop()) == astTop.end()) {
astTop.insert(tok->astTop());
if (!ret.empty())
ret += " ";
ret += tok->astTop()->astString();
}
}
return ret;
}
void astexpr() { // simple expressions with arithmetical ops
ASSERT_EQUALS("12+3+", testAst("1+2+3"));
ASSERT_EQUALS("12*3+", testAst("1*2+3"));
ASSERT_EQUALS("123*+", testAst("1+2*3"));
ASSERT_EQUALS("12*34*+", testAst("1*2+3*4"));
ASSERT_EQUALS("12*34*5*+", testAst("1*2+3*4*5"));
ASSERT_EQUALS("0(r.&", testAst("(&((typeof(x))0).r);"));
ASSERT_EQUALS("0(r.&", testAst("&((typeof(x))0).r;"));
ASSERT_EQUALS("0f1(||", testAst("; 0 || f(1);"));
// Various tests of precedence
ASSERT_EQUALS("ab::c+", testAst("a::b+c"));
ASSERT_EQUALS("abc+=", testAst("a=b+c"));
ASSERT_EQUALS("abc=,", testAst("a,b=c"));
ASSERT_EQUALS("a-1+", testAst("-a+1"));
ASSERT_EQUALS("ab++-c-", testAst("a-b++-c"));
ASSERT_EQUALS("ab<=>", testAst("a<=>b"));
// sizeof
ASSERT_EQUALS("ab.sizeof", testAst("sizeof a.b"));
// assignment operators
ASSERT_EQUALS("ab>>=", testAst("a>>=b;"));
ASSERT_EQUALS("ab<<=", testAst("a<<=b;"));
ASSERT_EQUALS("ab+=", testAst("a+=b;"));
ASSERT_EQUALS("ab-=", testAst("a-=b;"));
ASSERT_EQUALS("ab*=", testAst("a*=b;"));
ASSERT_EQUALS("ab/=", testAst("a/=b;"));
ASSERT_EQUALS("ab%=", testAst("a%=b;"));
ASSERT_EQUALS("ab&=", testAst("a&=b;"));
ASSERT_EQUALS("ab|=", testAst("a|=b;"));
ASSERT_EQUALS("ab^=", testAst("a^=b;"));
ASSERT_EQUALS("ab*c*.(+return", testAst("return a + ((*b).*c)();"));
// assignments are executed from right to left
ASSERT_EQUALS("abc==", testAst("a=b=c;"));
// ternary operator
ASSERT_EQUALS("ab0=c1=:?", testAst("a?b=0:c=1;"));
ASSERT_EQUALS("fabc,d:?=e,", testAst("f = a ? b, c : d, e;"));
ASSERT_EQUALS("fabc,de,:?=", testAst("f = (a ? (b, c) : (d, e));"));
ASSERT_EQUALS("fabc,de,:?=", testAst("f = (a ? b, c : (d, e));"));
ASSERT_EQUALS("ab35,4:?foo(:?return", testAst("return (a ? b ? (3,5) : 4 : foo());"));
ASSERT_EQUALS("check(result_type00,{invalid:?return", testAst("return check() ? result_type {0, 0} : invalid;"));
ASSERT_EQUALS("x01:?return", testAst("return x ? 0 : 1;"));
ASSERT_EQUALS("x00throw:?return", testAst("return x ? 0 : throw 0;")); // #9768
ASSERT_EQUALS("val0<1throwval:?return", testAst("return val < 0 ? throw 1 : val;")); // #8526
ASSERT_EQUALS("ix0<00throw:?=", testAst("int i = x < 0 ? 0 : throw 0;"));
ASSERT_EQUALS("pa[pb[<1-pa[pb[>:?return", testAst("return p[a] < p[b] ? -1 : p[a] > p[b];"));
ASSERT_EQUALS("a\"\"=", testAst("a=\"\""));
ASSERT_EQUALS("a\'\'=", testAst("a=\'\'"));
ASSERT_EQUALS("'X''a'>", testAst("('X' > 'a')"));
ASSERT_EQUALS("L'X'L'a'>", testAst("(L'X' > L'a')"));
ASSERT_EQUALS("u'X'u'a'>", testAst("(u'X' > u'a')"));
ASSERT_EQUALS("U'X'U'a'>", testAst("(U'X' > U'a')"));
ASSERT_EQUALS("u8'X'u8'a'>", testAst("(u8'X' > u8'a')"));
ASSERT_EQUALS("a0>bc/d:?", testAst("(a>0) ? (b/(c)) : d;"));
ASSERT_EQUALS("abc/+d+", testAst("a + (b/(c)) + d;"));
ASSERT_EQUALS("x1024x/0:?", testAst("void f() { x ? 1024 / x : 0; }"));
ASSERT_EQUALS("absizeofd(ef.+(=", testAst("a = b(sizeof(c d) + e.f)"));
ASSERT_EQUALS("a*b***", testAst("*a * **b;")); // Correctly distinguish between unary and binary operator*
// strings
ASSERT_EQUALS("f\"A\"1,(",testAst("f(\"A\" B, 1);"));
ASSERT_EQUALS("fA1,(",testAst("f(A \"B\", 1);"));
// C++ : type()
ASSERT_EQUALS("fint(0,(", testAst("f(int(),0);"));
ASSERT_EQUALS("f(0,(", testAst("f(int *(),0);")); // typedef int* X; f(X(),0);
ASSERT_EQUALS("f((0,(", testAst("f((intp)int *(),0);"));
ASSERT_EQUALS("zx1(&y2(&|=", testAst("z = (x & (unsigned)1) | (y & (unsigned)2);")); // not type()
// for
ASSERT_EQUALS("for;;(", testAst("for(;;)"));
ASSERT_EQUALS("fora0=a8<a++;;(", testAst("for(a=0;a<8;a++)"));
ASSERT_EQUALS("fori1=current0=,iNUM<=i++;;(", testAst("for(i = (1), current = 0; i <= (NUM); ++i)"));
ASSERT_EQUALS("foreachxy,((", testAst("for(each(x,y)){}")); // it's not well-defined what this ast should be
ASSERT_EQUALS("forvar1(;;(", testAst("for(int var(1);;)"));
ASSERT_EQUALS("forab:(", testAst("for (int a : b);"));
ASSERT_EQUALS("forvarb:(", testAst("for (int *var : b);"));
ASSERT_EQUALS("forvard:(", testAst("for (a<b> var : d);"));
ASSERT_EQUALS("forvare:(", testAst("for (a::b<c> var : e);"));
ASSERT_EQUALS("forx*0=yz;;(", testAst("for(*x=0;y;z)"));
ASSERT_EQUALS("forx0=y(8<z;;(", testAst("for (x=0;(int)y<8;z);"));
ASSERT_EQUALS("forab,c:(", testAst("for (auto [a,b]: c);"));
ASSERT_EQUALS("fora*++;;(", testAst("for (++(*a);;);"));
ASSERT_EQUALS("foryz:(", testAst("for (decltype(x) *y : z);"));
ASSERT_EQUALS("for(tmpNULL!=tmptmpnext.=;;( tmpa=", testAst("for ( ({ tmp = a; }) ; tmp != NULL; tmp = tmp->next ) {}"));
ASSERT_EQUALS("forx0=x;;(", testAst("for (int x=0; x;);"));
ASSERT_EQUALS("forae*bc.({:(", testAst("for (a *e : {b->c()});"));
ASSERT_EQUALS("fori0=iasize.(<i++;;( asize.(", testAst("for (decltype(a.size()) i = 0; i < a.size(); ++i);"));
ASSERT_EQUALS("foria:( asize.(", testAst("for(decltype(a.size()) i:a);"));
ASSERT_EQUALS("forec0{([,(:( fb.return", testAst("for (auto e : c(0, [](auto f) { return f->b; }));")); // #10802
ASSERT_EQUALS("forvar1{;;(", testAst("for(int var{1};;)")); // #12867
// for with initializer (c++20)
ASSERT_EQUALS("forab=ca:;(", testAst("for(a=b;int c:a)"));
// problems with multiple expressions
ASSERT_EQUALS("ax( whilex(", testAst("a(x) while (x)"));
ASSERT_EQUALS("ifx( i0= whilei(", testAst("if (x) { ({ int i = 0; while(i); }) };"));
ASSERT_EQUALS("ifx( BUG_ON{!( i0= whilei(", testAst("if (x) { BUG_ON(!({int i=0; while(i);})); }"));
ASSERT_EQUALS("v0= while{0!=( v0= while{0!=( v0=", testAst("({ v = 0; }); while (({ v = 0; }) != 0); while (({ v = 0; }) != 0);"));
ASSERT_EQUALS("abc.1:?1+bd.1:?+=", testAst("a =(b.c ? : 1) + 1 + (b.d ? : 1);"));
ASSERT_EQUALS("catch...(", testAst("try {} catch (...) {}"));
ASSERT_EQUALS("", testAst("void Foo(Bar&);"));
ASSERT_EQUALS("", testAst("void Foo(Bar&&);"));
ASSERT_EQUALS("Barb&", testAst("void Foo(Bar& b);"));
ASSERT_EQUALS("Barb&&", testAst("void Foo(Bar&& b);"));
ASSERT_EQUALS("DerivedDerived::(", testAst("Derived::~Derived() {}"));
ASSERT_EQUALS("ifCA_FarReadfilenew(,sizeofobjtype(,(!(", testAst("if (!CA_FarRead(file, (void far *)new, sizeof(objtype)))")); // #5910 - don't hang if C code is parsed as C++
// C++17: if (expr1; expr2)
ASSERT_EQUALS("ifx3=y;(", testAst("if (int x=3; y)"));
ASSERT_EQUALS("xstdstring::decltypes(a::{=", testAst("auto x = std::string{ decltype(s)::a };"));
ASSERT_EQUALS("if0decltypest.(X::>(", testAst("if (0 > decltype(s.t)::X) {}"));
}
void astexpr2() { // limit for large expressions
// #7724 - wrong AST causes hang
// Ideally a proper AST is created for this code.
const char code1[] = "const char * a(int type) {\n"
" return (\n"
" (type == 1) ? \"\"\n"
" : (type == 2) ? \"\"\n"
" : (type == 3) ? \"\"\n"
" : (type == 4) ? \"\"\n"
" : (type == 5) ? \"\"\n"
" : (type == 6) ? \"\"\n"
" : (type == 7) ? \"\"\n"
" : (type == 8) ? \"\"\n"
" : (type == 9) ? \"\"\n"
" : (type == 10) ? \"\"\n"
" : (type == 11) ? \"\"\n"
" : (type == 12) ? \"\"\n"
" : (type == 13) ? \"\"\n"
" : (type == 14) ? \"\"\n"
" : (type == 15) ? \"\"\n"
" : (type == 16) ? \"\"\n"
" : (type == 17) ? \"\"\n"
" : (type == 18) ? \"\"\n"
" : (type == 19) ? \"\"\n"
" : (type == 20) ? \"\"\n"
" : (type == 21) ? \"\"\n"
" : (type == 22) ? \"\"\n"
" : (type == 23) ? \"\"\n"
" : (type == 24) ? \"\"\n"
" : (type == 25) ? \"\"\n"
" : (type == 26) ? \"\"\n"
" : (type == 27) ? \"\"\n"
" : (type == 28) ? \"\"\n"
" : (type == 29) ? \"\"\n"
" : (type == 30) ? \"\"\n"
" : (type == 31) ? \"\"\n"
" : (type == 32) ? \"\"\n"
" : (type == 33) ? \"\"\n"
" : (type == 34) ? \"\"\n"
" : (type == 35) ? \"\"\n"
" : (type == 36) ? \"\"\n"
" : (type == 37) ? \"\"\n"
" : (type == 38) ? \"\"\n"
" : (type == 39) ? \"\"\n"
" : (type == 40) ? \"\"\n"
" : (type == 41) ? \"\"\n"
" : (type == 42) ? \"\"\n"
" : (type == 43) ? \"\"\n"
" : (type == 44) ? \"\"\n"
" : (type == 45) ? \"\"\n"
" : (type == 46) ? \"\"\n"
" : (type == 47) ? \"\"\n"
" : (type == 48) ? \"\"\n"
" : (type == 49) ? \"\"\n"
" : (type == 50) ? \"\"\n"
" : (type == 51) ? \"\"\n"
" : \"\");\n"
"}\n";
// Ensure that the AST is validated for the simplified token list
TODO_ASSERT_THROW(tokenizeAndStringify(code1), InternalError); // this should not crash/hang
const char code2[] = "template<uint64_t kInput>\n" // #11515
"struct ConstCTZ {\n"
" static constexpr uint32_t value =\n"
" (kInput & (uint64_t(1) << 0)) ? 0 :\n"
" (kInput & (uint64_t(1) << 1)) ? 1 :\n"
" (kInput & (uint64_t(1) << 2)) ? 2 :\n"
" (kInput & (uint64_t(1) << 3)) ? 3 :\n"
" (kInput & (uint64_t(1) << 4)) ? 4 :\n"
" (kInput & (uint64_t(1) << 5)) ? 5 :\n"
" (kInput & (uint64_t(1) << 6)) ? 6 :\n"
" (kInput & (uint64_t(1) << 7)) ? 7 :\n"
" (kInput & (uint64_t(1) << 8)) ? 8 :\n"
" (kInput & (uint64_t(1) << 9)) ? 9 :\n"
" (kInput & (uint64_t(1) << 10)) ? 10 :\n"
" (kInput & (uint64_t(1) << 11)) ? 11 :\n"
" (kInput & (uint64_t(1) << 12)) ? 12 :\n"
" (kInput & (uint64_t(1) << 13)) ? 13 :\n"
" (kInput & (uint64_t(1) << 14)) ? 14 :\n"
" (kInput & (uint64_t(1) << 15)) ? 15 :\n"
" (kInput & (uint64_t(1) << 16)) ? 16 :\n"
" (kInput & (uint64_t(1) << 17)) ? 17 :\n"
" (kInput & (uint64_t(1) << 18)) ? 18 :\n"
" (kInput & (uint64_t(1) << 19)) ? 19 :\n"
" (kInput & (uint64_t(1) << 20)) ? 20 :\n"
" (kInput & (uint64_t(1) << 21)) ? 21 :\n"
" (kInput & (uint64_t(1) << 22)) ? 22 :\n"
" (kInput & (uint64_t(1) << 23)) ? 23 :\n"
" (kInput & (uint64_t(1) << 24)) ? 24 :\n"
" (kInput & (uint64_t(1) << 25)) ? 25 :\n"
" (kInput & (uint64_t(1) << 26)) ? 26 :\n"
" (kInput & (uint64_t(1) << 27)) ? 27 :\n"
" (kInput & (uint64_t(1) << 28)) ? 28 :\n"
" (kInput & (uint64_t(1) << 29)) ? 29 :\n"
" (kInput & (uint64_t(1) << 30)) ? 30 :\n"
" (kInput & (uint64_t(1) << 31)) ? 31 :\n"
" (kInput & (uint64_t(1) << 32)) ? 32 :\n"
" (kInput & (uint64_t(1) << 33)) ? 33 :\n"
" (kInput & (uint64_t(1) << 34)) ? 34 :\n"
" (kInput & (uint64_t(1) << 35)) ? 35 :\n"
" (kInput & (uint64_t(1) << 36)) ? 36 :\n"
" (kInput & (uint64_t(1) << 37)) ? 37 :\n"
" (kInput & (uint64_t(1) << 38)) ? 38 :\n"
" (kInput & (uint64_t(1) << 39)) ? 39 :\n"
" (kInput & (uint64_t(1) << 40)) ? 40 :\n"
" (kInput & (uint64_t(1) << 41)) ? 41 :\n"
" (kInput & (uint64_t(1) << 42)) ? 42 :\n"
" (kInput & (uint64_t(1) << 43)) ? 43 :\n"
" (kInput & (uint64_t(1) << 44)) ? 44 :\n"
" (kInput & (uint64_t(1) << 45)) ? 45 :\n"
" (kInput & (uint64_t(1) << 46)) ? 46 :\n"
" (kInput & (uint64_t(1) << 47)) ? 47 :\n"
" (kInput & (uint64_t(1) << 48)) ? 48 :\n"
" (kInput & (uint64_t(1) << 49)) ? 49 :\n"
" (kInput & (uint64_t(1) << 50)) ? 50 :\n"
" (kInput & (uint64_t(1) << 51)) ? 51 :\n"
" (kInput & (uint64_t(1) << 52)) ? 52 :\n"
" (kInput & (uint64_t(1) << 53)) ? 53 :\n"
" (kInput & (uint64_t(1) << 54)) ? 54 :\n"
" (kInput & (uint64_t(1) << 55)) ? 55 :\n"
" (kInput & (uint64_t(1) << 56)) ? 56 :\n"
" (kInput & (uint64_t(1) << 57)) ? 57 :\n"
" (kInput & (uint64_t(1) << 58)) ? 58 :\n"
" (kInput & (uint64_t(1) << 59)) ? 59 :\n"
" (kInput & (uint64_t(1) << 60)) ? 60 :\n"
" (kInput & (uint64_t(1) << 61)) ? 61 :\n"
" (kInput & (uint64_t(1) << 62)) ? 62 :\n"
" (kInput & (uint64_t(1) << 63)) ? 63 : 64;\n"
"};\n";
ASSERT_NO_THROW(tokenizeAndStringify(code2));
const char code3[] = "void f(const std::vector<int>& v) {\n" // #12569
" ::std::for_each(v.begin(), v.end(), [](int i) {\n"
" int j(i ? i : 5);\n"
" });\n"
"}\n";
ASSERT_NO_THROW(tokenizeAndStringify(code3));
}
void astnewdelete() {
ASSERT_EQUALS("aintnew=", testAst("a = new int;"));
ASSERT_EQUALS("aint4[new=", testAst("a = new int[4];"));
ASSERT_EQUALS("aFoobar(new=", testAst("a = new Foo(bar);"));
ASSERT_EQUALS("aFoobar(new=", testAst("a = new Foo(bar);"));
ASSERT_EQUALS("aFoo(new=", testAst("a = new Foo<bar>();"));
ASSERT_EQUALS("aXnew(", testAst("a (new (X));"));
ASSERT_EQUALS("aXnew5,(", testAst("a (new (X), 5);"));
ASSERT_EQUALS("adelete", testAst("delete a;"));
ASSERT_EQUALS("adelete", testAst("delete (a);"));
ASSERT_EQUALS("adelete", testAst("delete[] a;"));
ASSERT_EQUALS("ab.3c-(delete", testAst("delete[] a.b(3 - c);"));
ASSERT_EQUALS("aA1(new(bB2(new(,", testAst("a(new A(1)), b(new B(2))"));
ASSERT_EQUALS("Fred10[new", testAst(";new Fred[10];"));
ASSERT_EQUALS("adelete", testAst("void f() { delete a; }"));
ASSERT_EQUALS("Aa*A{new=", testAst("A* a = new A{};"));
ASSERT_EQUALS("Aa*A12,{new=", testAst("A* a = new A{ 1, 2 };"));
ASSERT_EQUALS("Sv0[(new", testAst("new S(v[0]);")); // #10929
ASSERT_EQUALS("SS::x(px0>intx[{newint1[{new:?(:", testAst("S::S(int x) : p(x > 0 ? new int[x]{} : new int[1]{}) {}")); // #10793
ASSERT_EQUALS("a0[T{new=", testAst("a[0] = new T{};"));
ASSERT_EQUALS("a0[T::{new=", testAst("a[0] = new ::T{};"));
ASSERT_EQUALS("a0[ST::{new=", testAst("a[0] = new S::T{};"));
ASSERT_EQUALS("intnewdelete", testAst("delete new int;")); // #11039
ASSERT_EQUALS("intnewdelete", testAst("void f() { delete new int; }"));
ASSERT_EQUALS("pint3[new1+=", testAst("p = (new int[3]) + 1;")); // #11327
ASSERT_EQUALS("aType2[T1T2,{new=", testAst("a = new Type *[2] {T1, T2};")); // #11745
ASSERT_EQUALS("pSthis(new=", testAst("p = new S*(this);")); // #10809
ASSERT_EQUALS("pint0{new=", testAst("p = new int*{ 0 };"));
ASSERT_EQUALS("pint5[{new=", testAst("p = new int* [5]{};"));
ASSERT_EQUALS("pint5[0{new=", testAst("p = new int* [5]{ 0 };"));
ASSERT_EQUALS("sSint(new::(new=", testAst("s = new S(::new int());")); // #12502
ASSERT_EQUALS("sS(new::=", testAst("s = ::new (ptr) S();")); // #12552
ASSERT_EQUALS("pdelete::return", testAst("return ::delete p;"));
ASSERT_EQUALS("gn--(delete", testAst("delete g(--n);"));
// placement new
ASSERT_EQUALS("X12,3,(new ab,c,", testAst("new (a,b,c) X(1,2,3);"));
ASSERT_EQUALS("aX::new=", testAst("a = new (b) ::X;"));
ASSERT_EQUALS("cCnew= abc:?", testAst("c = new(a ? b : c) C;"));
// invalid code (libreoffice), don't hang
// #define SlideSorterViewShell
// SfxViewFrame* pFrame;
// new SlideSorterViewShell(pFrame,rViewShellBase,pParentWindow,pFrameViewArgument);
ASSERT_EQUALS("fxnewy,z,(", testAst("f(new (x,y,z));"));
// clang testsuite..
ASSERT_EQUALS("const0(new", testAst("new const auto (0);"));
ASSERT_EQUALS("autonew", testAst("new (auto) (0.0);"));
ASSERT_EQUALS("int3[4[5[new", testAst("new (int S::*[3][4][5]) ();"));
ASSERT_EQUALS("pSnew=", testAst("p=new (x)(S)(1,2);"));
ASSERT_EQUALS("inti[new(", testAst("(void)new (int[i]);"));
ASSERT_EQUALS("intp* pnew malloc4(", testAst("int*p; new (p) (malloc(4));"));
ASSERT_EQUALS("intnew", testAst("new (&w.x)(int*)(0);"));
ASSERT_EQUALS("&new", testAst("new (&w.x)(0);")); // <- the "(int*)" has been simplified
// gcc testsuite..
ASSERT_EQUALS("char10[new(", testAst("(void)new(char*)[10];"));
}
void astpar() { // parentheses
ASSERT_EQUALS("12+3*", testAst("(1+2)*3"));
ASSERT_EQUALS("123+*", testAst("1*(2+3)"));
ASSERT_EQUALS("123+*4*", testAst("1*(2+3)*4"));
ASSERT_EQUALS("ifab.c&d==(", testAst("if((a.b&c)==d){}"));
ASSERT_EQUALS("pf.pf.12,(&&", testAst("((p.f) && (p.f)(1,2))"));
ASSERT_EQUALS("forresdirGetFirst.file&_T(,(=;;(", testAst("for ((res = dir.GetFirst(&file, _T(" ")));;) {}"));
// problems with: if (x[y]==z)
ASSERT_EQUALS("ifa(0[1==(", testAst("if(a()[0]==1){}"));
ASSERT_EQUALS("ifbuff0[&(*1==(", testAst("if (*((DWORD*)&buff[0])==1){}"));
ASSERT_EQUALS("ifp*0[1==(", testAst("if((*p)[0]==1)"));
ASSERT_EQUALS("ifab.cd.[e==(", testAst("if(a.b[c.d]==e){}"));
ASSERT_EQUALS("iftpnote.i1-[note.0==tpnote.i1-[type.4>||(", testAst("if ((tp.note[i - 1].note == 0) || (tp.note[i - 1].type > 4)) {}"));
ASSERT_EQUALS("ab.i[j1+[", testAst("a.b[i][j+1]"));
// problems with: x=expr
ASSERT_EQUALS("(= x (( (. ([ a i) f)))",
testAst("x = ((a[i]).f)();", AstStyle::Z3));
ASSERT_EQUALS("abc.de.++[=", testAst("a = b.c[++(d.e)];"));
ASSERT_EQUALS("abc(1+=", testAst("a = b(c**)+1;"));
ASSERT_EQUALS("abc.=", testAst("a = (b).c;"));
// casts
ASSERT_EQUALS("a1(2(+=",testAst("a=(t)1+(t)2;"));
ASSERT_EQUALS("a1(2+=",testAst("a=(t)1+2;"));
ASSERT_EQUALS("a1(2+=",testAst("a=(t*)1+2;"));
ASSERT_EQUALS("a1(2+=",testAst("a=(t&)1+2;"));
ASSERT_EQUALS("a1(2+=",testAst("a=(t&&)1+2;"));
ASSERT_EQUALS("ab::r&c(=", testAst("a::b& r = (a::b&)c;")); // #5261
ASSERT_EQUALS("ab10:?=", testAst("a=(b)?1:0;"));
ASSERT_EQUALS("ac5[new(=", testAst("a = (b*)(new c[5]);")); // #8786
ASSERT_EQUALS("a(4+", testAst("(int)(a) + 4;"));
// (cast){data}[index]
ASSERT_EQUALS("a&{(0[1[5[0=", testAst("(int (**)[i]){&a}[0][1][5] = 0;"));
ASSERT_EQUALS("ab12,{(0[,(", testAst("a(b, (int []){1,2}[0]);"));
ASSERT_EQUALS("n0=", testAst("TrivialDefCtor{[2][2]}[1][1].n = 0;"));
ASSERT_EQUALS("aT12,3,{1[=", testAst("a = T{1, 2, 3}[1];"));
// Type{data}()
ASSERT_EQUALS("ab{(=", testAst("a=b{}();"));
ASSERT_EQUALS("abc{((=", testAst("a=b(c{}());"));
ASSERT_EQUALS("xNULL!=0(x(:?", testAst("void f() { {} ((x != NULL) ? (void)0 : x()); }"));
// ({..})
ASSERT_EQUALS("a{+d+ bc+", testAst("a+({b+c;})+d"));
ASSERT_EQUALS("a{d*+ bc+", testAst("a+({b+c;})*d"));
ASSERT_EQUALS("xa{((= bc( yd{((= ef(",
testAst("x=(int)(a({b(c);}));" // don't hang
"y=(int)(d({e(f);}));"));
ASSERT_EQUALS("A{{,( x0= Bx1={x2={,(", // TODO: This is not perfect!!
testAst("A({},{x=0;});" // don't hang
"B({x=1},{x=2});"));
ASSERT_EQUALS("xMACROtype.T=value.1=,{({=",
testAst("x = { MACRO( { .type=T, .value=1 } ) }")); // don't hang: MACRO({..})
ASSERT_EQUALS("fori10=i{;;( i--", testAst("for (i=10;i;({i--;}) ) {}"));
ASSERT_EQUALS("c{1{,{2.3f{,(",
testAst("c({{}, {1}}, {2.3f});"));
ASSERT_EQUALS("x{{= e0= assert0(", testAst("x = {({ int e = 0; assert(0); e; })};"));
// function pointer
TODO_ASSERT_EQUALS("todo", "va_argapvoid((,(*0=", testAst("*va_arg(ap, void(**) ()) = 0;"));
// struct/array initialization
ASSERT_EQUALS("name_bytes[bits~unusedBits>>unusedBits<<{=", testAst("const uint8_t name_bytes[] = { (~bits >> unusedBits) << unusedBits };"));
ASSERT_EQUALS("abuf.0{={=", testAst("a = { .buf = { 0 } };"));
ASSERT_EQUALS("ab2[a.0=b.0=,{a.0=b.0=,{,{=", testAst("struct AB ab[2] = { { .a=0, .b=0 }, { .a=0, .b=0 } };"));
ASSERT_EQUALS("tset{=", testAst("struct cgroup_taskset tset = {};"));
ASSERT_EQUALS("s1a&,{2b&,{,{=", testAst("s = { {1, &a}, {2, &b} };"));
ASSERT_EQUALS("s0[L.2[x={=", testAst("s = { [0].L[2] = x};"));
ASSERT_EQUALS("ac.0={(=", testAst("a = (b){.c=0,};")); // <- useless comma
ASSERT_EQUALS("xB[1y.z.1={(&=,{={=", testAst("x = { [B] = {1, .y = &(struct s) { .z=1 } } };"));
ASSERT_EQUALS("xab,c,{=", testAst("x={a,b,(c)};"));
ASSERT_EQUALS("x0fSa.1=b.2=,c.\"\"=,{(||=", testAst("x = 0 || f(S{.a = 1, .b = 2, .c = \"\" });"));
ASSERT_EQUALS("x0fSa.1{=b.2{,c.\"\"=,{(||=", testAst("x = 0 || f(S{.a = { 1 }, .b { 2 }, .c = \"\" });"));
ASSERT_EQUALS("a0\"\"abc12:?,{{,(", testAst("a(0, {{\"\", (abc) ? 1 : 2}});"));
ASSERT_EQUALS("a0\'\'abc12:?,{{,(", testAst("a(0, {{\'\', (abc) ? 1 : 2}});"));
ASSERT_EQUALS("x12,{34,{,{56,{78,{,{,{=", testAst("x = { { {1,2}, {3,4} }, { {5,6}, {7,8} } };"));
ASSERT_EQUALS("Sa.stdmove::s(=b.1=,{(", testAst("S({.a = std::move(s), .b = 1})"));
// struct initialization hang
ASSERT_EQUALS("sbar.1{,{(={= forfieldfield++;;(",
testAst("struct S s = {.bar = (struct foo) { 1, { } } };\n"
"void f(struct cmd *) { for (; field; field++) {} }"));
// template parentheses: <>
ASSERT_EQUALS("ab::c(de::(<=return", testAst("return a::b(c) <= d<double>::e();")); // #6195
// C++ initializer
ASSERT_EQUALS("Class{", testAst("Class{};"));
ASSERT_EQUALS("Class12,{", testAst("Class{1,2};"));
ASSERT_EQUALS("Class12,{", testAst("Class<X>{1,2};"));
ASSERT_EQUALS("abc{d:?=", testAst("a=b?c{}:d;"));
ASSERT_EQUALS("abc12,{d:?=", testAst("a=b?c{1,2}:d;"));
ASSERT_EQUALS("abc{d:?=", testAst("a=b?c<X>{}:d;"));
ASSERT_EQUALS("abc12,{d:?=", testAst("a=b?c<X>{1,2}:d;"));
ASSERT_EQUALS("a::12,{", testAst("::a{1,2};")); // operator precedence
ASSERT_EQUALS("Abc({newreturn", testAst("return new A {b(c)};"));
ASSERT_EQUALS("a{{return", testAst("return{{a}};"));
ASSERT_EQUALS("a{b{,{return", testAst("return{{a},{b}};"));
ASSERT_EQUALS("stdvector::{{,{return", testAst("return std::vector<std::vector<int> >{{},{}};"));
ASSERT_EQUALS("stdvector::{2{,{return", testAst("return std::vector<std::vector<int> >{{}, {2}};"));
ASSERT_EQUALS("forbstdvector::{{,{:(", testAst("for (auto b : std::vector<std::vector<int> >{{},{}});"));
ASSERT_EQUALS("forbstdvector::{2{,{:(", testAst("for (auto b : std::vector<std::vector<int> >{{}, {2}});"));
ASSERT_EQUALS("abR{{,P(,((", testAst("a(b(R{},{},P()));"));
ASSERT_EQUALS("f1{2{,3{,{x,(", testAst("f({{1},{2},{3}},x);"));
ASSERT_EQUALS("a1{ b2{", testAst("auto a{1}; auto b{2};"));
ASSERT_EQUALS("var1ab::23,{,{4ab::56,{,{,{", testAst("auto var{{1,a::b{2,3}}, {4,a::b{5,6}}};"));
ASSERT_EQUALS("var{{,{{,{", testAst("auto var{ {{},{}}, {} };"));
ASSERT_EQUALS("fXYabcfalse==CD:?,{,{(", testAst("f({X, {Y, abc == false ? C : D}});"));
ASSERT_EQUALS("stdvector::p0[{(return", testAst("return std::vector<int>({ p[0] });"));
ASSERT_EQUALS("vstdvector::{=", testAst("auto v = std::vector<int>{ };"));
// Initialization with decltype(expr) instead of a type
ASSERT_EQUALS("decltypex((", testAst("decltype(x)();"));
ASSERT_EQUALS("decltypex({", testAst("decltype(x){};"));
ASSERT_EQUALS("decltypexy+(yx+(", testAst("decltype(x+y)(y+x);"));
ASSERT_EQUALS("decltypexy+(yx+{", testAst("decltype(x+y){y+x};"));
ASSERT_EQUALS("adecltypeac::(,decltypead::(,",
testAst("template <typename a> void b(a &, decltype(a::c), decltype(a::d));"));
ASSERT_NO_THROW(tokenizeAndStringify("struct A;\n" // #10839
"struct B { A* hash; };\n"
"auto g(A* a) { return [=](void*) { return a; }; }\n"
"void f(void* p, B* b) {\n"
" b->hash = (g(b->hash))(p);\n"
"}\n"));
ignore_errout();
ASSERT_NO_THROW(tokenizeAndStringify("struct A;\n"
"struct B { A* hash; };\n"
"A* h(void* p);\n"
"typedef A* (*X)(void*);\n"
"X g(A*) { return h; }\n"
"void f(void* p, B * b) {\n"
"b->hash = (g(b->hash))(p);\n"
"}\n"));
ASSERT_EQUALS("", errout_str());
ASSERT_NO_THROW(tokenizeAndStringify("struct A;\n"
"struct B { A* hash; };\n"
"void f(void* p, B* b) {\n"
" b->hash = (decltype(b->hash))(p);\n"
"}\n"));
ASSERT_EQUALS("", errout_str());
ASSERT_NO_THROW(tokenizeAndStringify("void a(int);\n" // #10801
" struct b {\n"
" static int c();\n"
"} d;\n"
"void f() {\n"
" (decltype (&a)(d.c))(0);\n"
"}\n"));
ASSERT_EQUALS("", errout_str());
// #10334: Do not hang!
(void)tokenizeAndStringify("void foo(const std::vector<std::string>& locations = {\"\"}) {\n"
" for (int i = 0; i <= 123; ++i)\n"
" x->emplace_back(y);\n"
"}");
ignore_errout();
ASSERT_NO_THROW(tokenizeAndStringify("void f() {\n" // #10831
" auto g = [](std::function<void()> h = []() {}) { };\n"
"}"));
ASSERT_EQUALS("", errout_str());
ASSERT_NO_THROW(tokenizeAndStringify("void f() {\n" // #11379
" auto l = [x = 3](std::string&& v) { };\n"
"}\n"));
ASSERT_EQUALS(
"[test.cpp:2]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable x\n",
errout_str());
ASSERT_EQUALS("forinti(0=i5<=i++;;(", testAst("for (int (i) = 0; (i) <= 5; (i)++) {}")); // #13225
}
void astbrackets() { // []
ASSERT_EQUALS("a23+[4+", testAst("a[2+3]+4"));
ASSERT_EQUALS("a1[0[", testAst("a[1][0]"));
ASSERT_EQUALS("ab0[=", testAst("a=(b)[0];"));
ASSERT_EQUALS("abc.0[=", testAst("a=b.c[0];"));
ASSERT_EQUALS("ab0[1[=", testAst("a=b[0][1];"));
}
void astvardecl() {
// Variable declaration
ASSERT_EQUALS("a1[\"\"=", testAst("char a[1]=\"\";"));
ASSERT_EQUALS("charp*(3[char5[3[new=", testAst("char (*p)[3] = new char[5][3];"));
ASSERT_EQUALS("varp=", testAst("const int *var = p;"));
ASSERT_EQUALS("intrp0[*(&", testAst("int& r(*p[0]);"));
// #9127
const char code1[] = "using uno::Ref;\n"
"Ref<X> r;\n"
"int var(0);";
ASSERT_EQUALS("unoRef:: var0(", testAst(code1));
ASSERT_EQUALS("vary=", testAst("std::string var = y;"));
ASSERT_EQUALS("", testAst("void *(*var)(int);"));
ASSERT_EQUALS("", testAst("void *(*var[2])(int);"));
// create ast for decltype
ASSERT_EQUALS("decltypex( var1=", testAst("decltype(x) var = 1;"));
ASSERT_EQUALS("a1bdecltypet((>2,(", testAst("a(1 > b(decltype(t)), 2);")); // #10271
ASSERT_EQUALS("decltypex({01:?", testAst("decltype(x){} ? 0 : 1;"));
ASSERT_EQUALS("Tp* Tt* forctp.=;;( tp.", testAst("struct T { T* p; };\n" // #10874
"void f(T * t) {\n"
" for (decltype(t->p) (c) = t->p; ;) {}\n"
"}\n"));
ASSERT_EQUALS("x0=a, stdtie::a(x=", testAst("int x = 0, a; std::tie(a) = x;\n"));
ASSERT_EQUALS("tmpa*=a*b*=,b*tmp=,", testAst("{ ((tmp) = (*a)), ((*a) = (*b)), ((*b) = (tmp)); }"));
ASSERT_EQUALS("a(*v=", testAst("(*(volatile unsigned int *)(a) = (v));"));
ASSERT_EQUALS("i(j=", testAst("(int&)(i) = j;"));
ASSERT_EQUALS("", testAst("void f(enum E* var){}"));
ASSERT_EQUALS("", testAst("void f(enum E*& var){}"));
ASSERT_EQUALS("", testAst("void f(bool& var){}"));
}
void astunaryop() { // unary operators
ASSERT_EQUALS("1a--+", testAst("1 + --a"));
ASSERT_EQUALS("1a--+", testAst("1 + a--"));
ASSERT_EQUALS("ab+!", testAst("!(a+b)"));
ASSERT_EQUALS("ab.++", testAst("++a.b;"));
ASSERT_EQUALS("ab.++", testAst("a.b++;"));
ASSERT_EQUALS("ab::++", testAst("a::b++;"));
ASSERT_EQUALS("c5[--*", testAst("*c[5]--;"));
ASSERT_EQUALS("xreturn", testAst("return x;"));
ASSERT_EQUALS("x(throw", testAst(";throw x();"));
ASSERT_EQUALS("a*bc:?return", testAst("return *a ? b : c;"));
ASSERT_EQUALS("xy*--=", testAst("x = -- * y;"));
ASSERT_EQUALS("x(throw", testAst(";throw (foo) x;")); // #9955
// Unary :: operator
ASSERT_EQUALS("abcd::12,(e/:?=", testAst("a = b ? c : ::d(1,2) / e;"));
// how is "--" handled here:
ASSERT_EQUALS("ab4<<c--+1:?", testAst("a ? (b << 4) + --c : 1"));
ASSERT_EQUALS("ab4<<c--+1:?", testAst("a ? (b << 4) + c-- : 1"));
ASSERT_EQUALS("ai[i= i--", testAst("a[i]=i; --i;"));
ASSERT_EQUALS("fint0{1&(", testAst("f(int{ 0 } & 1);")); // #11572
ASSERT_EQUALS("int0{1&return", testAst("int g() { return int{ 0 } & 1; }"));
}
void astfunction() { // function calls
ASSERT_EQUALS("1f(+2+", testAst("1+f()+2"));
ASSERT_EQUALS("1f2(+3+", testAst("1+f(2)+3"));
ASSERT_EQUALS("1f23,(+4+", testAst("1+f(2,3)+4"));
ASSERT_EQUALS("1f2a&,(+", testAst("1+f(2,&a)"));
ASSERT_EQUALS("argv[", testAst("int f(char argv[]);"));
ASSERT_EQUALS("", testAst("void f();"));
ASSERT_EQUALS("", testAst("void f() {}"));
ASSERT_EQUALS("", testAst("int f() = delete;"));
ASSERT_EQUALS("", testAst("a::b f();"));
ASSERT_EQUALS("", testAst("a::b f() {}"));
ASSERT_EQUALS("", testAst("a::b f() = delete;"));
ASSERT_EQUALS("constdelete=", testAst("int f() const = delete;"));
ASSERT_EQUALS("", testAst("extern unsigned f(const char *);"));
ASSERT_EQUALS("charformat*...,", testAst("extern void f(const char *format, ...);"));
ASSERT_EQUALS("int(int(void,", testAst("extern int for_each_commit_graft(int (*)(int*), void *);"));
ASSERT_EQUALS("for;;(", testAst("for (;;) {}"));
ASSERT_EQUALS("xsizeofvoid(=", testAst("x=sizeof(void*)"));
ASSERT_EQUALS("abc{d{,{(=", testAst("a = b({ c{}, d{} });"));
ASSERT_EQUALS("abc;(", testAst("a(b;c)"));
ASSERT_EQUALS("x{( forbc;;(", testAst("x({ for(a;b;c){} });"));
ASSERT_EQUALS("PT.(", testAst("P->~T();")); // <- The "T" token::function() will be a destructor
ASSERT_EQUALS("double&(4[", testAst("void f(double(&)[4]) {}"));
ASSERT_EQUALS("voidu*", testAst("int* g ( void* (f) (void*), void* u);")); // #12475
ASSERT_EQUALS("f::(", testAst("::f();")); // #12544
ASSERT_EQUALS("(( f (, c ({ (= (. x) 0))))", testAst("f(c, { .x = 0 });", AstStyle::Z3)); // #12806
ASSERT_EQUALS("(= it (( (. s insert) (, it ({ (, (, (= (. a) i) (= (. b) 2)) (= (. c) 3))))))",
testAst("it = s.insert(it, { .a = i, .b = 2, .c = 3 });", AstStyle::Z3)); // #12815
}
void asttemplate() { // uninstantiated templates will have <,>,etc..
ASSERT_EQUALS("a(3==", testAst("a<int>()==3"));
ASSERT_EQUALS("", errout_str());
ASSERT_EQUALS("ab(== f(", testAst("a == b<c>(); f();"));
ASSERT_EQUALS("", errout_str());
ASSERT_EQUALS("static_casta(i[", testAst("; static_cast<char*>(a)[i];")); // #6203
ASSERT_EQUALS("", errout_str());
ASSERT_EQUALS("reinterpret_castreinterpret_castptr(123&(",
testAst(";reinterpret_cast<void*>(reinterpret_cast<unsigned>(ptr) & 123);")); // #7253
ASSERT_EQUALS("", errout_str());
ASSERT_EQUALS("bcd.(=", testAst(";a<int> && b = c->d();"));
ASSERT_EQUALS("", errout_str());
// This two unit tests were added to avoid a crash. The actual correct AST result for non-executable code has not been determined so far.
ASSERT_NO_THROW(testAst("class C : public ::a::b<bool> { };"));
ASSERT_EQUALS("", errout_str());
ASSERT_EQUALS("AB: abc+=", testAst("struct A : public B<C*> { void f() { a=b+c; } };"));
ASSERT_EQUALS("", errout_str());
ASSERT_EQUALS("xfts(=", testAst("; auto x = f(ts...);"));
ASSERT_EQUALS("", errout_str());
ASSERT_EQUALS("dae(new= ifd(", testAst("template <typename a, typename... b>\n" // #10199
"void c(b... e) {\n"
" a d = new a((e)...);\n"
" if (d) {}\n"
"}\n"));
ASSERT_EQUALS("", errout_str());
ASSERT_EQUALS("ad*astdforward::e((new= ifd(", testAst("struct a {};\n" // #11103
"template <class... b> void c(b... e) {\n"
" a* d = new a(std::forward<b>(e)...);\n"
" if (d) {}\n"
"}\n"));
ASSERT_EQUALS("", errout_str());
ASSERT_EQUALS("stddir::Args...&&, dir\"abc\"+= dirconcatstdforward::args((+return",
testAst("template <typename ...Args> std::string concat(std::string dir, Args&& ...args) {\n" // #10492
" dir += \"abc\";\n"
" return dir + concat(std::forward<Args>(args)...);\n"
"}\n"));
ASSERT_EQUALS("", errout_str());
// #11369
ASSERT_NO_THROW(tokenizeAndStringify("int a;\n"
"template <class> auto b() -> decltype(a) {\n"
" if (a) {}\n"
"}\n"));
ignore_errout();
}
void astrequires()
{
ASSERT_EQUALS("requires{ac::||= ac::", testAst("template <class a> concept b = requires { a::c; } || a::c;"));
ASSERT_EQUALS("requires{ac::||= a{b{||",
testAst("template <class a, class b> concept c = requires { a{} || b{}; } || a::c;"));
}
void astcast() {
ASSERT_EQUALS("ac&(=", testAst("a = (long)&c;"));
ASSERT_EQUALS("ac*(=", testAst("a = (Foo*)*c;"));
ASSERT_EQUALS("ac-(=", testAst("a = (long)-c;"));
ASSERT_EQUALS("ac~(=", testAst("a = (b)~c;"));
ASSERT_EQUALS("ac(=", testAst("a = (some<strange, type>)c;"));
ASSERT_EQUALS("afoveon_avgimage((foveon_avgimage((+=", testAst("a = foveon_avg(((short(*)[4]) image)) + foveon_avg(((short(*)[4]) image));"));
ASSERT_EQUALS("c(40<<return", testAst("return (long long)c << 40;"));
ASSERT_EQUALS("ab-(=", testAst("a = ((int)-b)")); // Multiple subsequent unary operators (cast and -)
ASSERT_EQUALS("xdouble123(i*(=", testAst("x = (int)(double(123)*i);"));
ASSERT_EQUALS("ac(=", testAst("a = (::b)c;"));
ASSERT_EQUALS("abcd,({(=", testAst("a = (s){b(c, d)};"));
ASSERT_EQUALS("xatoistr({(=", testAst("x = (struct X){atoi(str)};"));
ASSERT_EQUALS("xa.0=b.0=,c.0=,{(=", testAst("x = (struct abc) { .a=0, .b=0, .c=0 };"));
ASSERT_EQUALS("yz.(return", testAst("return (x)(y).z;"));
ASSERT_EQUALS("fon!(restoring01:?,(", testAst("f((long) !on, restoring ? 0 : 1);"));
ASSERT_EQUALS("esi.!(=", testAst("E e = (E)!s->i;")); // #10882
ASSERT_EQUALS("xp(= 12>34:?", testAst("x = ( const char ( * ) [ 1 > 2 ? 3 : 4 ] ) p ;"));
ASSERT_EQUALS("f{(si.,(", testAst("f((struct S){ }, s->i);")); // #11606
// not cast
ASSERT_EQUALS("AB||", testAst("(A)||(B)"));
ASSERT_EQUALS("abc[1&=", testAst("a = (b[c]) & 1;"));
ASSERT_EQUALS("abc::(=", testAst("a = (b::c)();"));
ASSERT_EQUALS("pcharnew(=", testAst("p = (void *)(new char);"));
}
void astlambda() {
// a lambda expression '[x](y){}' is compiled as:
// [
// `-(
// `-{
ASSERT_EQUALS("x{(a&[( ai=", testAst("x([&a](int i){a=i;});"));
ASSERT_EQUALS("{([(return 0return", testAst("return [](){ return 0; }();"));
// noexcept (which if simplified to always have a condition by the time AST is created)
ASSERT_EQUALS("x{([( ai=", testAst("x([](int i) noexcept(true) { a=i; });"));
ASSERT_EQUALS("x{([( ai=", testAst("x([](int i) mutable noexcept(true) { a=i; });"));
ASSERT_EQUALS("x{([( ai=", testAst("x([](int i) const noexcept(true) { a=i; });"));
// both mutable and constexpr (which is simplified to 'const' by the time AST is created)
ASSERT_EQUALS("x{([( ai=", testAst("x([](int i) const mutable { a=i; });"));
ASSERT_EQUALS("x{([( ai=", testAst("x([](int i) mutable const { a=i; });"));
ASSERT_EQUALS("x{([( ai=", testAst("x([](int i) const mutable noexcept(true) { a=i; });"));
ASSERT_EQUALS("x{([( ai=", testAst("x([](int i) mutable const noexcept(true) { a=i; });"));
// ->
ASSERT_EQUALS("{([(return 0return", testAst("return []() -> int { return 0; }();"));
ASSERT_EQUALS("{(something[(return 0return", testAst("return [something]() -> int { return 0; }();"));
ASSERT_EQUALS("{([cd,(return 0return", testAst("return [](int a, int b) -> int { return 0; }(c, d);"));
ASSERT_EQUALS("{([return", testAst("return []() -> decltype(0) {};"));
ASSERT_EQUALS("x{(&[=", testAst("x = [&]()->std::string const & {};"));
ASSERT_EQUALS("f{([=", testAst("f = []() -> foo* {};"));
ASSERT_EQUALS("f{([=", testAst("f = []() -> foo&& {};"));
ASSERT_EQUALS("f{([=", testAst("f = [](void) mutable -> foo* {};"));
ASSERT_EQUALS("f{([=", testAst("f = []() mutable {};"));
ASSERT_EQUALS("x{([= 0return", testAst("x = [](){return 0; };"));
ASSERT_EQUALS("ab{&[(= cd=", testAst("a = b([&]{c=d;});"));
// 8628
ASSERT_EQUALS("f{([( switchx( 1case y++", testAst("f([](){switch(x){case 1:{++y;}}});"));
ASSERT_EQUALS("{(=[{return ab=",
testAst("return {\n"
" [=]() {\n"
" a = b;\n"
" }\n"
"};\n"));
ASSERT_EQUALS("{=[{return ab=",
testAst("return {\n"
" [=] {\n"
" a = b;\n"
" }\n"
"};\n"));
ASSERT_EQUALS("{(=[{return ab=",
testAst("return {\n"
" [=]() -> int {\n"
" a=b;\n"
" }\n"
"}"));
ASSERT_EQUALS("{(=[{return ab=",
testAst("return {\n"
" [=]() mutable consteval -> int {\n"
" a=b;\n"
" }\n"
"}"));
// daca@home hang
ASSERT_EQUALS("a{(&[= 0return b{(=[= fori0=i10!=i++;;(",
testAst("a = [&]() -> std::pair<int, int> { return 0; };\n"
"b = [=]() { for (i = 0; i != 10; ++i); };"));
// #9662
ASSERT_EQUALS("b{[{ stdunique_ptr::0nullptrnullptr:?{", testAst("auto b{[] { std::unique_ptr<void *>{0 ? nullptr : nullptr}; }};"));
ASSERT_EQUALS("b{[=", testAst("void a() { [b = [] { ; }] {}; }"));
// Lambda capture expression (C++14)
ASSERT_EQUALS("a{b1=[= c2=", testAst("a = [b=1]{c=2;};"));
// #9729
ASSERT_NO_THROW(tokenizeAndStringify("void foo() { bar([]() noexcept { if (0) {} }); }"));
ASSERT_EQUALS("", errout_str());
// #11128
ASSERT_NO_THROW(tokenizeAndStringify("template <typename T>\n"
"struct S;\n"
"struct R;\n"
"S<R> y, z;\n"
"auto f(int x) -> S<R> {\n"
" if (const auto i = x; i != 0)\n"
" return y;\n"
" else\n"
" return z;\n"
"}\n", true, Platform::Type::Native, true, Standards::CPP17));
ignore_errout();
// #10079 - createInnerAST bug..
ASSERT_EQUALS("x{([= yz= switchy(",
testAst("x = []() -> std::vector<uint8_t> {\n"
" const auto y = z;\n"
" switch (y) {}\n"
"};"));
// #11357
ASSERT_NO_THROW(tokenizeAndStringify("void f(std::vector<int>& v, bool c) {\n"
" std::sort(v.begin(), v.end(), [&c](const auto a, const auto b) {\n"
" switch (c) {\n"
" case false: {\n"
" if (a < b) {}\n"
" }\n"
" }\n"
" return a < b;\n"
" });\n"
"}\n"));
ignore_errout();
ASSERT_NO_THROW(tokenizeAndStringify("namespace N {\n"
" enum E : bool { F };\n"
"}\n"
"void f(std::vector<int>& v, bool c) {\n"
" std::sort(v.begin(), v.end(), [&c](const auto a, const auto b) {\n"
" switch (c) {\n"
" case N::E::F: {\n"
" if (a < b) {}\n"
" }\n"
" }\n"
" return a < b;\n"
" });\n"
"}\n"));
ignore_errout();
ASSERT_NO_THROW(tokenizeAndStringify("void f(const std::vector<char>& v) {\n"
" std::for_each(v.begin(), v.end(), [&](char c) {\n"
" switch (c) {\n"
" case 'r': {\n"
" if (c) {}\n"
" }\n"
" break;\n"
" }\n"
" });\n"
"}\n"));
ASSERT_EQUALS("", errout_str());
ASSERT_NO_THROW(tokenizeAndStringify("struct A { A(int) {} };\n"
"void g(void (*)(int));\n"
"void f() {\n"
" g([](int i) {\n"
" switch (i) {\n"
" case static_cast<int>(1): {\n"
" A a(i);\n"
" if (1) {}\n"
" }\n"
" }\n"
" });\n"
"}\n"));
ASSERT_EQUALS("", errout_str());
// #11378
ASSERT_EQUALS("gT{(&[{= 0return", testAst("auto g = T{ [&]() noexcept -> int { return 0; } };"));
ASSERT_EQUALS("sf.{(i[{={", testAst("void g(int i) { S s{ .f = { [i]() {} } }; }"));
}
void astcase() {
ASSERT_EQUALS("0case", testAst("case 0:"));
ASSERT_EQUALS("12+case", testAst("case 1+2:"));
ASSERT_EQUALS("xyz:?case", testAst("case (x?y:z):"));
ASSERT_EQUALS("switchx( 1case y++ 2case", testAst("switch(x){case 1:{++y;break;case 2:break;}}"));
ASSERT_EQUALS("switchi( 12<<~case 0return", testAst("switch (i) { case ~(1 << 2) : return 0; }")); // #13197
}
void astrefqualifier() {
ASSERT_EQUALS("b(int.", testAst("class a { auto b() -> int&; };"));
ASSERT_EQUALS("b(int.", testAst("class a { auto b() -> int&&; };"));
ASSERT_EQUALS("b(", testAst("class a { void b() &&; };"));
ASSERT_EQUALS("b(", testAst("class a { void b() &; };"));
ASSERT_EQUALS("b(", testAst("class a { void b() && {} };"));
ASSERT_EQUALS("b(", testAst("class a { void b() & {} };"));
}
//Verify that returning a newly constructed object generates the correct AST even when the class name is scoped
//Addresses https://trac.cppcheck.net/ticket/9700
void astnewscoped() {
ASSERT_EQUALS("(return (new A))", testAst("return new A;", AstStyle::Z3));
ASSERT_EQUALS("(return (new (( A)))", testAst("return new A();", AstStyle::Z3));
ASSERT_EQUALS("(return (new (( A true)))", testAst("return new A(true);", AstStyle::Z3));
ASSERT_EQUALS("(return (new (:: A B)))", testAst("return new A::B;", AstStyle::Z3));
ASSERT_EQUALS("(return (new (( (:: A B))))", testAst("return new A::B();", AstStyle::Z3));
ASSERT_EQUALS("(return (new (( (:: A B) true)))", testAst("return new A::B(true);", AstStyle::Z3));
ASSERT_EQUALS("(return (new (:: (:: A B) C)))", testAst("return new A::B::C;", AstStyle::Z3));
ASSERT_EQUALS("(return (new (( (:: (:: A B) C))))", testAst("return new A::B::C();", AstStyle::Z3));
ASSERT_EQUALS("(return (new (( (:: (:: A B) C) true)))", testAst("return new A::B::C(true);", AstStyle::Z3));
ASSERT_EQUALS("(return (new (:: (:: (:: A B) C) D)))", testAst("return new A::B::C::D;", AstStyle::Z3));
ASSERT_EQUALS("(return (new (( (:: (:: (:: A B) C) D))))", testAst("return new A::B::C::D();", AstStyle::Z3));
ASSERT_EQUALS("(return (new (( (:: (:: (:: A B) C) D) true)))", testAst("return new A::B::C::D(true);", AstStyle::Z3));
}
#define isStartOfExecutableScope(offset, code) isStartOfExecutableScope_(offset, code, __FILE__, __LINE__)
template<size_t size>
bool isStartOfExecutableScope_(int offset, const char (&code)[size], const char* file, int line) {
SimpleTokenizer tokenizer(settings0, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
return Tokenizer::startOfExecutableScope(tokenizer.tokens()->tokAt(offset)) != nullptr;
}
void startOfExecutableScope() {
ASSERT(isStartOfExecutableScope(3, "void foo() { }"));
ASSERT(isStartOfExecutableScope(3, "void foo() const { }"));
ASSERT(isStartOfExecutableScope(3, "void foo() volatile { }"));
ASSERT(isStartOfExecutableScope(3, "void foo() override { }"));
ASSERT(isStartOfExecutableScope(3, "void foo() noexcept { }"));
ASSERT(isStartOfExecutableScope(3, "void foo() NOEXCEPT { }"));
ASSERT(isStartOfExecutableScope(3, "void foo() CONST NOEXCEPT { }"));
ASSERT(isStartOfExecutableScope(3, "void foo() const noexcept { }"));
ASSERT(isStartOfExecutableScope(3, "void foo() noexcept(true) { }"));
ASSERT(isStartOfExecutableScope(3, "void foo() const noexcept(true) { }"));
ASSERT(isStartOfExecutableScope(3, "void foo() throw() { }"));
ASSERT(isStartOfExecutableScope(3, "void foo() THROW() { }"));
ASSERT(isStartOfExecutableScope(3, "void foo() CONST THROW() { }"));
ASSERT(isStartOfExecutableScope(3, "void foo() const throw() { }"));
ASSERT(isStartOfExecutableScope(3, "void foo() throw(int) { }"));
ASSERT(isStartOfExecutableScope(3, "void foo() const throw(int) { }"));
ASSERT(isStartOfExecutableScope(2, "foo() : a(1) { }"));
ASSERT(isStartOfExecutableScope(2, "foo() : a(1), b(2) { }"));
ASSERT(isStartOfExecutableScope(2, "foo() : a{1} { }"));
ASSERT(isStartOfExecutableScope(2, "foo() : a{1}, b{2} { }"));
}
void removeMacroInClassDef() { // #6058
ASSERT_EQUALS("class Fred { } ;", tokenizeAndStringify("class DLLEXPORT Fred { } ;"));
ASSERT_EQUALS("class Fred : Base { } ;", tokenizeAndStringify("class Fred FINAL : Base { } ;"));
ASSERT_EQUALS("class Fred : Base { } ;", tokenizeAndStringify("class DLLEXPORT Fred final : Base { } ;")); // #11422
// Regression for C code:
ASSERT_EQUALS("struct Fred { } ;", tokenizeAndStringify("struct DLLEXPORT Fred { } ;", true, Platform::Type::Native, false));
}
void sizeofAddParentheses() {
ASSERT_EQUALS("sizeof ( sizeof ( 1 ) ) ;", tokenizeAndStringify("sizeof sizeof 1;"));
ASSERT_EQUALS("sizeof ( a . b ) + 3 ;", tokenizeAndStringify("sizeof a.b+3;"));
ASSERT_EQUALS("sizeof ( a [ 2 ] . b ) + 3 ;", tokenizeAndStringify("sizeof a[2].b+3;"));
ASSERT_EQUALS("f ( 0 , sizeof ( ptr . bar ) ) ;", tokenizeAndStringify("f(0, sizeof ptr->bar );"));
ASSERT_EQUALS("sizeof ( a ) > sizeof ( & main ) ;", tokenizeAndStringify("sizeof a > sizeof &main;"));
}
void reportUnknownMacros() {
const char code1[] = "MY_UNKNOWN_IMP1(IInStream)\n"
"STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize) { if (ptr); }";
ASSERT_THROW_INTERNAL(tokenizeAndStringify(code1), UNKNOWN_MACRO);
const char code2[] = "void foo() { dostuff(x 0); }";
ASSERT_THROW_INTERNAL(tokenizeAndStringify(code2), UNKNOWN_MACRO);
const char code3[] = "f(\"1\" __stringify(48) \"1\");";
ASSERT_THROW_INTERNAL(tokenizeAndStringify(code3), UNKNOWN_MACRO);
const char code4[] = "struct Foo {\n"
" virtual MACRO(int) f1() {}\n"
" virtual MACRO(int) f2() {}\n"
"};";
ASSERT_THROW_INTERNAL(tokenizeAndStringify(code4), UNKNOWN_MACRO);
const char code5[] = "void foo() {\n"
" EVALUATE(123, int x=a; int y=b+c;);\n"
"}";
ASSERT_THROW_INTERNAL(tokenizeAndStringify(code5), UNKNOWN_MACRO);
const char code6[] = "void foo() { dostuff(a, .x=0); }";
ASSERT_THROW_INTERNAL(tokenizeAndStringify(code6), UNKNOWN_MACRO);
const char code7[] = "void foo() { dostuff(ZEND_NUM_ARGS() TSRMLS_CC, x, y); }"; // #9476
ASSERT_THROW_INTERNAL(tokenizeAndStringify(code7), UNKNOWN_MACRO);
const char code8[] = "void foo() { a = [](int x, decltype(vec) y){}; }";
ASSERT_NO_THROW(tokenizeAndStringify(code8));
const char code9[] = "void f(std::exception c) { b(M() c.what()); }";
ASSERT_THROW_INTERNAL(tokenizeAndStringify(code9), UNKNOWN_MACRO);
const char code10[] = "void f(std::exception c) { b(M() M() + N(c.what())); }";
ASSERT_THROW_INTERNAL(tokenizeAndStringify(code10), UNKNOWN_MACRO);
const char code11[] = "struct B { B(B&&) noexcept {} ~B() noexcept {} };";
ASSERT_NO_THROW(tokenizeAndStringify(code11));
ASSERT_NO_THROW(tokenizeAndStringify("alignas(8) alignas(16) int x;")); // alignas is not unknown macro
ASSERT_THROW_INTERNAL(tokenizeAndStringify("void foo() { if(x) SYSTEM_ERROR }"), UNKNOWN_MACRO);
ASSERT_THROW_INTERNAL(tokenizeAndStringify("void foo() { dostuff(); SYSTEM_ERROR }"), UNKNOWN_MACRO);
ASSERT_NO_THROW(tokenizeAndStringify("void f(void* q) {\n"
" g(&(S) { .p = (int*)q });\n"
"}\n", /*expand*/ true, Platform::Type::Native, false));
ASSERT_NO_THROW(tokenizeAndStringify("typedef struct { int i; } S;\n"
"void f(float a) {\n"
"S s = (S){ .i = (int)a };\n"
"}\n", /*expand*/ true, Platform::Type::Native, false));
ASSERT_THROW_INTERNAL(tokenizeAndStringify("std::string g();\n"
"std::string f() {\n"
" return std::string{ g() + \"abc\" MACRO \"def\" };\n"
"}\n", /*expand*/ true, Platform::Type::Native, true), UNKNOWN_MACRO);
ASSERT_THROW_INTERNAL_EQUALS(tokenizeAndStringify("static void handle_toggle(void (*proc) PROTO_XT_CALLBACK_ARGS, int var) {}\n"), // #13198
UNKNOWN_MACRO,
"There is an unknown macro here somewhere. Configuration is required. If PROTO_XT_CALLBACK_ARGS is a macro then please configure it.");
ignore_errout();
}
void findGarbageCode() { // Test Tokenizer::findGarbageCode()
// C++ try/catch in global scope
ASSERT_THROW_INTERNAL_EQUALS(tokenizeAndStringify("try { }"), SYNTAX, "syntax error: keyword 'try' is not allowed in global scope");
ASSERT_NO_THROW(tokenizeAndStringify("void f() try { } catch (int) { }"));
ASSERT_NO_THROW(tokenizeAndStringify("struct S {\n" // #9716
" S();\n"
" int x, y;\n"
"};\n"
"S::S()\n"
" try : x(1), y{ 2 } { f(); }\n"
" catch (const std::exception& e) { g(); }\n"
" catch (...) { g(); }\n"));
ASSERT_NO_THROW(tokenizeAndStringify("void f()\n"
" try { g(); }\n"
" catch (const std::exception& e) { h(); }\n"
" catch (...) { h(); }\n"));
// before if|for|while|switch
ASSERT_NO_THROW(tokenizeAndStringify("void f() { do switch (a) {} while (1); }"));
ASSERT_NO_THROW(tokenizeAndStringify("void f() { label: switch (a) {} }"));
ASSERT_NO_THROW(tokenizeAndStringify("void f() { UNKNOWN_MACRO if (a) {} }"));
ASSERT_NO_THROW(tokenizeAndStringify("void f() { []() -> int * {}; }"));
ASSERT_NO_THROW(tokenizeAndStringify("void f() { const char* var = \"1\" \"2\"; }"));
ASSERT_THROW_INTERNAL(tokenizeAndStringify("void f() { MACRO(switch); }"), UNKNOWN_MACRO);
ASSERT_THROW_INTERNAL(tokenizeAndStringify("void f() { MACRO(x,switch); }"), UNKNOWN_MACRO);
ASSERT_THROW_INTERNAL(tokenizeAndStringify("void foo() { for_chain( if (!done) done = 1); }"), UNKNOWN_MACRO);
ASSERT_THROW_INTERNAL(tokenizeAndStringify("void foo() { for_chain( a, b, if (!done) done = 1); }"), UNKNOWN_MACRO);
ASSERT_THROW_INTERNAL_EQUALS(tokenizeAndStringify("void f() { if (retval==){} }"), SYNTAX, "syntax error: ==)");
// after (expr)
ASSERT_NO_THROW(tokenizeAndStringify("void f() { switch (a) int b; }"));
ASSERT_NO_THROW(tokenizeAndStringify("S s = { .x=2, .y[0]=3 };"));
ASSERT_NO_THROW(tokenizeAndStringify("S s = { .ab.a=2, .ab.b=3 };"));
ASSERT_NO_THROW(tokenizeAndStringify("extern \"C\" typedef void FUNC();"));
// Ticket #9572
ASSERT_NO_THROW(tokenizeAndStringify("struct poc { "
" struct { int d; } port[1]; "
"}; "
"struct poc p = { .port[0] = {.d = 3} };"));
// Ticket #9664
ASSERT_NO_THROW(tokenizeAndStringify("S s = { .x { 2 }, .y[0] { 3 } };"));
ASSERT_THROW_INTERNAL(tokenizeAndStringify("f(0, .x());"), SYNTAX); // #12823
// Ticket #11134
ASSERT_NO_THROW(tokenizeAndStringify("struct my_struct { int x; }; "
"std::string s; "
"func(my_struct{ .x=42 }, s.size());"));
ASSERT_NO_THROW(tokenizeAndStringify("struct my_struct { int x; int y; }; "
"std::string s; "
"func(my_struct{ .x{42}, .y=3 }, s.size());"));
ASSERT_NO_THROW(tokenizeAndStringify("struct my_struct { int x; int y; }; "
"std::string s; "
"func(my_struct{ .x=42, .y{3} }, s.size());"));
ASSERT_NO_THROW(tokenizeAndStringify("struct my_struct { int x; }; "
"void h() { "
" for (my_struct ms : { my_struct{ .x=5 } }) {} "
"}"));
ASSERT_NO_THROW(tokenizeAndStringify("struct my_struct { int x; int y; }; "
"void h() { "
" for (my_struct ms : { my_struct{ .x=5, .y{42} } }) {} "
"}"));
ASSERT_NO_THROW(tokenizeAndStringify("template <typename T> void foo() {} "
"void h() { "
" [func=foo<int>]{func();}(); "
"}"));
ASSERT_NO_THROW(tokenizeAndStringify("template <class T> constexpr int n = 1;\n"
"template <class T> T a[n<T>];\n"));
ASSERT_EQUALS("std :: vector < int > x ;", // #11785
tokenizeAndStringify("std::vector<int> typedef v; v x;\n"));
// op op
ASSERT_THROW_INTERNAL_EQUALS(tokenizeAndStringify("void f() { dostuff (x==>y); }"), SYNTAX, "syntax error: == >");
ASSERT_THROW_INTERNAL_EQUALS(tokenizeAndStringify("void f() { assert(a==()); }"), SYNTAX, "syntax error: ==()");
ASSERT_THROW_INTERNAL_EQUALS(tokenizeAndStringify("void f() { assert(a+()); }"), SYNTAX, "syntax error: +()");
// #9445 - typeof is not a keyword in C
ASSERT_NO_THROW(tokenizeAndStringify("void foo() { char *typeof, *value; }", false, Platform::Type::Native, false));
ASSERT_THROW_INTERNAL_EQUALS(tokenizeAndStringify("enum : { };"), SYNTAX, "syntax error: Unexpected token '{'");
ASSERT_THROW_INTERNAL_EQUALS(tokenizeAndStringify("enum : 3 { };"), SYNTAX, "syntax error: Unexpected token '3'");
ASSERT_NO_THROW(tokenizeAndStringify("enum { E = int{} };"));
ASSERT_THROW_INTERNAL_EQUALS(tokenizeAndStringify("int a() { b((c)return 0) }"), SYNTAX, "syntax error");
ASSERT_THROW_INTERNAL_EQUALS(tokenizeAndStringify("int f() { MACRO(x) return 0; }"),
UNKNOWN_MACRO,
"There is an unknown macro here somewhere. Configuration is required. If MACRO is a macro then please configure it.");
ASSERT_THROW_INTERNAL_EQUALS(tokenizeAndStringify("void f(int i) {\n" // #11770
" if (i == 0) {}\n"
" else if (i == 1) {}\n"
" else\n"
" MACRO(i)\n"
"}\n"
"void g() {}\n"),
UNKNOWN_MACRO,
"There is an unknown macro here somewhere. Configuration is required. If MACRO is a macro then please configure it.");
ASSERT_NO_THROW(tokenizeAndStringify("void f(int i) {\n"
" if (i == 0) {}\n"
" else if (i == 1) {}\n"
" else\n"
" MACRO(i);\n"
"}\n"
"void g() {}\n"));
ASSERT_THROW_INTERNAL_EQUALS(tokenizeAndStringify("class C : public QObject {\n" // #11770
" struct S { static void g() {} };\n"
"private Q_SLOTS:\n"
" void f() { S::g(); }\n"
"};\n"),
UNKNOWN_MACRO,
"There is an unknown macro here somewhere. Configuration is required. If Q_SLOTS is a macro then please configure it.");
ASSERT_THROW_INTERNAL_EQUALS(tokenizeAndStringify("class C : public QObject {\n"
" struct S { static void g() {} };\n"
"private slots:\n"
" void f() { S::g(); }\n"
"};\n"),
UNKNOWN_MACRO,
"There is an unknown macro here somewhere. Configuration is required. If slots is a macro then please configure it.");
ASSERT_THROW_INTERNAL_EQUALS(tokenizeAndStringify("namespace U_ICU_ENTRY_POINT_RENAME(icu) { }\n"
"namespace icu = U_ICU_ENTRY_POINT_RENAME(icu);\n"
"namespace U_ICU_ENTRY_POINT_RENAME(icu) {\n"
" class BreakIterator;\n"
"}\n"
"typedef int UStringCaseMapper(icu::BreakIterator* iter);\n"),
UNKNOWN_MACRO,
"There is an unknown macro here somewhere. Configuration is required. If U_ICU_ENTRY_POINT_RENAME is a macro then please configure it.");
ASSERT_THROW_INTERNAL_EQUALS(tokenizeAndStringify("void f() { MACRO(x(), y(), \"abc\", z(); ok = true); }\n"), // #12006
UNKNOWN_MACRO,
"There is an unknown macro here somewhere. Configuration is required. If MACRO is a macro then please configure it.");
ASSERT_THROW_INTERNAL_EQUALS(tokenizeAndStringify("int (*f) MACRO((void *));\n"), // #12010
UNKNOWN_MACRO,
"There is an unknown macro here somewhere. Configuration is required. If MACRO is a macro then please configure it.");
ASSERT_THROW_INTERNAL_EQUALS(tokenizeAndStringify("struct S { int a[2] PACKED; };\n"),
UNKNOWN_MACRO,
"There is an unknown macro here somewhere. Configuration is required. If PACKED is a macro then please configure it.");
ASSERT_THROW_INTERNAL_EQUALS(tokenizeAndStringify("MACRO(a, b,,)\n"),
UNKNOWN_MACRO,
"There is an unknown macro here somewhere. Configuration is required. If MACRO is a macro then please configure it.");
ASSERT_THROW_INTERNAL(tokenizeAndStringify("{ for (()()) }"), SYNTAX); // #11643
ASSERT_NO_THROW(tokenizeAndStringify("S* g = ::new(ptr) S();")); // #12552
ASSERT_NO_THROW(tokenizeAndStringify("void f(int* p) { return ::delete p; }"));
ASSERT_NO_THROW(tokenizeAndStringify("template <typename T, int N>\n" // #12659
"constexpr void f(T(&&a)[N]) {}"));
ASSERT_NO_THROW(tokenizeAndStringify("typedef struct { typedef int T; } S;")); // #12700
ASSERT_NO_THROW(tokenizeAndStringify("class A { bool restrict() const; };\n"
"bool A::restrict() const { return true; }")); // #12718
ASSERT_NO_THROW(tokenizeAndStringify("enum { E = sizeof(struct { int i; }) };")); // #13249
ignore_errout();
}
void checkEnableIf() {
ASSERT_NO_THROW(tokenizeAndStringify(
"template<\n"
" typename U,\n"
" typename std::enable_if<\n"
" std::is_convertible<U, T>{}>::type* = nullptr>\n"
"void foo(U x);\n"));
ASSERT_EQUALS("", errout_str());
ASSERT_NO_THROW(tokenizeAndStringify(
"template<class t>\n"
"T f(const T a, const T b) {\n"
" return a < b ? b : a;\n"
"}\n"));
ASSERT_EQUALS("", errout_str());
ASSERT_NO_THROW(tokenizeAndStringify(
"template<class T>\n"
"struct A {\n"
" T f(const T a, const T b) {\n"
" return a < b ? b : a;\n"
" }\n"
"};\n"));
ASSERT_EQUALS("", errout_str());
ASSERT_NO_THROW(tokenizeAndStringify(
"const int a = 1;\n"
"const int b = 2;\n"
"template<class T>\n"
"struct A {\n"
" int x = a < b ? b : a;"
"};\n"));
ASSERT_EQUALS("", errout_str());
// #10139
ASSERT_NO_THROW(tokenizeAndStringify("template<typename F>\n"
"void foo(std::enable_if_t<value<F>>* = 0) {}\n"));
ASSERT_EQUALS("", errout_str());
// #10001
ASSERT_NO_THROW(tokenizeAndStringify("struct a {\n"
" int c;\n"
" template <class b> void d(b e) const { c < e ? c : e; }\n"
"};\n"));
ASSERT_EQUALS("", errout_str());
ASSERT_NO_THROW(tokenizeAndStringify("struct a {\n"
" int c;\n"
" template <class b> void d(b e) const { c > e ? c : e; }\n"
"};\n"));
ASSERT_EQUALS("", errout_str());
}
void checkTemplates() {
// #9109
ASSERT_NO_THROW(tokenizeAndStringify(
"namespace {\n"
"template <typename> struct a;\n"
"template <typename> struct b {};\n"
"}\n"
"namespace {\n"
"template <typename> struct c;\n"
"template <typename d> struct e {\n"
" using f = a< b<typename c<d>::g> >;\n"
" bool h = f::h;\n"
"};\n"
"template <typename i> using j = typename e<i>::g;\n"
"}\n"));
ASSERT_NO_THROW(tokenizeAndStringify(
"template <typename = void> struct a {\n"
" void c();\n"
"};\n"
"void f() {\n"
" a<> b;\n"
" b.a<>::c();\n"
"}\n"));
// #9138
ASSERT_NO_THROW(tokenizeAndStringify(
"template <typename> struct a;\n"
"template <bool> using c = int;\n"
"template <bool b> c<b> d;\n"
"template <> struct a<int> {\n"
"template <typename e> constexpr auto g() { d<0 || e::f>; return 0; }\n"
"};\n"));
// #9144
ASSERT_NO_THROW(tokenizeAndStringify(
"namespace a {\n"
"template <typename b, bool = __is_empty(b) && __is_final(b)> struct c;\n"
"}\n"
"namespace boost {\n"
"using a::c;\n"
"}\n"
"namespace d = boost;\n"
"using d::c;\n"
"template <typename...> struct e {};\n"
"static_assert(sizeof(e<>) == sizeof(e<c<int>, c<int>, int>), \"\");\n"));
// #9146
ASSERT_NO_THROW(tokenizeAndStringify(
"template <int> struct a;\n"
"template <class, class b> using c = typename a<int{b::d}>::e;\n"
"template <class> struct f;\n"
"template <class b> using g = typename f<c<int, b>>::e;\n"));
// #9153
ASSERT_NO_THROW(tokenizeAndStringify(
"namespace {\n"
"template <class> struct a;\n"
"}\n"
"namespace {\n"
"namespace b {\n"
"template <int c> struct B { using B<c / 2>::d; };\n"
"}\n"
"template <class, class> using e = typename b::B<int{}>;\n"
"namespace b {\n"
"template <class> struct f;\n"
"}\n"
"template <class c> using g = b::f<e<int, c>>;\n"
"}\n"));
// #9154
ASSERT_NO_THROW(tokenizeAndStringify(
"template <bool> using a = int;\n"
"template <class b> using aa = a<b::c>;\n"
"template <class...> struct A;\n"
"template <class> struct d;\n"
"template <class... f> using e = typename d<f...>::g;\n"
"template <class> struct h;\n"
"template <class, class... b> using i = typename h<b...>::g;\n"
"template <class f, template <class> class j> using k = typename f::g;\n"
"template <class... b> using l = a<k<A<b...>, aa>::c>;\n"
"template <int> struct m;\n"
"template <class, class n> using o = typename m<int{n::c}>::g;\n"
"template <class> struct p;\n"
"template <class, class n> using q = typename p<o<A<>, n>>::g;\n"
"template <class f, class r, class... b> using c = e<i<q<f, r>, b...>>;\n"
"template <class, class> struct s;\n"
"template <template <class> class t, class... w, template <class> class x,\n"
" class... u>\n"
"struct s<t<w...>, x<u...>>;\n"));
// #9156
ASSERT_NO_THROW(tokenizeAndStringify(
"template <typename> struct a;\n"
"template <bool> struct b;\n"
"template <class k, class> using d = typename b<k::c>::e;\n"
"template <class> struct f;\n"
"template <template <class> class, class... g> using i = typename f<g...>::e;\n"
"template <template <class> class h, class... g> using ab = d<i<h, g...>, int>;\n"
"template <template <class> class h, class... g> struct j {\n"
" template <class... ag> using ah = typename ab<h, ag..., g...>::e;\n"
"};\n"
"template <class> struct F;\n"
"int main() { using T = void (*)(a<j<F, char[]>>); }\n"));
// #9245
ASSERT_NO_THROW(tokenizeAndStringify("struct a {\n"
" typedef int b;\n"
" operator b();\n"
"};\n"
"template <int> using c = a;\n"
"template <int d> c<d> e;\n"
"auto f = ((e<4> | 0));\n"));
// #9340
ASSERT_NO_THROW(tokenizeAndStringify(
"struct a {\n"
" template <class... b> void c(b... p1) {\n"
" using d = a;\n"
" d e = {(p1)...};\n"
" }\n"
"};\n"));
// #9444
ASSERT_NO_THROW(tokenizeAndStringify("template <int> struct a;\n"
"template <long b> using c = a<b>;\n"
"template <long b> c<b> d;\n"
"template <typename> struct e {\n"
" template <typename... f> void g() const { d<e<f &&...>::h>; }\n"
"};\n"));
// #9858
ASSERT_NO_THROW(tokenizeAndStringify(
"struct a {\n"
" struct b {};\n"
"};\n"
"void c(a::b, a::b);\n"
"void g(a::b f) { c(f, {a::b{}}); }\n"
"template <class> void h() {\n"
" int e;\n"
" for (int d = 0; d < e; d++)\n"
" ;\n"
"}\n"));
// #10015
ASSERT_NO_THROW(tokenizeAndStringify(
"void func() {\n"
" if (std::is_same_v<int, int> || 1)\n"
" ;\n"
"}\n"));
// #10309
ASSERT_NO_THROW(tokenizeAndStringify(
"using a = void *;\n"
"void b() {\n"
" std::unique_ptr<a, void (*)(a *)>(new a(0), [](a *c) {\n"
" if (c)\n"
" ;\n"
" });\n"
"}\n"));
ASSERT_NO_THROW(tokenizeAndStringify("a<b?0:1>()==3;"));
// #10336
ASSERT_NO_THROW(tokenizeAndStringify("struct a {\n"
" template <class b> a(b);\n"
"};\n"
"struct c;\n"
"void fn1(int, a);\n"
"void f() { fn1(0, {a{0}}); }\n"
"template <class> std::vector<c> g() {\n"
" int d;\n"
" for (size_t e = 0; e < d; e++)\n"
" ;\n"
"}\n"));
// #9523
ASSERT_NO_THROW(tokenizeAndStringify(
"template <int> struct a;\n"
"template <typename, typename> struct b;\n"
"template <typename c> struct b<c, typename a<c{} && 0>::d> {\n"
" void e() {\n"
" if (0) {}\n"
" }\n"
"};\n"));
ASSERT_NO_THROW(tokenizeAndStringify(
"template <std::size_t First, std::size_t... Indices, typename Functor>\n"
"constexpr void constexpr_for_fold_impl([[maybe_unused]] Functor&& f, std::index_sequence<Indices...>) noexcept {\n"
" (std::forward<Functor>(f).template operator() < First + Indices > (), ...);\n"
"}\n"));
// #9301
ASSERT_NO_THROW(tokenizeAndStringify("template <typename> constexpr char x[] = \"\";\n"
"template <> constexpr char x<int>[] = \"\";\n"));
// #10951
ASSERT_NO_THROW(tokenizeAndStringify("struct a {\n"
" template <class> static void b() {}\n"
" ~a();\n"
"};\n"
"void d() { a::b<int>(); }\n"));
// #11090
ASSERT_NO_THROW(tokenizeAndStringify("using a = char;\n"
"using c = int;\n"
"template <typename = void> struct d {};\n"
"using b = c;\n"
"template <> struct d<b> : d<a> {};\n"
"template <> struct d<> : d<a> {};\n"));
ignore_errout();
}
void checkNamespaces() {
ASSERT_NO_THROW(tokenizeAndStringify("namespace x { namespace y { namespace z {}}}"));
}
void checkLambdas() {
ASSERT_NO_THROW(tokenizeAndStringify("auto f(int& i) { return [=, &i] {}; }"));
ASSERT_NO_THROW(tokenizeAndStringify("auto f(int& i) { return [&, i] {}; }"));
ASSERT_NO_THROW(tokenizeAndStringify("auto f(int& i) { return [&, i = std::move(i)] {}; }"));
ASSERT_NO_THROW(tokenizeAndStringify("auto f(int& i) { return [=, i = std::move(i)] {}; }"));
ASSERT_NO_THROW(tokenizeAndStringify("struct c {\n"
" void d() {\n"
" int a;\n"
" auto b = [this, a] {};\n"
" }\n"
"};\n"));
// #9525
ASSERT_NO_THROW(tokenizeAndStringify("struct a {\n"
" template <class b> a(b) {}\n"
"};\n"
"auto c() -> a {\n"
" return {[] {\n"
" if (0) {}\n"
" }};\n"
"}\n"));
ASSERT_NO_THROW(tokenizeAndStringify("struct a {\n"
" template <class b> a(b) {}\n"
"};\n"
"auto c() -> a {\n"
" return {[]() -> int {\n"
" if (0) {}\n"
" return 0;\n"
" }};\n"
"}\n"));
ASSERT_NO_THROW(tokenizeAndStringify("struct a {\n"
" template <class b> a(b) {}\n"
"};\n"
"auto c() -> a {\n"
" return {[]() mutable -> int {\n"
" if (0) {}\n"
" return 0;\n"
" }};\n"
"}\n"));
// #0535
ASSERT_NO_THROW(tokenizeAndStringify("template <typename, typename> struct a;\n"
"template <typename, typename b> void c() {\n"
" ([]() -> decltype(0) {\n"
" if (a<b, decltype(0)>::d) {}\n"
" });\n"
"}\n"));
// #9563
ASSERT_NO_THROW(tokenizeAndStringify("template <typename> struct a;\n"
"template <typename b, typename... c> struct a<b(c...)> {\n"
" template <typename d> a(d);\n"
"};\n"
"void e(\n"
" int, a<void()> f = [] {});\n"));
// #9644
ASSERT_NO_THROW(tokenizeAndStringify("void a() {\n"
" char b[]{};\n"
" auto c = [](int d) {\n"
" for (char e = 0; d;) {}\n"
" };\n"
"}\n"));
// #9537
ASSERT_NO_THROW(tokenizeAndStringify("struct a {\n"
" template <typename b> a(b) {}\n"
"};\n"
"a c{[] {\n"
" if (0) {}\n"
"}};\n"));
// #9185
ASSERT_NO_THROW(tokenizeAndStringify("void a() {\n"
" [b = [] { ; }] {};\n"
"}\n"));
// #10739
ASSERT_NO_THROW(tokenizeAndStringify("struct a {\n"
" std::vector<int> b;\n"
"};\n"
"void c() {\n"
" a bar;\n"
" (decltype(bar.b)::value_type){};\n"
"}\n"));
ASSERT_NO_THROW(tokenizeAndStringify("struct S { char c{}; };\n" // #11400
"void takesFunc(auto f) {}\n"
"int main() { \n"
" takesFunc([func = [](S s) { return s.c; }] {});\n"
"}\n"));
ignore_errout();
}
void checkIfCppCast() {
ASSERT_NO_THROW(tokenizeAndStringify("struct a {\n"
" int b();\n"
"};\n"
"struct c {\n"
" bool d() const;\n"
" a e;\n"
"};\n"
"bool c::d() const {\n"
" int f = 0;\n"
" if (!const_cast<a *>(&e)->b()) {}\n"
" return f;\n"
"}\n"));
}
void checkRefQualifiers() {
// #9511
ASSERT_NO_THROW(tokenizeAndStringify("class a {\n"
" void b() && {\n"
" if (this) {}\n"
" }\n"
"};\n"));
ASSERT_NO_THROW(tokenizeAndStringify("class a {\n"
" void b() & {\n"
" if (this) {}\n"
" }\n"
"};\n"));
ASSERT_NO_THROW(tokenizeAndStringify("class a {\n"
" auto b() && -> void {\n"
" if (this) {}\n"
" }\n"
"};\n"));
ASSERT_NO_THROW(tokenizeAndStringify("class a {\n"
" auto b() & -> void {\n"
" if (this) {}\n"
" }\n"
"};\n"));
ASSERT_NO_THROW(tokenizeAndStringify("class a {\n"
" auto b(int& x) -> int& {\n"
" if (this) {}\n"
" return x;\n"
" }\n"
"};\n"));
ASSERT_NO_THROW(tokenizeAndStringify("class a {\n"
" auto b(int& x) -> int&& {\n"
" if (this) {}\n"
" return x;\n"
" }\n"
"};\n"));
ASSERT_NO_THROW(tokenizeAndStringify("class a {\n"
" auto b(int& x) && -> int& {\n"
" if (this) {}\n"
" return x;\n"
" }\n"
"};\n"));
// #9524
ASSERT_NO_THROW(tokenizeAndStringify("auto f() -> int* {\n"
" if (0) {}\n"
" return 0;\n"
"};\n"));
ASSERT_NO_THROW(tokenizeAndStringify("auto f() -> int** {\n"
" if (0) {}\n"
" return 0;\n"
"};\n"));
ignore_errout();
}
void checkConditionBlock() {
ASSERT_NO_THROW(tokenizeAndStringify("void a() {\n"
" for (auto b : std::vector<std::vector<int>>{{}, {}}) {}\n"
"}\n"));
}
void checkUnknownCircularVar()
{
ASSERT_NO_THROW(tokenizeAndStringify("void execute() {\n"
" const auto &bias = GEMM_CTX_ARG_STORAGE(bias);\n"
" auto &c = GEMM_CTX_ARG_STORAGE(c);\n"
"}\n"));
ignore_errout(); // we do not care about the output
}
void checkRequires()
{
ASSERT_NO_THROW(tokenizeAndStringify("template<class T, class U>\n"
"struct X { X(U) requires true {} };\n"));
ASSERT_NO_THROW(tokenizeAndStringify("template<class T, class U>\n"
"struct X { X(U) requires bool{std::is_integral<T>{}} {} };\n"));
ASSERT_NO_THROW(tokenizeAndStringify("template <typename T>\n"
"struct test { operator int() requires true { return 0; } };\n"));
ASSERT_NO_THROW(tokenizeAndStringify("template <typename T>\n"
"struct test { operator int() requires bool{std::is_integral<T>{}} { return 0; } };\n"));
}
void noCrash1() {
ASSERT_NO_THROW(tokenizeAndStringify(
"struct A {\n"
" A( const std::string &name = \" \" );\n"
"};\n"
"A::A( const std::string &name ) { return; }\n"));
}
// #9007
void noCrash2() {
ASSERT_NO_THROW(tokenizeAndStringify(
"class a {\n"
"public:\n"
" enum b {};\n"
"};\n"
"struct c;\n"
"template <class> class d {\n"
" d(const int &, a::b, double, double);\n"
" d(const d &);\n"
"};\n"
"template <> d<int>::d(const int &, a::b, double, double);\n"
"template <> d<int>::d(const d &) {}\n"
"template <> d<c>::d(const d &) {}\n"));
ignore_errout(); // we do not care about the output
}
void noCrash3() {
ASSERT_NO_THROW(tokenizeAndStringify("void a(X<int> x, typename Y1::Y2<int, A::B::C, 2> y, Z z = []{});"));
}
void noCrash4() {
ASSERT_NO_THROW(tokenizeAndStringify("static int foo() {\n"
" zval ref ;\n"
" p = &(ref).value;\n"
" return result ;\n"
"}\n"));
ignore_errout();
}
void noCrash5() { // #10603
ASSERT_NO_THROW(tokenizeAndStringify("class B { using shared_ptr = std::shared_ptr<Foo>; };\n"
"class D : public B { void f(const std::shared_ptr<int>& ptr) {} };\n"));
}
void noCrash6() { // #10212
ASSERT_NO_THROW(tokenizeAndStringify("template <long, long a = 0> struct b;\n"
"template <class, bool> struct c;\n"
"template <template <class, class> class a, class e, class... d>\n"
"struct c<a<e, d...>, true> {};\n"));
}
void noCrash7() {
ASSERT_THROW_INTERNAL(tokenizeAndStringify("void g() {\n"// TODO: don't throw
" for (using T = int; (T)false;) {}\n" // C++23 P2360R0: Extend init-statement to allow alias-declaration
"}\n"), SYNTAX);
}
template<size_t size>
void checkConfig(const char (&code)[size]) {
const Settings s = settingsBuilder().checkConfiguration().build();
// tokenize..
SimpleTokenizer tokenizer(s, *this);
ASSERT(tokenizer.tokenize(code));
}
void checkConfiguration() {
ASSERT_THROW_INTERNAL_EQUALS(checkConfig("void f() { DEBUG(x();y()); }"),
UNKNOWN_MACRO,
"There is an unknown macro here somewhere. Configuration is required. If DEBUG is a macro then please configure it.");
}
void unknownType() { // #8952
const Settings settings = settingsBuilder().debugwarnings().build();
char code[] = "class A {\n"
"public:\n"
" enum Type { Null };\n"
"};\n"
"using V = A;\n"
"V::Type value;";
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT(tokenizer.tokenize(code));
tokenizer.printUnknownTypes();
ASSERT_EQUALS("", errout_str());
}
void unknownMacroBeforeReturn() {
ASSERT_THROW_INTERNAL(tokenizeAndStringify("int f() { X return 0; }"), UNKNOWN_MACRO);
}
void cppcast() {
const char code[] = "a = const_cast<int>(x);\n"
"a = dynamic_cast<int>(x);\n"
"a = reinterpret_cast<int>(x);\n"
"a = static_cast<int>(x);\n";
SimpleTokenizer tokenizer(settingsDefault, *this);
ASSERT(tokenizer.tokenize(code));
for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) {
ASSERT_EQUALS(tok->str() == "(", tok->isCast());
}
}
#define checkHdrs(...) checkHdrs_(__FILE__, __LINE__, __VA_ARGS__)
std::string checkHdrs_(const char* file, int line, const char code[], bool checkHeadersFlag) {
const Settings settings = settingsBuilder().checkHeaders(checkHeadersFlag).build();
std::vector<std::string> files(1, "test.cpp");
Tokenizer tokenizer(settings, *this);
PreprocessorHelper::preprocess(code, files, tokenizer, *this);
// Tokenizer..
ASSERT_LOC(tokenizer.simplifyTokens1(""), file, line);
return tokenizer.tokens()->stringifyList();
}
void checkHeader1() {
// #9977
const char code[] = "# 1 \"test.h\"\n"
"struct A {\n"
" int a = 1;\n"
" void f() { g(1); }\n"
" template <typename T> void g(T x) { a = 2; }\n" // <- template is used and should be kept
"};";
ASSERT_EQUALS("\n\n##file 1\n"
"1: struct A {\n"
"2: int a ; a = 1 ;\n"
"3: void f ( ) { g<int> ( 1 ) ; }\n"
"4: void g<int> ( int x ) ;\n"
"5: } ;\n"
"4: void A :: g<int> ( int x ) { a = 2 ; }\n",
checkHdrs(code, true));
ASSERT_EQUALS("\n\n##file 1\n\n"
"1:\n"
"|\n"
"4:\n"
"5: ;\n",
checkHdrs(code, false));
}
void removeExtraTemplateKeywords() {
const char code1[] = "typename GridView::template Codim<0>::Iterator iterator;";
const char expected1[] = "GridView :: Codim < 0 > :: Iterator iterator ;";
ASSERT_EQUALS(expected1, tokenizeAndStringify(code1));
const char code2[] = "typename GridView::template Codim<0>::Iterator it = gv.template begin<0>();";
const char expected2[] = "GridView :: Codim < 0 > :: Iterator it ; it = gv . begin < 0 > ( ) ;";
ASSERT_EQUALS(expected2, tokenizeAndStringify(code2));
}
void removeAlignas1() {
const char code[] = "alignas(float) unsigned char c[sizeof(float)];";
const char expected[] = "unsigned char c [ sizeof ( float ) ] ;";
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
}
void removeAlignas2() { // Do not remove alignas and alignof in the same way
const char code[] = "static_assert( alignof( VertexC ) == 4 );";
const char expected[] = "static_assert ( alignof ( VertexC ) == 4 ) ;";
ASSERT_EQUALS(expected, tokenizeAndStringify(code));
}
void removeAlignas3() {
const char code[] = "alignas(16) int x;";
const char expected[] = "int x ;";
// According to cppreference alignas() is a C23 macro; but it is often available when compiling C11.
// Misra C has C11 examples with alignas.
// Microsoft provides alignas in C11.
ASSERT_EQUALS(expected, tokenizeAndStringify(code, true, Platform::Type::Native, false, Standards::CPP11, Standards::C11));
ASSERT_EQUALS(expected, tokenizeAndStringify(code, true, Platform::Type::Native, true, Standards::CPP11, Standards::C11));
}
void dumpAlignas() {
Settings settings;
SimpleTokenizer tokenizer(settings, *this);
ASSERT(tokenizer.tokenize("int alignas(8) alignas(16) x;", false));
ASSERT(Token::simpleMatch(tokenizer.tokens(), "int x ;"));
std::ostringstream ostr;
tokenizer.dump(ostr);
const std::string dump = ostr.str();
ASSERT(dump.find(" alignas=\"8\" alignas2=\"16\"") != std::string::npos);
}
void simplifyCoroutines() {
const Settings settings = settingsBuilder().cpp(Standards::CPP20).build();
const char code1[] = "generator<int> f() { co_yield start++; }";
const char expected1[] = "generator < int > f ( ) { co_yield ( start ++ ) ; }";
ASSERT_EQUALS(expected1, tokenizeAndStringify(code1, settings));
const char code2[] = "task<> f() { co_await foo(); }";
const char expected2[] = "task < > f ( ) { co_await ( foo ( ) ) ; }";
ASSERT_EQUALS(expected2, tokenizeAndStringify(code2, settings));
const char code3[] = "generator<int> f() { co_return 7; }";
const char expected3[] = "generator < int > f ( ) { co_return ( 7 ) ; }";
ASSERT_EQUALS(expected3, tokenizeAndStringify(code3, settings));
}
void simplifySpaceshipOperator() {
const Settings settings = settingsBuilder().cpp(Standards::CPP20).build();
ASSERT_EQUALS("; x <=> y ;", tokenizeAndStringify(";x<=>y;", settings));
}
void simplifyIfSwitchForInit1() {
const Settings settings = settingsBuilder().cpp(Standards::CPP17).build();
const char code[] = "void f() { if (a;b) {} }";
ASSERT_EQUALS("void f ( ) { { a ; if ( b ) { } } }", tokenizeAndStringify(code, settings));
}
void simplifyIfSwitchForInit2() {
const Settings settings = settingsBuilder().cpp(Standards::CPP20).build();
const char code[] = "void f() { if (a;b) {} else {} }";
ASSERT_EQUALS("void f ( ) { { a ; if ( b ) { } else { } } }", tokenizeAndStringify(code, settings));
}
void simplifyIfSwitchForInit3() {
const Settings settings = settingsBuilder().cpp(Standards::CPP20).build();
const char code[] = "void f() { switch (a;b) {} }";
ASSERT_EQUALS("void f ( ) { { a ; switch ( b ) { } } }", tokenizeAndStringify(code, settings));
}
void simplifyIfSwitchForInit4() {
const Settings settings = settingsBuilder().cpp(Standards::CPP20).build();
const char code[] = "void f() { for (a;b:c) {} }";
ASSERT_EQUALS("void f ( ) { { a ; for ( b : c ) { } } }", tokenizeAndStringify(code, settings));
}
void simplifyIfSwitchForInit5() {
const Settings settings = settingsBuilder().cpp(Standards::CPP20).build();
const char code[] = "void f() { if ([] { ; }) {} }";
ASSERT_EQUALS("void f ( ) { if ( [ ] { ; } ) { } }", tokenizeAndStringify(code, settings));
}
void cpp20_default_bitfield_initializer() {
const Settings s1 = settingsBuilder().cpp(Standards::CPP20).build();
const char code[] = "struct S { int a:2 = 0; };";
ASSERT_EQUALS("struct S { int a ; a = 0 ; } ;", tokenizeAndStringify(code, s1));
const Settings s2 = settingsBuilder().cpp(Standards::CPP17).build();
ASSERT_THROW_INTERNAL(tokenizeAndStringify(code, s2), SYNTAX);
}
void cpp11init() {
#define testIsCpp11init(...) testIsCpp11init_(__FILE__, __LINE__, __VA_ARGS__)
auto testIsCpp11init_ = [this](const char* file, int line, const char* code, const char* find, TokenImpl::Cpp11init expected) {
SimpleTokenizer tokenizer(settingsDefault, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
const Token* tok = Token::findsimplematch(tokenizer.tokens(), find, strlen(find));
ASSERT_LOC(tok, file, line);
ASSERT_LOC(tok->isCpp11init() == expected, file, line);
};
testIsCpp11init("class X : public A<int>, C::D {};",
"D {",
TokenImpl::Cpp11init::NOINIT);
testIsCpp11init("auto f() -> void {}",
"void {",
TokenImpl::Cpp11init::NOINIT);
testIsCpp11init("auto f() & -> void {}",
"void {",
TokenImpl::Cpp11init::NOINIT);
testIsCpp11init("auto f() const noexcept(false) -> void {}",
"void {",
TokenImpl::Cpp11init::NOINIT);
testIsCpp11init("auto f() -> std::vector<int> { return {}; }",
"{ return",
TokenImpl::Cpp11init::NOINIT);
testIsCpp11init("auto f() -> std::vector<int> { return {}; }",
"vector",
TokenImpl::Cpp11init::NOINIT);
testIsCpp11init("auto f() -> std::vector<int> { return {}; }",
"std ::",
TokenImpl::Cpp11init::NOINIT);
testIsCpp11init("class X{};",
"{ }",
TokenImpl::Cpp11init::NOINIT);
testIsCpp11init("class X{}", // forgotten ; so not properly recognized as a class
"{ }",
TokenImpl::Cpp11init::CPP11INIT);
testIsCpp11init("namespace abc::def { TEST(a, b) {} }",
"{ TEST",
TokenImpl::Cpp11init::NOINIT);
testIsCpp11init("namespace { TEST(a, b) {} }", // anonymous namespace
"{ TEST",
TokenImpl::Cpp11init::NOINIT);
testIsCpp11init("enum { e = decltype(s)::i };",
"{ e",
TokenImpl::Cpp11init::NOINIT);
testIsCpp11init("template <typename T>\n" // #11378
"class D<M<T, 1>> : public B<M<T, 1>, T> {\n"
"public:\n"
" D(int x) : B<M<T, 1>, T>(x) {}\n"
"};\n",
"{ public:",
TokenImpl::Cpp11init::NOINIT);
testIsCpp11init("template <typename T>\n"
"class D<M<T, 1>> : B<M<T, 1>, T> {\n"
"public:\n"
" D(int x) : B<M<T, 1>, T>(x) {}\n"
"};\n",
"{ public:",
TokenImpl::Cpp11init::NOINIT);
testIsCpp11init("using namespace std;\n"
"namespace internal {\n"
" struct S { S(); };\n"
"}\n"
"namespace internal {\n"
" S::S() {}\n"
"}\n",
"{ } }",
TokenImpl::Cpp11init::NOINIT);
testIsCpp11init("template <std::size_t N>\n"
"struct C : public C<N - 1>, public B {\n"
" ~C() {}\n"
"};\n",
"{ } }",
TokenImpl::Cpp11init::NOINIT);
testIsCpp11init("struct S { int i; } s;\n"
"struct T : decltype (s) {\n"
" T() : decltype(s) ({ 0 }) { }\n"
"};\n",
"{ } }",
TokenImpl::Cpp11init::NOINIT);
testIsCpp11init("struct S {};\n"
"template<class... Args>\n"
"struct T;\n"
"template<class... Args>\n"
"struct T<void, Args...> final : S {\n"
" void operator()(Args...) {}\n"
"};\n",
"{ void",
TokenImpl::Cpp11init::NOINIT);
testIsCpp11init("struct S {\n"
" std::uint8_t* p;\n"
" S() : p{ new std::uint8_t[1]{} } {}\n"
"};\n",
"{ } } {",
TokenImpl::Cpp11init::CPP11INIT);
testIsCpp11init("struct S {\n"
" S() : p{new (malloc(4)) int{}} {}\n"
" int* p;\n"
"};\n",
"{ } } {",
TokenImpl::Cpp11init::CPP11INIT);
ASSERT_NO_THROW(tokenizeAndStringify("template<typename U> struct X {};\n" // don't crash
"template<typename T> auto f(T t) -> X<decltype(t + 1)> {}\n"));
ASSERT_EQUALS("[test.cpp:2]: (debug) auto token with no type.\n", errout_str());
#undef testIsCpp11init
}
void testDirectiveIncludeTypes() {
const char filedata[] = "#define macro some definition\n"
"#undef macro\n"
"#ifdef macro\n"
"#elif some (complex) condition\n"
"#else\n"
"#endif\n"
"#if some other condition\n"
"#pragma some proprietary content\n"
"#\n" /* may appear in old C code */
"#ident some text\n" /* may appear in old C code */
"#unknownmacro some unpredictable text\n"
"#warning some warning message\n"
"#error some error message\n";
const char dumpdata[] = " <directivelist>\n"
" <directive file=\"test.c\" linenr=\"1\" str=\"#define macro some definition\">\n"
" <token column=\"1\" str=\"#\"/>\n"
" <token column=\"2\" str=\"define\"/>\n"
" <token column=\"9\" str=\"macro\"/>\n"
" <token column=\"15\" str=\"some\"/>\n"
" <token column=\"20\" str=\"definition\"/>\n"
" </directive>\n"
" <directive file=\"test.c\" linenr=\"2\" str=\"#undef macro\">\n"
" <token column=\"1\" str=\"#\"/>\n"
" <token column=\"2\" str=\"undef\"/>\n"
" <token column=\"8\" str=\"macro\"/>\n"
" </directive>\n"
" <directive file=\"test.c\" linenr=\"3\" str=\"#ifdef macro\">\n"
" <token column=\"1\" str=\"#\"/>\n"
" <token column=\"2\" str=\"ifdef\"/>\n"
" <token column=\"8\" str=\"macro\"/>\n"
" </directive>\n"
" <directive file=\"test.c\" linenr=\"4\" str=\"#elif some (complex) condition\">\n"
" <token column=\"1\" str=\"#\"/>\n"
" <token column=\"2\" str=\"elif\"/>\n"
" <token column=\"7\" str=\"some\"/>\n"
" <token column=\"12\" str=\"(\"/>\n"
" <token column=\"13\" str=\"complex\"/>\n"
" <token column=\"20\" str=\")\"/>\n"
" <token column=\"22\" str=\"condition\"/>\n"
" </directive>\n"
" <directive file=\"test.c\" linenr=\"5\" str=\"#else\">\n"
" <token column=\"1\" str=\"#\"/>\n"
" <token column=\"2\" str=\"else\"/>\n"
" </directive>\n"
" <directive file=\"test.c\" linenr=\"6\" str=\"#endif\">\n"
" <token column=\"1\" str=\"#\"/>\n"
" <token column=\"2\" str=\"endif\"/>\n"
" </directive>\n"
" <directive file=\"test.c\" linenr=\"7\" str=\"#if some other condition\">\n"
" <token column=\"1\" str=\"#\"/>\n"
" <token column=\"2\" str=\"if\"/>\n"
" <token column=\"5\" str=\"some\"/>\n"
" <token column=\"10\" str=\"other\"/>\n"
" <token column=\"16\" str=\"condition\"/>\n"
" </directive>\n"
" <directive file=\"test.c\" linenr=\"8\" str=\"#pragma some proprietary content\">\n"
" <token column=\"1\" str=\"#\"/>\n"
" <token column=\"2\" str=\"pragma\"/>\n"
" <token column=\"9\" str=\"some\"/>\n"
" <token column=\"14\" str=\"proprietary\"/>\n"
" <token column=\"26\" str=\"content\"/>\n"
" </directive>\n"
" <directive file=\"test.c\" linenr=\"9\" str=\"#\">\n"
" <token column=\"1\" str=\"#\"/>\n"
" </directive>\n"
" <directive file=\"test.c\" linenr=\"10\" str=\"#ident some text\">\n"
" <token column=\"1\" str=\"#\"/>\n"
" <token column=\"2\" str=\"ident\"/>\n"
" <token column=\"8\" str=\"some\"/>\n"
" <token column=\"13\" str=\"text\"/>\n"
" </directive>\n"
" <directive file=\"test.c\" linenr=\"11\" str=\"#unknownmacro some unpredictable text\">\n"
" <token column=\"1\" str=\"#\"/>\n"
" <token column=\"2\" str=\"unknownmacro\"/>\n"
" <token column=\"15\" str=\"some\"/>\n"
" <token column=\"20\" str=\"unpredictable\"/>\n"
" <token column=\"34\" str=\"text\"/>\n"
" </directive>\n"
" <directive file=\"test.c\" linenr=\"12\" str=\"#warning some warning message\">\n"
" <token column=\"1\" str=\"#\"/>\n"
" <token column=\"2\" str=\"warning\"/>\n"
" <token column=\"10\" str=\"some warning message\"/>\n"
" </directive>\n"
" <directive file=\"test.c\" linenr=\"13\" str=\"#error some error message\">\n"
" <token column=\"1\" str=\"#\"/>\n"
" <token column=\"2\" str=\"error\"/>\n"
" <token column=\"8\" str=\"some error message\"/>\n"
" </directive>\n"
" </directivelist>\n"
" <tokenlist>\n"
" </tokenlist>\n";
std::ostringstream ostr;
directiveDump(filedata, ostr);
ASSERT_EQUALS(dumpdata, ostr.str());
}
void testDirectiveIncludeLocations() {
const char filedata[] = "#define macro1 val\n"
"#file \"inc1.h\"\n"
"#define macro2 val\n"
"#file \"inc2.h\"\n"
"#define macro3 val\n"
"#endfile\n"
"#define macro4 val\n"
"#endfile\n"
"#define macro5 val\n";
const char dumpdata[] = " <directivelist>\n"
" <directive file=\"test.c\" linenr=\"1\" str=\"#define macro1 val\">\n"
" <token column=\"1\" str=\"#\"/>\n"
" <token column=\"2\" str=\"define\"/>\n"
" <token column=\"9\" str=\"macro1\"/>\n"
" <token column=\"16\" str=\"val\"/>\n"
" </directive>\n"
" <directive file=\"test.c\" linenr=\"2\" str=\"#include "inc1.h"\">\n"
" <token column=\"1\" str=\"#\"/>\n"
" <token column=\"2\" str=\"file\"/>\n"
" <token column=\"7\" str=\""inc1.h"\"/>\n"
" </directive>\n"
" <directive file=\"inc1.h\" linenr=\"1\" str=\"#define macro2 val\">\n"
" <token column=\"1\" str=\"#\"/>\n"
" <token column=\"2\" str=\"define\"/>\n"
" <token column=\"9\" str=\"macro2\"/>\n"
" <token column=\"16\" str=\"val\"/>\n"
" </directive>\n"
" <directive file=\"inc1.h\" linenr=\"2\" str=\"#include "inc2.h"\">\n"
" <token column=\"1\" str=\"#\"/>\n"
" <token column=\"2\" str=\"file\"/>\n"
" <token column=\"7\" str=\""inc2.h"\"/>\n"
" </directive>\n"
" <directive file=\"inc2.h\" linenr=\"1\" str=\"#define macro3 val\">\n"
" <token column=\"1\" str=\"#\"/>\n"
" <token column=\"2\" str=\"define\"/>\n"
" <token column=\"9\" str=\"macro3\"/>\n"
" <token column=\"16\" str=\"val\"/>\n"
" </directive>\n"
" <directive file=\"inc1.h\" linenr=\"3\" str=\"#define macro4 val\">\n"
" <token column=\"1\" str=\"#\"/>\n"
" <token column=\"2\" str=\"define\"/>\n"
" <token column=\"9\" str=\"macro4\"/>\n"
" <token column=\"16\" str=\"val\"/>\n"
" </directive>\n"
" <directive file=\"test.c\" linenr=\"3\" str=\"#define macro5 val\">\n"
" <token column=\"1\" str=\"#\"/>\n"
" <token column=\"2\" str=\"define\"/>\n"
" <token column=\"9\" str=\"macro5\"/>\n"
" <token column=\"16\" str=\"val\"/>\n"
" </directive>\n"
" </directivelist>\n"
" <tokenlist>\n"
" </tokenlist>\n";
std::ostringstream ostr;
directiveDump(filedata, ostr);
ASSERT_EQUALS(dumpdata, ostr.str());
}
void testDirectiveIncludeComments() {
const char filedata[] = "#ifdef macro2 /* this will be removed */\n"
"#else /* this will be removed too */\n"
"#endif /* this will also be removed */\n";
const char dumpdata[] = " <directivelist>\n"
" <directive file=\"test.c\" linenr=\"1\" str=\"#ifdef macro2\">\n"
" <token column=\"1\" str=\"#\"/>\n"
" <token column=\"2\" str=\"ifdef\"/>\n"
" <token column=\"8\" str=\"macro2\"/>\n"
" </directive>\n"
" <directive file=\"test.c\" linenr=\"2\" str=\"#else\">\n"
" <token column=\"1\" str=\"#\"/>\n"
" <token column=\"2\" str=\"else\"/>\n"
" </directive>\n"
" <directive file=\"test.c\" linenr=\"3\" str=\"#endif\">\n"
" <token column=\"1\" str=\"#\"/>\n"
" <token column=\"2\" str=\"endif\"/>\n"
" </directive>\n"
" </directivelist>\n"
" <tokenlist>\n"
" </tokenlist>\n";
std::ostringstream ostr;
directiveDump(filedata, ostr);
ASSERT_EQUALS(dumpdata, ostr.str());
}
void testDirectiveRelativePath() {
const char filedata[] = "#define macro 1\n";
const char dumpdata[] = " <directivelist>\n"
" <directive file=\"test.c\" linenr=\"1\" str=\"#define macro 1\">\n"
" <token column=\"1\" str=\"#\"/>\n"
" <token column=\"2\" str=\"define\"/>\n"
" <token column=\"9\" str=\"macro\"/>\n"
" <token column=\"15\" str=\"1\"/>\n"
" </directive>\n"
" </directivelist>\n"
" <tokenlist>\n"
" </tokenlist>\n";
std::ostringstream ostr;
Settings s(settingsDefault);
s.relativePaths = true;
s.basePaths.emplace_back("/some/path");
directiveDump(filedata, "/some/path/test.c", s, ostr);
ASSERT_EQUALS(dumpdata, ostr.str());
}
};
REGISTER_TEST(TestTokenizer)
class TestTokenizerCompileLimits : public TestFixture
{
public:
TestTokenizerCompileLimits() : TestFixture("TestTokenizerCompileLimits") {}
private:
void run() override
{
TEST_CASE(test); // #5592 crash: gcc: testsuit: gcc.c-torture/compile/limits-declparen.c
}
#define tokenizeAndStringify(...) tokenizeAndStringify_(__FILE__, __LINE__, __VA_ARGS__)
std::string tokenizeAndStringify_(const char* file, int linenr, const std::string& code) {
const Settings settings;
// tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, linenr);
if (tokenizer.tokens())
return tokenizer.tokens()->stringifyList(false, true, false, true, false, nullptr, nullptr);
return "";
}
void test() {
const char raw_code[] = "#define PTR1 (* (* (* (*\n"
"#define PTR2 PTR1 PTR1 PTR1 PTR1\n"
"#define PTR3 PTR2 PTR2 PTR2 PTR2\n"
"#define PTR4 PTR3 PTR3 PTR3 PTR3\n"
"\n"
"#define RBR1 ) ) ) )\n"
"#define RBR2 RBR1 RBR1 RBR1 RBR1\n"
"#define RBR3 RBR2 RBR2 RBR2 RBR2\n"
"#define RBR4 RBR3 RBR3 RBR3 RBR3\n"
"\n"
"int PTR4 q4_var RBR4 = 0;\n";
// Preprocess file..
std::istringstream fin(raw_code);
simplecpp::OutputList outputList;
std::vector<std::string> files;
const simplecpp::TokenList tokens1(fin, files, emptyString, &outputList);
const std::string filedata = tokens1.stringify();
const Settings settings;
const std::string code = PreprocessorHelper::getcode(settings, *this, filedata, emptyString, emptyString);
ASSERT_THROW_INTERNAL_EQUALS(tokenizeAndStringify(code), AST, "maximum AST depth exceeded");
}
};
REGISTER_TEST(TestTokenizerCompileLimits)
| null |
1,027 | cpp | cppcheck | example.cc | test/tools/htmlreport/example.cc | null | #include "missing.h"
int main()
{
int x;
x++;
}
| null |
1,028 | cpp | cppcheck | wxwidgets.cpp | test/cfg/wxwidgets.cpp | null |
// Test library configuration for wxwidgets.cfg
//
// Usage:
// $ ./cppcheck --check-library --library=wxwidgets --enable=style,information --inconclusive --error-exitcode=1 --inline-suppr test/cfg/wxwidgets.cpp
// =>
// No warnings about bad library configuration, unmatched suppressions, etc. exitcode=0
//
// cppcheck-suppress-file valueFlowBailout
// cppcheck-suppress-file purgedConfiguration
#include <wx/wx.h>
#include <wx/accel.h>
#include <wx/any.h>
#include <wx/app.h>
#include <wx/archive.h>
#include <wx/artprov.h>
#include <wx/bitmap.h>
#if wxCHECK_VERSION(3, 1, 6) // wxWidets-3.1.6 or higher
#include <wx/bmpbndl.h>
#endif
#include <wx/brush.h>
#include <wx/calctrl.h>
#include <wx/colour.h>
#include <wx/combo.h>
#include <wx/cursor.h>
#include <wx/dc.h>
#include <wx/dataview.h>
#include <wx/datetime.h>
#include <wx/dc.h>
#include <wx/dynarray.h>
#include <wx/filefn.h>
#include <wx/font.h>
#include <wx/fontenum.h>
#include <wx/fontutil.h>
#include <wx/frame.h>
#include <wx/gbsizer.h>
#include <wx/gdicmn.h>
#include <wx/geometry.h>
#include <wx/graphics.h>
#include <wx/grid.h>
#include <wx/icon.h>
#include <wx/iconbndl.h>
#include <wx/iconloc.h>
#include <wx/image.h>
#include <wx/imaggif.h>
#include <wx/imagiff.h>
#include <wx/imagjpeg.h>
#include <wx/imagpcx.h>
#include <wx/log.h>
#include <wx/menu.h>
#include <wx/memory.h>
#include <wx/mimetype.h>
#if defined(__WXMSW__)
#include <wx/msw/ole/automtn.h>
#include <wx/metafile.h>
#include <wx/msw/ole/oleutils.h>
#endif
#include <wx/palette.h>
#include <wx/pen.h>
#include <wx/position.h>
#include <wx/propgrid/property.h>
#include <wx/regex.h>
#include <wx/region.h>
#include <wx/renderer.h>
#include <wx/settings.h>
#include <wx/spinctrl.h>
#include <wx/sizer.h>
#include <wx/string.h>
#include <wx/sysopt.h>
#include <wx/tarstrm.h>
#include <wx/textctrl.h>
#include <wx/unichar.h>
#include <wx/ustring.h>
#include <wx/variant.h>
#include <wx/vector.h>
#include <wx/versioninfo.h>
#include <wx/wrapsizer.h>
#include <wx/zipstrm.h>
#if wxCHECK_VERSION(3, 1, 6) // wxWidets-3.1.6 or higher
void unreadVariable_wxBitmapBundle(const wxBitmap &bmp, const wxIcon &icon, const wxImage &image, const char *const * xpm, const wxBitmapBundle &bundle)
{
// cppcheck-suppress unusedVariable
wxBitmapBundle a;
// cppcheck-suppress unreadVariable
wxBitmapBundle b(bmp);
// cppcheck-suppress unreadVariable
wxBitmapBundle c(icon);
// cppcheck-suppress unreadVariable
wxBitmapBundle d(image);
// cppcheck-suppress unreadVariable
wxBitmapBundle e(xpm);
// cppcheck-suppress unreadVariable
wxBitmapBundle f(bundle);
}
#endif
#if wxCHECK_VERSION(3, 1, 3) // wxWidets-3.1.3 or higher
void unreadVariable_wxDCTextBgModeChanger(wxDC &dc)
{
// cppcheck-suppress unreadVariable
wxDCTextBgModeChanger a(dc);
}
void unreadVariable_wxDCTextBgColourChanger(wxDC &dc, const wxColour &colour)
{
// cppcheck-suppress unreadVariable
wxDCTextBgColourChanger a(dc);
// cppcheck-suppress unreadVariable
wxDCTextBgColourChanger b(dc, colour);
}
#endif
void unreadVariable_wxZipEntry(const wxZipEntry &entry)
{
// cppcheck-suppress unreadVariable
wxZipEntry a(entry);
}
void unreadVariable_wxTarEntry(const wxTarEntry &entry)
{
// cppcheck-suppress unreadVariable
wxTarEntry a(entry);
}
void unreadVariable_wxDCTextColourChanger(wxDC &dc, const wxColour &colour)
{
// cppcheck-suppress unreadVariable
wxDCTextColourChanger a(dc);
// cppcheck-suppress unreadVariable
wxDCTextColourChanger b(dc, colour);
}
void unreadVariable_wxDCPenChanger(wxDC &dc, const wxPen &pen)
{
// cppcheck-suppress unreadVariable
wxDCPenChanger a(dc, pen);
}
void unreadVariable_wxDCFontChanger(wxDC &dc, const wxFont &font)
{
// cppcheck-suppress unreadVariable
wxDCFontChanger a(dc);
// cppcheck-suppress unreadVariable
wxDCFontChanger b(dc, font);
}
void unreadVariable_wxDCBrushChanger(wxDC &dc, const wxBrush &brush)
{
// cppcheck-suppress unreadVariable
wxDCBrushChanger a(dc, brush);
}
void unreadVariable_wxGBSpan(const int x)
{
// cppcheck-suppress unusedVariable
wxGBSpan a;
// cppcheck-suppress unreadVariable
wxGBSpan b(x, x);
}
void unreadVariable_wxGBPosition(const int x)
{
// cppcheck-suppress unusedVariable
wxGBPosition a;
// cppcheck-suppress unreadVariable
wxGBPosition b(x, x);
}
void unreadVariable_wxWrapSizer(const int x)
{
// cppcheck-suppress unreadVariable
wxWrapSizer a(x, x);
}
void unreadVariable_wxGridBagSizer(const int x)
{
// cppcheck-suppress unreadVariable
wxGridBagSizer a(x, x);
}
void unreadVariable_wxGBSizerItem(const int x, const wxGBPosition &pos)
{
// cppcheck-suppress unreadVariable
wxGBSizerItem a(x, x, pos);
}
void unreadVariable_wxSizerItem(const int x)
{
// cppcheck-suppress unreadVariable
wxSizerItem a(x, x);
}
void unreadVariable_wxFlexGridSizer(const int x)
{
// cppcheck-suppress unreadVariable
wxFlexGridSizer a(x, x, x);
}
void unreadVariable_wxBoxSizer(const int orient)
{
// cppcheck-suppress unreadVariable
wxBoxSizer a(orient);
}
void unreadVariable_wxGridSizer(int x)
{
// cppcheck-suppress unreadVariable
wxGridSizer a(x, x, x);
}
void unreadVariable_wxStaticBoxSizer(wxStaticBox *box, const int orient, wxWindow *parent, const wxString &label)
{
// cppcheck-suppress unreadVariable
wxStaticBoxSizer a(box, orient);
// cppcheck-suppress unreadVariable
wxStaticBoxSizer b(orient, parent);
// cppcheck-suppress unreadVariable
wxStaticBoxSizer c(orient, parent, label);
}
void unusedVariable_wxDelegateRendererNative()
{
// cppcheck-suppress unusedVariable
wxDelegateRendererNative a;
}
void unusedVariable_wxHeaderButtonParams()
{
// cppcheck-suppress unusedVariable
wxHeaderButtonParams a;
}
void unusedVariable_wxRegionIterator()
{
// cppcheck-suppress unusedVariable
wxRegionIterator a;
}
void unusedVariable_wxRegionContain()
{
// cppcheck-suppress unusedVariable
wxRegionContain a;
}
void unusedVariable_wxPalette()
{
// cppcheck-suppress unusedVariable
wxPalette a;
}
void unusedVariable_wxJPEGHandler()
{
// cppcheck-suppress unusedVariable
wxJPEGHandler a;
}
void unusedVariable_wxGIFHandler()
{
// cppcheck-suppress unusedVariable
wxGIFHandler a;
}
void unusedVariable_wxPCXHandler()
{
// cppcheck-suppress unusedVariable
wxPCXHandler a;
}
void unusedVariable_wxIFFHandler()
{
// cppcheck-suppress unusedVariable
wxIFFHandler a;
}
void unusedVariable_wxGraphicsBrush()
{
// cppcheck-suppress unusedVariable
wxGraphicsBrush a;
}
void unusedVariable_wxGraphicsMatrix()
{
// cppcheck-suppress unusedVariable
wxGraphicsMatrix a;
}
void unusedVariable_wxGraphicsFont()
{
// cppcheck-suppress unusedVariable
wxGraphicsFont a;
}
void unusedVariable_wxIconBundle()
{
// cppcheck-suppress unusedVariable
wxIconBundle a;
}
void unusedVariable_wxStdDialogButtonSizer()
{
// cppcheck-suppress unusedVariable
wxStdDialogButtonSizer a;
}
void unusedVariable_wxColourDatabase()
{
// cppcheck-suppress unusedVariable
wxColourDatabase a;
}
void unusedVariable_wxFontEnumerator()
{
// cppcheck-suppress unusedVariable
wxFontEnumerator a;
}
void unusedVariable_wxCursor()
{
// cppcheck-suppress unusedVariable
wxCursor a;
}
void unusedVariable_wxBitmapHandler()
{
// cppcheck-suppress unusedVariable
wxBitmapHandler a;
}
void unusedVariable_wxNativeFontInfo()
{
// cppcheck-suppress unusedVariable
wxNativeFontInfo a;
}
void unreadVariable_wxDCClipper(wxDC &dc, const wxRegion ®ion)
{
// cppcheck-suppress unreadVariable
wxDCClipper a(dc, region);
}
void unreadVariable_wxMask(const wxBitmap &bmp, int x, const wxColour & colour)
{
// cppcheck-suppress unusedVariable
wxMask a;
// cppcheck-suppress unreadVariable
wxMask b(bmp);
// cppcheck-suppress unreadVariable
wxMask c(bmp, x);
// cppcheck-suppress unreadVariable
wxMask d(bmp, colour);
}
void unreadVariable_wxGraphicsGradientStops()
{
// cppcheck-suppress unusedVariable
wxGraphicsGradientStops a;
// cppcheck-suppress unreadVariable
wxGraphicsGradientStops b(wxTransparentColour);
// cppcheck-suppress unreadVariable
wxGraphicsGradientStops c(wxTransparentColour, wxTransparentColour);
}
void unreadVariable_wxGraphicsGradientStop()
{
// cppcheck-suppress unusedVariable
wxGraphicsGradientStop a;
// cppcheck-suppress unreadVariable
wxGraphicsGradientStop b(wxTransparentColour);
// cppcheck-suppress unreadVariable
wxGraphicsGradientStop c(wxTransparentColour, 0.42);
}
void unusedVariable_wxFontMetrics()
{
// cppcheck-suppress unusedVariable
wxFontMetrics a;
}
void unusedVariable_wxIconLocation()
{
// cppcheck-suppress unusedVariable
wxIconLocation a;
}
void unreadVariable_wxIcon(const wxIcon &icon, const wxIconLocation &loc, const char *const *ptr)
{
// cppcheck-suppress unusedVariable
wxIcon a;
// cppcheck-suppress unreadVariable
wxIcon b(icon);
// cppcheck-suppress unreadVariable
wxIcon c(loc);
// cppcheck-suppress unreadVariable
wxIcon d(ptr);
}
void unreadVariable_wxImage(const wxImage &image, const int x)
{
// cppcheck-suppress unusedVariable
wxImage a;
// cppcheck-suppress unreadVariable
wxImage b(image);
// cppcheck-suppress unreadVariable
wxImage c(x, x);
// cppcheck-suppress unreadVariable
wxImage d(x, x, true);
}
void unreadVariable_wxUString(const wxUString &str, const wxChar32 *strPtr)
{
// cppcheck-suppress unusedVariable
wxUString a;
// cppcheck-suppress unreadVariable
wxUString b(str);
// cppcheck-suppress unreadVariable
wxUString c(strPtr);
}
void unreadVariable_wxAny(const wxVariant &variant, const wxAny &any)
{
// cppcheck-suppress unusedVariable
wxAny a;
// cppcheck-suppress unreadVariable
wxAny b(42);
// cppcheck-suppress unreadVariable
wxAny c(variant);
// cppcheck-suppress unreadVariable
wxAny d(any);
}
void unreadVariable_wxVariant(wxVariantData *data,
const wxString &name,
const wxVariant &variant,
const wxAny &any,
const wxChar *valuePtr,
const wxString &valueStr,
const wxChar charValue,
long lValue,
bool bvalue)
{
// cppcheck-suppress unusedVariable
wxVariant a;
// cppcheck-suppress unreadVariable
wxVariant b(data);
// cppcheck-suppress unreadVariable
wxVariant c(data, name);
// cppcheck-suppress unreadVariable
wxVariant d(variant);
// cppcheck-suppress unreadVariable
wxVariant e(any);
// cppcheck-suppress unreadVariable
wxVariant f(valuePtr);
// cppcheck-suppress unreadVariable
wxVariant g(valuePtr, name);
// cppcheck-suppress unreadVariable
wxVariant h(valueStr);
// cppcheck-suppress unreadVariable
wxVariant i(valueStr, name);
// cppcheck-suppress unreadVariable
wxVariant j(charValue);
// cppcheck-suppress unreadVariable
wxVariant k(charValue, name);
// cppcheck-suppress unreadVariable
wxVariant l(lValue);
// cppcheck-suppress unreadVariable
wxVariant m(lValue, name);
// cppcheck-suppress unreadVariable
wxVariant n(bvalue);
// cppcheck-suppress unreadVariable
wxVariant o(bvalue, name);
}
#if defined(__WXMSW__)
void unusedVariable_wxMetafile()
{
// cppcheck-suppress unusedVariable
wxMetafile a;
}
void unusedVariable_wxVariantDataErrorCode()
{
// cppcheck-suppress unusedVariable
wxVariantDataErrorCode a;
}
void unusedVariable_wxVariantDataCurrency()
{
// cppcheck-suppress unusedVariable
wxVariantDataCurrency a;
}
void unusedVariable_wxVariantDataSafeArray()
{
// cppcheck-suppress unusedVariable
wxVariantDataSafeArray a;
}
#endif
void unreadVariable_wxBitmap(const wxBitmap &bmp, const char bits[], const int x, const wxSize &sz)
{
// cppcheck-suppress unusedVariable
wxBitmap a;
// cppcheck-suppress unreadVariable
wxBitmap b(bmp);
// cppcheck-suppress unreadVariable
wxBitmap c(bits, x, x);
// cppcheck-suppress unreadVariable
wxBitmap d(bits, x, x, x);
// cppcheck-suppress unreadVariable
wxBitmap e(x, x);
// cppcheck-suppress unreadVariable
wxBitmap f(x, x, x);
// cppcheck-suppress unreadVariable
wxBitmap g(sz);
// cppcheck-suppress unreadVariable
wxBitmap h(sz, x);
}
void unusedVariable_wxChar()
{
// cppcheck-suppress unusedVariable
wxChar a;
}
void unusedVariable_wxUniChar(const int c)
{
// cppcheck-suppress unusedVariable
wxUniChar a;
// cppcheck-suppress unreadVariable
wxUniChar b(c);
}
void unusedVariable_wxSystemOptions()
{
// cppcheck-suppress unusedVariable
wxSystemOptions a;
}
void unusedVariable_wxSystemSettings()
{
// cppcheck-suppress unusedVariable
wxSystemSettings a;
}
void unusedVariable_wxPenList()
{
// cppcheck-suppress unusedVariable
wxPenList a;
}
void unusedVariable_wxPen(const wxColour &colour, int width, const wxPenStyle style, const wxPen &pen)
{
// cppcheck-suppress unusedVariable
wxPen a;
// cppcheck-suppress unreadVariable
wxPen b(colour, width);
// cppcheck-suppress unreadVariable
wxPen c(colour, width, style);
// cppcheck-suppress unreadVariable
wxPen d(pen);
}
void unusedVariable_wxBrush(const wxColour &color, const wxBrushStyle style, const wxBitmap &bmp, const wxBrush &brush)
{
// cppcheck-suppress unusedVariable
wxBrush a;
// cppcheck-suppress unreadVariable
wxBrush b(color, style);
// cppcheck-suppress unreadVariable
wxBrush c(bmp);
// cppcheck-suppress unreadVariable
wxBrush d(brush);
}
void unusedVariable_wxFontList()
{
// cppcheck-suppress unusedVariable
wxFontList a;
}
void unusedVariable_wxFontInfo(const double pointSize, const wxSize &sz)
{
// cppcheck-suppress unusedVariable
wxFontInfo a;
// cppcheck-suppress unreadVariable
wxFontInfo b(pointSize);
// cppcheck-suppress unreadVariable
wxFontInfo c(sz);
}
void unusedVariable_wxFont(const wxFont &font,
const wxFontInfo &fontInfo,
const int pointSize,
const wxFontFamily family,
const wxFontStyle style,
const wxFontWeight weight,
const bool underline,
const wxString &faceName,
const wxFontEncoding encoding)
{
// cppcheck-suppress unusedVariable
wxFont a;
// cppcheck-suppress unreadVariable
wxFont b(font);
// cppcheck-suppress unreadVariable
wxFont c(fontInfo);
// cppcheck-suppress unreadVariable
wxFont d(pointSize, family, style, weight);
// cppcheck-suppress unreadVariable
wxFont e(pointSize, family, style, weight, underline);
// cppcheck-suppress unreadVariable
wxFont f(pointSize, family, style, weight, underline, faceName);
// cppcheck-suppress unreadVariable
wxFont g(pointSize, family, style, weight, underline, faceName, encoding);
}
void unusedVariable_wxVector()
{
// cppcheck-suppress unusedVariable
wxVector<int> a;
}
void unusedVariable_wxArrayInt()
{
// cppcheck-suppress unusedVariable
wxArrayInt a;
}
void unusedVariable_wxArrayDouble()
{
// cppcheck-suppress unusedVariable
wxArrayDouble a;
}
void unusedVariable_wxArrayShort()
{
// cppcheck-suppress unusedVariable
wxArrayShort a;
}
void unusedVariable_wxArrayString()
{
// cppcheck-suppress unusedVariable
wxArrayString a;
}
void unusedVariable_wxArrayPtrVoid()
{
// cppcheck-suppress unusedVariable
wxArrayPtrVoid a;
}
void unreadVariable_wxColour(const unsigned char uc, const wxString &name, const unsigned long colRGB, const wxColour &colour)
{
// cppcheck-suppress unusedVariable
wxColour a;
// cppcheck-suppress unreadVariable
wxColour b(uc, uc, uc);
// cppcheck-suppress unreadVariable
wxColour c(uc, uc, uc, uc);
// cppcheck-suppress unreadVariable
wxColour d(name);
// cppcheck-suppress unreadVariable
wxColour e(colRGB);
// cppcheck-suppress unreadVariable
wxColour f(colour);
}
void unreadVariable_wxPoint2DInt(const wxInt32 x, const wxPoint2DInt& pti, const wxPoint &pt)
{
// cppcheck-suppress unusedVariable
wxPoint2DInt a;
// cppcheck-suppress unreadVariable
wxPoint2DInt b(x, x);
// cppcheck-suppress unreadVariable
wxPoint2DInt c(pti);
// cppcheck-suppress unreadVariable
wxPoint2DInt d(pt);
}
void unreadVariable_wxPoint2DDouble(const wxDouble x, const wxPoint2DDouble& ptd, const wxPoint2DInt& pti, const wxPoint &pt)
{
// cppcheck-suppress unusedVariable
wxPoint2DDouble a;
// cppcheck-suppress unreadVariable
wxPoint2DDouble b(x, x);
// cppcheck-suppress unreadVariable
wxPoint2DDouble c(ptd);
// cppcheck-suppress unreadVariable
wxPoint2DDouble d(pti);
// cppcheck-suppress unreadVariable
wxPoint2DDouble e(pt);
}
void unusedVariable_wxAcceleratorEntry()
{
// cppcheck-suppress unusedVariable
wxAcceleratorEntry a;
}
void unreadVariable_wxDateSpan(const int x)
{
// cppcheck-suppress unusedVariable
wxDateSpan a;
// cppcheck-suppress unreadVariable
wxDateSpan b{x};
// cppcheck-suppress unreadVariable
wxDateSpan c{x, x};
// cppcheck-suppress unreadVariable
wxDateSpan d{x, x, x};
// cppcheck-suppress unreadVariable
wxDateSpan e{x, x, x, x};
}
void unreadVariable_wxTimeSpan(const long x, const wxLongLong y)
{
// cppcheck-suppress unusedVariable
wxTimeSpan a;
// cppcheck-suppress unreadVariable
wxTimeSpan b{};
// cppcheck-suppress unreadVariable
wxTimeSpan c{x};
// cppcheck-suppress unreadVariable
wxTimeSpan d{x, x};
// cppcheck-suppress unreadVariable
wxTimeSpan e{x, x, y};
// cppcheck-suppress unreadVariable
wxTimeSpan f{x, x, y, y};
}
void unreadVariable_wxFileType(const wxFileTypeInfo &info)
{
// cppcheck-suppress unreadVariable
wxFileType a(info);
}
void unreadVariable_wxPosition(const int x)
{
// cppcheck-suppress unusedVariable
wxPosition a;
// cppcheck-suppress unreadVariable
wxPosition b{};
// cppcheck-suppress unreadVariable
wxPosition c{x,x};
}
void unreadVariable_wxRegEx(const wxString &expr, const int flags)
{
// cppcheck-suppress unusedVariable
wxRegEx a;
// cppcheck-suppress unreadVariable
wxRegEx b{expr};
// cppcheck-suppress unreadVariable
wxRegEx c{expr, flags};
}
void unreadVariable_wxRegion(const wxCoord x, const wxPoint &pt, const wxRect &rect, const wxRegion ®ion, const wxBitmap &bmp)
{
// cppcheck-suppress unusedVariable
wxRegion a;
// cppcheck-suppress unreadVariable
wxRegion b{};
// cppcheck-suppress unreadVariable
wxRegion c{x,x,x,x};
// cppcheck-suppress unreadVariable
wxRegion d{pt,pt};
// cppcheck-suppress unreadVariable
wxRegion e{rect};
// cppcheck-suppress unreadVariable
wxRegion f{region};
// cppcheck-suppress unreadVariable
wxRegion g{bmp};
}
void unreadVariable_wxVersionInfo(const wxString &name, const int major, const int minor, const int micro, const wxString &description, const wxString ©right)
{
// cppcheck-suppress unusedVariable
wxVersionInfo a;
// cppcheck-suppress unreadVariable
wxVersionInfo b(name);
// cppcheck-suppress unreadVariable
wxVersionInfo c(name, major);
// cppcheck-suppress unreadVariable
wxVersionInfo d(name, major, minor);
// cppcheck-suppress unreadVariable
wxVersionInfo e(name, major, minor, micro);
// cppcheck-suppress unreadVariable
wxVersionInfo f(name, major, minor, micro, description);
// cppcheck-suppress unreadVariable
wxVersionInfo g(name, major, minor, micro, description, copyright);
}
void unreadVariable_wxSize(const wxSize &s)
{
// cppcheck-suppress unusedVariable
wxSize a;
// cppcheck-suppress unreadVariable
wxSize b{};
// cppcheck-suppress unreadVariable
wxSize c{4, 2};
// cppcheck-suppress unreadVariable
wxSize d(4, 2);
// cppcheck-suppress unreadVariable
wxSize e(s);
}
void unreadVariable_wxPoint(const wxRealPoint &rp, const int x, const int y)
{
// cppcheck-suppress unusedVariable
wxPoint a;
// cppcheck-suppress unreadVariable
wxPoint b{};
// cppcheck-suppress unreadVariable
wxPoint c{4, 2};
// cppcheck-suppress unreadVariable
wxPoint d(4, 2);
// cppcheck-suppress unreadVariable
wxPoint e{x, 2};
// cppcheck-suppress unreadVariable
wxPoint f(4, y);
// cppcheck-suppress unreadVariable
wxPoint g(rp);
}
void unreadVariable_wxRealPoint(const wxPoint &pt, const double x, const double y)
{
// cppcheck-suppress unusedVariable
wxRealPoint a;
// cppcheck-suppress unreadVariable
wxRealPoint b{};
// cppcheck-suppress unreadVariable
wxRealPoint c{4.0, 2.0};
// cppcheck-suppress unreadVariable
wxRealPoint d(4.0, 2.0);
// cppcheck-suppress unreadVariable
wxRealPoint e{x, 2.0};
// cppcheck-suppress unreadVariable
wxRealPoint f(4.0, y);
// cppcheck-suppress unreadVariable
wxRealPoint g(pt);
}
void unreadVariable_wxRect(const int x, const wxPoint &pt, const wxSize &sz)
{
// cppcheck-suppress unusedVariable
wxRect a;
// cppcheck-suppress unreadVariable
wxRect b{};
// cppcheck-suppress unreadVariable
wxRect c{x,x,x,x};
// cppcheck-suppress unreadVariable
wxRect d{pt,sz};
// cppcheck-suppress unreadVariable
wxRect e{sz};
// cppcheck-suppress unreadVariable
wxRect f(x,x,x,x);
// cppcheck-suppress unreadVariable
wxRect g(pt,sz);
// cppcheck-suppress unreadVariable
wxRect h(sz);
}
void uninitvar_wxRegEx_GetMatch(const wxRegEx &obj, size_t *start, size_t *len, size_t index)
{
size_t s,l;
size_t *sPtr,*lPtr;
// cppcheck-suppress uninitvar
(void)obj.GetMatch(&s,lPtr);
// TODO cppcheck-suppress uninitvar
(void)obj.GetMatch(sPtr,&l);
(void)obj.GetMatch(&s,&l);
(void)obj.GetMatch(start,len);
(void)obj.GetMatch(start,len,0);
(void)obj.GetMatch(start,len,index);
}
#ifdef __VISUALC__
// Ensure no duplicateBreak warning is issued after wxLogApiError() calls.
// This function does not terminate execution.
bool duplicateBreak_wxLogApiError(const wxString &msg, const HRESULT &hr, wxString &str)
{
if (hr) {
wxLogApiError(msg,hr);
str = "fail";
return false;
}
return true;
}
#endif
void argDirection_wxString_ToDouble(const wxString &str)
{
// No warning is expected. Ensure both arguments are treated
// as output by library configuration
double value;
const bool convOk = str.ToDouble(&value);
if (convOk && value <= 42.0) {}
}
void argDirection_wxString_ToCDouble(const wxString &str)
{
// No warning is expected. Ensure both arguments are treated
// as output by library configuration
double value;
const bool convOk = str.ToCDouble(&value);
if (convOk && value <= 42.0) {}
}
void argDirection_wxTextCtrl_GetSelection(const wxTextCtrl *const textCtrl)
{
// No warning is expected. Ensure both arguments are treated
// as output by library configuration
long start;
long end;
textCtrl->GetSelection(&start, &end);
if (start > 0 && end > 0) {}
}
void useRetval_wxString_MakeCapitalized(wxString &str)
{
// No warning is expected for
str.MakeCapitalized();
}
void useRetval_wxString_MakeLower(wxString &str)
{
// No warning is expected for
str.MakeLower();
}
void useRetval_wxString_MakeUpper(wxString &str)
{
// No warning is expected for
str.MakeUpper();
}
wxString containerOutOfBounds_wxArrayString(void)
{
wxArrayString a;
a.Add("42");
a.Clear();
// TODO: wxArrayString is defined to be a vector
// TODO: cppcheck-suppress containerOutOfBounds
return a[0];
}
int containerOutOfBounds_wxArrayInt(void)
{
wxArrayInt a;
a.Add(42);
a.Clear();
// TODO: wxArrayString is defined to be a vector
// TODO: cppcheck-suppress containerOutOfBounds
return a[0];
}
void ignoredReturnValue_wxDC_GetSize(const wxDC &dc, wxCoord *width, wxCoord *height)
{
// No warning is expected for
dc.GetSize(width, height);
// No warning is expected for
(void)dc.GetSize();
}
void ignoredReturnValue_wxDC_GetSizeMM(const wxDC &dc, wxCoord *width, wxCoord *height)
{
// No warning is expected for
dc.GetSizeMM(width, height);
// Now warning is expected for
(void)dc.GetSizeMM();
}
wxSizerItem* invalidFunctionArgBool_wxSizer_Add(wxSizer *sizer, wxWindow * window, const wxSizerFlags &flags)
{
// No warning is expected for
return sizer->Add(window,flags);
}
bool invalidFunctionArgBool_wxPGProperty_Hide(wxPGProperty *pg, bool hide, int flags)
{
// cppcheck-suppress invalidFunctionArgBool
(void)pg->Hide(hide, true);
// No warning is expected for
return pg->Hide(hide, flags);
}
wxTextCtrlHitTestResult nullPointer_wxTextCtrl_HitTest(const wxTextCtrl& txtCtrl, const wxPoint& pos)
{
// no nullPointer-warning is expected
return txtCtrl.HitTest(pos, NULL);
}
void validCode()
{
wxString str = wxGetCwd();
(void)str;
wxLogGeneric(wxLOG_Message, "test %d", 0);
wxLogMessage("test %s", "str");
wxString translation1 = _("text");
wxString translation2 = wxGetTranslation("text");
wxString translation3 = wxGetTranslation("string", "domain");
(void)translation1;
(void)translation2;
(void)translation3;
}
#if wxUSE_GUI==1
void validGuiCode()
{
#if wxUSE_SPINCTRL==1
extern wxSpinCtrl spinCtrlInstance;
spinCtrlInstance.SetBase(10);
spinCtrlInstance.SetBase(16);
#endif
}
#endif
void nullPointer(const wxString &str)
{
// cppcheck-suppress nullPointer
wxLogGeneric(wxLOG_Message, (char*)NULL);
// cppcheck-suppress nullPointer
wxLogMessage((char*)NULL);
double *doublePtr = NULL;
// cppcheck-suppress nullPointer
(void)str.ToDouble(doublePtr);
double *doublePtr1 = NULL;
// cppcheck-suppress nullPointer
(void)str.ToCDouble(doublePtr1);
long * longPtr = NULL;
// cppcheck-suppress nullPointer
(void)str.ToLong(longPtr);
long * longPtr1 = NULL;
// cppcheck-suppress nullPointer
(void)str.ToCLong(longPtr1);
unsigned long * ulongPtr = NULL;
// cppcheck-suppress nullPointer
(void)str.ToULong(ulongPtr);
unsigned long * ulongPtr1 = NULL;
// cppcheck-suppress nullPointer
(void)str.ToCULong(ulongPtr1);
long long * longLongPtr = NULL;
// cppcheck-suppress nullPointer
(void)str.ToLongLong(longLongPtr);
unsigned long long * ulongLongPtr = NULL;
// cppcheck-suppress nullPointer
(void)str.ToULongLong(ulongLongPtr);
}
void nullPointer_wxSizer_Add(wxSizer &sizer, wxWindow *w)
{
wxWindow * const ptr = 0;
// @todo cppcheck-suppress nullPointer
sizer.Add(ptr);
// No warning shall be issued for
sizer.Add(w);
}
void uninitvar_wxSizer_Add(wxSizer &sizer, wxWindow *w,wxObject* userData)
{
int uninit1, uninit2, uninit3;
// cppcheck-suppress uninitvar
sizer.Add(w,uninit1);
// cppcheck-suppress uninitvar
sizer.Add(w,4,uninit2);
// cppcheck-suppress uninitvar
sizer.Add(w,4,2,uninit3,userData);
}
void ignoredReturnValue(const wxString &s)
{
// cppcheck-suppress ignoredReturnValue
wxGetCwd();
// cppcheck-suppress ignoredReturnValue
wxAtoi(s);
// cppcheck-suppress ignoredReturnValue
wxAtol(s);
// cppcheck-suppress ignoredReturnValue
wxAtof(s);
}
void invalidFunctionArg(const wxString &str)
{
#if wxUSE_SPINCTRL==1
extern wxSpinCtrl spinCtrlInstance;
// cppcheck-suppress invalidFunctionArg
spinCtrlInstance.SetBase(0);
// cppcheck-suppress invalidFunctionArg
spinCtrlInstance.SetBase(5);
#endif
long l;
// cppcheck-suppress invalidFunctionArg
(void)str.ToLong(&l, -1);
// cppcheck-suppress invalidFunctionArg
(void)str.ToLong(&l, 1);
// cppcheck-suppress invalidFunctionArg
(void)str.ToLong(&l, 37);
}
void uninitvar(wxWindow &w)
{
wxLogLevel logLevelUninit;
// cppcheck-suppress constVariable
char cBufUninit[10];
const char *pcUninit;
bool uninitBool;
// cppcheck-suppress uninitvar
wxLogGeneric(logLevelUninit, "test");
// cppcheck-suppress uninitvar
wxLogMessage(cBufUninit);
// cppcheck-suppress uninitvar
wxLogMessage(pcUninit);
// cppcheck-suppress uninitvar
w.Close(uninitBool);
}
void uninitvar_wxStaticText(wxStaticText &s)
{
// no warning
s.Wrap(-1);
int uninitInt;
// cppcheck-suppress uninitvar
s.Wrap(uninitInt);
}
void uninitvar_wxString_NumberConversion(const wxString &str, const int numberBase)
{
int uninitInteger1;
int uninitInteger2;
int uninitInteger3;
int uninitInteger4;
int uninitInteger5;
int uninitInteger6;
long l;
long long ll;
unsigned long ul;
unsigned long long ull;
// cppcheck-suppress uninitvar
(void)str.ToLong(&l, uninitInteger1);
// cppcheck-suppress uninitvar
(void)str.ToLongLong(&ll, uninitInteger2);
// cppcheck-suppress uninitvar
(void)str.ToULong(&ul, uninitInteger3);
// cppcheck-suppress uninitvar
(void)str.ToULongLong(&ull, uninitInteger4);
// cppcheck-suppress uninitvar
(void)str.ToCLong(&l, uninitInteger5);
// cppcheck-suppress uninitvar
(void)str.ToCULong(&ul, uninitInteger6);
}
void uninitvar_SetMenuBar(wxFrame * const framePtr, wxMenuBar * const menuBarPtr)
{
wxMenuBar *menuBar;
// cppcheck-suppress uninitvar
framePtr->SetMenuBar(menuBar);
framePtr->SetMenuBar(menuBarPtr);
}
void uninitvar_wxMenuBarAppend(wxMenuBar * const menuBarPtr, wxMenu * const menuPtr, const wxString &title)
{
wxMenu *menu;
// cppcheck-suppress uninitvar
menuBarPtr->Append(menu, title);
menuBarPtr->Append(menuPtr, title);
}
void deprecatedFunctions_wxDataViewCustomRenderer(wxDataViewCustomRenderer &dataViewCustomRenderer, wxPoint cursor, wxRect cell, wxDataViewModel *model, const wxDataViewItem &item, unsigned int col)
{
// cppcheck-suppress ActivateCalled
dataViewCustomRenderer.Activate(cell, model, item, col);
// cppcheck-suppress LeftClickCalled
dataViewCustomRenderer.LeftClick(cursor, cell, model, item, col);
}
void deprecatedFunctions([[maybe_unused]] wxApp &a,
const wxString &s,
[[maybe_unused]] wxArtProvider *artProvider,
[[maybe_unused]] wxCalendarCtrl &calenderCtrl,
wxComboCtrl &comboCtrl,
wxChar * path)
{
#ifdef __WXOSX__
// cppcheck-suppress MacOpenFileCalled
a.MacOpenFile(s);
#endif
#if wxCHECK_VERSION(3, 1, 0) // wxWidets-3.1.0 or higher:
// Some functions are not available anymore in newer versions
// @todo cppcheck-suppress ShowPopupCalled
comboCtrl.ShowPopup();
#else
// cppcheck-suppress InsertCalled
wxArtProvider::Insert(artProvider);
// cppcheck-suppress GetTextIndentCalled
// cppcheck-suppress ignoredReturnValue
comboCtrl.GetTextIndent();
// cppcheck-suppress HidePopupCalled
comboCtrl.HidePopup(true);
// cppcheck-suppress HidePopupCalled
comboCtrl.HidePopup(false);
// cppcheck-suppress HidePopupCalled
comboCtrl.HidePopup(/*default=false*/);
// cppcheck-suppress SetTextIndentCalled
comboCtrl.SetTextIndent(0);
#if wxUSE_DEBUG_CONTEXT==1
// cppcheck-suppress GetLevelCalled
// cppcheck-suppress ignoredReturnValue
wxDebugContext::GetLevel();
// cppcheck-suppress SetLevelCalled
wxDebugContext::SetLevel(42);
#endif
// cppcheck-suppress wxDos2UnixFilenameCalled
wxDos2UnixFilename(path);
// cppcheck-suppress wxFileNameFromPathCalled
// cppcheck-suppress ignoredReturnValue
wxFileNameFromPath(wxT_2("../test.c"));
#endif
#if defined(__WXMSW__) || defined(__WXGTK__)
// EnableYearChange() is not available on these GUI systems
#else
// cppcheck-suppress EnableYearChangeCalled
calenderCtrl.EnableYearChange(false);
// cppcheck-suppress EnableYearChangeCalled
calenderCtrl.EnableYearChange(true);
// cppcheck-suppress EnableYearChangeCalled
calenderCtrl.EnableYearChange(/*default=yes*/);
#endif
}
void wxString_test1(wxString s)
{
for (int i = 0; i <= s.size(); ++i) {
// cppcheck-suppress stlOutOfBounds
s[i] = 'x';
}
}
void wxString_test2()
{
wxString s;
// cppcheck-suppress containerOutOfBounds
s[1] = 'a';
s.append("abc");
s[1] = 'B';
printf("%s", static_cast<const char*>(s.c_str()));
wxPrintf("%s", s);
wxPrintf("%s", s.c_str());
s.Clear();
}
wxString::iterator wxString_test3()
{
wxString wxString1;
wxString wxString2;
// cppcheck-suppress mismatchingContainers
for (wxString::iterator it = wxString1.begin(); it != wxString2.end(); ++it)
{}
wxString::iterator it = wxString1.begin();
// cppcheck-suppress returnDanglingLifetime
return it;
}
wxGrid::wxGridSelectionModes get_wxGridSelectionModes()
{
// cppcheck-suppress valueFlowBailoutIncompleteVar // TODO: configure enum #8183
return wxGrid::wxGridSelectCells;
}
| null |
1,029 | cpp | cppcheck | windows.cpp | test/cfg/windows.cpp | null |
// Test library configuration for windows.cfg
//
// Usage:
// $ cppcheck --check-library --library=windows --enable=style,information --inconclusive --error-exitcode=1 --inline-suppr test/cfg/windows.cpp
// =>
// No warnings about bad library configuration, unmatched suppressions, etc. exitcode=0
//
// cppcheck-suppress-file [valueFlowBailout,purgedConfiguration]
#include <Windows.h>
#include <WinCon.h>
#include <cstdio>
#include <direct.h>
#include <evntrace.h>
#include <cstdlib>
#include <ctime>
#include <memory.h>
#include <mbstring.h>
#include <tchar.h>
#include <wchar.h>
#include <atlstr.h>
#include <string>
bool UpdateTraceACalled(TRACEHANDLE traceHandle, LPCSTR loggerName, EVENT_TRACE_PROPERTIES* pProperties)
{
// cppcheck-suppress UpdateTraceACalled
return UpdateTraceA(traceHandle, loggerName, pProperties) != ERROR_SUCCESS;
}
bool UpdateTraceWCalled(TRACEHANDLE traceHandle, LPCWSTR loggerName, EVENT_TRACE_PROPERTIES* pProperties)
{
// cppcheck-suppress UpdateTraceWCalled
return UpdateTraceW(traceHandle, loggerName, pProperties) != ERROR_SUCCESS;
}
void invalidHandle_CreateFile(LPCWSTR lpFileName)
{
HANDLE file = CreateFile(lpFileName, GENERIC_READ, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
// INVALID_HANDLE_VALUE is not the same as 0
if (file != INVALID_HANDLE_VALUE && file) {}
// cppcheck-suppress resourceLeak
}
void invalid_socket()
{
SOCKET sock = socket(AF_INET, SOCK_RAW, IPPROTO_TCP);
// INVALID_SOCKET is not the same as 0
if (sock != INVALID_SOCKET && sock) {}
// cppcheck-suppress resourceLeak
}
void resourceLeak_OpenThread(const DWORD dwDesiredAccess, const BOOL bInheritHandle, const DWORD dwThreadId)
{
HANDLE proc = OpenThread(dwDesiredAccess, bInheritHandle, dwThreadId);
if (proc != INVALID_HANDLE_VALUE) {}
// cppcheck-suppress resourceLeak
}
void resourceLeak_OpenProcess(const DWORD dwDesiredAccess, const BOOL bInheritHandle, const DWORD dwProcessId)
{
HANDLE proc = OpenProcess(dwDesiredAccess, bInheritHandle, dwProcessId);
if (proc != INVALID_HANDLE_VALUE) {}
// cppcheck-suppress resourceLeak
}
/// https://learn.microsoft.com/en-us/windows/console/flushconsoleinputbuffer
BOOL unreachableCode_FlushConsoleInputBuffer(int &val)
{
const BOOL retVal = FlushConsoleInputBuffer(GetStdHandle(STD_INPUT_HANDLE));
// still reachable after call FlushConsoleInputBuffer()
val = 42;
return retVal;
}
/// https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getmodulefilenamew
std::string constVariable_GetModuleFileName(void) {
char path[42];
if (GetModuleFileNameA(NULL, path, sizeof(path))==0)
return std::string();
return std::string{path};
}
int stringCompare_mbscmp(const unsigned char *string1, const unsigned char *string2)
{
// cppcheck-suppress stringCompare
(void) _mbscmp(string1, string1);
const unsigned char x[] = "x";
// cppcheck-suppress stringCompare
(void) _mbscmp(x, x);
return _mbscmp(string1, string2);
}
int stringCompare_mbscmp_l(const unsigned char *string1, const unsigned char *string2, _locale_t locale)
{
// cppcheck-suppress stringCompare
(void) _mbscmp_l(string1, string1, locale);
const unsigned char x[] = "x";
// cppcheck-suppress stringCompare
(void) _mbscmp_l(x, x, locale);
return _mbscmp_l(string1, string2, locale);
}
int ignoredReturnValue__wtoi_l(const wchar_t *str, _locale_t locale)
{
// cppcheck-suppress ignoredReturnValue
_wtoi_l(str,locale);
return _wtoi_l(str,locale);
}
int ignoredReturnValue__atoi_l(const char *str, _locale_t locale)
{
// cppcheck-suppress ignoredReturnValue
_atoi_l(str,locale);
return _atoi_l(str,locale);
}
void invalidFunctionArg__fseeki64(FILE* stream, __int64 offset, int origin)
{
// cppcheck-suppress invalidFunctionArg
(void)_fseeki64(stream, offset, -1);
// cppcheck-suppress invalidFunctionArg
(void)_fseeki64(stream, offset, 3);
// cppcheck-suppress invalidFunctionArg
(void)_fseeki64(stream, offset, 42+SEEK_SET);
// cppcheck-suppress invalidFunctionArg
(void)_fseeki64(stream, offset, SEEK_SET+42);
// No warning is expected for
(void)_fseeki64(stream, offset, origin);
(void)_fseeki64(stream, offset, SEEK_SET);
(void)_fseeki64(stream, offset, SEEK_CUR);
(void)_fseeki64(stream, offset, SEEK_END);
}
void invalidFunctionArgBool__fseeki64(FILE* stream, __int64 offset)
{
// cppcheck-suppress invalidFunctionArgBool
(void)_fseeki64(stream, offset, true);
// cppcheck-suppress invalidFunctionArgBool
(void)_fseeki64(stream, offset, false);
}
unsigned char * overlappingWriteFunction__mbscat(unsigned char *src, unsigned char *dest)
{
// No warning shall be shown:
(void)_mbscat(dest, src);
// cppcheck-suppress overlappingWriteFunction
return _mbscat(src, src);
}
void* overlappingWriteFunction__memccpy(const unsigned char *src, unsigned char *dest, int c, size_t count)
{
// No warning shall be shown:
(void)_memccpy(dest, src, c, count);
(void)_memccpy(dest, src, 42, count);
// cppcheck-suppress overlappingWriteFunction
(void) _memccpy(dest, dest, c, 4);
// cppcheck-suppress overlappingWriteFunction
return _memccpy(dest, dest+3, c, 4);
}
unsigned char * overlappingWriteFunction__mbscpy(unsigned char *src, unsigned char *dest)
{
// No warning shall be shown:
(void)_mbscpy(dest, src);
// cppcheck-suppress overlappingWriteFunction
return _mbscpy(src, src);
}
void overlappingWriteFunction__swab(char *src, char *dest, int n)
{
// No warning shall be shown:
_swab(dest, src, n);
// cppcheck-suppress overlappingWriteFunction
_swab(src, src+3, 4);
}
SYSTEM_INFO uninitvar_GetSystemInfo()
{
// No warning is expected
SYSTEM_INFO SystemInfo;
GetSystemInfo(&SystemInfo);
return SystemInfo;
}
void uninitvar__putenv(const char * envstr)
{
// No warning is expected
(void)_putenv(envstr);
const char * p;
// cppcheck-suppress uninitvar
(void)_putenv(p);
}
void nullPointer__putenv(const char * envstr)
{
// No warning is expected
(void)_putenv(envstr);
const char * p=NULL;
// cppcheck-suppress nullPointer
(void)_putenv(p);
}
void invalidFunctionArg__getcwd(char * buffer)
{
// Passing NULL as the buffer forces getcwd to allocate
// memory for the path, which allows the code to support file paths
// longer than _MAX_PATH, which are supported by NTFS.
if ((buffer = _getcwd(NULL, 0)) == NULL) {
return;
}
free(buffer);
}
// DWORD GetPrivateProfileString(
// [in] LPCTSTR lpAppName,
// [in] LPCTSTR lpKeyName,
// [in] LPCTSTR lpDefault,
// [out] LPTSTR lpReturnedString,
// [in] DWORD nSize,
// [in] LPCTSTR lpFileName)
void nullPointer_GetPrivateProfileString(LPCTSTR lpAppName,
LPCTSTR lpKeyName,
LPCTSTR lpDefault,
LPTSTR lpReturnedString,
DWORD nSize,
LPCTSTR lpFileName)
{
// No warning is expected
(void)GetPrivateProfileString(lpAppName, lpKeyName, lpDefault, lpReturnedString, nSize, lpFileName);
// No warning is expected for 1st arg as nullptr
(void)GetPrivateProfileString(nullptr, lpKeyName, lpDefault, lpReturnedString, nSize, lpFileName);
// No warning is expected for 2nd arg as nullptr
(void)GetPrivateProfileString(lpAppName, nullptr, lpDefault, lpReturnedString, nSize, lpFileName);
}
void nullPointer__get_timezone(long *sec)
{
// No warning is expected
(void)_get_timezone(sec);
long *pSec = NULL;
// cppcheck-suppress nullPointer
(void)_get_timezone(pSec);
}
void nullPointer__get_daylight(int *h)
{
// No warning is expected
(void)_get_daylight(h);
int *pHours = NULL;
// cppcheck-suppress nullPointer
(void)_get_daylight(pHours);
}
void validCode()
{
DWORD dwordInit = 0;
WORD wordInit = 0;
BYTE byteInit = 0;
// Valid Semaphore usage, no leaks, valid arguments
HANDLE hSemaphore1;
hSemaphore1 = CreateSemaphore(NULL, 0, 1, NULL);
CloseHandle(hSemaphore1);
HANDLE hSemaphore2;
// cppcheck-suppress valueFlowBailoutIncompleteVar
hSemaphore2 = CreateSemaphoreEx(NULL, 0, 1, NULL, 0, SEMAPHORE_ALL_ACCESS);
CloseHandle(hSemaphore2);
HANDLE hSemaphore3;
hSemaphore3 = OpenSemaphore(SEMAPHORE_ALL_ACCESS, TRUE, L"sem");
CloseHandle(hSemaphore3);
// Valid lstrcat usage, but with warning because it is deprecated
char buf[30] = "hello world";
// cppcheck-suppress lstrcatACalled
lstrcatA(buf, "test");
// cppcheck-suppress strlwrCalled
strlwr(buf);
// cppcheck-suppress struprCalled
strupr(buf);
// Valid Mutex usage, no leaks, valid arguments
HANDLE hMutex1;
hMutex1 = CreateMutex(NULL, TRUE, NULL);
if (hMutex1) {
ReleaseMutex(hMutex1);
}
CloseHandle(hMutex1);
HANDLE hMutex2;
hMutex2 = CreateMutexEx(NULL, NULL, 0, MUTEX_ALL_ACCESS);
CloseHandle(hMutex2);
HANDLE hMutex3;
hMutex3 = OpenMutex(MUTEX_ALL_ACCESS, FALSE, _T("sem"));
CloseHandle(hMutex3);
// Valid Module usage, no leaks, valid arguments
HMODULE hModule = GetModuleHandle(L"My.dll");
FreeLibrary(hModule);
hModule = GetModuleHandle(TEXT("somedll"));
FreeLibrary(hModule);
hModule = GetModuleHandle(NULL);
FreeLibrary(hModule);
// Valid Event usage, no leaks, valid arguments
HANDLE event;
event = CreateEvent(NULL, FALSE, FALSE, NULL);
if (NULL != event) {
SetEvent(event);
CloseHandle(event);
}
event = OpenEvent(EVENT_ALL_ACCESS, FALSE, L"testevent");
if (NULL != event) {
PulseEvent(event);
SetEvent(event);
CloseHandle(event);
}
event = CreateEventEx(NULL, L"testevent3", CREATE_EVENT_INITIAL_SET, EVENT_MODIFY_STATE);
if (NULL != event) {
ResetEvent(event);
CloseHandle(event);
}
// cppcheck-suppress unusedAllocatedMemory
void *pMem1 = _malloca(1);
_freea(pMem1);
// Memory from _alloca must not be freed
// cppcheck-suppress _allocaCalled
void *pMem2 = _alloca(10);
memset(pMem2, 0, 10);
SYSTEMTIME st;
GetSystemTime(&st);
DWORD lastError = GetLastError();
SetLastError(lastError);
PSID pEveryoneSID = NULL;
SID_IDENTIFIER_AUTHORITY SIDAuthWorld = SECURITY_WORLD_SID_AUTHORITY;
AllocateAndInitializeSid(&SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &pEveryoneSID);
FreeSid(pEveryoneSID);
LPVOID pMem = HeapAlloc(GetProcessHeap(), 0, 10);
pMem = HeapReAlloc(GetProcessHeap(), 0, pMem, 0);
HeapFree(GetProcessHeap(), 0, pMem);
char bufC[50];
sprintf_s(bufC, "Hello");
printf("%s", bufC);
sprintf_s(bufC, "%s", "test");
printf("%s", bufC);
sprintf_s(bufC, _countof(bufC), "%s", "test");
printf("%s", bufC);
wchar_t bufWC[50];
swprintf_s(bufWC, L"Hello");
wprintf(L"%s\n", bufWC);
swprintf_s(bufWC, L"%s %d", L"swprintf_s", 3);
wprintf(L"%s\n", bufWC);
swprintf_s(bufWC, _countof(bufWC), L"%s %d", L"swprintf_s", 6);
wprintf(L"%s\n", bufWC);
TCHAR bufTC[50];
_stprintf(bufTC, TEXT("Hello"));
_tprintf(TEXT("%s"), bufTC);
_stprintf(bufTC, TEXT("%d"), 1);
_tprintf(TEXT("%s"), bufTC);
_stprintf(bufTC, TEXT("%d"), 2);
_tprintf(TEXT("%s"), bufTC);
GetUserName(NULL, &dwordInit);
dwordInit = 10;
GetUserName(bufTC, &dwordInit);
WSADATA wsaData = {0};
WSAStartup(2, &wsaData);
SOCKET sock = socket(1, 2, 3);
u_long ulongInit = 0;
ioctlsocket(sock, FIONBIO, &ulongInit);
if (sock != INVALID_SOCKET) {
closesocket(sock);
}
WSACleanup();
wordInit = MAKEWORD(1, 2);
// TODO cppcheck-suppress redundantAssignment
dwordInit = MAKELONG(1, 2);
// cppcheck-suppress redundantAssignment
wordInit = LOWORD(dwordInit);
byteInit = LOBYTE(wordInit);
wordInit = HIWORD(dwordInit);
// cppcheck-suppress redundantAssignment
byteInit = HIBYTE(wordInit);
// cppcheck-suppress knownConditionTrueFalse
if (byteInit) {}
bool boolVar;
uint8_t byteBuf[5] = {0};
uint8_t byteBuf2[10] = {0};
boolVar = RtlEqualMemory(byteBuf, byteBuf2, sizeof(byteBuf));
if (boolVar) {}
boolVar = RtlCompareMemory(byteBuf, byteBuf2, sizeof(byteBuf));
if (boolVar) {}
RtlMoveMemory(byteBuf, byteBuf2, sizeof(byteBuf));
RtlCopyMemory(byteBuf, byteBuf2, sizeof(byteBuf));
RtlZeroMemory(byteBuf, sizeof(byteBuf));
ZeroMemory(byteBuf, sizeof(byteBuf));
RtlSecureZeroMemory(byteBuf, sizeof(byteBuf));
SecureZeroMemory(byteBuf, sizeof(byteBuf));
RtlFillMemory(byteBuf, sizeof(byteBuf), 0xff);
// cppcheck-suppress [LocalAllocCalled, unusedAllocatedMemory]
HLOCAL pLocalAlloc = LocalAlloc(1, 2);
LocalFree(pLocalAlloc);
// cppcheck-suppress lstrlenCalled
(void)lstrlen(bufTC);
// cppcheck-suppress lstrlenCalled
(void)lstrlen(NULL);
// Intrinsics
__noop();
__noop(1, "test", NULL);
__nop();
// cppcheck-suppress unusedAllocatedMemory
void * pAlloc1 = _aligned_malloc(100, 2);
_aligned_free(pAlloc1);
::PostMessage(nullptr, WM_QUIT, 0, 0);
printf("%zu", __alignof(int));
printf("%zu", _alignof(double));
// Valid Library usage, no leaks, valid arguments
HINSTANCE hInstLib = LoadLibrary(L"My.dll");
FreeLibrary(hInstLib);
hInstLib = LoadLibraryA("My.dll");
FreeLibrary(hInstLib);
hInstLib = LoadLibraryEx(L"My.dll", NULL, 0);
FreeLibrary(hInstLib);
hInstLib = LoadLibraryExW(L"My.dll", NULL, 0);
FreeLibrary(hInstLib);
hInstLib = ::LoadLibrary(L"My.dll");
FreeLibraryAndExitThread(hInstLib, 0); // Does not return! Must be at the end!
}
void bufferAccessOutOfBounds()
{
wchar_t buf[10];
// Verifying _countof macro configuration
// Valid loop over array
for (size_t i = 0; i < _countof(buf); ++i) {
buf[i] = L'\0';
}
// Wrong loop over array accessing one element past the end
for (size_t i = 0; i <= _countof(buf); ++i) {
// cppcheck-suppress arrayIndexOutOfBounds
buf[i] = L'\0';
}
uint8_t byteBuf[5] = {0};
uint8_t byteBuf2[10] = {0};
// cppcheck-suppress ignoredReturnValue
// cppcheck-suppress bufferAccessOutOfBounds
RtlEqualMemory(byteBuf, byteBuf2, 20);
// cppcheck-suppress ignoredReturnValue
// cppcheck-suppress bufferAccessOutOfBounds
RtlCompareMemory(byteBuf, byteBuf2, 20);
// cppcheck-suppress bufferAccessOutOfBounds
RtlMoveMemory(byteBuf, byteBuf2, 20);
// TODO cppcheck-suppress redundantCopy
// cppcheck-suppress bufferAccessOutOfBounds
MoveMemory(byteBuf, byteBuf2, 20);
// TODO cppcheck-suppress redundantCopy
// cppcheck-suppress bufferAccessOutOfBounds
RtlCopyMemory(byteBuf, byteBuf2, 20);
// TODO cppcheck-suppress redundantCopy
// cppcheck-suppress bufferAccessOutOfBounds
CopyMemory(byteBuf, byteBuf2, 20);
// cppcheck-suppress bufferAccessOutOfBounds
RtlZeroMemory(byteBuf, sizeof(byteBuf)+1);
// cppcheck-suppress bufferAccessOutOfBounds
ZeroMemory(byteBuf, sizeof(byteBuf)+1);
// cppcheck-suppress bufferAccessOutOfBounds
RtlSecureZeroMemory(byteBuf, sizeof(byteBuf)+1);
// cppcheck-suppress bufferAccessOutOfBounds
SecureZeroMemory(byteBuf, sizeof(byteBuf)+1);
// cppcheck-suppress bufferAccessOutOfBounds
RtlFillMemory(byteBuf, sizeof(byteBuf)+1, 0x01);
// cppcheck-suppress bufferAccessOutOfBounds
FillMemory(byteBuf, sizeof(byteBuf)+1, 0x01);
char * pAlloc1 = static_cast<char*>(_malloca(32));
// cppcheck-suppress nullPointerOutOfMemory
memset(pAlloc1, 0, 32);
// cppcheck-suppress bufferAccessOutOfBounds
// cppcheck-suppress nullPointerOutOfMemory
memset(pAlloc1, 0, 33);
_freea(pAlloc1);
}
void mismatchAllocDealloc()
{
char * pChar = static_cast<char*>(_aligned_malloc(100, 2));
// cppcheck-suppress mismatchAllocDealloc
free(pChar);
// cppcheck-suppress unusedAllocatedMemory
pChar = static_cast<char*>(_malloca(32));
// cppcheck-suppress mismatchAllocDealloc
_aligned_free(pChar);
}
void nullPointer()
{
HANDLE hSemaphore;
// cppcheck-suppress [nullPointer,valueFlowBailoutIncompleteVar]
hSemaphore = OpenSemaphore(SEMAPHORE_ALL_ACCESS, FALSE, NULL);
CloseHandle(hSemaphore);
// cppcheck-suppress lstrcatCalled
// cppcheck-suppress nullPointer
lstrcat(NULL, _T("test"));
TCHAR buf[10] = _T("\0");
// cppcheck-suppress lstrcatCalled
// cppcheck-suppress nullPointer
lstrcat(buf, NULL);
HANDLE hMutex;
// cppcheck-suppress nullPointer
hMutex = OpenMutex(MUTEX_ALL_ACCESS, FALSE, NULL);
CloseHandle(hMutex);
//Incorrect: 1. parameter, must not be null
// cppcheck-suppress nullPointer
FARPROC pAddr = GetProcAddress(NULL, "name");
(void)pAddr;
HMODULE * phModule = NULL;
// cppcheck-suppress nullPointer
GetModuleHandleEx(0, NULL, phModule);
// cppcheck-suppress leakReturnValNotUsed
// cppcheck-suppress nullPointer
OpenEvent(EVENT_ALL_ACCESS, FALSE, NULL);
HANDLE hEvent = NULL;
// cppcheck-suppress nullPointer
PulseEvent(hEvent);
// cppcheck-suppress nullPointer
ResetEvent(hEvent);
// cppcheck-suppress nullPointer
SetEvent(hEvent);
char *str = NULL;
// cppcheck-suppress strlwrCalled
// cppcheck-suppress nullPointer
strlwr(str);
// cppcheck-suppress struprCalled
// cppcheck-suppress nullPointer
strupr(str);
// cppcheck-suppress nullPointer
GetSystemTime(NULL);
// cppcheck-suppress nullPointer
GetLocalTime(NULL);
// TODO: error message: arg1 must not be nullptr if variable pointed to by arg2 is not 0
DWORD dwordInit = 10;
GetUserName(NULL, &dwordInit);
TCHAR bufTC[10];
// cppcheck-suppress nullPointer
GetUserName(bufTC, NULL);
SOCKET socketInit = {0};
sockaddr sockaddrUninit;
int intInit = 0;
int *pIntNull = NULL;
char charArray[] = "test";
// cppcheck-suppress nullPointer
WSAStartup(1, NULL);
// cppcheck-suppress nullPointer
bind(socketInit, NULL, 5);
// cppcheck-suppress nullPointer
getpeername(socketInit, NULL, &intInit);
// cppcheck-suppress nullPointer
getpeername(socketInit, &sockaddrUninit, pIntNull);
// cppcheck-suppress nullPointer
getsockopt(socketInit, 1, 2, NULL, &intInit);
// cppcheck-suppress nullPointer
getsockopt(socketInit, 1, 2, charArray, pIntNull);
}
void memleak_malloca()
{
// cppcheck-suppress [unusedAllocatedMemory, unreadVariable, constVariablePointer]
void *pMem = _malloca(10);
// cppcheck-suppress memleak
}
void memleak_AllocateAndInitializeSid()
{
PSID pEveryoneSID = NULL;
SID_IDENTIFIER_AUTHORITY SIDAuthWorld = SECURITY_WORLD_SID_AUTHORITY;
AllocateAndInitializeSid(&SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &pEveryoneSID);
// cppcheck-suppress memleak
}
void memleak_HeapAlloc()
{
LPVOID pMem;
pMem = HeapAlloc(GetProcessHeap(), 0, 10);
HeapValidate(GetProcessHeap(), 0, pMem);
// cppcheck-suppress unreadVariable
SIZE_T memSize = HeapSize(GetProcessHeap(), 0, pMem);
// cppcheck-suppress memleak
}
void memleak_LocalAlloc()
{
LPTSTR pszBuf;
// cppcheck-suppress [LocalAllocCalled, cstyleCast, valueFlowBailoutIncompleteVar]
pszBuf = (LPTSTR)LocalAlloc(LPTR, MAX_PATH*sizeof(TCHAR));
(void)LocalSize(pszBuf);
(void)LocalFlags(pszBuf);
LocalLock(pszBuf);
LocalUnlock(pszBuf);
// cppcheck-suppress memleak
}
void memleak_dupenv_s() // #10646
{
char* pValue;
size_t len;
errno_t err = _dupenv_s(&pValue, &len, "pathext");
if (err) return;
printf("pathext = %s\n", pValue);
free(pValue);
err = _dupenv_s(&pValue, &len, "nonexistentvariable");
if (err) return;
printf("nonexistentvariable = %s\n", pValue);
// cppcheck-suppress memleak
}
void resourceLeak_CreateSemaphoreA()
{
HANDLE hSemaphore;
// cppcheck-suppress unreadVariable
hSemaphore = CreateSemaphoreA(NULL, 0, 1, "sem1");
// cppcheck-suppress resourceLeak
}
void resourceLeak_CreateSemaphoreEx()
{
HANDLE hSemaphore;
// cppcheck-suppress [unreadVariable,valueFlowBailoutIncompleteVar]
hSemaphore = CreateSemaphoreEx(NULL, 0, 1, NULL, 0, SEMAPHORE_ALL_ACCESS);
// cppcheck-suppress resourceLeak
}
void resourceLeak_OpenSemaphore()
{
HANDLE hSemaphore;
// cppcheck-suppress [unreadVariable,valueFlowBailoutIncompleteVar]
hSemaphore = OpenSemaphore(SEMAPHORE_ALL_ACCESS, TRUE, _T("sem"));
// cppcheck-suppress resourceLeak
}
void resourceLeak_CreateMutexA()
{
HANDLE hMutex;
// cppcheck-suppress unreadVariable
hMutex = CreateMutexA(NULL, TRUE, "sem1");
// cppcheck-suppress resourceLeak
}
void resourceLeak_CreateMutexEx()
{
HANDLE hMutex;
// cppcheck-suppress [unreadVariable,valueFlowBailoutIncompleteVar]
hMutex = CreateMutexEx(NULL, _T("sem"), 0, MUTEX_ALL_ACCESS);
// cppcheck-suppress resourceLeak
}
void resourceLeak_OpenMutex()
{
HANDLE hMutex;
// cppcheck-suppress unreadVariable
hMutex = OpenMutex(MUTEX_ALL_ACCESS, TRUE, _T("sem"));
// cppcheck-suppress resourceLeak
}
void resourceLeak_LoadLibrary()
{
HINSTANCE hInstLib;
hInstLib = ::LoadLibrary(L"My.dll");
typedef BOOL (WINAPI *fpFunc)();
// cppcheck-suppress [unreadVariable, cstyleCast]
fpFunc pFunc = (fpFunc)GetProcAddress(hInstLib, "name");
// cppcheck-suppress resourceLeak
}
void resourceLeak_CreateEvent()
{
HANDLE hEvent;
hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
SetEvent(hEvent);
// cppcheck-suppress resourceLeak
}
void resourceLeak_CreateEventExA()
{
HANDLE hEvent;
// cppcheck-suppress unreadVariable
hEvent = CreateEventExA(NULL, "test", CREATE_EVENT_INITIAL_SET, EVENT_MODIFY_STATE);
// cppcheck-suppress resourceLeak
}
void resourceLeak_OpenEventW()
{
HANDLE hEvent;
// cppcheck-suppress [unreadVariable,valueFlowBailoutIncompleteVar]
hEvent = OpenEventW(EVENT_ALL_ACCESS, TRUE, L"testevent");
// cppcheck-suppress resourceLeak
}
void resourceLeak_socket()
{
SOCKET sock;
// cppcheck-suppress unreadVariable
sock = socket(1, 2, 3);
// cppcheck-suppress resourceLeak
}
void ignoredReturnValue(FILE* fp)
{
// cppcheck-suppress leakReturnValNotUsed
CreateSemaphoreW(NULL, 0, 1, NULL);
// cppcheck-suppress [leakReturnValNotUsed,valueFlowBailoutIncompleteVar]
CreateSemaphoreExA(NULL, 0, 1, NULL, 0, SEMAPHORE_ALL_ACCESS);
// cppcheck-suppress leakReturnValNotUsed
OpenSemaphoreA(SEMAPHORE_ALL_ACCESS, TRUE, "sem");
// cppcheck-suppress leakReturnValNotUsed
CreateMutexW(NULL, FALSE, NULL);
// cppcheck-suppress leakReturnValNotUsed
CreateMutexExA(NULL, NULL, 1, MUTEX_ALL_ACCESS);
// cppcheck-suppress leakReturnValNotUsed
OpenMutexA(MUTEX_ALL_ACCESS, TRUE, "sem");
// cppcheck-suppress leakReturnValNotUsed
LoadLibrary(L"My.dll");
// cppcheck-suppress leakReturnValNotUsed
LoadLibraryEx(L"My.dll", NULL, 0);
HINSTANCE hInstLib = LoadLibrary(L"My.dll");
// cppcheck-suppress ignoredReturnValue
GetProcAddress(hInstLib, "name");
FreeLibrary(hInstLib);
// cppcheck-suppress leakReturnValNotUsed
CreateEvent(NULL, FALSE, FALSE, NULL);
// cppcheck-suppress leakReturnValNotUsed
OpenEvent(EVENT_ALL_ACCESS, FALSE, L"testevent");
// cppcheck-suppress leakReturnValNotUsed
CreateEventEx(NULL, L"test", CREATE_EVENT_INITIAL_SET, EVENT_MODIFY_STATE);
// cppcheck-suppress leakReturnValNotUsed
_malloca(10);
// cppcheck-suppress ignoredReturnValue
// cppcheck-suppress _allocaCalled
_alloca(5);
// cppcheck-suppress ignoredReturnValue
GetLastError();
// cppcheck-suppress ignoredReturnValue
GetProcessHeap();
// cppcheck-suppress leakReturnValNotUsed
HeapAlloc(GetProcessHeap(), 0, 10);
// cppcheck-suppress [leakReturnValNotUsed, nullPointer]
HeapReAlloc(GetProcessHeap(), 0, nullptr, 0);
// cppcheck-suppress leakReturnValNotUsed
socket(1, 2, 3);
// cppcheck-suppress ignoredReturnValue
_fileno(fp);
// cppcheck-suppress lstrlenCalled
// cppcheck-suppress ignoredReturnValue
lstrlen(TEXT("test"));
}
void invalidFunctionArg()
{
HANDLE hSemaphore;
// cppcheck-suppress invalidFunctionArg
hSemaphore = CreateSemaphore(NULL, 0, 0, NULL);
CloseHandle(hSemaphore);
// cppcheck-suppress invalidFunctionArgBool
hSemaphore = CreateSemaphore(NULL, 0, 1, false);
CloseHandle(hSemaphore);
// cppcheck-suppress [invalidFunctionArg,valueFlowBailoutIncompleteVar]
hSemaphore = CreateSemaphoreEx(NULL, 0, 0, NULL, 0, SEMAPHORE_ALL_ACCESS);
CloseHandle(hSemaphore);
// cppcheck-suppress invalidFunctionArg
hSemaphore = CreateSemaphoreEx(NULL, 0, 1, NULL, 1, SEMAPHORE_ALL_ACCESS);
CloseHandle(hSemaphore);
HANDLE hMutex;
// cppcheck-suppress invalidFunctionArgBool
hMutex = CreateMutex(NULL, TRUE, false);
CloseHandle(hMutex);
// cppcheck-suppress invalidFunctionArgBool
hMutex = CreateMutex(NULL, FALSE, false);
CloseHandle(hMutex);
// cppcheck-suppress invalidFunctionArg
hMutex = CreateMutexEx(NULL, NULL, 3, MUTEX_ALL_ACCESS);
CloseHandle(hMutex);
//Incorrect: 2. parameter to LoadLibraryEx() must be NULL
// cppcheck-suppress [invalidFunctionArg, cstyleCast]
HINSTANCE hInstLib = LoadLibraryEx(L"My.dll", HANDLE(1), 0);
FreeLibrary(hInstLib);
// cppcheck-suppress invalidFunctionArg
void *pMem = _malloca(-1);
_freea(pMem);
// FIXME cppcheck-suppress unreadVariable
// cppcheck-suppress invalidFunctionArg
// cppcheck-suppress _allocaCalled
pMem = _alloca(-5);
}
void uninitvar()
{
// cppcheck-suppress unassignedVariable
HANDLE hSemaphore;
// cppcheck-suppress uninitvar
CloseHandle(hSemaphore);
TCHAR buf[10];
// cppcheck-suppress lstrcatCalled
// cppcheck-suppress uninitvar
lstrcat(buf, _T("test"));
buf[0] = _T('\0');
// TODO cppcheck-suppress constVariable
TCHAR buf2[2];
// cppcheck-suppress lstrcatCalled
// cppcheck-suppress uninitvar
lstrcat(buf, buf2);
// cppcheck-suppress unassignedVariable
HANDLE hMutex1, hMutex2;
// cppcheck-suppress uninitvar
ReleaseMutex(hMutex1);
// cppcheck-suppress uninitvar
CloseHandle(hMutex2);
// cppcheck-suppress unassignedVariable
HANDLE hEvent1, hEvent2, hEvent3, hEvent4;
// cppcheck-suppress uninitvar
PulseEvent(hEvent1);
// cppcheck-suppress uninitvar
ResetEvent(hEvent2);
// cppcheck-suppress uninitvar
SetEvent(hEvent3);
// cppcheck-suppress uninitvar
CloseHandle(hEvent4);
char buf_uninit1[10];
char buf_uninit2[10];
// cppcheck-suppress strlwrCalled
// cppcheck-suppress uninitvar
strlwr(buf_uninit1);
// cppcheck-suppress struprCalled
// cppcheck-suppress uninitvar
strupr(buf_uninit2);
DWORD dwordUninit;
// cppcheck-suppress uninitvar
SetLastError(dwordUninit);
DWORD dwordUninit2;
// cppcheck-suppress uninitvar
GetUserName(NULL, &dwordUninit2);
FILE *pFileUninit;
// cppcheck-suppress uninitvar
// cppcheck-suppress ignoredReturnValue
_fileno(pFileUninit);
}
void unreferencedParameter(int i) {
UNREFERENCED_PARAMETER(i);
}
void errorPrintf()
{
char bufC[50];
// cppcheck-suppress wrongPrintfScanfArgNum
sprintf_s(bufC, _countof(bufC), "%s %d", "sprintf_s");
printf("%s\n", bufC);
// cppcheck-suppress wrongPrintfScanfArgNum
sprintf_s(bufC, "%s %d", "sprintf_s");
printf("%s\n", bufC);
// cppcheck-suppress wrongPrintfScanfArgNum
sprintf_s(bufC, _countof(bufC), "test", 0);
printf("%s\n", bufC);
// cppcheck-suppress wrongPrintfScanfArgNum
sprintf_s(bufC, "test", "sprintf_s");
printf("%s\n", bufC);
// cppcheck-suppress invalidPrintfArgType_s
sprintf_s(bufC, _countof(bufC), "%s", 1);
printf("%s\n", bufC);
// cppcheck-suppress invalidPrintfArgType_s
sprintf_s(bufC, "%s", 1);
printf("%s\n", bufC);
wchar_t bufWC[50];
// cppcheck-suppress wrongPrintfScanfArgNum
swprintf_s(bufWC, _countof(bufWC), L"%s %d", L"swprintf_s");
wprintf(L"%s\n", bufWC);
// cppcheck-suppress wrongPrintfScanfArgNum
swprintf_s(bufWC, L"%s %d", L"swprintf_s");
wprintf(L"%s\n", bufWC);
// cppcheck-suppress wrongPrintfScanfArgNum
swprintf_s(bufWC, _countof(bufWC), L"test", 0);
wprintf(L"%s\n", bufWC);
// cppcheck-suppress wrongPrintfScanfArgNum
swprintf_s(bufWC, L"test", L"swprintf_s");
wprintf(L"%s\n", bufWC);
// cppcheck-suppress invalidPrintfArgType_s
swprintf_s(bufWC, _countof(bufWC), L"%s", 1);
wprintf(L"%s\n", bufWC);
// cppcheck-suppress invalidPrintfArgType_s
swprintf_s(bufWC, L"%s", 1);
wprintf(L"%s\n", bufWC);
TCHAR bufTC[50];
// cppcheck-suppress wrongPrintfScanfArgNum
_stprintf_s(bufTC, _countof(bufTC), TEXT("%s %d"), TEXT("_stprintf_s"));
_tprintf(L"%s\n", bufTC);
// cppcheck-suppress wrongPrintfScanfArgNum
_stprintf_s(bufTC, TEXT("%s %d"), TEXT("_stprintf_s"));
_tprintf(TEXT("%s\n"), bufTC);
// cppcheck-suppress wrongPrintfScanfArgNum
_stprintf_s(bufTC, _countof(bufTC), TEXT("test"), 0);
_tprintf(TEXT("%s\n"), bufTC);
// cppcheck-suppress wrongPrintfScanfArgNum
_stprintf_s(bufTC, TEXT("test"), TEXT("_stprintf_s"));
_tprintf(TEXT("%s\n"), bufTC);
// cppcheck-suppress invalidPrintfArgType_s
_stprintf_s(bufTC, _countof(bufTC), TEXT("%s"), 1);
_tprintf(TEXT("%s\n"), bufTC);
// cppcheck-suppress invalidPrintfArgType_s
_stprintf_s(bufTC, TEXT("%s"), 1);
_tprintf(TEXT("%s\n"), bufTC);
}
void allocDealloc_GetModuleHandleEx()
{
// For GetModuleHandleEx it depends on the first argument if FreeLibrary
// must be called or is not allowed to be called.
// If the first argument is GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT
// (0x00000002), a call to FreeLibrary is not allowed, otherwise it is
// necessary.
// Since this is not possible to configure at the moment cppcheck should
// accept not calling FreeLibrary and also calling it for the handle.
// TODO: Enhance cppcheck to conditionally check for alloc/dealloc issues.
// No warning because of correct FreeLibrary on 'hModule' should be issued.
HMODULE hModule1;
if (GetModuleHandleEx(0, NULL, &hModule1)) {
FreeLibrary(hModule1);
}
//This is a false negative, but it is not detected to avoid false positives.
HMODULE hModule2;
GetModuleHandleEx(0, NULL, &hModule2);
}
void uninitvar_tolower(_locale_t l)
{
int c1, c2;
// cppcheck-suppress uninitvar
(void)_tolower(c1);
// cppcheck-suppress uninitvar
(void)_tolower_l(c2, l);
}
void uninitvar_toupper(_locale_t l)
{
int c1, c2;
// cppcheck-suppress uninitvar
(void)_toupper(c1);
// cppcheck-suppress uninitvar
(void)_toupper_l(c2, l);
}
void uninitvar_towlower(_locale_t l)
{
wint_t i;
// cppcheck-suppress uninitvar
(void)_towlower_l(i, l);
}
void uninitvar_towupper(_locale_t l)
{
wint_t i;
// cppcheck-suppress uninitvar
(void)_towupper_l(i, l);
}
void oppositeInnerCondition_SUCCEEDED_FAILED(HRESULT hr)
{
if (SUCCEEDED(hr)) {
// TODO ticket #8596 cppcheck-suppress oppositeInnerCondition
if (FAILED(hr)) {}
}
}
/*HANDLE WINAPI CreateThread(
_In_opt_ LPSECURITY_ATTRIBUTES lpThreadAttributes,
_In_ SIZE_T dwStackSize,
_In_ LPTHREAD_START_ROUTINE lpStartAddress,
_In_opt_ LPVOID lpParameter,
_In_ DWORD dwCreationFlags,
_Out_opt_ LPDWORD lpThreadId
);*/
HANDLE test_CreateThread(LPSECURITY_ATTRIBUTES lpThreadAttributes,
SIZE_T dwStackSize,
LPTHREAD_START_ROUTINE lpStartAddress,
LPVOID lpParameter,
DWORD dwCreationFlags,
LPDWORD lpThreadId)
{
// Create uninitialized variables
LPSECURITY_ATTRIBUTES uninit_lpThreadAttributes;
SIZE_T uninit_dwStackSize;
LPTHREAD_START_ROUTINE uninit_lpStartAddress;
LPVOID uninit_lpParameter;
DWORD uninit_dwCreationFlags;
// cppcheck-suppress leakReturnValNotUsed
// cppcheck-suppress uninitvar
(void) CreateThread(lpThreadAttributes, dwStackSize, lpStartAddress, lpParameter, uninit_dwCreationFlags, lpThreadId);
// cppcheck-suppress leakReturnValNotUsed
// cppcheck-suppress uninitvar
(void) CreateThread(lpThreadAttributes, dwStackSize, lpStartAddress, uninit_lpParameter, dwCreationFlags, lpThreadId);
// @todo uninitvar shall be reported
// cppcheck-suppress leakReturnValNotUsed
(void) CreateThread(lpThreadAttributes, dwStackSize, uninit_lpStartAddress, lpParameter, dwCreationFlags, lpThreadId);
// cppcheck-suppress leakReturnValNotUsed
// cppcheck-suppress uninitvar
(void) CreateThread(lpThreadAttributes, uninit_dwStackSize, lpStartAddress, lpParameter, dwCreationFlags, lpThreadId);
// @todo uninitvar shall be reported
// cppcheck-suppress leakReturnValNotUsed
(void) CreateThread(uninit_lpThreadAttributes, dwStackSize, lpStartAddress, lpParameter, dwCreationFlags, lpThreadId);
// cppcheck-suppress leakReturnValNotUsed
// cppcheck-suppress nullPointer
(void) CreateThread(lpThreadAttributes, dwStackSize, 0, lpParameter, dwCreationFlags, lpThreadId);
// cppcheck-suppress leakReturnValNotUsed
// cppcheck-suppress invalidFunctionArg
(void) CreateThread(lpThreadAttributes, -1, lpStartAddress, lpParameter, dwCreationFlags, lpThreadId);
// no warning shall be shown for
return CreateThread(lpThreadAttributes, dwStackSize, lpStartAddress, lpParameter, dwCreationFlags, lpThreadId);
}
// unsigned char *_mbscat(unsigned char *strDestination, const unsigned char *strSource);
unsigned char * uninitvar_mbscat(unsigned char *strDestination, const unsigned char *strSource)
{
unsigned char *uninit_deststr;
const unsigned char *uninit_srcstr1, *uninit_srcstr2;
// cppcheck-suppress uninitvar
(void)_mbscat(uninit_deststr,uninit_srcstr1);
// cppcheck-suppress uninitvar
(void)_mbscat(strDestination,uninit_srcstr2);
// no warning shall be shown for
return _mbscat(strDestination,strSource);
}
// unsigned char *_mbscat(unsigned char *strDestination, const unsigned char *strSource);
unsigned char * nullPointer_mbscat(unsigned char *strDestination, const unsigned char *strSource)
{
// cppcheck-suppress nullPointer
(void)_mbscat(0,strSource);
// cppcheck-suppress nullPointer
(void)_mbscat(strDestination,0);
// no warning shall be shown for
return _mbscat(strDestination,strSource);
}
// errno_t _mbscat_s(unsigned char *strDestination, size_t numberOfElements, const unsigned char *strSource );
errno_t uninitvar_mbscat_s(unsigned char *strDestination, size_t numberOfElements, const unsigned char *strSource)
{
unsigned char *uninit_strDestination;
size_t uninit_numberOfElements;
const unsigned char *uninit_strSource;
// cppcheck-suppress uninitvar
(void)_mbscat_s(uninit_strDestination, numberOfElements, strSource);
// cppcheck-suppress uninitvar
(void)_mbscat_s(strDestination, uninit_numberOfElements, strSource);
// cppcheck-suppress uninitvar
(void)_mbscat_s(strDestination, numberOfElements, uninit_strSource);
// no warning shall be shown for
return _mbscat_s(strDestination, numberOfElements, strSource);
}
// errno_t _mbscat_s(unsigned char *strDestination, size_t numberOfElements, const unsigned char *strSource );
errno_t nullPointer_mbscat_s(unsigned char *strDestination, size_t numberOfElements, const unsigned char *strSource)
{
// cppcheck-suppress nullPointer
(void)_mbscat_s(0, numberOfElements, strSource);
// cppcheck-suppress nullPointer
(void)_mbscat_s(strDestination, numberOfElements, 0);
// no warning shall be shown for
return _mbscat_s(strDestination, numberOfElements, strSource);
}
#if !UNICODE
// errno_t _strncpy_s_l(char *strDest, size_t numberOfElements, const char *strSource, size_t count, _locale_t locale);
errno_t uninitvar__strncpy_s_l(char *strDest, size_t numberOfElements, const char *strSource, size_t count, _locale_t locale)
{
size_t uninit_numberOfElements;
const char *uninit_strSource;
size_t uninit_count;
_locale_t uninit_locale;
// cppcheck-suppress uninitvar
(void)_strncpy_s_l(strDest, uninit_numberOfElements, strSource, count, locale);
// cppcheck-suppress uninitvar
(void)_strncpy_s_l(strDest, numberOfElements, uninit_strSource, count, locale);
// cppcheck-suppress uninitvar
(void)_strncpy_s_l(strDest, numberOfElements, strSource, uninit_count, locale);
// cppcheck-suppress uninitvar
(void)_strncpy_s_l(strDest, numberOfElements, strSource, count, uninit_locale);
// no warning shall be shown for
return _strncpy_s_l(strDest, numberOfElements, strSource, count, locale);
}
errno_t nullPointer__strncpy_s_l(char *strDest, size_t numberOfElements, const char *strSource, size_t count, _locale_t locale)
{
// cppcheck-suppress nullPointer
(void)_strncpy_s_l(0, numberOfElements, strSource, count, locale);
// cppcheck-suppress nullPointer
(void)_strncpy_s_l(strDest, numberOfElements, 0, count, locale);
// no warning shall be shown for
return _strncpy_s_l(strDest, numberOfElements, strSource, count, locale);
}
#endif
void GetShortPathName_validCode(const TCHAR* lpszPath)
{
long length = GetShortPathName(lpszPath, NULL, 0);
if (length == 0) {
_tprintf(TEXT("error"));
return;
}
TCHAR* buffer = new TCHAR[length];
length = GetShortPathName(lpszPath, buffer, length);
if (length == 0) {
delete[] buffer;
_tprintf(TEXT("error"));
return;
}
_tprintf(TEXT("long name = %s short name = %s"), lpszPath, buffer);
delete[] buffer;
}
void invalidPrintfArgType_StructMember(double d) { // #9672
typedef struct { CString st; } my_struct_t;
my_struct_t my_struct;
// cppcheck-suppress invalidPrintfArgType_sint
my_struct.st.Format(_T("%d"), d);
}
BOOL MyEnableWindow(HWND hWnd, BOOL bEnable) {
return EnableWindow(hWnd, bEnable);
}
int SEH_filter(unsigned int code, struct _EXCEPTION_POINTERS* ep);
int SEH_throwing_func();
void SEH_knownConditionTrueFalse() { // #8434
int r = 0;
__try {
r = SEH_throwing_func();
}
__except (SEH_filter(GetExceptionCode(), GetExceptionInformation())) {
r = 1;
}
if (r == 0) {}
}
void SEH_unusedLabel() { // #13233
__try {
}
__finally {
}
}
| null |
1,030 | cpp | cppcheck | emscripten.cpp | test/cfg/emscripten.cpp | null |
// Test library configuration for emscripten.cfg
//
// Usage:
// $ cppcheck --check-library --library=emscripten --enable=style,information --inconclusive --error-exitcode=1 --inline-suppr test/cfg/emscripten.cpp
// =>
// No warnings about bad library configuration, unmatched suppressions, etc. exitcode=0
//
#include <stdio.h>
#include <emscripten.h>
void em_asm_test()
{
// inline some JavaScript
EM_ASM(alert('hello'); );
MAIN_THREAD_EM_ASM(alert('hello main thread'); );
// pass parameters to JavaScript
EM_ASM(
{
console.log('I received: ' + [$0, $1]);
},
100, 35.5);
// pass a string to JavaScript
EM_ASM({console.log('hello ' + UTF8ToString($0))}, "world!");
}
void em_asm_int_test()
{
// cppcheck-suppress unreadVariable
const int x = EM_ASM_INT({
return $0 + 42;
}, 100);
// cppcheck-suppress unreadVariable
const int y = MAIN_THREAD_EM_ASM_INT({return 2;});
}
void em_asm_double_test()
{
// cppcheck-suppress unreadVariable
const double x = EM_ASM_DOUBLE({
return $0 + 1.0;
}, 2.0);
// cppcheck-suppress unreadVariable
const double y = MAIN_THREAD_EM_ASM_DOUBLE({return 1.0;});
}
void em_asm_ptr_test()
{
void* ptr = EM_ASM_PTR({
return stringToNewUTF8("Hello");
});
printf("%s", static_cast<const char*>(ptr));
free(ptr);
}
void em_asm_ptr_memleak_test()
{
const char *str = static_cast<char*>(EM_ASM_PTR({
return stringToNewUTF8("Hello");
}));
// cppcheck-suppress nullPointerOutOfMemory
printf("%s", str);
// cppcheck-suppress memleak
}
void main_thread_em_asm_ptr_test()
{
// cppcheck-suppress leakReturnValNotUsed
MAIN_THREAD_EM_ASM_PTR(
return stringToNewUTF8("Hello");
);
}
EM_JS(void, two_alerts, (), {
alert('hai');
alert('bai');
});
EM_JS(void, take_args, (int x, float y), {
console.log('I received: ' + [x, y]);
});
void em_js_test()
{
two_alerts();
take_args(100, 35.5);
}
| null |
1,031 | cpp | cppcheck | opencv2.cpp | test/cfg/opencv2.cpp | null |
// Test library configuration for opencv2.cfg
//
// Usage:
// $ cppcheck --check-library --library=opencv2 --enable=style,information --inconclusive --error-exitcode=1 --inline-suppr test/cfg/opencv2.cpp
// =>
// No warnings about bad library configuration, unmatched suppressions, etc. exitcode=0
//
// cppcheck-suppress-file valueFlowBailout
#include <iostream>
#include <opencv2/opencv.hpp>
void validCode(const char* argStr)
{
cv::Mat image;
// cppcheck-suppress valueFlowBailoutIncompleteVar
image = cv::imread(argStr, cv::IMREAD_COLOR);
if (!image.data) {
printf("No image data \n");
return;
}
cv::namedWindow("Display Image", cv::WINDOW_AUTOSIZE);
cv::imshow("Display Image", image);
cv::waitKey(0);
cv::String cvStr("Hello");
cvStr += " World";
std::cout << cvStr;
// cppcheck-suppress [cstyleCast, unusedAllocatedMemory]
char * pBuf = (char *)cv::fastMalloc(20);
cv::fastFree(pBuf);
}
void ignoredReturnValue()
{
// cppcheck-suppress ignoredReturnValue
cv::imread("42.png");
}
void memleak()
{
// cppcheck-suppress cstyleCast
const char * pBuf = (char *)cv::fastMalloc(1000);
// cppcheck-suppress [uninitdata, valueFlowBailoutIncompleteVar]
std::cout << pBuf;
// cppcheck-suppress memleak
}
| null |
1,032 | cpp | cppcheck | cppunit.cpp | test/cfg/cppunit.cpp | null | // Test library configuration for cppunit.cfg
//
// Usage:
// $ cppcheck --check-library --library=cppunit --enable=style,information --inconclusive --error-exitcode=1 --inline-suppr test/cfg/cppunit.cpp
// =>
// No warnings about bad library configuration, unmatched suppressions, etc. exitcode=0
//
// cppcheck-suppress-file valueFlowBailout
#include <cppunit/TestAssert.h>
void cppunit_assert_equal(int x, double y)
{
CPPUNIT_ASSERT(true);
CPPUNIT_ASSERT(false);
CPPUNIT_ASSERT(1 < 2);
CPPUNIT_ASSERT_MESSAGE("Test failed", true);
CPPUNIT_ASSERT_MESSAGE("Test failed", false);
CPPUNIT_ASSERT_MESSAGE("Test failed", 1 < 2);
CPPUNIT_ASSERT_EQUAL(1, 2);
CPPUNIT_ASSERT_EQUAL(true, 3 == x);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Test failed", 1, 4);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Test failed", true, 4 == x);
CPPUNIT_ASSERT_DOUBLES_EQUAL(1.0, 2.0, 1e-7);
CPPUNIT_ASSERT_DOUBLES_EQUAL(1.0, y, 1e-7);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Test failed", 1.0, 2.0, 1e-7);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Test failed", 1.0, y, 1e-7);
}
void cppunit_throw()
{
CPPUNIT_ASSERT_NO_THROW(1 + 1);
CPPUNIT_ASSERT_NO_THROW_MESSAGE("Unexpected throw", 1 + 1);
CPPUNIT_ASSERT_THROW(1 + 1, CPPUNIT_NS::Exception);
CPPUNIT_ASSERT_THROW_MESSAGE("Did not throw", 1 + 1, CPPUNIT_NS::Exception);
}
void cppunit_assertion_assert()
{
CPPUNIT_ASSERT_ASSERTION_FAIL(true);
CPPUNIT_ASSERT_ASSERTION_FAIL_MESSAGE("hello", false);
CPPUNIT_ASSERT_ASSERTION_PASS(false);
CPPUNIT_ASSERT_ASSERTION_PASS_MESSAGE("goodbye", true);
}
void cppunit_assert_fail()
{
CPPUNIT_FAIL("This fails");
}
| null |
1,033 | cpp | cppcheck | libsigc++.cpp | test/cfg/libsigc++.cpp | null |
// Test library configuration for libsigc++.cfg
//
// Usage:
// $ cppcheck --check-library --library=libsigc++ --enable=style,information --inconclusive --error-exitcode=1 --inline-suppr test/cfg/libsigc++.cpp
// =>
// No warnings about bad library configuration, unmatched suppressions, etc. exitcode=0
//
#include <sigc++/sigc++.h>
struct struct1 : public sigc::trackable {
void func1(int) const {}
};
void valid_code()
{
const struct1 my_sruct1;
sigc::slot<void, int> sl = sigc::mem_fun(my_sruct1, &struct1::func1);
if (sl) {}
}
void ignoredReturnValue()
{
const struct1 my_sruct1;
// cppcheck-suppress ignoredReturnValue
sigc::mem_fun(my_sruct1, &struct1::func1);
}
| null |
1,034 | cpp | cppcheck | std.cpp | test/cfg/std.cpp | null |
// Test library configuration for std.cfg
//
// Usage:
// $ cppcheck --check-library --library=std --enable=style,information --inconclusive --error-exitcode=1 --inline-suppr test/cfg/std.cpp
// =>
// No warnings about bad library configuration, unmatched suppressions, etc. exitcode=0
//
// cppcheck-suppress-file valueFlowBailout
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <cfenv>
#include <cinttypes>
#include <clocale>
#include <cmath>
#include <complex>
#include <csetjmp>
#include <csignal>
#include <cstdarg>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#define __STDC_WANT_LIB_EXT1__ 1
#include <ctime>
#include <cwchar>
#include <deque>
#include <exception>
#include <filesystem>
#include <fstream>
#include <functional>
#ifndef __STDC_NO_THREADS__
#include <threads.h>
#endif
#include <iomanip>
#include <ios>
#include <iostream>
#include <istream>
#include <iterator>
#include <list>
#include <map>
#include <memory>
#include <mutex>
#include <numeric>
#include <queue>
#include <set>
#include <streambuf>
#include <string_view>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <variant>
#include <vector>
#include <version>
#ifdef __cpp_lib_span
#include <span>
#endif
#ifdef __cpp_lib_format
#include <format>
#endif
#if __cplusplus <= 201402L
void unreachableCode_std_unexpected(int &x)
{
// cppcheck-suppress unexpectedCalled
std::unexpected();
// cppcheck-suppress unreachableCode
x=42;
}
#endif
void unreachableCode_std_terminate(int &x)
{
std::terminate();
// cppcheck-suppress unreachableCode
x=42;
}
bool ignoredReturnValue_std_filesystem_exists(const std::filesystem::path &path, std::error_code& ec)
{
// cppcheck-suppress ignoredReturnValue
std::filesystem::exists(path);
// cppcheck-suppress ignoredReturnValue
std::filesystem::exists(path, ec);
const bool b {std::filesystem::exists(path)};
return b && std::filesystem::exists(path, ec);
}
// https://en.cppreference.com/w/cpp/io/manip/quoted
void uninitvar_std_quoted(std::stringstream &ss, const std::string &input, const char delim, const char escape)
{
ss << std::quoted(input);
ss << std::quoted(input, delim);
ss << std::quoted(input, delim, escape);
char delimChar;
// cppcheck-suppress uninitvar
ss << std::quoted(input, delimChar);
char escapeChar;
// cppcheck-suppress uninitvar
ss << std::quoted(input, delim, escapeChar);
}
int zerodiv_ldexp()
{
int i = std::ldexp(0.0, 42.0);
// cppcheck-suppress zerodiv
return 42 / i;
}
int zerodiv_ilogb()
{
int i = std::ilogb(1.0);
// cppcheck-suppress zerodiv
return 42 / i;
}
int zerodiv_hypot()
{
int i = std::hypot(0.0, 0.0);
// cppcheck-suppress zerodiv
return 42 / i;
}
int zerodiv_fmod()
{
int i = std::fmod(0.0, 42.0);
// cppcheck-suppress zerodiv
return 42 / i;
}
int zerodiv_fmin()
{
int i = std::fmin(0.0, 0.0);
// cppcheck-suppress zerodiv
return 42 / i;
}
int zerodiv_fmax()
{
int i = std::fmax(0.0, 0.0);
// cppcheck-suppress zerodiv
return 42 / i;
}
int zerodiv_floor()
{
int i = std::floor(0.0);
// cppcheck-suppress zerodiv
return 42 / i;
}
int zerodiv_fabs()
{
int i = std::fabs(-0.0) + std::fabs(+0.0) + std::fabs(0.0);
// cppcheck-suppress zerodiv
return 42 / i;
}
int zerodiv_fdim()
{
int i = std::fdim(1.0, 1.0);
// cppcheck-suppress zerodiv
return 42 / i;
}
int zerodiv_trunc()
{
int i = std::trunc(0);
// cppcheck-suppress zerodiv
return 42 / i;
}
int zerodiv_ceil()
{
int i = std::ceil(0);
// cppcheck-suppress zerodiv
return 42 / i;
}
int zerodiv_sqrt()
{
int i = std::sqrt(0);
// cppcheck-suppress zerodiv
return 42 / i;
}
int zerodiv_cbrt()
{
int i = std::cbrt(0);
// cppcheck-suppress zerodiv
return 42 / i;
}
int zerodiv_erf()
{
int i = std::erf(0);
// cppcheck-suppress zerodiv
return 42 / i;
}
int zerodiv_erfc()
{
int i = std::erfc(42);
// cppcheck-suppress zerodiv
return 42 / i;
}
int zerodiv_asin()
{
int i = std::asin(0);
// cppcheck-suppress zerodiv
return 42 / i;
}
int zerodiv_acos()
{
int i = std::acos(1);
// cppcheck-suppress zerodiv
return 42 / i;
}
int zerodiv_asinh()
{
int i = std::asinh(0);
// cppcheck-suppress zerodiv
return 42 / i;
}
int zerodiv_acosh()
{
int i = std::acosh(1);
// cppcheck-suppress zerodiv
return 42 / i;
}
int zerodiv_log1p()
{
int i = std::log1p(0);
// cppcheck-suppress zerodiv
return 42 / i;
}
int zerodiv_nearbyint()
{
int i = std::nearbyint(0);
// cppcheck-suppress zerodiv
return 42 / i;
}
int zerodiv_round()
{
int i = std::round(0);
// cppcheck-suppress zerodiv
return 42 / i;
}
int zerodiv_sinh()
{
int i = std::sinh(0);
// cppcheck-suppress zerodiv
return 42 / i;
}
int zerodiv_tanh()
{
int i = std::tanh(0);
// cppcheck-suppress zerodiv
return 42 / i;
}
int zerodiv_atanh()
{
int i = std::atanh(0);
// cppcheck-suppress zerodiv
return 42 / i;
}
int zerodiv_atan()
{
int i = std::atan(0);
// cppcheck-suppress zerodiv
return 42 / i;
}
int zerodiv_sin()
{
int i = std::sin(0)+std::sin(M_PI)+std::sin(2*M_PI);
// cppcheck-suppress zerodiv
return 42 / i;
}
int zerodiv_expm1()
{
int i = std::expm1(0);
// cppcheck-suppress zerodiv
return 42 / i;
}
int moduloofone_cos()
{
int i = std::cos(0);
// cppcheck-suppress moduloofone
return 42 % i;
}
int moduloofone_exp()
{
int i = std::exp(0);
// cppcheck-suppress moduloofone
return 42 % i;
}
int moduloofone_exp2()
{
int i = std::exp2(0);
// cppcheck-suppress moduloofone
return 42 % i;
}
int moduloofone_pow()
{
int i = std::pow(2, 0);
// cppcheck-suppress moduloofone
return 42 % i;
}
char* invalidFunctionArgStr_strncpy(char * destination)
{
// Copies the first num characters of source to destination.
// If the end of the source C string (which is signaled by a null-character)
// is found before num characters have been copied, destination
// is padded with zeros until a total of num characters have been written to it.
const char source = 'x';
const std::size_t num = 1U;
return strncpy(destination, &source, num);
}
void invalidFunctionArgStr_fprintf(FILE *stream, const char *format)
{
const char formatBuf[] = {'%','d'};
// cppcheck-suppress invalidFunctionArgStr
(void)fprintf(stream,formatBuf,42);
(void)fprintf(stream,format,42);
}
void invalidFunctionArgStr_fopen(const char * const fileName, const char * const mode)
{
const char fileNameBuf[] = {'f','i','l','e'};
const char modeBuf[] = {'r'};
// cppcheck-suppress invalidFunctionArgStr
FILE *fp = fopen(fileName, modeBuf);
// cppcheck-suppress nullPointerOutOfResources
fclose(fp);
// cppcheck-suppress invalidFunctionArgStr
fp = fopen(fileNameBuf, mode);
// cppcheck-suppress nullPointerOutOfResources
fclose(fp);
}
float invalidFunctionArg_remquo (float x, float y, int* quo )
{
// cppcheck-suppress invalidFunctionArg
(void) std::remquo(x,0.0f,quo);
// cppcheck-suppress invalidFunctionArg
(void) std::remquof(x,0.0f,quo);
return std::remquo(x,y,quo);
}
double invalidFunctionArg_remquo (double x, double y, int* quo )
{
// cppcheck-suppress invalidFunctionArg
(void) std::remquo(x,0.0,quo);
// cppcheck-suppress invalidFunctionArg
(void) std::remquo(x,0.0f,quo);
// cppcheck-suppress invalidFunctionArg
(void) std::remquo(x,0.0L,quo);
return std::remquo(x,y,quo);
}
double invalidFunctionArg_remquo (long double x, long double y, int* quo )
{
// cppcheck-suppress invalidFunctionArg
(void) std::remquo(x,0.0L,quo);
// cppcheck-suppress invalidFunctionArg
(void) std::remquol(x,0.0L,quo);
return std::remquo(x,y,quo);
}
void invalidFunctionArg_remainderl(long double f1, long double f2)
{
// cppcheck-suppress invalidFunctionArg
(void)std::remainderl(f1,0.0);
// cppcheck-suppress invalidFunctionArg
(void)std::remainderl(f1,0.0L);
(void)std::remainderl(f1,f2);
}
void invalidFunctionArg_remainder(double f1, double f2)
{
// cppcheck-suppress invalidFunctionArg
(void)std::remainder(f1,0.0);
(void)std::remainder(f1,f2);
}
void invalidFunctionArg_remainderf(float f1, float f2)
{
// cppcheck-suppress invalidFunctionArg
(void)std::remainderf(f1,0.0);
// cppcheck-suppress invalidFunctionArg
(void)std::remainderf(f1,0.0f);
(void)std::remainderf(f1,f2);
}
void uninitvar_std_fstream_open(std::fstream &fs, const std::string &strFileName, const char* filename, std::ios_base::openmode mode)
{
std::string s;
const char *ptr;
std::ios_base::openmode m;
fs.open(s, mode);
// cppcheck-suppress uninitvar
fs.open(ptr, mode);
// TODO cppcheck-suppress uninitvar
fs.open(filename, m);
// TODO cppcheck-suppress uninitvar
fs.open(strFileName, m);
fs.open(s);
// TODO cppcheck-suppress uninitvar
fs.open(ptr);
}
void uninitvar_std_ifstream_open(std::ifstream &ifs, const std::string &strFileName, const char* filename, std::ios_base::openmode mode)
{
std::string s;
const char *ptr;
std::ios_base::openmode m;
ifs.open(s, mode);
// cppcheck-suppress uninitvar
ifs.open(ptr, mode);
// TODO cppcheck-suppress uninitvar
ifs.open(filename, m);
// TODO cppcheck-suppress uninitvar
ifs.open(strFileName, m);
ifs.open(s);
// TODO cppcheck-suppress uninitvar
ifs.open(ptr);
}
void uninitvar_std_ofstream_open(std::ofstream &os, const std::string &strFileName, const char* filename, std::ios_base::openmode mode)
{
std::string s;
const char *ptr;
std::ios_base::openmode m;
os.open(s, mode);
// cppcheck-suppress uninitvar
os.open(ptr, mode);
// TODO cppcheck-suppress uninitvar
os.open(filename, m);
// TODO cppcheck-suppress uninitvar
os.open(strFileName, m);
os.open(s);
// TODO cppcheck-suppress uninitvar
os.open(ptr);
}
void uninitvar_std_ofstream_precision(std::ofstream& os)
{
std::streamsize s;
// cppcheck-suppress uninitvar
os.precision(s);
}
void nullPointer_std_filebuf_open(std::filebuf &fb, const std::string &strFileName, const char* filename, std::ios_base::openmode mode)
{
// cppcheck-suppress nullPointer
(void)fb.open(nullptr, mode);
(void)fb.open(filename, mode);
(void)fb.open(strFileName, mode);
}
void nullPointer_std_ofstream_open(std::ofstream &os, const std::string &strFileName, const char* filename, std::ios_base::openmode mode)
{
// cppcheck-suppress nullPointer
os.open(nullptr, mode);
os.open(filename, mode);
os.open(strFileName, mode);
// cppcheck-suppress nullPointer
os.open(nullptr);
os.open(filename);
os.open(strFileName);
}
void nullPointer_std_fstream_open(std::fstream &fs, const std::string &strFileName, const char* filename, std::ios_base::openmode mode)
{
// cppcheck-suppress nullPointer
fs.open(nullptr, mode);
fs.open(filename, mode);
fs.open(strFileName, mode);
// cppcheck-suppress nullPointer
fs.open(nullptr);
fs.open(filename);
fs.open(strFileName);
}
void nullPointer_std_ifstream_open(std::ifstream &is, const std::string &strFileName, const char* filename, std::ios_base::openmode mode)
{
// cppcheck-suppress nullPointer
is.open(nullptr, mode);
is.open(filename, mode);
is.open(strFileName, mode);
// cppcheck-suppress nullPointer
is.open(nullptr);
is.open(filename);
is.open(strFileName);
}
void bufferAccessOutOfBounds_std_fstream_write(std::fstream &fs, const char* s, std::streamsize n)
{
const char buf[42] = {0};
(void)fs.write(buf,42);
// cppcheck-suppress bufferAccessOutOfBounds
(void)fs.write(buf,43);
(void)fs.write(buf,n);
(void)fs.write(s,n);
}
void bufferAccessOutOfBounds_std_ostream_write(std::ostream &os, const char* s, std::streamsize n)
{
const char buf[42] = {0};
(void)os.write(buf,42);
// cppcheck-suppress bufferAccessOutOfBounds
(void)os.write(buf,43);
(void)os.write(buf,n);
(void)os.write(s,n);
}
void bufferAccessOutOfBounds_std_ostringstream_write(std::ostringstream &oss, const char* s, std::streamsize n)
{
const char buf[42] = {0};
(void)oss.write(buf,42);
// cppcheck-suppress bufferAccessOutOfBounds
(void)oss.write(buf,43);
(void)oss.write(buf,n);
(void)oss.write(s,n);
}
void bufferAccessOutOfBounds_std_ofstream_write(std::ofstream &os, const char* s, std::streamsize n)
{
const char buf[42] = {0};
(void)os.write(buf,42);
// cppcheck-suppress bufferAccessOutOfBounds
(void)os.write(buf,43);
(void)os.write(buf,n);
(void)os.write(s,n);
}
// cppcheck-suppress constParameterReference // TODO: FP
void bufferAccessOutOfBounds_std_ifstream_get(std::ifstream& in, std::streambuf& sb)
{
char cBuf[10];
// cppcheck-suppress bufferAccessOutOfBounds
in.getline(cBuf, 100);
// cppcheck-suppress bufferAccessOutOfBounds
in.read(cBuf, 100);
// cppcheck-suppress bufferAccessOutOfBounds
in.readsome(cBuf, 100);
// cppcheck-suppress bufferAccessOutOfBounds
in.get(cBuf, 100);
// cppcheck-suppress bufferAccessOutOfBounds
in.get(cBuf, 100, 'a');
// cppcheck-suppress bufferAccessOutOfBounds
in.getline(cBuf, 100, 'a');
in.get(sb, 'a');
in.close();
}
void invalidFunctionArg_fesetexceptflag(const fexcept_t* flagp, int excepts)
{
(void)std::fesetexceptflag(flagp, excepts);
// cppcheck-suppress invalidFunctionArg
(void)std::fesetexceptflag(flagp, 0);
(void)std::fesetexceptflag(flagp, FE_DIVBYZERO);
(void)std::fesetexceptflag(flagp, FE_INEXACT);
(void)std::fesetexceptflag(flagp, FE_INVALID);
(void)std::fesetexceptflag(flagp, FE_OVERFLOW);
(void)std::fesetexceptflag(flagp, FE_UNDERFLOW);
(void)std::fesetexceptflag(flagp, FE_ALL_EXCEPT);
// cppcheck-suppress invalidFunctionArg
(void)std::fesetexceptflag(flagp, FE_ALL_EXCEPT+1);
}
void invalidFunctionArg_fetestexcept(int excepts)
{
(void)std::fetestexcept(excepts);
// cppcheck-suppress invalidFunctionArg
(void)std::fetestexcept(0);
(void)std::fetestexcept(FE_DIVBYZERO);
(void)std::fetestexcept(FE_INEXACT);
(void)std::fetestexcept(FE_INVALID);
(void)std::fetestexcept(FE_OVERFLOW);
(void)std::fetestexcept(FE_UNDERFLOW);
(void)std::fetestexcept(FE_ALL_EXCEPT);
// cppcheck-suppress invalidFunctionArg
(void)std::fetestexcept(FE_ALL_EXCEPT+1);
}
void nullPointer_fprintf(FILE *Stream, const char *Format, int Argument)
{
// cppcheck-suppress nullPointer
(void)std::fprintf(Stream, nullptr, Argument);
// no warning is expected
(void)std::fprintf(Stream, Format, Argument);
}
void bufferAccessOutOfBounds_wcsftime(wchar_t* ptr, size_t maxsize, const wchar_t* format, const struct tm* timeptr)
{
wchar_t buf[42];
(void)std::wcsftime(buf, 42, format, timeptr);
// TODO cppcheck-suppress bufferAccessOutOfBounds
(void)std::wcsftime(buf, 43, format, timeptr);
(void)std::wcsftime(ptr, maxsize, format, timeptr);
}
int qsort_cmpfunc (const void * a, const void * b) {
return (*static_cast<const int*>(a) - *static_cast<const int*>(b));
}
void nullPointer_qsort(void *base, std::size_t n, std::size_t size, int (*cmp)(const void *, const void *))
{
// cppcheck-suppress nullPointer
std::qsort(nullptr, n, size, qsort_cmpfunc);
// cppcheck-suppress nullPointer
std::qsort(base, n, size, nullptr);
std::qsort(base, n, size, qsort_cmpfunc);
}
void nullPointer_vfprintf(FILE *Stream, const char *Format, va_list Arg)
{
// cppcheck-suppress nullPointer
(void)std::vfprintf(Stream, nullptr, Arg);
(void)std::vfprintf(Stream, Format, Arg);
}
void nullPointer_vfwprintf(FILE *Stream, const wchar_t *Format, va_list Arg)
{
// cppcheck-suppress nullPointer
(void)std::vfwprintf(Stream, nullptr, Arg);
(void)std::vfwprintf(Stream, Format, Arg);
}
void *bufferAccessOutOfBounds_memchr(void *s, int c, size_t n)
{
char buf[42]={0};
(void)std::memchr(buf,c,42);
// cppcheck-suppress bufferAccessOutOfBounds
(void)std::memchr(buf,c,43);
return std::memchr(s,c,n);
}
// As with all bounds-checked functions, localtime_s is only guaranteed to be available if __STDC_LIB_EXT1__ is defined by the implementation and if the user defines __STDC_WANT_LIB_EXT1__ to the integer constant 1 before including time.h.
#ifdef __STDC_LIB_EXT1__
void uninitvar_localtime_s(const std::time_t *restrict time, struct tm *restrict result)
{
// cppcheck-suppress valueFlowBailoutIncompleteVar
const std::time_t *restrict Time;
// TODO cppcheck-suppress uninitvar
(void)std::localtime_s(Time, result);
(void)std::localtime_s(time, result);
}
void nullPointer_localtime_s(const std::time_t *restrict time, struct tm *restrict result)
{
// cppcheck-suppress nullPointer
(void)std::localtime_s(NULL, result);
// cppcheck-suppress nullPointer
(void)std::localtime_s(time, NULL);
(void)std::localtime_s(time, result);
}
void memleak_localtime_s(const std::time_t *restrict time, struct tm *restrict result) // #9258
{
const time_t t = time(0);
const struct tm* const now = new tm();
if (localtime_s(now, &t) == 0) {
// cppcheck-suppress valueFlowBailoutIncompleteVar
std::cout << now->tm_mday << std::endl;
}
// cppcheck-suppress memleak
}
#endif // __STDC_LIB_EXT1__
size_t nullPointer_strftime(char *s, size_t max, const char *fmt, const struct tm *p)
{
// cppcheck-suppress nullPointer
(void) std::strftime(NULL,max,fmt,p);
// cppcheck-suppress nullPointer
(void) std::strftime(s,max,NULL,p);
// cppcheck-suppress nullPointer
(void) std::strftime(s,max,fmt,NULL);
return std::strftime(s,max,fmt,p);
}
size_t bufferAccessOutOfBounds_wcsrtombs(char * dest, const wchar_t ** src, size_t len, mbstate_t * ps)
{
char buf[42];
(void)std::wcsrtombs(buf,src,42,ps);
// cppcheck-suppress bufferAccessOutOfBounds
(void)std::wcsrtombs(buf,src,43,ps);
return std::wcsrtombs(dest,src,len,ps);
}
void deallocuse_wcrtomb(char *buff) { // #13119
free(buff);
// cppcheck-suppress deallocuse
wcrtomb(buff, L'x', nullptr);
}
void invalidFunctionArg_std_string_substr(const std::string &str, std::size_t pos, std::size_t len) {
// cppcheck-suppress invalidFunctionArg
(void)str.substr(-1,len);
// cppcheck-suppress invalidFunctionArg
(void)str.substr(pos,-1);
// no warning is expected for
(void)str.substr(pos,len);
// cppcheck-suppress valueFlowBailoutIncompleteVar
(void)str.substr(pos, std::string::npos);
}
void invalidFunctionArg_std_wstring_substr(const std::wstring &str, std::size_t pos, std::size_t len) {
// cppcheck-suppress invalidFunctionArg
(void)str.substr(-1,len);
// cppcheck-suppress invalidFunctionArg
(void)str.substr(pos,-1);
// no warning is expected for
(void)str.substr(pos,len);
// cppcheck-suppress valueFlowBailoutIncompleteVar
(void)str.substr(pos, std::wstring::npos);
}
double invalidFunctionArg_log10(double d = 0.0) {
// cppcheck-suppress invalidFunctionArg
return log10(d);
}
void uninitvar_std_next(const std::vector<int> &v, int count)
{
// No warning shall be shown:
if (std::next(v.begin()) != v.end()) {}
if (std::next(v.begin(), count) != v.end()) {}
std::vector<int>::iterator it;
// cppcheck-suppress uninitvar
if (std::next(it) != v.end()) {}
std::vector<int>::const_iterator const_it;
// cppcheck-suppress uninitvar
if (std::next(const_it) != v.end()) {}
std::vector<int>::reverse_iterator rit;
// cppcheck-suppress uninitvar
if (std::next(rit) != v.rend()) {}
std::vector<int>::const_reverse_iterator const_rit;
// cppcheck-suppress uninitvar
if (std::next(const_rit) != v.rend()) {}
}
void uninitvar_std_prev(const std::vector<int> &v, int count)
{
// No warning shall be shown:
if (std::prev(v.begin()) != v.end()) {}
if (std::prev(v.begin(), count) != v.end()) {}
std::vector<int>::iterator it;
// cppcheck-suppress uninitvar
if (std::prev(it) != v.end()) {}
std::vector<int>::const_iterator const_it;
// cppcheck-suppress uninitvar
if (std::prev(const_it) != v.end()) {}
std::vector<int>::reverse_iterator rit;
// cppcheck-suppress uninitvar
if (std::prev(rit) != v.rend()) {}
std::vector<int>::const_reverse_iterator const_rit;
// cppcheck-suppress uninitvar
if (std::prev(const_rit) != v.rend()) {}
}
void overlappingWriteFunction_wcscat(wchar_t *src, wchar_t *dest)
{
// No warning shall be shown:
(void)wcscat(dest, src);
// cppcheck-suppress overlappingWriteFunction
(void)wcscat(src, src);
}
void overlappingWriteFunction_wcsxfrm(wchar_t *s1, const wchar_t *s2, size_t n)
{
// No warning shall be shown:
(void)wcsxfrm(s1, s2, n);
}
char * overlappingWriteFunction_strcat(char *src, char *dest)
{
// No warning shall be shown:
(void)strcat(dest, src);
// cppcheck-suppress overlappingWriteFunction
return strcat(src, src);
}
int nullPointer_wcsncmp(const wchar_t* s1, const wchar_t* s2, size_t n)
{
// cppcheck-suppress nullPointer
(void) std::wcsncmp(NULL,s2,n);
// cppcheck-suppress nullPointer
(void) std::wcsncmp(s1,NULL,n);
return std::wcsncmp(s1,s2,n);
}
wchar_t* nullPointer_wcsncpy(wchar_t *s, const wchar_t *cs, size_t n)
{
// cppcheck-suppress nullPointer
(void) std::wcsncpy(NULL,cs,n);
// cppcheck-suppress nullPointer
(void) std::wcsncpy(s,NULL,n);
return std::wcsncpy(s,cs,n);
}
char * overlappingWriteFunction_strncat(const char *src, char *dest, const std::size_t count)
{
// No warning shall be shown:
(void)strncat(dest, src, 42);
(void)strncat(dest, src, count);
(void)strncat(dest, dest, count);
// cppcheck-suppress overlappingWriteFunction
(void)strncat(dest, dest+1, 2);
char buffer[] = "strncat";
// cppcheck-suppress overlappingWriteFunction
return strncat(buffer, buffer + 1, 3);
}
wchar_t * overlappingWriteFunction_wcsncat(const wchar_t *src, wchar_t *dest, const std::size_t count)
{
// No warning shall be shown:
(void)wcsncat(dest, src, 42);
(void)wcsncat(dest, src, count);
(void)wcsncat(dest, dest, count);
// cppcheck-suppress overlappingWriteFunction
(void)wcsncat(dest, dest+1, 2);
wchar_t buffer[] = L"strncat";
// cppcheck-suppress overlappingWriteFunction
return wcsncat(buffer, buffer + 1, 3);
}
wchar_t * overlappingWriteFunction_wcscpy(wchar_t *src, wchar_t *dest)
{
// No warning shall be shown:
(void)wcscpy(dest, src);
const wchar_t * destBuf = dest;
// TODO-cppcheck-suppress overlappingWriteFunction #10355
(void)wcscpy(dest, destBuf);
// cppcheck-suppress overlappingWriteFunction
return wcscpy(src, src);
}
wchar_t * overlappingWriteFunction_wcsncpy(wchar_t *buf, const std::size_t count)
{
// No warning shall be shown:
(void)wcsncpy(&buf[0], &buf[3], count); // size is not known
(void)wcsncpy(&buf[0], &buf[3], 3U); // no-overlap
// cppcheck-suppress overlappingWriteFunction
return wcsncpy(&buf[0], &buf[3], 4U);
}
char * overlappingWriteFunction_strncpy(char *buf, const std::size_t count)
{
// No warning shall be shown:
(void)strncpy(&buf[0], &buf[3], count); // size is not known
(void)strncpy(&buf[0], &buf[3], 3U); // no-overlap
// cppcheck-suppress overlappingWriteFunction
return strncpy(&buf[0], &buf[3], 4U);
}
void * overlappingWriteFunction_memmove(void)
{
// No warning shall be shown:
char str[] = "memmove handles overlapping data well";
return memmove(str,str+3,4);
}
std::bitset<10> std_bitset_test_ignoredReturnValue()
{
std::bitset<10> b1("1111010000");
// cppcheck-suppress ignoredReturnValue
b1.test(2);
return b1;
}
std::bitset<10> std_bitset_all_ignoredReturnValue()
{
std::bitset<10> b1("1111010000");
// cppcheck-suppress ignoredReturnValue
b1.all();
return b1;
}
std::bitset<10> std_bitset_none_ignoredReturnValue()
{
std::bitset<10> b1("1111010000");
// cppcheck-suppress ignoredReturnValue
b1.none();
return b1;
}
std::bitset<10> std_bitset_any_ignoredReturnValue()
{
std::bitset<10> b1("1111010000");
// cppcheck-suppress ignoredReturnValue
b1.any();
return b1;
}
std::bitset<10> std_bitset_size_ignoredReturnValue()
{
std::bitset<10> b1("1111010000");
// cppcheck-suppress ignoredReturnValue
b1.size();
return b1;
}
std::bitset<10> std_bitset_count_ignoredReturnValue()
{
std::bitset<10> b1("1111010000");
// cppcheck-suppress ignoredReturnValue
b1.count();
return b1;
}
void std_unordered_set_count_ignoredReturnValue(const std::unordered_set<int>& u)
{
int i;
// cppcheck-suppress [uninitvar, ignoredReturnValue]
u.count(i);
}
void std_unordered_map_count_ignoredReturnValue(const std::unordered_map<int, int>& u)
{
int i;
// cppcheck-suppress [uninitvar, ignoredReturnValue]
u.count(i);
}
void std_multimap_count_ignoredReturnValue(const std::multimap<int, int>& m)
{
int i;
// cppcheck-suppress [uninitvar, ignoredReturnValue]
m.count(i);
}
void std_unordered_map_insert_unnitvar(std::unordered_set<int>& u)
{
int i;
// cppcheck-suppress uninitvar
u.insert(i);
}
void std_unordered_map_emplace_unnitvar(std::unordered_set<int>& u)
{
int i;
// cppcheck-suppress uninitvar
u.emplace(i);
}
int std_map_find_constref(std::map<int, int>& m) // #11857
{
std::map<int, int>& r = m;
std::map<int, int>::iterator it = r.find(42);
int* p = &it->second;
return ++*p;
}
void std_queue_front_ignoredReturnValue(const std::queue<int>& q) {
// cppcheck-suppress ignoredReturnValue
q.front();
}
void std_priority_queue_top_ignoredReturnValue(const std::priority_queue<int>& pq) {
// cppcheck-suppress ignoredReturnValue
pq.top();
}
void std_tie_ignoredReturnValue(int a, int b)
{
std::set<int> s;
std::set<int>::iterator it;
bool success;
std::tie(it, success) = s.insert(1);
// cppcheck-suppress ignoredReturnValue
std::tie();
// cppcheck-suppress ignoredReturnValue
std::tie(a, b);
}
void std_exception_ignoredReturnValue(const std::exception& e)
{
// cppcheck-suppress ignoredReturnValue
e.what();
}
void valid_code()
{
std::vector<int> vecInt{0, 1, 2};
std::fill_n(vecInt.begin(), 2, 0);
vecInt.push_back(1);
vecInt.pop_back();
}
void returnValue_std_isgreater(void)
{
// cppcheck-suppress knownConditionTrueFalse
if (std::isgreater(4,2) == 0) {}
// @todo support floats
if (std::isgreater(4.0f,2.0f) == 0) {}
}
void returnValue_std_isgreaterequal(void)
{
// cppcheck-suppress knownConditionTrueFalse
if (std::isgreaterequal(4,2) == 0) {}
// @todo support floats
if (std::isgreaterequal(4.0f,2.0f) == 0) {}
}
void returnValue_std_isless(void)
{
// cppcheck-suppress knownConditionTrueFalse
if (std::isless(4,2) == 0) {}
// @todo support floats
if (std::isless(4.0f,2.0f) == 0) {}
}
void returnValue_std_islessequal(void)
{
// cppcheck-suppress knownConditionTrueFalse
if (std::islessequal(4,2) == 0) {}
// @todo support floats
if (std::islessequal(4.0f,2.0f) == 0) {}
}
void returnValue_std_islessgreater(void)
{
// cppcheck-suppress knownConditionTrueFalse
if (std::islessgreater(4,2) == 0) {}
// cppcheck-suppress knownConditionTrueFalse
if (std::islessgreater(2,4) == 0) {}
if (std::islessgreater(4.0f,2.0f) == 0) {} // @todo support floats
if (std::islessgreater(2.0f,4.0f) == 0) {} // @todo support floats
}
void bufferAccessOutOfBounds(void)
{
char a[5];
std::strcpy(a,"abcd");
// cppcheck-suppress bufferAccessOutOfBounds
// TODO cppcheck-suppress redundantCopy
std::strcpy(a, "abcde");
// TODO cppcheck-suppress redundantCopy
// cppcheck-suppress terminateStrncpy
std::strncpy(a,"abcde",5);
// cppcheck-suppress bufferAccessOutOfBounds
// TODO cppcheck-suppress redundantCopy
std::strncpy(a,"abcde",6);
}
void uninitvar_abs(void)
{
int i;
// cppcheck-suppress uninitvar
(void)std::abs(i);
}
void uninivar_imaxabs(void)
{
intmax_t i1, i2;
// cppcheck-suppress uninitvar
(void)std::imaxabs(i1);
// cppcheck-suppress uninitvar
(void)imaxabs(i2);
}
void uninitvar_isalnum(void)
{
int i;
// cppcheck-suppress uninitvar
(void)std::isalnum(i);
}
void uninitvar_isalpha(void)
{
int i;
// cppcheck-suppress uninitvar
(void)std::isalpha(i);
}
void uninitvar_iscntrl(void)
{
int i;
// cppcheck-suppress uninitvar
(void)std::iscntrl(i);
}
void uninitvar_isdigit(void)
{
int i;
// cppcheck-suppress uninitvar
(void)std::isdigit(i);
}
void uninitvar_isgraph(void)
{
int i;
// cppcheck-suppress uninitvar
(void)std::isgraph(i);
}
void uninitvar_islower(void)
{
int i;
// cppcheck-suppress uninitvar
(void)std::islower(i);
}
void uninitvar_isprint(void)
{
int i;
// cppcheck-suppress uninitvar
(void)std::isprint(i);
}
void uninitvar_isspace(void)
{
int i;
// cppcheck-suppress uninitvar
(void)std::isspace(i);
}
void uninitvar_isupper(void)
{
int i;
// cppcheck-suppress uninitvar
(void)std::isupper(i);
}
void uninitvar_isxdigit(void)
{
int i;
// cppcheck-suppress uninitvar
(void)std::isxdigit(i);
}
void uninitvar_proj(void)
{
double d;
// cppcheck-suppress uninitvar
const std::complex<double> dc(d,d);
(void)std::proj(dc);
}
void uninitvar_acos(void)
{
float f;
// cppcheck-suppress uninitvar
(void)std::acos(f);
double d;
// cppcheck-suppress uninitvar
(void)std::acos(d);
long double ld;
// cppcheck-suppress uninitvar
(void)std::acos(ld);
}
void uninitvar_acosh(void)
{
float f;
// cppcheck-suppress uninitvar
(void)std::acoshf(f);
double d;
// cppcheck-suppress uninitvar
(void)std::acosh(d);
long double ld;
// cppcheck-suppress uninitvar
(void)std::acoshl(ld);
}
void uninitvar_asctime(void)
{
const struct tm *tm;
// cppcheck-suppress uninitvar
// cppcheck-suppress asctimeCalled
(void)std::asctime(tm);
}
void uninitvar_sqrt(void)
{
float f;
// cppcheck-suppress uninitvar
(void)std::sqrt(f);
double d;
// cppcheck-suppress uninitvar
(void)std::sqrt(d);
long double ld;
// cppcheck-suppress uninitvar
(void)std::sqrt(ld);
}
void uninitvar_sinh(void)
{
float f;
// cppcheck-suppress uninitvar
(void)std::sinh(f);
double d;
// cppcheck-suppress uninitvar
(void)std::sinh(d);
long double ld;
// cppcheck-suppress uninitvar
(void)std::sinh(ld);
}
void uninitvar_sin(void)
{
float f;
// cppcheck-suppress uninitvar
(void)std::sin(f);
double d;
// cppcheck-suppress uninitvar
(void)std::sin(d);
long double ld;
// cppcheck-suppress uninitvar
(void)std::sin(ld);
}
void uninitvar_asin(void)
{
float f;
// cppcheck-suppress uninitvar
(void)std::asin(f);
double d;
// cppcheck-suppress uninitvar
(void)std::asin(d);
long double ld;
// cppcheck-suppress uninitvar
(void)std::asin(ld);
}
void uninitvar_asinh(void)
{
float f;
// cppcheck-suppress uninitvar
(void)std::asinhf(f);
double d;
// cppcheck-suppress uninitvar
(void)std::asinh(d);
long double ld;
// cppcheck-suppress uninitvar
(void)std::asinhl(ld);
}
void uninitvar_wcsftime(wchar_t* ptr)
{
size_t maxsize;
const wchar_t* format;
const struct tm* timeptr;
// cppcheck-suppress uninitvar
(void)std::wcsftime(ptr, maxsize, format, timeptr);
}
void uninitvar_tan(void)
{
float f;
// cppcheck-suppress uninitvar
(void)std::tan(f);
double d;
// cppcheck-suppress uninitvar
(void)std::tan(d);
long double ld;
// cppcheck-suppress uninitvar
(void)std::tan(ld);
}
void uninitvar_tanh(void)
{
float f;
// cppcheck-suppress uninitvar
(void)std::tanh(f);
double d;
// cppcheck-suppress uninitvar
(void)std::tanh(d);
long double ld;
// cppcheck-suppress uninitvar
(void)std::tanh(ld);
}
void uninitvar_atan(void)
{
float f;
// cppcheck-suppress uninitvar
(void)std::atan(f);
double d;
// cppcheck-suppress uninitvar
(void)std::atan(d);
long double ld;
// cppcheck-suppress uninitvar
(void)std::atan(ld);
}
void uninitvar_tgamma(void)
{
float f;
// cppcheck-suppress uninitvar
(void)std::tgammaf(f);
double d;
// cppcheck-suppress uninitvar
(void)std::tgamma(d);
long double ld;
// cppcheck-suppress uninitvar
(void)std::tgammal(ld);
}
void uninitvar_trunc(void)
{
float f;
// cppcheck-suppress uninitvar
(void)std::truncf(f);
double d;
// cppcheck-suppress uninitvar
(void)std::trunc(d);
long double ld;
// cppcheck-suppress uninitvar
(void)std::truncl(ld);
}
void uninitvar_atanh(void)
{
float f;
// cppcheck-suppress uninitvar
(void)std::atanhf(f);
double d;
// cppcheck-suppress uninitvar
(void)std::atanh(d);
long double ld;
// cppcheck-suppress uninitvar
(void)std::atanhl(ld);
}
void uninitvar_atan2(void)
{
float f1,f2;
// cppcheck-suppress uninitvar
(void)std::atan2(f1,f2);
double d1,d2;
// cppcheck-suppress uninitvar
(void)std::atan2(d1,d2);
long double ld1,ld2;
// cppcheck-suppress uninitvar
(void)std::atan2(ld1,ld2);
}
void uninitvar_atof(void)
{
const char * c;
// cppcheck-suppress uninitvar
(void)std::atof(c);
}
void uninitvar_atol(void)
{
const char * c1, *c2, *c3;
// cppcheck-suppress uninitvar
(void)std::atoi(c1);
// cppcheck-suppress uninitvar
(void)std::atol(c2);
// cppcheck-suppress uninitvar
(void)std::atoll(c3);
}
void uninitvar_ceil(void)
{
float f;
// cppcheck-suppress uninitvar
(void)std::ceil(f);
double d;
// cppcheck-suppress uninitvar
(void)std::ceil(d);
long double ld;
// cppcheck-suppress uninitvar
(void)std::ceil(ld);
}
void uninitvar_copysign(void)
{
float f1, f2;
// cppcheck-suppress uninitvar
(void)std::copysignf(f1, f2);
double d1, d2;
// cppcheck-suppress uninitvar
(void)std::copysign(d1, d2);
long double ld1, ld2;
// cppcheck-suppress uninitvar
(void)std::copysignl(ld1, ld2);
}
void uninitvar_cbrt(void)
{
float f;
// cppcheck-suppress uninitvar
(void)std::cbrtf(f);
double d;
// cppcheck-suppress uninitvar
(void)std::cbrt(d);
long double ld;
// cppcheck-suppress uninitvar
(void)std::cbrtl(ld);
}
void uninitvar_cos(void)
{
float f;
// cppcheck-suppress uninitvar
(void)std::cos(f);
double d;
// cppcheck-suppress uninitvar
(void)std::cos(d);
long double ld;
// cppcheck-suppress uninitvar
(void)std::cos(ld);
}
void uninitvar_clearerr(void)
{
FILE * stream;
// cppcheck-suppress uninitvar
std::clearerr(stream);
}
void uninitvar_cosh(void)
{
float f;
// cppcheck-suppress uninitvar
(void)std::cosh(f);
double d;
// cppcheck-suppress uninitvar
(void)std::cosh(d);
long double ld;
// cppcheck-suppress uninitvar
(void)std::cosh(ld);
}
void uninitvar_feraiseexcept(void)
{
int expects;
// cppcheck-suppress uninitvar
(void)std::feraiseexcept(expects);
}
void uninitvar_fesetexceptflag(const fexcept_t* flagp)
{
int expects;
// cppcheck-suppress uninitvar
(void)std::fesetexceptflag(flagp, expects);
}
void uninitvar_feclearexcept(void)
{
int i;
// cppcheck-suppress uninitvar
(void)std::feclearexcept(i);
}
void uninitvar_fesetenv(void)
{
const fenv_t* envp;
// cppcheck-suppress uninitvar
(void)std::fesetenv(envp);
}
void uninitvar_fesetround(void)
{
int i;
// cppcheck-suppress uninitvar
(void)std::fesetround(i);
}
void uninitvar_fetestexcept(void)
{
int i;
// cppcheck-suppress uninitvar
(void)std::fetestexcept(i);
}
void uninitvar_feupdateenv(void)
{
const fenv_t* envp;
// cppcheck-suppress uninitvar
(void)std::feupdateenv(envp);
}
void uninitvar_ctime(void)
{
const time_t *tp;
// cppcheck-suppress uninitvar
(void)std::ctime(tp);
}
void uninitvar_difftime(void)
{
time_t t1,t2;
// cppcheck-suppress uninitvar
(void)std::difftime(t1, t2);
}
void uninitvar_div(void)
{
int num;
int denom;
// cppcheck-suppress uninitvar
(void)std::div(num,denom);
}
void uninitvar_imaxdiv(void)
{
intmax_t numer1, numer2;
intmax_t denom1, denom2;
// cppcheck-suppress uninitvar
(void)std::imaxdiv(numer1,denom1);
// cppcheck-suppress uninitvar
(void)imaxdiv(numer2,denom2);
}
void uninitvar_exit(void)
{
int i;
// cppcheck-suppress uninitvar
std::exit(i);
}
void uninitvar_erf(void)
{
float f;
// cppcheck-suppress uninitvar
(void)std::erff(f);
double d;
// cppcheck-suppress uninitvar
(void)std::erf(d);
long double ld;
// cppcheck-suppress uninitvar
(void)std::erfl(ld);
}
void uninitvar_erfc(void)
{
float f;
// cppcheck-suppress uninitvar
(void)std::erfcf(f);
double d;
// cppcheck-suppress uninitvar
(void)std::erfc(d);
long double ld;
// cppcheck-suppress uninitvar
(void)std::erfcl(ld);
}
void uninitvar_exp(void)
{
float f;
// cppcheck-suppress uninitvar
(void)std::exp(f);
double d;
// cppcheck-suppress uninitvar
(void)std::exp(d);
long double ld;
// cppcheck-suppress uninitvar
(void)std::exp(ld);
}
void uninitvar_exp2(void)
{
float f;
// cppcheck-suppress uninitvar
(void)std::exp2f(f);
double d;
// cppcheck-suppress uninitvar
(void)std::exp2(d);
long double ld;
// cppcheck-suppress uninitvar
(void)std::exp2l(ld);
}
void uninitvar_expm1(void)
{
float f;
// cppcheck-suppress uninitvar
(void)std::expm1f(f);
double d;
// cppcheck-suppress uninitvar
(void)std::expm1(d);
long double ld;
// cppcheck-suppress uninitvar
(void)std::expm1l(ld);
}
void uninitvar_fabs(void)
{
float f;
// cppcheck-suppress uninitvar
(void)std::fabs(f);
double d;
// cppcheck-suppress uninitvar
(void)std::fabs(d);
long double ld;
// cppcheck-suppress uninitvar
(void)std::fabs(ld);
}
void uninitvar_fdim(void)
{
float f1,f2;
// cppcheck-suppress uninitvar
(void)std::fdimf(f1,f2);
double d1,d2;
// cppcheck-suppress uninitvar
(void)std::fdim(d1,d2);
long double ld1,ld2;
// cppcheck-suppress uninitvar
(void)std::fdiml(ld1,ld2);
}
void uninitvar_fclose(void)
{
// cppcheck-suppress unassignedVariable
FILE *stream;
// cppcheck-suppress uninitvar
(void)std::fclose(stream);
}
void uninitvar_ferror(void)
{
FILE *stream;
// cppcheck-suppress uninitvar
(void)std::ferror(stream);
}
void uninitvar_feof(void)
{
FILE *stream;
// cppcheck-suppress uninitvar
(void)std::feof(stream);
}
void uninitvar_fflush(void)
{
FILE *stream;
// cppcheck-suppress uninitvar
(void)std::fflush(stream);
}
void uninitvar_fgetc(void)
{
FILE *stream;
// cppcheck-suppress uninitvar
(void)std::fgetc(stream);
}
void uninitvar_fgetwc(void)
{
FILE *stream;
// cppcheck-suppress uninitvar
(void)std::fgetwc(stream);
}
void uninitvar_fgetpos(void)
{
FILE* stream;
fpos_t *ptr;
// cppcheck-suppress uninitvar
(void)std::fgetpos(stream,ptr);
}
void uninitvar_floor(void)
{
float f;
// cppcheck-suppress uninitvar
(void)std::floor(f);
double d;
// cppcheck-suppress uninitvar
(void)std::floor(d);
long double ld;
// cppcheck-suppress uninitvar
(void)std::floor(ld);
}
void uninitvar_fma(void)
{
float f1,f2,f3;
// cppcheck-suppress uninitvar
(void)std::fmaf(f1,f2,f3);
double d1,d2,d3;
// cppcheck-suppress uninitvar
(void)std::fma(d1,d2,d3);
long double ld1,ld2,ld3;
// cppcheck-suppress uninitvar
(void)std::fmal(ld1,ld2,ld3);
}
void uninitvar_fmax(void)
{
float f1,f2;
// cppcheck-suppress uninitvar
(void)std::fmaxf(f1,f2);
double d1,d2;
// cppcheck-suppress uninitvar
(void)std::fmax(d1,d2);
long double ld1,ld2;
// cppcheck-suppress uninitvar
(void)std::fmaxl(ld1,ld2);
}
void uninitvar_fmin(void)
{
float f1,f2;
// cppcheck-suppress uninitvar
(void)std::fminf(f1,f2);
double d1,d2;
// cppcheck-suppress uninitvar
(void)std::fmin(d1,d2);
long double ld1,ld2;
// cppcheck-suppress uninitvar
(void)std::fminl(ld1,ld2);
}
void uninitvar_fmod(void)
{
float f1,f2;
// cppcheck-suppress uninitvar
(void)std::fmod(f1,f2);
double d1,d2;
// cppcheck-suppress uninitvar
(void)std::fmod(d1,d2);
long double ld1,ld2;
// cppcheck-suppress uninitvar
(void)std::fmod(ld1,ld2);
}
void uninitar_fopen(void)
{
const char *filename;
const char *mode;
// cppcheck-suppress uninitvar
FILE * fp = std::fopen(filename, mode);
fclose(fp);
}
void uninitar_fprintf(FILE *Stream, const char *Format, int Argument)
{
FILE *stream1, *stream2;
const char *format1, *format2;
int argument1, argument2;
// cppcheck-suppress uninitvar
(void)std::fprintf(stream1, format1, argument1);
// cppcheck-suppress uninitvar
(void)std::fprintf(stream2, Format, Argument);
// cppcheck-suppress uninitvar
(void)std::fprintf(Stream, format2, Argument);
// cppcheck-suppress uninitvar
(void)std::fprintf(Stream, Format, argument2);
// no warning is expected
(void)std::fprintf(Stream, Format, Argument);
}
void uninitar_vfprintf(FILE *Stream, const char *Format, va_list Arg)
{
FILE *stream1, *stream2;
const char *format1, *format2;
va_list arg;
// cppcheck-suppress va_list_usedBeforeStarted
// cppcheck-suppress uninitvar
(void)std::vfprintf(stream1, format1, arg);
// cppcheck-suppress uninitvar
(void)std::vfprintf(stream2, Format, Arg);
// cppcheck-suppress uninitvar
(void)std::vfprintf(Stream, format2, Arg);
// no warning is expected
(void)std::vfprintf(Stream, Format, Arg);
// cppcheck-suppress va_list_usedBeforeStarted
(void)std::vfprintf(Stream, Format, arg);
}
void uninitar_vfwprintf(FILE *Stream, const wchar_t *Format, va_list Arg)
{
FILE *stream1, *stream2;
const wchar_t *format1, *format2;
va_list arg;
// cppcheck-suppress va_list_usedBeforeStarted
// cppcheck-suppress uninitvar
(void)std::vfwprintf(stream1, format1, arg);
// cppcheck-suppress uninitvar
(void)std::vfwprintf(stream2, Format, Arg);
// cppcheck-suppress uninitvar
(void)std::vfwprintf(Stream, format2, Arg);
// no warning is expected
(void)std::vfwprintf(Stream, Format, Arg);
// cppcheck-suppress va_list_usedBeforeStarted
(void)std::vfwprintf(Stream, Format, arg);
}
void uninitvar_fputc(void)
{
int c;
FILE *stream;
// cppcheck-suppress uninitvar
(void)std::fputc(c,stream);
}
void uninitvar_fputwc(void)
{
wchar_t c;
FILE *stream;
// cppcheck-suppress uninitvar
(void)std::fputwc(c,stream);
}
void uninitvar_fputs(void)
{
const char *string;
FILE *stream;
// cppcheck-suppress uninitvar
(void)std::fputs(string,stream);
}
void uninitvar_fputws(void)
{
const wchar_t *string;
FILE *stream;
// cppcheck-suppress uninitvar
(void)std::fputws(string,stream);
}
void uninitvar_fread(void)
{
void *ptr;
size_t size;
size_t nobj;
FILE *stream;
// cppcheck-suppress uninitvar
(void)std::fread(ptr,size,nobj,stream);
}
void uninitvar_free(void)
{
// cppcheck-suppress unassignedVariable
void *block;
// cppcheck-suppress uninitvar
std::free(block);
}
void uninitvar_freopen(void)
{
const char *filename;
const char *mode;
FILE *stream;
// cppcheck-suppress uninitvar
FILE * p = std::freopen(filename,mode,stream);
std::fclose(p);
}
void uninitvar_frexp(void)
{
float f1;
int *i1;
// cppcheck-suppress uninitvar
(void)std::frexp(f1,i1);
double d1;
int *i2;
// cppcheck-suppress uninitvar
(void)std::frexp(d1,i2);
long double ld1;
int *i3;
// cppcheck-suppress uninitvar
(void)std::frexp(ld1,i3);
}
void uninitvar_hypot(void)
{
float f1,f2;
// cppcheck-suppress uninitvar
(void)std::hypotf(f1,f2);
double d1,d2;
// cppcheck-suppress uninitvar
(void)std::hypot(d1,d2);
long double ld1,ld2;
// cppcheck-suppress uninitvar
(void)std::hypotl(ld1,ld2);
}
void uninitvar_fscanf(void)
{
FILE *stream;
const char *format;
int i;
// cppcheck-suppress uninitvar
(void)std::fscanf(stream,format,i);
}
void uninitvar_vfscanf(void)
{
FILE *stream;
const char *format;
va_list arg;
// cppcheck-suppress va_list_usedBeforeStarted
// cppcheck-suppress uninitvar
(void)std::vfscanf(stream,format,arg);
}
void uninitvar_vfwscanf(void)
{
FILE *stream;
const wchar_t *format;
va_list arg;
// cppcheck-suppress va_list_usedBeforeStarted
// cppcheck-suppress uninitvar
(void)std::vfwscanf(stream,format,arg);
}
void uninitvar_fseek(void)
{
FILE* stream;
long int offset;
int origin;
// cppcheck-suppress uninitvar
(void)std::fseek(stream,offset,origin);
}
void invalidFunctionArg_fseek(FILE* stream, long int offset, int origin)
{
// cppcheck-suppress invalidFunctionArg
(void)std::fseek(stream, offset, -1);
// cppcheck-suppress invalidFunctionArg
(void)std::fseek(stream, offset, 3);
// cppcheck-suppress invalidFunctionArg
(void)std::fseek(stream, offset, 42+SEEK_SET);
// cppcheck-suppress invalidFunctionArg
(void)std::fseek(stream, offset, SEEK_SET+42);
// No warning is expected for
(void)std::fseek(stream, offset, origin);
(void)std::fseek(stream, offset, SEEK_SET);
(void)std::fseek(stream, offset, SEEK_CUR);
(void)std::fseek(stream, offset, SEEK_END);
}
void invalidFunctionArgBool_fseek(FILE* stream, long int offset, int origin)
{
// cppcheck-suppress invalidFunctionArgBool
(void)std::fseek(stream, offset, true);
// cppcheck-suppress invalidFunctionArgBool
(void)std::fseek(stream, offset, false);
}
void uninitvar_fsetpos(void)
{
FILE* stream;
const fpos_t *ptr;
// cppcheck-suppress uninitvar
(void)std::fsetpos(stream,ptr);
}
wchar_t* nullPointer_fgetws(wchar_t* buffer, int n, FILE* stream)
{
// cppcheck-suppress nullPointer
(void)std::fgetws(NULL,n,stream);
// cppcheck-suppress nullPointer
(void)std::fgetws(buffer,n,NULL);
// No warning is expected
return std::fgetws(buffer, n, stream);
}
void nullPointer_wmemcmp(const wchar_t* s1, const wchar_t* s2, size_t n)
{
// cppcheck-suppress nullPointer
(void)std::wmemcmp(NULL,s2,n);
// cppcheck-suppress nullPointer
(void)std::wmemcmp(s1,NULL,n);
(void)std::wmemcmp(s1,s2,n);
}
void nullPointer_memcmp(const void *s1, const void *s2, size_t n)
{
// cppcheck-suppress nullPointer
(void)std::memcmp(NULL,s2,n);
// cppcheck-suppress nullPointer
(void)std::memcmp(s1,NULL,n);
(void)std::memcmp(s1,s2,n);
}
void nullPointer_strncat(char *d, const char *s, size_t n)
{
// cppcheck-suppress nullPointer
(void)std::strncat(NULL,s,n);
// cppcheck-suppress nullPointer
(void)std::strncat(d,NULL,n);
// no warning is expected for
(void)std::strncat(d,s,n);
}
void nullPointer_strcpy(char *dest, const char * const source)
{
// cppcheck-suppress nullPointer
(void)std::strcpy(NULL,source);
// cppcheck-suppress nullPointer
(void)std::strcpy(dest,NULL);
// no warning shall be shown for
(void)std::strcpy(dest,source);
}
void nullPointer_strcat(char *dest, const char * const source)
{
// cppcheck-suppress nullPointer
(void)std::strcat(NULL,source);
// cppcheck-suppress nullPointer
(void)std::strcat(dest,NULL);
// no warning shall be shown for
(void)std::strcat(dest,source);
}
void nullPointer_strncpy(char *d, const char *s, size_t n)
{
// cppcheck-suppress nullPointer
(void)std::strncpy(NULL,s,n);
// cppcheck-suppress nullPointer
(void)std::strncpy(d,NULL,n);
// no warning is expected for
(void)std::strncpy(d,s,n);
}
void nullPointer_strncmp(const char *s1, const char *s2, size_t n)
{
// cppcheck-suppress nullPointer
(void)std::strncmp(NULL,s2,n);
// cppcheck-suppress nullPointer
(void)std::strncmp(s1,NULL,n);
(void)std::strncmp(s1,s2,n);
}
char* nullPointer_fgets(char *buffer, int n, FILE *stream)
{
// cppcheck-suppress nullPointer
(void)std::fgets(NULL,n,stream);
// cppcheck-suppress nullPointer
(void)std::fgets(buffer,n,NULL);
// No warning is expected
return std::fgets(buffer, n, stream);
}
void uninitvar_fgets(void)
{
char *buffer;
int n;
FILE *stream;
// cppcheck-suppress uninitvar
(void)std::fgets(buffer,n,stream);
}
void uninitvar_fgetws(void)
{
wchar_t *buffer;
int n;
FILE *stream;
// cppcheck-suppress uninitvar
(void)std::fgetws(buffer,n,stream);
}
void uninitvar_ftell(void)
{
FILE *stream;
// cppcheck-suppress uninitvar
(void)std::ftell(stream);
}
void uninitvar_fwide(void)
{
FILE *stream;
int mode;
// cppcheck-suppress uninitvar
(void)std::fwide(stream,mode);
}
void uninitvar_fwrite(void)
{
const void *ptr;
size_t size;
size_t nobj;
FILE *stream;
// cppcheck-suppress uninitvar
(void)std::fwrite(ptr,size,nobj,stream);
}
void uninitvar_mblen(void)
{
const char *string;
size_t size;
// cppcheck-suppress uninitvar
(void)std::mblen(string,size);
}
void uninitvar_mbtowc(void)
{
wchar_t* pwc;
const char* pmb;
size_t max;
// cppcheck-suppress uninitvar
(void)std::mbtowc(pwc,pmb,max);
}
void uninitvar_mbrlen(const char* p, size_t m, mbstate_t* s)
{
const char* pmb1, *pmb2;
size_t max1, max2;
mbstate_t* ps1, *ps2;
// cppcheck-suppress uninitvar
(void)std::mbrlen(pmb1,max1,ps1);
// cppcheck-suppress uninitvar
(void)std::mbrlen(pmb2,m,s);
// cppcheck-suppress uninitvar
(void)std::mbrlen(p,max2,s);
// cppcheck-suppress uninitvar
(void)std::mbrlen(p,m,ps2);
// no warning is expected
(void)std::mbrlen(p,m,s);
}
void nullPointer_mbrlen(const char* p, size_t m, mbstate_t* s)
{
// no warning is expected: A call to the function with a null pointer as pmb resets the shift state (and ignores parameter max).
(void)std::mbrlen(NULL,m,s);
(void)std::mbrlen(NULL,0,s);
// cppcheck-suppress nullPointer
(void)std::mbrlen(p,m,NULL);
}
void uninitvar_btowc(void)
{
int c;
// cppcheck-suppress uninitvar
(void)std::btowc(c);
}
void uninitvar_mbsinit(void)
{
const mbstate_t* ps;
// cppcheck-suppress uninitvar
(void)std::mbsinit(ps);
}
void uninitvar_mbstowcs(void)
{
wchar_t *ws;
const char *s;
size_t n;
// cppcheck-suppress uninitvar
(void)std::mbstowcs(ws,s,n);
}
void uninitvar_mbsrtowcs(void)
{
wchar_t* dest;
const char* src;
size_t max;
mbstate_t* ps;
// cppcheck-suppress uninitvar
(void)std::mbsrtowcs(dest,&src,max,ps);
}
void uninitvar_wctob(void)
{
wint_t wc;
// cppcheck-suppress uninitvar
(void)std::wctob(wc);
}
void uninitvar_wctomb(void)
{
char *s;
wchar_t wc;
// cppcheck-suppress uninitvar
(void)std::wctomb(s,wc);
}
void uninitvar_wcstombs(void)
{
char *mbstr;
const wchar_t *wcstr;
size_t n;
// cppcheck-suppress uninitvar
(void)std::wcstombs(mbstr,wcstr,n);
}
void uninitvar_getc(void)
{
FILE *stream;
// cppcheck-suppress uninitvar
(void)std::getc(stream);
}
void uninitvar_getwc(void)
{
FILE *stream;
// cppcheck-suppress uninitvar
(void)std::getwc(stream);
}
void uninitvar_ungetc(void)
{
int c;
FILE *stream;
// cppcheck-suppress uninitvar
(void)std::ungetc(c,stream);
}
void uninitvar_ungetwc(void)
{
wint_t c;
FILE *stream;
// cppcheck-suppress uninitvar
(void)std::ungetwc(c,stream);
}
void uninitvar_getenv(void)
{
const char *name;
// cppcheck-suppress uninitvar
(void)std::getenv(name);
}
void uninitvar_gmtime(void)
{
const time_t *tp;
// cppcheck-suppress uninitvar
(void)std::gmtime(tp);
}
void uninitvar_iswalnum(void)
{
wint_t i;
// cppcheck-suppress uninitvar
(void)std::iswalnum(i);
}
void uninitvar_iswalpha(void)
{
wint_t i;
// cppcheck-suppress uninitvar
(void)std::iswalpha(i);
}
void uninitvar_isblank(void)
{
int i;
// cppcheck-suppress uninitvar
(void)std::isblank(i);
}
void uninitvar_iswblank(void)
{
wint_t i;
// cppcheck-suppress uninitvar
(void)std::iswblank(i);
}
void uninitvar_iswcntrl(void)
{
wint_t i;
// cppcheck-suppress uninitvar
(void)std::iswcntrl(i);
}
void uninitvar_iswctype(void)
{
wint_t c;
wctype_t desc;
// cppcheck-suppress uninitvar
(void)std::iswctype(c,desc);
}
void uninitvar_iswdigit(void)
{
wint_t i;
// cppcheck-suppress uninitvar
(void)std::iswdigit(i);
}
void uninitvar_iswgraph(void)
{
wint_t i;
// cppcheck-suppress uninitvar
(void)std::iswgraph(i);
}
void uninitvar_iswlower(void)
{
wint_t i;
// cppcheck-suppress uninitvar
(void)std::iswlower(i);
}
void uninitvar_iswprint(void)
{
wint_t i;
// cppcheck-suppress uninitvar
(void)std::iswprint(i);
}
void uninitvar_ispunct(void)
{
int i;
// cppcheck-suppress uninitvar
(void)std::ispunct(i);
}
void uninitvar_iswpunct(void)
{
wint_t i;
// cppcheck-suppress uninitvar
(void)std::iswpunct(i);
}
void uninitvar_iswspace(void)
{
wint_t i;
// cppcheck-suppress uninitvar
(void)std::iswspace(i);
}
void uninitvar_iswupper(void)
{
wint_t i;
// cppcheck-suppress uninitvar
(void)std::iswupper(i);
}
void uninitvar_iswxdigit(void)
{
wint_t i;
// cppcheck-suppress uninitvar
(void)std::iswxdigit(i);
}
void uninitvar_towctrans(void)
{
wint_t c;
wctrans_t desc;
// cppcheck-suppress uninitvar
(void)std::towctrans(c,desc);
}
void uninitvar_towlower(void)
{
wint_t i;
// cppcheck-suppress uninitvar
(void)std::towlower(i);
}
void uninitvar_towupper(void)
{
wint_t i;
// cppcheck-suppress uninitvar
(void)std::towupper(i);
}
void uninitvar_wctrans(void)
{
const char* property;
// cppcheck-suppress uninitvar
(void)std::wctrans(property);
}
void uninitvar_wctype(void)
{
const char* property;
// cppcheck-suppress uninitvar
(void)std::wctype(property);
}
void uninitvar_labs(void)
{
long int li;
// cppcheck-suppress uninitvar
(void)std::labs(li);
long long int lli;
// cppcheck-suppress uninitvar
(void)std::llabs(lli);
}
void uninitvar_ldexp(void)
{
float fd;
int e1;
// cppcheck-suppress uninitvar
(void)std::ldexp(fd,e1);
double dc;
int e2;
// cppcheck-suppress uninitvar
(void)std::ldexp(dc,e2);
long double ldc;
int e3;
// cppcheck-suppress uninitvar
(void)std::ldexp(ldc,e3);
}
void invalidFunctionArg_lgamma(float f, double d, long double ld)
{
(void)lgamma(d);
// TODO cppcheck-suppress invalidFunctionArg
(void)lgamma(-0.1);
// cppcheck-suppress invalidFunctionArg
(void)lgamma(0.0);
(void)lgamma(0.1);
(void)lgammaf(f);
// TODO cppcheck-suppress invalidFunctionArg
(void)lgammaf(-0.1f);
// cppcheck-suppress invalidFunctionArg
(void)lgammaf(0.0f);
(void)lgammaf(0.1f);
(void)lgammal(ld);
// TODO cppcheck-suppress invalidFunctionArg
(void)lgammal(-0.1L);
// cppcheck-suppress invalidFunctionArg
(void)lgammal(0.0L);
(void)lgammal(0.1L);
}
void invalidFunctionArg_tgamma(float f, double d, long double ld)
{
(void)tgamma(d);
// TODO cppcheck-suppress invalidFunctionArg
(void)tgamma(-0.1);
// cppcheck-suppress invalidFunctionArg
(void)tgamma(0.0);
(void)tgamma(0.1);
(void)tgammaf(f);
// TODO cppcheck-suppress invalidFunctionArg
(void)tgammaf(-0.1f);
// cppcheck-suppress invalidFunctionArg
(void)tgammaf(0.0f);
(void)tgammaf(0.1f);
(void)tgammal(ld);
// TODO cppcheck-suppress invalidFunctionArg
(void)tgammal(-0.1L);
// cppcheck-suppress invalidFunctionArg
(void)tgammal(0.0L);
(void)tgammal(0.1L);
}
void uninitvar_lgamma(void)
{
float f;
// cppcheck-suppress uninitvar
(void)std::lgammaf(f);
double d;
// cppcheck-suppress uninitvar
(void)std::lgamma(d);
long double ld;
// cppcheck-suppress uninitvar
(void)std::lgammal(ld);
}
void uninitvar_rint(void)
{
float f;
// cppcheck-suppress uninitvar
(void)std::rintf(f);
double d;
// cppcheck-suppress uninitvar
(void)std::rint(d);
long double ld;
// cppcheck-suppress uninitvar
(void)std::rintl(ld);
}
void uninitvar_lrint(void)
{
float f;
// cppcheck-suppress uninitvar
(void)std::lrintf(f);
double d;
// cppcheck-suppress uninitvar
(void)std::lrint(d);
long double ld;
// cppcheck-suppress uninitvar
(void)std::lrintl(ld);
}
void uninitvar_llrint(void)
{
float f;
// cppcheck-suppress uninitvar
(void)std::llrintf(f);
double d;
// cppcheck-suppress uninitvar
(void)std::llrint(d);
long double ld;
// cppcheck-suppress uninitvar
(void)std::llrintl(ld);
}
void uninitvar_lround(void)
{
float f;
// cppcheck-suppress uninitvar
(void)std::lroundf(f);
double d;
// cppcheck-suppress uninitvar
(void)std::lround(d);
long double ld;
// cppcheck-suppress uninitvar
(void)std::lroundl(ld);
}
void uninitvar_llround(void)
{
float f;
// cppcheck-suppress uninitvar
(void)std::llroundf(f);
double d;
// cppcheck-suppress uninitvar
(void)std::llround(d);
long double ld;
// cppcheck-suppress uninitvar
(void)std::llroundl(ld);
}
void unusedScopedObject_std_monostate(void)
{
// cppcheck-suppress unusedScopedObject
std::monostate{};
}
void unusedScopedObject_std_logic_error()
{
// cppcheck-suppress unusedScopedObject
std::logic_error("abc");
}
void uninitvar_srand(void)
{
unsigned int seed;
// cppcheck-suppress uninitvar
(void)std::srand(seed);
// cppcheck-suppress ignoredReturnValue
std::rand();
}
void uninitvar_ldiv(void)
{
long int l1;
long int l2;
// cppcheck-suppress uninitvar
(void)std::ldiv(l1,l2);
long long int ll1;
long long int ll2;
// cppcheck-suppress uninitvar
(void)std::lldiv(ll1,ll2);
}
void uninitvar_localtime(void)
{
const time_t *tp;
// cppcheck-suppress uninitvar
(void)std::localtime(tp);
}
void uninitvar_log(void)
{
float f;
// cppcheck-suppress uninitvar
(void)std::log(f);
double d;
// cppcheck-suppress uninitvar
(void)std::log(d);
long double ld;
// cppcheck-suppress uninitvar
(void)std::log(ld);
}
void uninitvar_fpclassify(void)
{
float f;
// cppcheck-suppress uninitvar
(void)std::fpclassify(f);
double d;
// cppcheck-suppress uninitvar
(void)std::fpclassify(d);
long double ld;
// cppcheck-suppress uninitvar
(void)std::fpclassify(ld);
}
void bool_isfinite(float f)
{
// cppcheck-suppress compareBoolExpressionWithInt
// cppcheck-suppress compareValueOutOfTypeRangeError
// cppcheck-suppress knownConditionTrueFalse
if (std::isfinite(f)==123) {}
}
void uninitvar_isfinite(void)
{
float f;
// cppcheck-suppress uninitvar
(void)std::isfinite(f);
double d;
// cppcheck-suppress uninitvar
(void)std::isfinite(d);
long double ld;
// cppcheck-suppress uninitvar
(void)std::isfinite(ld);
}
void bool_isgreater(float f1, float f2)
{
// cppcheck-suppress compareBoolExpressionWithInt
// cppcheck-suppress compareValueOutOfTypeRangeError
// cppcheck-suppress knownConditionTrueFalse
if (std::isgreater(f1,f2)==123) {}
}
void uninitvar_isgreater(void)
{
float f1,f2;
// cppcheck-suppress uninitvar
(void)std::isgreater(f1,f2);
double d1,d2;
// cppcheck-suppress uninitvar
(void)std::isgreater(d1,d2);
long double ld1,ld2;
// cppcheck-suppress uninitvar
(void)std::isgreater(ld1,ld2);
}
void bool_isgreaterequal(float f1, float f2)
{
// cppcheck-suppress compareBoolExpressionWithInt
// cppcheck-suppress compareValueOutOfTypeRangeError
// cppcheck-suppress knownConditionTrueFalse
if (std::isgreaterequal(f1, f2)==123) {}
}
void uninitvar_isgreaterequal(void)
{
float f1,f2;
// cppcheck-suppress uninitvar
(void)std::isgreaterequal(f1,f2);
double d1,d2;
// cppcheck-suppress uninitvar
(void)std::isgreaterequal(d1,d2);
long double ld1,ld2;
// cppcheck-suppress uninitvar
(void)std::isgreaterequal(ld1,ld2);
}
void bool_isinf(float f)
{
// cppcheck-suppress compareBoolExpressionWithInt
// cppcheck-suppress compareValueOutOfTypeRangeError
// cppcheck-suppress knownConditionTrueFalse
if (std::isinf(f)==123) {}
}
void uninitvar_isinf(void)
{
double d;
// cppcheck-suppress uninitvar
(void)std::isinf(d);
}
void uninitvar_logb(void)
{
float f;
// cppcheck-suppress uninitvar
(void)std::logbf(f);
double d;
// cppcheck-suppress uninitvar
(void)std::logb(d);
long double ld;
// cppcheck-suppress uninitvar
(void)std::logbl(ld);
}
void uninitvar_isless(void)
{
float f1,f2;
// cppcheck-suppress uninitvar
(void)std::isless(f1,f2);
double d1,d2;
// cppcheck-suppress uninitvar
(void)std::isless(d1,d2);
long double ld1,ld2;
// cppcheck-suppress uninitvar
(void)std::isless(ld1,ld2);
}
void uninitvar_islessequal(void)
{
float f1,f2;
// cppcheck-suppress uninitvar
(void)std::islessequal(f1,f2);
double d1,d2;
// cppcheck-suppress uninitvar
(void)std::islessequal(d1,d2);
long double ld1,ld2;
// cppcheck-suppress uninitvar
(void)std::islessequal(ld1,ld2);
}
void uninitvar_islessgreater(void)
{
float f1,f2;
// cppcheck-suppress uninitvar
(void)std::islessgreater(f1,f2);
double d1,d2;
// cppcheck-suppress uninitvar
(void)std::islessgreater(d1,d2);
long double ld1,ld2;
// cppcheck-suppress uninitvar
(void)std::islessgreater(ld1,ld2);
}
void uninitvar_nan(void)
{
const char *tagp1, *tagp2, *tagp3;
// cppcheck-suppress uninitvar
(void)std::nanf(tagp1);
// cppcheck-suppress uninitvar
(void)std::nan(tagp2);
// cppcheck-suppress uninitvar
(void)std::nanl(tagp3);
}
void uninitvar_isnan(void)
{
double d;
// cppcheck-suppress uninitvar
(void)std::isnan(d);
}
void uninitvar_isnormal(void)
{
double d;
// cppcheck-suppress uninitvar
(void)std::isnormal(d);
}
void uninitvar_isunordered(void)
{
double d1,d2;
// cppcheck-suppress uninitvar
(void)std::isunordered(d1,d2);
}
void uninitvar_ilogb(void)
{
float f;
// cppcheck-suppress uninitvar
(void)std::ilogb(f);
double d;
// cppcheck-suppress uninitvar
(void)std::ilogb(d);
long double ld;
// cppcheck-suppress uninitvar
(void)std::ilogb(ld);
}
void uninitvar_log10(void)
{
float f;
// cppcheck-suppress uninitvar
(void)std::log10(f);
double d;
// cppcheck-suppress uninitvar
(void)std::log10(d);
long double ld;
// cppcheck-suppress uninitvar
(void)std::log10(ld);
}
void uninitvar_log1p(void)
{
float f;
// cppcheck-suppress uninitvar
(void)std::log1pf(f);
double d;
// cppcheck-suppress uninitvar
(void)std::log1p(d);
long double ld;
// cppcheck-suppress uninitvar
(void)std::log1pl(ld);
}
void uninitvar_log2(void)
{
float f;
// cppcheck-suppress uninitvar
(void)std::log2f(f);
double d;
// cppcheck-suppress uninitvar
(void)std::log2(d);
long double ld;
// cppcheck-suppress uninitvar
(void)std::log2l(ld);
}
void uninitvar_nearbyint(void)
{
float f;
// cppcheck-suppress uninitvar
(void)std::nearbyintf(f);
double d;
// cppcheck-suppress uninitvar
(void)std::nearbyint(d);
long double ld;
// cppcheck-suppress uninitvar
(void)std::nearbyintl(ld);
}
void uninitvar_nextafter(void)
{
float f1,f2;
// cppcheck-suppress uninitvar
(void)std::nextafterf(f1,f2);
double d1,d2;
// cppcheck-suppress uninitvar
(void)std::nextafter(d1,d2);
long double ld1,ld2;
// cppcheck-suppress uninitvar
(void)std::nextafterl(ld1,ld2);
}
void uninitvar_nexttoward(void)
{
float f1,f2;
// cppcheck-suppress uninitvar
(void)std::nexttowardf(f1,f2);
double d1,d2;
// cppcheck-suppress uninitvar
(void)std::nexttoward(d1,d2);
long double ld1,ld2;
// cppcheck-suppress uninitvar
(void)std::nexttowardl(ld1,ld2);
}
void uninitvar_longjmp(void)
{
jmp_buf env;
int val;
// cppcheck-suppress uninitvar
(void)std::longjmp(env,val);
}
void uninitvar_malloc(void)
{
size_t size;
// cppcheck-suppress [uninitvar, cstyleCast, unusedAllocatedMemory]
int *p = (int*)std::malloc(size);
free(p);
}
void uninitvar_memchr(void)
{
void *cs;
int c;
size_t n;
// cppcheck-suppress uninitvar
(void)std::memchr(cs,c,n);
}
void uninitvar_wmemchr(void)
{
wchar_t *cs;
wchar_t c;
size_t n;
// cppcheck-suppress uninitvar
(void)std::wmemchr(cs,c,n);
}
void uninitvar_memcmp(void)
{
const void *s1;
const void *s2;
size_t n;
// cppcheck-suppress uninitvar
(void)std::memcmp(s1,s2,n);
}
void uninitvar_wmemcmp(void)
{
const wchar_t *s1;
const wchar_t *s2;
size_t n;
// cppcheck-suppress uninitvar
(void)std::wmemcmp(s1,s2,n);
}
void uninitvar_memcpy(void)
{
void *ct;
const void *cs;
size_t n;
// cppcheck-suppress uninitvar
(void)std::memcpy(ct,cs,n);
}
void uninitvar_wmemcpy(void)
{
wchar_t *cs;
const wchar_t *c;
size_t n;
// cppcheck-suppress uninitvar
(void)std::wmemcpy(cs,c,n);
}
void uninitvar_memmove(void)
{
void *ct;
const void *cs;
size_t n;
// cppcheck-suppress uninitvar
(void)std::memmove(ct,cs,n);
}
void uninitvar_wmemmove(void)
{
wchar_t *cs;
wchar_t *c;
size_t n;
// cppcheck-suppress uninitvar
(void)std::wmemmove(cs,c,n);
}
void uninitvar_memset(void)
{
void *s;
int c;
size_t n;
// cppcheck-suppress uninitvar
(void)std::memset(s,c,n);
}
void uninitvar_wmemset(void)
{
wchar_t *cs;
wchar_t c;
size_t n;
// cppcheck-suppress uninitvar
(void)std::wmemset(cs,c,n);
}
void uninitvar_mktime(void)
{
struct tm *tp;
// cppcheck-suppress uninitvar
(void)std::mktime(tp);
}
void uninivar_modf(void)
{
float f1;
float *f2;
// cppcheck-suppress uninitvar
(void)std::modf(f1,f2);
double d1;
double *d2;
// cppcheck-suppress uninitvar
(void)std::modf(d1,d2);
long double ld1;
long double *ld2;
// cppcheck-suppress uninitvar
(void)std::modf(ld1,ld2);
}
void uninivar_perror(void)
{
const char *string;
// cppcheck-suppress uninitvar
(void)std::perror(string);
}
void uninitvar_pow(void)
{
float f1,f2;
// cppcheck-suppress uninitvar
(void)std::pow(f1,f2);
double d1,d2;
// cppcheck-suppress uninitvar
(void)std::pow(d1,d2);
long double ld1,ld2;
// cppcheck-suppress uninitvar
(void)std::pow(ld1,ld2);
}
void uninitvar_remainder(void)
{
float f1,f2;
// cppcheck-suppress uninitvar
(void)std::remainderf(f1,f2);
double d1,d2;
// cppcheck-suppress uninitvar
(void)std::remainder(d1,d2);
long double ld1,ld2;
// cppcheck-suppress uninitvar
(void)std::remainderl(ld1,ld2);
}
void uninitvar_remquo(void)
{
float f1,f2;
int *i1;
// cppcheck-suppress uninitvar
(void)std::remquof(f1,f2,i1);
double d1,d2;
int *i2;
// cppcheck-suppress uninitvar
(void)std::remquo(d1,d2,i2);
long double ld1,ld2;
int *i3;
// cppcheck-suppress uninitvar
(void)std::remquol(ld1,ld2,i3);
}
void uninivar_printf(const char *Format, int Argument)
{
const char * format_1, * format_2, * format_3;
int argument1, argument2;
// no warning is expected
(void)std::printf("x");
// cppcheck-suppress uninitvar
(void)std::printf(format_1,argument1);
// cppcheck-suppress uninitvar
(void)std::printf(Format,argument2);
// cppcheck-suppress uninitvar
(void)std::printf(format_2,Argument);
// cppcheck-suppress uninitvar
(void)std::printf(format_3,1);
// no warning is expected
(void)std::printf(Format,Argument);
}
void uninivar_vprintf(const char *Format, va_list Arg)
{
const char * format1, *format2;
va_list arg;
// cppcheck-suppress va_list_usedBeforeStarted
// cppcheck-suppress uninitvar
(void)std::vprintf(format1,arg);
// cppcheck-suppress uninitvar
(void)std::vprintf(format2,Arg);
// no warning is expected
(void)std::vprintf(Format,Arg);
// cppcheck-suppress va_list_usedBeforeStarted
(void)std::vprintf(Format,arg);
}
void uninivar_vwprintf(const wchar_t *Format, va_list Arg)
{
const wchar_t * format1, *format2;
va_list arg;
// cppcheck-suppress va_list_usedBeforeStarted
// cppcheck-suppress uninitvar
(void)std::vwprintf(format1,arg);
// cppcheck-suppress uninitvar
(void)std::vwprintf(format2,Arg);
// no warning is expected
(void)std::vwprintf(Format,Arg);
// cppcheck-suppress va_list_usedBeforeStarted
(void)std::vwprintf(Format,arg);
}
void uninivar_bsearch(void)
{
const void* key;
const void* base;
size_t num;
size_t size;
// cppcheck-suppress [uninitvar, cstyleCast]
(void)std::bsearch(key,base,num,size,(int (*)(const void*,const void*))strcmp);
}
void minsize_bsearch(const void* key, const void* base,
size_t num, size_t size,
int (*compar)(const void*,const void*))
{
const int Base[3] = {42, 43, 44};
(void)std::bsearch(key,Base,2,size,(int (*)(const void*,const void*))strcmp); // cppcheck-suppress cstyleCast
(void)std::bsearch(key,Base,3,size,(int (*)(const void*,const void*))strcmp); // cppcheck-suppress cstyleCast
(void)std::bsearch(key,Base,4,size,(int (*)(const void*,const void*))strcmp); // cppcheck-suppress cstyleCast
(void)std::bsearch(key,base,2,size,(int (*)(const void*,const void*))strcmp); // cppcheck-suppress cstyleCast
}
void uninitvar_qsort(void)
{
void *base;
size_t n;
size_t size;
// cppcheck-suppress uninitvar
(void)std::qsort(base,n,size, (int (*)(const void*,const void*))strcmp); // cppcheck-suppress cstyleCast
}
void uninitvar_stable_sort(std::vector<int>& v)
{
std::vector<int>::iterator end;
// cppcheck-suppress uninitvar
std::stable_sort(v.begin(), end);
}
void uninitvar_merge(const std::vector<int>& a, const std::vector<int>& b)
{
std::vector<int>::iterator dst;
// cppcheck-suppress uninitvar
std::merge(a.begin(), a.end(), b.begin(), b.end(), dst);
}
void uninitvar_push_heap(std::vector<int>& v)
{
std::vector<int>::iterator end;
// cppcheck-suppress uninitvar
std::push_heap(v.begin(), end);
}
void uninitvar_copy_n(const std::vector<int>& v)
{
std::vector<int>::iterator dst;
// cppcheck-suppress [uninitvar, invalidFunctionArg]
std::copy_n(v.begin(), -1, dst);
}
void uninitvar_iota(std::vector<int>& v)
{
int i;
// cppcheck-suppress uninitvar
std::iota(v.begin(), v.end(), i);
}
void uninitvar_putc(void)
{
int c;
FILE *stream;
// cppcheck-suppress uninitvar
(void)std::putc(c,stream);
}
void uninitvar_putwc(void)
{
wchar_t c;
FILE *stream;
// cppcheck-suppress uninitvar
(void)std::putc(c,stream);
}
void uninitvar_putchar(void)
{
int c;
// cppcheck-suppress uninitvar
(void)std::putchar(c);
}
void uninitvar_putwchar(void)
{
wchar_t c;
// cppcheck-suppress uninitvar
(void)std::putwchar(c);
}
void uninitvar_puts(void)
{
const char *s;
// cppcheck-suppress uninitvar
(void)std::puts(s);
}
void uninitvar_realloc(void)
{
void *block;
size_t newsize;
// cppcheck-suppress uninitvar
void *p = std::realloc(block, newsize);
free(p);
}
void uninitvar_remove(void)
{
const char *s;
// cppcheck-suppress uninitvar
(void)std::remove(s);
}
void uninitvar_rename(void)
{
const char *s1;
const char *s2;
// cppcheck-suppress uninitvar
(void)std::rename(s1,s2);
}
void uninitvar_rewind(void)
{
FILE *f;
// cppcheck-suppress uninitvar
(void)std::rewind(f);
}
void uninitvar_round(void)
{
float f;
// cppcheck-suppress uninitvar
(void)std::roundf(f);
double d;
// cppcheck-suppress uninitvar
(void)std::round(d);
long double ld;
// cppcheck-suppress uninitvar
(void)std::roundl(ld);
}
void uninivar_scalbn(void)
{
float f;
int i1;
// cppcheck-suppress uninitvar
(void)std::scalbnf(f,i1);
double d;
int i2;
// cppcheck-suppress uninitvar
(void)std::scalbn(d,i2);
long double ld;
int i3;
// cppcheck-suppress uninitvar
(void)std::scalbnl(ld,i3);
}
void uninivar_scalbln(void)
{
float f;
long int i1;
// cppcheck-suppress uninitvar
(void)std::scalblnf(f,i1);
double d;
long int i2;
// cppcheck-suppress uninitvar
(void)std::scalbln(d,i2);
long double ld;
long int i3;
// cppcheck-suppress uninitvar
(void)std::scalblnl(ld,i3);
}
void uninitvar_signbit(void)
{
double d;
// cppcheck-suppress uninitvar
(void)std::signbit(d);
}
void uninivar_signal(void)
{
int i;
// cppcheck-suppress uninitvar
std::signal(i, exit);
}
void uninivar_raise(void)
{
int i;
// cppcheck-suppress uninitvar
(void)std::raise(i);
}
void uninivar_scanf(void)
{
const char *format;
char str[42];
// cppcheck-suppress uninitvar
(void)std::scanf(format, str);
}
void uninivar_vsscanf(void)
{
const char *s;
const char *format;
va_list arg;
// cppcheck-suppress va_list_usedBeforeStarted
// cppcheck-suppress uninitvar
(void)std::vsscanf(s,format,arg);
}
void uninivar_vswscanf(void)
{
const wchar_t *s;
const wchar_t *format;
va_list arg;
// cppcheck-suppress va_list_usedBeforeStarted
// cppcheck-suppress uninitvar
(void)std::vswscanf(s,format,arg);
}
void uninivar_vscanf(void)
{
const char *format;
va_list arg;
// cppcheck-suppress va_list_usedBeforeStarted
// cppcheck-suppress uninitvar
(void)std::vscanf(format,arg);
}
void uninivar_vwscanf(void)
{
const wchar_t *format;
va_list arg;
// cppcheck-suppress va_list_usedBeforeStarted
// cppcheck-suppress uninitvar
(void)std::vwscanf(format,arg);
}
void uninivar_setbuf(void)
{
FILE *stream;
char *buf;
// cppcheck-suppress uninitvar
(void)std::setbuf(stream,buf);
}
void nullPointer_setbuf(FILE *stream, char *buf)
{
// cppcheck-suppress nullPointer
std::setbuf(NULL,buf);
std::setbuf(stream,NULL);
std::setbuf(stream,buf);
}
int bufferAccessOutOfBounds_setvbuf(FILE* stream, int mode, size_t size)
{
char buf[42]={0};
// cppcheck-suppress bufferAccessOutOfBounds
(void) std::setvbuf(stream, buf, mode, 43);
return std::setvbuf(stream, buf, mode, 42);
}
int nullPointer_setvbuf(FILE* stream, char *buf, int mode, size_t size)
{
// cppcheck-suppress nullPointer
(void) std::setvbuf(NULL, buf, mode, size);
(void) std::setvbuf(stream, NULL, mode, size);
return std::setvbuf(stream, buf, mode, size);
}
void uninivar_setvbuf(void)
{
FILE *stream;
char *buf;
int mode;
size_t size;
// cppcheck-suppress uninitvar
(void)std::setvbuf(stream,buf,mode,size);
}
void uninitvar_strcat(char *dest, const char * const source)
{
char *deststr1, *deststr2;
const char *srcstr1, *srcstr2;
// cppcheck-suppress uninitvar
(void)std::strcat(deststr1,srcstr1);
// cppcheck-suppress uninitvar
(void)std::strcat(dest,srcstr2);
// cppcheck-suppress uninitvar
(void)std::strcat(deststr2,source);
// no warning shall be shown for
(void)std::strcat(dest,source);
}
void uninitvar_wcscat(wchar_t *dest, const wchar_t * const source)
{
wchar_t *deststr_1, *deststr_2;
const wchar_t *srcstr1, *srcstr2;
// cppcheck-suppress uninitvar
(void)std::wcscat(deststr_1,srcstr1);
// cppcheck-suppress uninitvar
(void)std::wcscat(dest,srcstr2);
// cppcheck-suppress uninitvar
(void)std::wcscat(deststr_2,source);
// no warning shall be shown for
(void)std::wcscat(dest,source);
}
void uninivar_wcrtomb(void)
{
char *s;
wchar_t wc;
mbstate_t *ps;
// cppcheck-suppress uninitvar
(void)std::wcrtomb(s,wc,ps);
}
void uninivar_strchr(void)
{
const char *cs;
int c;
// cppcheck-suppress uninitvar
(void)std::strchr(cs,c);
}
void uninivar_wcschr(void)
{
const wchar_t *cs;
wchar_t c;
// cppcheck-suppress uninitvar
(void)std::wcschr(cs,c);
}
void uninivar_strcmp(void)
{
const char *str1;
const char *str2;
// cppcheck-suppress uninitvar
(void)std::strcmp(str1,str2);
}
void uninivar_wcscmp(void)
{
const wchar_t *str1;
const wchar_t *str2;
// cppcheck-suppress uninitvar
(void)std::wcscmp(str1,str2);
}
void uninivar_strcpy(void)
{
char *str1;
const char *str2;
// cppcheck-suppress uninitvar
(void)std::strcpy(str1,str2);
}
void uninivar_wcscpy(void)
{
wchar_t *str1;
const wchar_t *str2;
// cppcheck-suppress uninitvar
(void)std::wcscpy(str1,str2);
}
void uninivar_strftime(void)
{
char *s;
size_t max;
const char *fmt;
const struct tm *p;
// cppcheck-suppress uninitvar
(void)std::strftime(s,max,fmt,p);
}
void uninivar_strlen(void)
{
const char *s;
// cppcheck-suppress uninitvar
(void)std::strlen(s);
}
void uninivar_wcslen(void)
{
const wchar_t *s;
// cppcheck-suppress uninitvar
(void)std::wcslen(s);
}
void uninivar_strncpy(void)
{
char *s;
const char *ct;
size_t n;
// cppcheck-suppress uninitvar
(void)std::strncpy(s,ct,n);
}
void uninivar_strpbrk(void)
{
const char *cs;
const char *ct;
// cppcheck-suppress uninitvar
(void)std::strpbrk(cs,ct);
}
void uninivar_strncat(char *Ct, const char *S, size_t N)
{
char *ct_1, *ct_2;
const char *s1, *s2;
size_t n1, n2;
// cppcheck-suppress uninitvar
(void)std::strncat(ct_1,s1,n1);
// cppcheck-suppress uninitvar
(void)std::strncat(ct_2,S,N);
// cppcheck-suppress uninitvar
(void)std::strncat(Ct,s2,N);
// cppcheck-suppress uninitvar
(void)std::strncat(Ct,S,n2);
// no warning is expected for
(void)std::strncat(Ct,S,N);
}
void uninivar_wcsncat(wchar_t *Ct, const wchar_t *S, size_t N)
{
wchar_t *ct_1, *ct_2;
const wchar_t *s1, *s2;
size_t n1, n2;
// cppcheck-suppress uninitvar
(void)std::wcsncat(ct_1,s1,n1);
// cppcheck-suppress uninitvar
(void)std::wcsncat(ct_2,S,N);
// cppcheck-suppress uninitvar
(void)std::wcsncat(Ct,s2,N);
// cppcheck-suppress uninitvar
(void)std::wcsncat(Ct,S,n2);
// no warning is expected for
(void)std::wcsncat(Ct,S,N);
}
void uninivar_strncmp(const char *Ct, const char *S, size_t N)
{
const char *ct1, *ct2;
const char *s1, *s2;
size_t n1, n2;
// cppcheck-suppress uninitvar
(void)std::strncmp(ct1,s1,n1);
// cppcheck-suppress uninitvar
(void)std::strncmp(ct2,S,N);
// cppcheck-suppress uninitvar
(void)std::strncmp(Ct,s2,N);
// cppcheck-suppress uninitvar
(void)std::strncmp(Ct,S,n2);
// no warning is expected for
(void)std::strncmp(Ct,S,N);
}
void uninivar_wcsncmp(const wchar_t *Ct, const wchar_t *S, size_t N)
{
const wchar_t *ct1, *ct2;
const wchar_t *s1, *s2;
size_t n1, n2;
// cppcheck-suppress uninitvar
(void)std::wcsncmp(ct1,s1,n1);
// cppcheck-suppress uninitvar
(void)std::wcsncmp(ct2,S,N);
// cppcheck-suppress uninitvar
(void)std::wcsncmp(Ct,s2,N);
// cppcheck-suppress uninitvar
(void)std::wcsncmp(Ct,S,n2);
// no warning is expected for
(void)std::wcsncmp(Ct,S,N);
}
void uninivar_strstr(void)
{
char *cs;
const char *ct;
// cppcheck-suppress uninitvar
(void)std::strstr(cs,ct);
}
void uninivar_wcsstr(void)
{
wchar_t *cs;
const wchar_t *ct;
// cppcheck-suppress uninitvar
(void)std::wcsstr(cs,ct);
}
void uninivar_strspn(void)
{
const char *cs;
const char *ct;
// cppcheck-suppress uninitvar
(void)std::strspn(cs,ct);
}
void uninivar_strxfrm(void)
{
char *ds;
const char *ss;
size_t n;
// cppcheck-suppress uninitvar
(void)std::strxfrm(ds,ss,n);
}
void uninivar_wcsxfrm(void)
{
wchar_t *ds;
const wchar_t *ss;
size_t n;
// cppcheck-suppress uninitvar
(void)std::wcsxfrm(ds,ss,n);
}
void uninivar_wcsspn(void)
{
const wchar_t *ds;
const wchar_t *ss;
// cppcheck-suppress uninitvar
(void)std::wcsspn(ds,ss);
}
void uninivar_setlocale(void)
{
int category;
const char* locale;
// cppcheck-suppress uninitvar
(void)std::setlocale(category,locale);
}
void uninivar_strerror(void)
{
int i;
// cppcheck-suppress uninitvar
(void)std::strerror(i);
}
void uninivar_strcspn(void)
{
const char *cs;
const char *ct;
// cppcheck-suppress uninitvar
(void)std::strcspn(cs,ct);
}
void uninivar_wcscspn(void)
{
const wchar_t *cs;
const wchar_t *ct;
// cppcheck-suppress uninitvar
(void)std::wcscspn(cs,ct);
}
void uninivar_wcspbrk(void)
{
const wchar_t *cs;
const wchar_t *ct;
// cppcheck-suppress uninitvar
(void)std::wcspbrk(cs,ct);
}
void uninivar_wcsncpy(void)
{
wchar_t *cs;
const wchar_t *ct;
size_t n;
// cppcheck-suppress uninitvar
(void)std::wcsncpy(cs,ct,n);
}
void uninivar_strcoll(void)
{
const char *cs;
const char *ct;
// cppcheck-suppress uninitvar
(void)std::strcoll(cs,ct);
}
void uninivar_wcscoll(void)
{
const wchar_t *cs;
const wchar_t *ct;
// cppcheck-suppress uninitvar
(void)std::wcscoll(cs,ct);
}
void uninivar_strrchr(void)
{
const char * str;
int c;
// cppcheck-suppress uninitvar
(void)std::strrchr(str,c);
}
void uninivar_wcsrchr(void)
{
wchar_t* ws;
wchar_t wc;
// cppcheck-suppress uninitvar
(void)std::wcsrchr(ws,wc);
}
void uninivar_wcsrtombs(void)
{
char *dst;
const wchar_t * p;;
size_t len;
mbstate_t *ps;
// cppcheck-suppress uninitvar
(void)std::wcsrtombs(dst,&p,len,ps);
}
void uninivar_strtok(void)
{
char *s;
const char *ct;
// cppcheck-suppress uninitvar
(void)std::strtok(s,ct);
}
void uninivar_strtoimax(void)
{
const char *s1, *s2;
char **endp1, **endp2;
int base1, base2;
// cppcheck-suppress uninitvar
(void)std::strtoimax(s1,endp1,base1);
// cppcheck-suppress uninitvar
(void)std::strtoumax(s2,endp2,base2);
}
void uninivar_strtof(void)
{
const char *s1, *s2, *s3;
char **endp1, **endp2, **endp3;
// cppcheck-suppress uninitvar
(void)std::strtof(s1,endp1);
// cppcheck-suppress uninitvar
(void)std::strtod(s2,endp2);
// cppcheck-suppress uninitvar
(void)std::strtold(s3,endp3);
}
void uninivar_strtol(void)
{
const char *s1,*s2,*s3,*s4,*s5,*s6,*s7,*s8;
char **endp1, **endp2, **endp3, **endp4, **endp5, **endp6, **endp7, **endp8;
int base1, base2, base3, base4, base5, base6, base7, base8;
// cppcheck-suppress uninitvar
(void)std::strtol(s1,endp1,base1);
// cppcheck-suppress uninitvar
(void)std::strtoll(s2,endp2,base2);
// cppcheck-suppress uninitvar
(void)std::strtoul(s3,endp3,base3);
// cppcheck-suppress uninitvar
(void)std::strtoull(s4,endp4,base4);
// cppcheck-suppress uninitvar
(void)std::strtoimax(s5,endp5,base5);
// cppcheck-suppress uninitvar
(void)strtoimax(s6,endp6,base6);
// cppcheck-suppress uninitvar
(void)std::strtoumax(s7,endp7,base7);
// cppcheck-suppress uninitvar
(void)strtoumax(s8,endp8,base8);
}
void uninitvar_time(void)
{
time_t *tp;
// cppcheck-suppress uninitvar
(void)std::time(tp);
}
void uninitvar_tmpnam(void)
{
char *s;
// cppcheck-suppress uninitvar
(void)std::tmpnam(s);
}
void uninivar_tolower(void)
{
int c;
// cppcheck-suppress uninitvar
(void)std::tolower(c);
}
void uninivar_toupper(void)
{
int c;
// cppcheck-suppress uninitvar
(void)std::toupper(c);
}
void uninivar_wcstof(void)
{
const wchar_t *s1, *s2, *s3;
wchar_t **endp1, **endp2, **endp3;
// cppcheck-suppress uninitvar
(void)std::wcstof(s1,endp1);
// cppcheck-suppress uninitvar
(void)std::wcstod(s2,endp2);
// cppcheck-suppress uninitvar
(void)std::wcstold(s3,endp3);
}
void uninivar_stoX(void)
{
std::string str;
std::wstring wstr;
size_t* idx1;
size_t* idx2;
size_t* idx3;
size_t* idx4;
size_t* idx5;
size_t* idx6;
size_t* idx7;
size_t* idx8;
size_t* idx9;
size_t* idx10;
size_t* idx11;
size_t* idx12;
size_t* idx13;
size_t* idx14;
size_t* idx15;
size_t* idx16;
// cppcheck-suppress uninitvar
(void)std::stod(str,idx1);
// cppcheck-suppress uninitvar
(void)std::stod(wstr,idx2);
// cppcheck-suppress uninitvar
(void)std::stof(str,idx3);
// cppcheck-suppress uninitvar
(void)std::stof(wstr,idx4);
// cppcheck-suppress uninitvar
(void)std::stoi(str,idx5);
// cppcheck-suppress uninitvar
(void)std::stoi(wstr,idx6);
// cppcheck-suppress uninitvar
(void)std::stol(str,idx7);
// cppcheck-suppress uninitvar
(void)std::stol(wstr,idx8);
// cppcheck-suppress uninitvar
(void)std::stold(str,idx9);
// cppcheck-suppress uninitvar
(void)std::stold(wstr,idx10);
// cppcheck-suppress uninitvar
(void)std::stoll(str,idx11);
// cppcheck-suppress uninitvar
(void)std::stoll(wstr,idx12);
// cppcheck-suppress uninitvar
(void)std::stoul(str,idx13);
// cppcheck-suppress uninitvar
(void)std::stoul(wstr,idx14);
// cppcheck-suppress uninitvar
(void)std::stoull(str,idx15);
// cppcheck-suppress uninitvar
(void)std::stoull(wstr,idx16);
}
void uninivar_to_string(void)
{
int i;
long l;
long long ll;
unsigned u;
unsigned long ul;
unsigned long long ull;
float f;
double d;
long double ld;
// cppcheck-suppress uninitvar
(void)std::to_string(i);
// cppcheck-suppress uninitvar
(void)std::to_string(l);
// cppcheck-suppress uninitvar
(void)std::to_string(ll);
// cppcheck-suppress uninitvar
(void)std::to_string(u);
// cppcheck-suppress uninitvar
(void)std::to_string(ul);
// cppcheck-suppress uninitvar
(void)std::to_string(ull);
// cppcheck-suppress uninitvar
(void)std::to_string(f);
// cppcheck-suppress uninitvar
(void)std::to_string(d);
// cppcheck-suppress uninitvar
(void)std::to_string(ld);
}
void uninivar_to_wstring(void)
{
int i;
long l;
long long ll;
unsigned u;
unsigned long ul;
unsigned long long ull;
float f;
double d;
long double ld;
// cppcheck-suppress uninitvar
(void)std::to_wstring(i);
// cppcheck-suppress uninitvar
(void)std::to_wstring(l);
// cppcheck-suppress uninitvar
(void)std::to_wstring(ll);
// cppcheck-suppress uninitvar
(void)std::to_wstring(u);
// cppcheck-suppress uninitvar
(void)std::to_wstring(ul);
// cppcheck-suppress uninitvar
(void)std::to_wstring(ull);
// cppcheck-suppress uninitvar
(void)std::to_wstring(f);
// cppcheck-suppress uninitvar
(void)std::to_wstring(d);
// cppcheck-suppress uninitvar
(void)std::to_wstring(ld);
}
void uninivar_mbrtowc(void)
{
wchar_t* pwc;
const char* pmb;
size_t max;
mbstate_t* ps;
// cppcheck-suppress uninitvar
(void)std::mbrtowc(pwc,pmb,max,ps);
}
void uninivar_wcstok(void)
{
wchar_t *s;
const wchar_t *ct;
wchar_t **ptr;
// cppcheck-suppress uninitvar
(void)std::wcstok(s,ct,ptr);
}
void uninivar_wcstoimax(void)
{
const wchar_t *s1, *s2;
wchar_t ** endp1, **endp2;
int base1, base2;
// cppcheck-suppress uninitvar
(void)std::wcstoimax(s1,endp1,base1);
// cppcheck-suppress uninitvar
(void)std::wcstoumax(s2,endp2,base2);
}
void uninivar_wcstol(void)
{
const wchar_t *s1,*s2,*s3,*s4,*s5,*s6,*s7,*s8;
wchar_t **endp1, **endp2, **endp3, **endp4, **endp5, **endp6, **endp7, **endp8;
int base1, base2, base3, base4, base5, base6, base7, base8;
// cppcheck-suppress uninitvar
(void)std::wcstol(s1,endp1,base1);
// cppcheck-suppress uninitvar
(void)std::wcstoll(s2,endp2,base2);
// cppcheck-suppress uninitvar
(void)std::wcstoul(s3,endp3,base3);
// cppcheck-suppress uninitvar
(void)std::wcstoull(s4,endp4,base4);
// cppcheck-suppress uninitvar
(void)std::wcstoimax(s5,endp5,base5);
// cppcheck-suppress uninitvar
(void)wcstoimax(s6,endp6,base6);
// cppcheck-suppress uninitvar
(void)std::wcstoumax(s7,endp7,base7);
// cppcheck-suppress uninitvar
(void)wcstoumax(s8,endp8,base8);
}
void uninitvar_wprintf(const wchar_t *Format, int Argument)
{
const wchar_t *format1, *format2, *format3;
int argument1, argument2;
// cppcheck-suppress uninitvar
(void)std::wprintf(format1,argument1);
// cppcheck-suppress uninitvar
(void)std::wprintf(format2);
// cppcheck-suppress uninitvar
(void)std::wprintf(Format,argument2);
// cppcheck-suppress uninitvar
(void)std::wprintf(format3,Argument);
// no warning is expected
(void)std::wprintf(Format,Argument);
(void)std::wprintf(Format);
}
void uninitvar_sprintf(void)
{
char *s;
const char *format;
int i;
// cppcheck-suppress uninitvar
(void)std::sprintf(s,format,i);
}
void uninitvar_swprintf(void)
{
wchar_t *s;
size_t n;
const wchar_t *format;
// cppcheck-suppress uninitvar
(void)std::swprintf(s,n,format);
}
void uninitvar_vsprintf(void)
{
char *s;
const char *format;
va_list arg;
// cppcheck-suppress va_list_usedBeforeStarted
// cppcheck-suppress uninitvar
(void)std::vsprintf(s,format,arg);
}
void nullPointer_vsprintf(va_list arg,const char *format)
{
char *s = NULL;
(void)std::vsprintf(s,format,arg); // Its allowed to provide 's' as NULL pointer
// cppcheck-suppress nullPointer
(void)std::vsprintf(s,NULL,arg);
}
void uninitvar_vswprintf(void)
{
wchar_t *s;
size_t n;
const wchar_t *format;
va_list arg;
// cppcheck-suppress va_list_usedBeforeStarted
// cppcheck-suppress uninitvar
(void)std::vswprintf(s,n,format,arg);
}
void uninivar_fwprintf(void)
{
FILE* stream;
const wchar_t* format;
int i;
// cppcheck-suppress uninitvar
(void)std::fwprintf(stream,format,i);
}
void uninivar_snprintf(char *S, size_t N, const char *Format, int Int)
{
size_t n1, n2;
const char *format1, *format2;
int i1, i2;
char *s1, *s2;
// cppcheck-suppress uninitvar
(void)std::snprintf(s1,n1,format1,i1);
// cppcheck-suppress uninitvar
(void)std::snprintf(S,n2,Format,Int); // n is uninitialized
// cppcheck-suppress uninitvar
(void)std::snprintf(S,N,format2,Int); // format is uninitialized
// cppcheck-suppress uninitvar
(void)std::snprintf(S,N,Format,i2); // i is uninitialized
// cppcheck-suppress uninitvar
(void)std::snprintf(s2,N,Format,Int);
// no warning is expected for
(void)std::snprintf(S,N,Format,Int);
}
void uninivar_vsnprintf(char *S, size_t N, const char *Format, va_list Arg)
{
char *s1, *s2;
size_t n1, n2;
const char *format1, *format2;
va_list arg;
// cppcheck-suppress va_list_usedBeforeStarted
// cppcheck-suppress uninitvar
(void)std::vsnprintf(s1,n1,format1,arg);
// cppcheck-suppress uninitvar
(void)std::vsnprintf(s2,N,Format,Arg);
// cppcheck-suppress uninitvar
(void)std::vsnprintf(S,n2,Format,Arg);
// cppcheck-suppress uninitvar
(void)std::vsnprintf(S,N,format2,Arg);
// no warning is expected for
(void)std::vsnprintf(S,N,Format,Arg);
// cppcheck-suppress va_list_usedBeforeStarted
(void)std::vsnprintf(S,N,Format,arg);
}
void uninivar_wscanf(void)
{
const wchar_t *format1, *format2;
int i;
// cppcheck-suppress uninitvar
(void)std::wscanf(format1);
// cppcheck-suppress uninitvar
(void)std::wscanf(format2,&i);
}
void uninivar_sscanf(void)
{
const char *string1, *string2;
const char * format;
int i;
// cppcheck-suppress uninitvar
(void)std::sscanf(string1,format);
// cppcheck-suppress uninitvar
(void)std::sscanf(string2,format,&i);
}
void uninivar_fwscanf(void)
{
FILE* stream;
const wchar_t* format1, *format2;
int i;
// cppcheck-suppress uninitvar
(void)std::fwscanf(stream,format1);
// cppcheck-suppress uninitvar
(void)std::fwscanf(stream,format2,&i);
}
void uninivar_swscanf(void)
{
const wchar_t* s;
const wchar_t* format1, *format2;
int i;
// cppcheck-suppress uninitvar
(void)std::swscanf(s,format1);
// cppcheck-suppress uninitvar
(void)std::swscanf(s,format2,&i);
}
void uninitvar_system(void)
{
const char *c;
// cppcheck-suppress uninitvar
(void)std::system(c);
}
#ifndef __STDC_NO_THREADS__
void nullPointer_mtx_destroy(mtx_t *mutex )
{
// cppcheck-suppress nullPointer
mtx_destroy(nullptr);
mtx_destroy(mutex);
}
void nullPointer_mtx_lock( mtx_t *mutex )
{
// cppcheck-suppress nullPointer
mtx_lock(nullptr);
mtx_lock(mutex);
}
void nullPointer_mtx_trylock( mtx_t *mutex )
{
// cppcheck-suppress nullPointer
mtx_trylock(nullptr);
mtx_trylock(mutex);
}
int nullPointer_mtx_timedlock( mtx_t *mutex, const struct timespec *time_point )
{
// cppcheck-suppress nullPointer
(void) mtx_timedlock(nullptr, time_point);
// cppcheck-suppress nullPointer
(void) mtx_timedlock(mutex, nullptr);
return mtx_timedlock(mutex, time_point);
}
#endif
void nullPointer_system(const char *c)
{
// If a null pointer is given, command processor is checked for existence
(void)std::system(NULL);
(void)std::system(c);
}
void uninitvar_setw(void)
{
int i;
// cppcheck-suppress [uninitvar,valueFlowBailoutIncompleteVar]
std::cout << std::setw(i);
}
void uninitvar_setiosflags(void)
{
std::ios_base::fmtflags mask;
// TODO cppcheck-suppress uninitvar
// cppcheck-suppress valueFlowBailoutIncompleteVar
std::cout << std::setiosflags(mask); // #6987 - false negative
}
void uninitvar_resetiosflags(void)
{
std::ios_base::fmtflags mask;
// TODO cppcheck-suppress uninitvar
// cppcheck-suppress valueFlowBailoutIncompleteVar
std::cout << std::resetiosflags(mask); // #6987 - false negative
}
void uninitvar_setfill(void)
{
char c;
// cppcheck-suppress [uninitvar,valueFlowBailoutIncompleteVar]
std::cout << std::setfill(c);
wchar_t wc;
// cppcheck-suppress uninitvar
std::wcout << std::setfill(wc);
}
void uninitvar_setprecision(void)
{
int p;
// cppcheck-suppress [uninitvar,valueFlowBailoutIncompleteVar]
std::cout << std::setprecision(p);
}
void uninitvar_setbase(void)
{
int p;
// cppcheck-suppress [uninitvar,valueFlowBailoutIncompleteVar]
std::cout << std::setbase(p);
}
// cppcheck-suppress passedByValue
void uninitvar_find(std::string s)
{
// testing of size_t find (const string& str, size_t pos = 0)
size_t pos1, pos2, pos3, pos4, pos5, pos6, pos7;
// cppcheck-suppress uninitvar
(void)s.find("find",pos1); // #6991
// testing of size_t find (const char* s, size_t pos = 0) const;
char *pc, *pc2;
// cppcheck-suppress uninitvar
(void)s.find(pc,0);
// cppcheck-suppress uninitvar
(void)s.find(pc,pos2);
// cppcheck-suppress uninitvar
(void)s.find("test",pos3);
// testing of size_t find (char c, size_t pos = 0) const;
char c;
// cppcheck-suppress uninitvar
(void)s.find(c,pos4);
// testing of size_t find (const char* pc, size_t pos, size_t n) const;
size_t n1,n2,n3;
// cppcheck-suppress uninitvar
(void)s.find(pc,pos5,n1); // #6991
// cppcheck-suppress uninitvar
(void)s.find("test",pos6,n2);
// cppcheck-suppress uninitvar
(void)s.find("test",1,n3);
// cppcheck-suppress uninitvar
(void)s.find("test",pos7,1);
// cppcheck-suppress uninitvar
(void)s.find(pc2,1,1);
}
void uninivar_ifstream_read(std::ifstream &f)
{
int size;
char buffer[10];
// cppcheck-suppress uninitvar
f.read(buffer, size);
}
void uninivar_istream_read(std::istream &f)
{
int size;
char buffer[10];
// cppcheck-suppress uninitvar
f.read(buffer, size);
}
void uninitvar_string_compare(const std::string &teststr, const std::wstring &testwstr)
{
const char *pStrUninit;
// cppcheck-suppress uninitvar
(void)teststr.compare(pStrUninit);
const wchar_t *pWStrUninit;
// cppcheck-suppress uninitvar
(void)testwstr.compare(pWStrUninit);
}
void invalidFunctionArgBool_abs(bool b, double x, double y)
{
// cppcheck-suppress invalidFunctionArgBool
(void)std::abs(true); // #6990
// cppcheck-suppress invalidFunctionArgBool
(void)std::abs(b); // #6990
// cppcheck-suppress invalidFunctionArgBool
(void)std::abs(x<y); // #5635
}
void ignoredReturnValue_abs(int i)
{
// cppcheck-suppress ignoredReturnValue
std::abs(i);
// cppcheck-suppress ignoredReturnValue
std::abs(-199);
}
// cppcheck-suppress passedByValue
void ignoredReturnValue_string_compare(std::string teststr, std::wstring testwstr)
{
// cppcheck-suppress ignoredReturnValue
teststr.compare("test");
// cppcheck-suppress ignoredReturnValue
testwstr.compare(L"wtest");
}
// cppcheck-suppress constParameterReference
void ignoredReturnValue_container_access(std::string& s, std::string_view& sv, std::vector<int>& v)
{
// cppcheck-suppress ignoredReturnValue
s.begin();
// cppcheck-suppress ignoredReturnValue
v.end();
// cppcheck-suppress ignoredReturnValue
sv.front();
// cppcheck-suppress ignoredReturnValue
s.at(0);
}
void ignoredReturnValue_locale_global(const std::locale& loc)
{
// no ignoredReturnValue shall be shown for
std::locale::global(loc);
}
void ignoredReturnValue_make_pair()
{
// cppcheck-suppress ignoredReturnValue
std::make_pair(1, 2);
}
void nullPointer_ifstream_read(std::ifstream &f)
{
// cppcheck-suppress nullPointer
f.read(NULL, 10);
}
void nullPointer_istream_read(std::istream &f)
{
// cppcheck-suppress nullPointer
f.read(NULL, 10);
}
std::size_t nullPointer_strxfrm(char *dest, const char *src, std::size_t count)
{
(void)strxfrm(dest, src, count);
// In case the 3rd argument is 0, the 1st argument is permitted to be a null pointer. (#6306)
(void)strxfrm(nullptr, src, 0);
(void)strxfrm(nullptr, src, 1);
(void)strxfrm(nullptr, src, count);
// cppcheck-suppress nullPointer
return strxfrm(dest, nullptr, count);
}
std::size_t nullPointer_wcsxfrm(wchar_t *dest, const wchar_t *src, std::size_t count)
{
(void)wcsxfrm(dest, src, count);
// In case the 3rd argument is 0, the 1st argument is permitted to be a null pointer. (#6306)
(void)wcsxfrm(nullptr, src, 0);
(void)wcsxfrm(nullptr, src, 1);
(void)wcsxfrm(nullptr, src, count);
// cppcheck-suppress nullPointer
return wcsxfrm(dest, nullptr, count);
}
void nullPointer_asctime(void)
{
const struct tm *tm = 0;
// cppcheck-suppress asctimeCalled
// cppcheck-suppress nullPointer
(void)std::asctime(tm);
// cppcheck-suppress asctimeCalled
// cppcheck-suppress nullPointer
(void)std::asctime(0);
}
void nullPointer_wcsftime(wchar_t* ptr, size_t maxsize, const wchar_t* format, const struct tm* timeptr)
{
// cppcheck-suppress nullPointer
(void)std::wcsftime(NULL, maxsize, format, timeptr);
// cppcheck-suppress nullPointer
(void)std::wcsftime(ptr, maxsize, NULL, timeptr);
// cppcheck-suppress nullPointer
(void)std::wcsftime(ptr, maxsize, format, NULL);
(void)std::wcsftime(ptr, maxsize, format, timeptr);
}
void nullPointer_fegetenv(void)
{
fenv_t* envp = 0;
// cppcheck-suppress nullPointer
(void)std::fegetenv(envp);
// cppcheck-suppress nullPointer
(void)std::fegetenv(0);
}
void nullPointer_fegetexceptflag(int expects)
{
fexcept_t* flagp = 0;
// cppcheck-suppress nullPointer
(void)std::fegetexceptflag(flagp,expects);
// cppcheck-suppress nullPointer
(void)std::fegetexceptflag(0,expects);
}
void nullPointer_feholdexcept(void)
{
fenv_t* envp = 0;
// cppcheck-suppress nullPointer
(void)std::feholdexcept(envp);
// cppcheck-suppress nullPointer
(void)std::feholdexcept(0);
}
void nullPointer_fesetenv(void)
{
const fenv_t* envp = 0;
// cppcheck-suppress nullPointer
(void)std::fesetenv(envp);
// cppcheck-suppress nullPointer
(void)std::fesetenv(0);
}
void nullPointer_fesetexceptflag(int expects)
{
const fexcept_t* flagp = 0;
// cppcheck-suppress nullPointer
(void)std::fesetexceptflag(flagp,expects);
// cppcheck-suppress nullPointer
(void)std::fesetexceptflag(0,expects);
}
void nullPointer_feupdateenv(void)
{
const fenv_t* envp = 0;
// cppcheck-suppress nullPointer
(void)std::feupdateenv(envp);
// cppcheck-suppress nullPointer
(void)std::feupdateenv(0);
}
void nullPointer_atexit(void)
{
// cppcheck-suppress nullPointer
(void)std::atexit(0);
}
void nullPointer_atof(void)
{
const char * c = 0;
// cppcheck-suppress nullPointer
(void)std::atof(c);
// cppcheck-suppress nullPointer
(void)std::atof(0);
}
void nullPointer_memcpy(void *s1, const void *s2, size_t n)
{
// cppcheck-suppress nullPointer
(void)std::memcpy(NULL,s2,n);
// cppcheck-suppress nullPointer
(void)std::memcpy(s1,NULL,n);
(void)std::memcpy(s1,s2,n);
}
void nullPointer_memmove(void *s1, void *s2, size_t n)
{
// cppcheck-suppress nullPointer
(void)std::memmove(NULL,s2,n);
// cppcheck-suppress nullPointer
(void)std::memmove(s1,NULL,n);
(void)std::memmove(s1,s2,n);
}
void nullPointer_wmemmove(wchar_t* s1, const wchar_t* s2, size_t n)
{
// cppcheck-suppress nullPointer
(void)std::wmemmove(NULL,s2,n);
// cppcheck-suppress nullPointer
(void)std::wmemmove(s1,NULL,n);
(void)std::wmemmove(s1,s2,n);
}
void nullPointer_wmemset(wchar_t* s, wchar_t c, size_t n)
{
// cppcheck-suppress nullPointer
(void)std::wmemset(NULL,c,n);
(void)std::wmemset(s,c,n);
}
///////////////////////////////////////////////////////////////////////
// <algorithm>
///////////////////////////////////////////////////////////////////////
#include <algorithm>
#include <list>
#define pred [] (int i) {return i==0;}
void stdalgorithm(const std::list<int> &ints1, const std::list<int> &ints2)
{
// <!-- InputIterator std::find(InputIterator first, InputIterator last, T val) -->
// cppcheck-suppress mismatchingContainers
// cppcheck-suppress ignoredReturnValue
std::find(ints1.begin(), ints2.end(), 123);
// cppcheck-suppress mismatchingContainers
if (std::find(ints1.begin(), ints1.end(), 123) == ints2.end()) {}
// #9455
std::list<int>::const_iterator uninitItBegin;
std::list<int>::const_iterator uninitItEnd;
// cppcheck-suppress uninitvar
if (std::find(uninitItBegin, uninitItEnd, 123) == uninitItEnd) {}
// <!-- InputIterator std::find_if(InputIterator first, InputIterator last, UnaryPredicate val) -->
// cppcheck-suppress mismatchingContainers
// cppcheck-suppress ignoredReturnValue
std::find_if(ints1.begin(), ints2.end(), pred);
// cppcheck-suppress mismatchingContainers
if (std::find_if(ints1.begin(), ints1.end(), pred) == ints2.end()) {}
// <!-- InputIterator std::find_if_not(InputIterator first, InputIterator last, UnaryPredicate val) -->
// cppcheck-suppress mismatchingContainers
// cppcheck-suppress ignoredReturnValue
std::find_if_not(ints1.begin(), ints2.end(), pred);
// cppcheck-suppress mismatchingContainers
if (std::find_if_not(ints1.begin(), ints1.end(), pred) == ints2.end()) {}
// <!-- bool std::all_of(InputIterator first, InputIterator last, UnaryPredicate pred) -->
// cppcheck-suppress mismatchingContainers
// cppcheck-suppress ignoredReturnValue
std::all_of(ints1.begin(), ints2.end(), pred);
// <!-- bool std::any_of(InputIterator first, InputIterator last, UnaryPredicate pred) -->
// cppcheck-suppress mismatchingContainers
// cppcheck-suppress ignoredReturnValue
std::any_of(ints1.begin(), ints2.end(), pred);
// <!-- bool std::none_of(InputIterator first, InputIterator last, UnaryPredicate pred) -->
// cppcheck-suppress mismatchingContainers
// cppcheck-suppress ignoredReturnValue
std::none_of(ints1.begin(), ints2.end(), pred);
// <!-- difference_type std::count(InputIterator first, InputIterator last, T val) -->
// cppcheck-suppress mismatchingContainers
// cppcheck-suppress ignoredReturnValue
std::count(ints1.begin(), ints2.end(), 123);
// <!-- difference_type std::count_if(InputIterator first, InputIterator last, UnaryPredicate val) -->
// cppcheck-suppress mismatchingContainers
// cppcheck-suppress ignoredReturnValue
std::count_if(ints1.begin(), ints2.end(), pred);
// <!-- Function std::for_each(InputIterator first, InputIterator last, Function func) -->
// cppcheck-suppress mismatchingContainers
std::for_each(ints1.begin(), ints2.end(), [](int i) {});
}
void getline()
{
// #837
std::ifstream in("test1.txt");
char cBuf[10];
// cppcheck-suppress bufferAccessOutOfBounds
in.getline(cBuf, 100);
// cppcheck-suppress bufferAccessOutOfBounds
in.read(cBuf, 100);
// cppcheck-suppress bufferAccessOutOfBounds
in.readsome(cBuf, 100);
// cppcheck-suppress bufferAccessOutOfBounds
in.get(cBuf, 100);
// cppcheck-suppress bufferAccessOutOfBounds
in.get(cBuf, 100, 'a');
// cppcheck-suppress bufferAccessOutOfBounds
in.getline(cBuf, 100, 'a');
in.close();
}
// cppcheck-suppress passedByValue
void stream_write(std::ofstream& s, std::vector<char> v) {
if (v.empty()) {}
s.write(v.data(), v.size());
}
void stdstring()
{
std::string s;
// cppcheck-suppress ignoredReturnValue
s.size();
// valid
s.assign("a");
#ifdef __cpp_lib_starts_ends_with
// cppcheck-suppress ignoredReturnValue
s.starts_with("abc");
#endif
}
void stdvector()
{
int uninit1, uninit2, uninit3;
std::vector<int> v;
// cppcheck-suppress ignoredReturnValue
v.size();
// cppcheck-suppress ignoredReturnValue
v.capacity();
// cppcheck-suppress uselessCallsEmpty
// cppcheck-suppress ignoredReturnValue
v.empty();
// cppcheck-suppress ignoredReturnValue
v.max_size();
// cppcheck-suppress uninitvar
v.push_back(uninit1);
// cppcheck-suppress uninitvar
v.reserve(uninit2);
// cppcheck-suppress invalidFunctionArg
v.reserve(-1);
// no warning is expected for capacity 0 as it simply has no effect
v.reserve(0);
// cppcheck-suppress uninitvar
v.resize(uninit3);
// cppcheck-suppress invalidFunctionArg
v.resize(-1);
v.clear();
v.shrink_to_fit();
// no warning is expected for pop_back()
v.push_back(42);
v.pop_back();
v.push_back(42);
// cppcheck-suppress ignoredReturnValue
v.back();
// cppcheck-suppress ignoredReturnValue
v.front();
}
void stdbind_helper(int a)
{
printf("%d", a);
}
void stdbind()
{
using namespace std::placeholders;
// TODO cppcheck-suppress ignoredReturnValue #9369
std::bind(stdbind_helper, 1);
// TODO cppcheck-suppress unreadVariable
// cppcheck-suppress autoNoType
auto f1 = std::bind(stdbind_helper, _1);
// TODO cppcheck-suppress unreadVariable
// cppcheck-suppress autoNoType
auto f2 = std::bind(stdbind_helper, 10);
}
int stdexchange() {
int i;
// cppcheck-suppress uninitvar
int j = std::exchange(i, 5);
return j;
}
class A
{
std::vector<std::string> m_str;
public:
A() {}
// cppcheck-suppress functionConst
void begin_const_iterator(void)
{
for (std::vector<std::string>::const_iterator it = m_str.begin(); it != m_str.end(); ++it) {;}
}
// cppcheck-suppress functionConst
void cbegin_const_iterator(void)
{
for (std::vector<std::string>::const_iterator it = m_str.cbegin(); it != m_str.cend(); ++it) {;}
}
// cppcheck-suppress functionConst
void crbegin_const_iterator(void)
{
for (std::vector<std::string>::const_reverse_iterator it = m_str.crbegin(); it != m_str.crend(); ++it) {;}
}
// cppcheck-suppress functionConst
void rbegin_const_iterator(void)
{
for (std::vector<std::string>::const_reverse_iterator it = m_str.rbegin(); it != m_str.rend(); ++it) {;}
}
// cppcheck-suppress functionConst
void cbegin_auto(void)
{
for (auto it = m_str.cbegin(); it != m_str.cend(); ++it) {;}
}
void baz_begin_no_const_iterator(void)
{
for (std::vector<std::string>::iterator it = m_str.begin(); it != m_str.end(); ++it) {;}
}
void rbegin_no_const_iterator(void)
{
for (std::vector<std::string>::reverse_iterator it = m_str.rbegin(); it != m_str.rend(); ++it) {;}
}
};
void addressof(int a)
{
// cppcheck-suppress ignoredReturnValue
std::addressof(a);
}
void string_view_unused(std::string_view v)
{
// cppcheck-suppress ignoredReturnValue
v.substr(1, 3);
}
// cppcheck-suppress passedByValue
void string_substr(std::string s)
{
// cppcheck-suppress ignoredReturnValue
s.substr(1, 3);
}
#ifndef __cpp_lib_span
#warning "This compiler does not support std::span"
#else
void stdspan()
{
std::vector<int> vec{1,2,3,4};
std::span spn{vec};
// cppcheck-suppress unreadVariable
std::span spn2 = spn;
//cppcheck-suppress ignoredReturnValue
spn.begin();
//cppcheck-suppress ignoredReturnValue
spn.end();
//cppcheck-suppress ignoredReturnValue
spn.rbegin();
//cppcheck-suppress ignoredReturnValue
spn.front();
//cppcheck-suppress ignoredReturnValue
spn.back();
//cppcheck-suppress constStatement
spn[0];
//cppcheck-suppress ignoredReturnValue
spn.data();
//cppcheck-suppress ignoredReturnValue
spn.size();
//cppcheck-suppress ignoredReturnValue
spn.size_bytes();
//cppcheck-suppress ignoredReturnValue
spn.empty();
//cppcheck-suppress ignoredReturnValue
spn.first(2);
//cppcheck-suppress ignoredReturnValue
spn.last(2);
//cppcheck-suppress ignoredReturnValue
spn.subspan(1, 2);
spn.subspan<1>();
static constexpr std::array<int, 2> arr{1, 2};
constexpr std::span spn3{arr};
spn3.first<1>();
spn3.last<1>();
spn3.subspan<1, 1>();
}
std::span<const int> returnDanglingLifetime_std_span0() {
static int a[10]{};
return a;
}
std::span<const int> returnDanglingLifetime_std_span1() {
static std::vector<int> v;
return v;
}
#endif
void beginEnd()
{
std::vector<int> v;
//cppcheck-suppress ignoredReturnValue
std::begin(v);
//cppcheck-suppress ignoredReturnValue
std::rbegin(v);
//cppcheck-suppress ignoredReturnValue
std::cbegin(v);
//cppcheck-suppress ignoredReturnValue
std::crbegin(v);
//cppcheck-suppress ignoredReturnValue
std::end(v);
//cppcheck-suppress ignoredReturnValue
std::rend(v);
//cppcheck-suppress ignoredReturnValue
std::cend(v);
//cppcheck-suppress ignoredReturnValue
std::crend(v);
// cppcheck-suppress constVariable
int arr[4];
//cppcheck-suppress ignoredReturnValue
std::begin(arr);
//cppcheck-suppress ignoredReturnValue
std::rbegin(arr);
//cppcheck-suppress ignoredReturnValue
std::cbegin(arr);
//cppcheck-suppress ignoredReturnValue
std::crbegin(arr);
//cppcheck-suppress ignoredReturnValue
std::end(arr);
//cppcheck-suppress ignoredReturnValue
std::rend(arr);
//cppcheck-suppress ignoredReturnValue
std::cend(arr);
//cppcheck-suppress ignoredReturnValue
std::crend(arr);
}
void smartPtr_get()
{
std::unique_ptr<int> p;
//cppcheck-suppress ignoredReturnValue
p.get();
//cppcheck-suppress nullPointer
*p = 1;
}
void smartPtr_get2(std::vector<std::unique_ptr<int>>& v)
{
// cppcheck-suppress autoNoType
for (auto& u : v) {
int* p = u.get();
*p = 0;
}
}
bool smartPtr_get3(size_t n, size_t i) { // #12748
std::unique_ptr<int[]> buf = std::make_unique<int[]>(n);
const int* p = buf.get() + i;
return p != nullptr;
}
void smartPtr_reset()
{
std::unique_ptr<int> p(new int());
p.reset(nullptr);
//cppcheck-suppress nullPointer
*p = 1;
}
void smartPtr_release()
{
std::unique_ptr<int> p{ new int() };
//cppcheck-suppress ignoredReturnValue
p.release();
//cppcheck-suppress nullPointer
*p = 1;
}
void std_vector_data_arithmetic()
{
std::vector<char> buf;
buf.resize(1);
memcpy(buf.data() + 0, "", 1);
}
void memleak_std_malloc() // #12332
{
//cppcheck-suppress [unreadVariable, constVariablePointer, unusedAllocatedMemory]
void* p = std::malloc(1);
//cppcheck-suppress memleak
}
void memleak_std_realloc(void* block, size_t newsize)
{
//cppcheck-suppress [unreadVariable, constVariablePointer]
void* p = std::realloc(block, newsize);
//cppcheck-suppress memleak
}
void unusedAllocatedMemory_std_free()
{
// cppcheck-suppress unusedAllocatedMemory
void* p = std::malloc(1);
std::free(p);
}
std::string global_scope_std() // #12355
{
::std::stringstream ss;
return ss.str();
}
::std::size_t global_scope_std2() // #12378
{
std::vector<::std::size_t> v;
// cppcheck-suppress containerOutOfBounds
return v.front();
}
void unique_lock_const_ref(std::mutex& m)
{
std::unique_lock lock(m);
}
void eraseIteratorOutOfBounds_std_deque(std::deque<int>& x) // #8690
{
// cppcheck-suppress eraseIteratorOutOfBounds
x.erase(x.end());
}
void assertWithSideEffect_system()
{
// cppcheck-suppress [assertWithSideEffect,checkLibraryNoReturn] // TODO: #8329
assert(std::system("abc"));
}
void assertWithSideEffect_std_map_at(const std::map<int, int>& m) // #12695
{
// cppcheck-suppress checkLibraryNoReturn
assert(m.at(0));
}
void assertWithSideEffect_std_unique_ptr_get(std::unique_ptr<int>& p)
{
// cppcheck-suppress checkLibraryNoReturn
assert(p.get());
}
void assertWithSideEffect_std_begin(const std::vector<std::string>& v) {
// cppcheck-suppress checkLibraryFunction // TODO
assert(std::is_sorted(std::begin(v), std::end(v), [](const std::string& a, const std::string& b) {
return a.size() < b.size();
})); // cppcheck-suppress checkLibraryNoReturn
}
void assertWithSideEffect_std_prev_next(const std::vector<int>& v, std::vector<int>::const_iterator it) {
assert(std::prev(it, 1) == v.begin());
// cppcheck-suppress checkLibraryNoReturn
assert(std::next(it, 1) == v.end());
}
std::vector<int> containerOutOfBounds_push_back() { // #12775
std::vector<int> v;
for (int i = 0; i < 4; ++i) {
v.push_back(i);
(void)v[i];
}
return v;
}
template<typename T>
void constVariablePointer_push_back(std::vector<T*>& d, const std::vector<T*>& s) {
for (const auto& e : s) {
T* newE = new T(*e);
d.push_back(newE);
}
}
// cppcheck-suppress constParameterReference
void constParameterReference_push_back(std::vector<std::string>& v, std::string& s) { // #12661
v.push_back(s);
}
// cppcheck-suppress constParameterReference
void constParameterReference_assign(std::vector<int>& v, int& r) {
v.assign(5, r);
}
// cppcheck-suppress constParameterReference
void constParameterReference_insert(std::list<int>& l, int& r) {
l.insert(l.end(), r);
l.insert(l.end(), 5, r);
}
const char* variableScope_cstr_dummy(const char* q); // #12812
std::size_t variableScope_cstr(const char* p) {
std::string s;
if (!p) {
s = "abc";
p = variableScope_cstr_dummy(s.c_str());
}
return std::strlen(p);
}
void unusedvar_stringstream(const char* p)
{
// cppcheck-suppress unreadVariable
std::istringstream istr(p);
// cppcheck-suppress unreadVariable
std::ostringstream ostr(p);
// cppcheck-suppress unreadVariable
std::stringstream sstr(p);
}
void unusedvar_stdcomplex()
{
// cppcheck-suppress unusedVariable
std::complex<double> z1;
// cppcheck-suppress unreadVariable
std::complex<double> z2(0.0, 0.0);
}
int passedByValue_std_array1(std::array<int, 2> a)
{
return a[0] + a[1];
}
// cppcheck-suppress passedByValue
int passedByValue_std_array2(std::array<int, 200> a)
{
return a[0] + a[1];
}
int passedByValue_std_bitset1(std::bitset<4> bs) // #12961
{
return bs.size();
}
// cppcheck-suppress passedByValue
int passedByValue_std_bitset2(std::bitset<256> bs)
{
return bs.size();
}
struct S_std_as_const { // #12974
// cppcheck-suppress functionConst
void f() {
for (const int i : std::as_const(l)) {}
}
std::list<int> l;
};
#if __cpp_lib_format
void unreadVariable_std_format_error(char * c)
{
// cppcheck-suppress unreadVariable
std::format_error x(c);
}
#endif
void eraseIteratorOutOfBounds_std_list1()
{
std::list<int> a;
std::list<int>::iterator p = a.begin();
// cppcheck-suppress eraseIteratorOutOfBounds
a.erase(p);
}
int eraseIteratorOutOfBounds_std_list2()
{
std::list<int> a;
std::list<int>::iterator p = a.begin();
std::list<int>::iterator q = p;
// cppcheck-suppress eraseIteratorOutOfBounds
a.erase(q);
return *q;
}
void containerOutOfBounds_std_string(std::string &var) { // #11403
std::string s0{"x"};
// cppcheck-suppress containerOutOfBounds
var+= s0[2];
std::string s1{ R"(x)" };
// cppcheck-suppress containerOutOfBounds
var+= s1[2];
std::string s2 = R"--(XYZ)--";
// cppcheck-suppress containerOutOfBounds
var+= s2[3];
std::string s3 = {R"--(XYZ)--"};
// cppcheck-suppress containerOutOfBounds
var+= s3[3];
const char *x = R"--(XYZ)--";
std::string s4(x);
// TODO cppcheck-suppress containerOutOfBounds
var+= s4[3];
std::string s5{x};
// TODO cppcheck-suppress containerOutOfBounds
var+= s5[3];
}
| null |
1,035 | cpp | cppcheck | googletest.cpp | test/cfg/googletest.cpp | null |
// Test library configuration for googletest.cfg
//
// Usage:
// $ cppcheck --check-library --library=googletest --enable=style,information --inconclusive --error-exitcode=1 --inline-suppr test/cfg/googletest.cpp
// =>
// No warnings about bad library configuration, unmatched suppressions, etc. exitcode=0
//
// cppcheck-suppress-file valueFlowBailout
#include <gmock/gmock-generated-matchers.h>
#include <gtest/gtest.h>
namespace ExampleNamespace {
constexpr long long TOLERANCE = 10;
// #9397 syntaxError when MATCHER_P is not known
// cppcheck-suppress symbolDatabaseWarning
MATCHER_P(ExampleMatcherPTest, expected, "")
{
// cppcheck-suppress valueFlowBailoutIncompleteVar
return ((arg <= (expected + TOLERANCE)) && (arg >= (expected - TOLERANCE)));
}
// syntaxError when MATCHER is not known
// cppcheck-suppress symbolDatabaseWarning
MATCHER(ExampleMatcherTest, "")
{
return (arg == TOLERANCE);
}
// syntaxError when TYPED_TEST is not known
TYPED_TEST (ExampleTypedTest, cppcheck_test)
{
}
// syntaxError when TYPED_TEST_P is not known
TYPED_TEST_P (ExampleTypedTestP, cppcheck)
{
}
}
TEST(ASSERT, ASSERT)
{
int *a = (int*)calloc(10,sizeof(int)); // cppcheck-suppress cstyleCast
ASSERT_TRUE(a != nullptr);
a[0] = 10;
free(a);
}
// Avoid syntax error: https://sourceforge.net/p/cppcheck/discussion/general/thread/6ccc7283e2/
TEST(test_cppcheck, cppcheck)
{
TestStruct<int> it;
ASSERT_THROW(it.operator->(), std::out_of_range);
}
// #9964 - avoid compareBoolExpressionWithInt false positive
TEST(Test, assert_false_fp)
{
// cppcheck-suppress valueFlowBailoutIncompleteVar
ASSERT_FALSE(errno < 0);
}
// Check that conditions in the ASSERT_* macros are processed correctly.
TEST(Test, warning_in_assert_macros)
{
int i = 5;
int j = 6;
// cppcheck-suppress knownConditionTrueFalse
ASSERT_TRUE(i == 5);
// cppcheck-suppress knownConditionTrueFalse
ASSERT_FALSE(i != 5);
// cppcheck-suppress duplicateExpression
ASSERT_EQ(i, i);
ASSERT_NE(i, j); // expected knownConditionTrueFalse...
ASSERT_LT(i, j); // expected knownConditionTrueFalse...
// cppcheck-suppress duplicateExpression
ASSERT_LE(i, i);
ASSERT_GT(j, i); // expected knownConditionTrueFalse
// cppcheck-suppress duplicateExpression
ASSERT_GE(i, i);
// cppcheck-suppress valueFlowBailoutIncompleteVar
unsigned int u = errno;
// cppcheck-suppress [unsignedPositive]
ASSERT_GE(u, 0);
// cppcheck-suppress [unsignedLessThanZero]
ASSERT_LT(u, 0);
}
| null |
1,036 | cpp | cppcheck | boost.cpp | test/cfg/boost.cpp | null |
// Test library configuration for boost.cfg
//
// Usage:
// $ cppcheck --check-library --library=boost --enable=style,information --inconclusive --error-exitcode=1 --inline-suppr test/cfg/boost.cpp
// =>
// No warnings about bad library configuration, unmatched suppressions, etc. exitcode=0
//
// cppcheck-suppress-file valueFlowBailout
#include <boost/config.hpp>
#include <boost/math/special_functions/round.hpp>
#include <boost/endian/conversion.hpp>
#include <boost/bind/bind.hpp>
#include <boost/function.hpp>
#include <boost/smart_ptr/scoped_array.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/lock_guard.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/core/scoped_enum.hpp>
BOOST_FORCEINLINE void boost_forceinline_test()
{}
BOOST_NOINLINE void boost_noinline_test()
{}
BOOST_NORETURN void boost_noreturn_test()
{}
void print_hello()
{
printf("hello");
}
void valid_code(boost::function<void(void)> &pf_print_hello)
{
if (BOOST_LIKELY(1)) {}
if (BOOST_UNLIKELY(0)) {}
int int1 = 5;
boost::endian::endian_reverse_inplace(int1);
boost::bind(print_hello)();
pf_print_hello = boost::bind(print_hello);
}
void ignoredReturnValue()
{
// cppcheck-suppress ignoredReturnValue
boost::math::round(1.5);
// cppcheck-suppress ignoredReturnValue
boost::math::iround(1.5);
// cppcheck-suppress ignoredReturnValue
boost::math::lround(1.5);
// cppcheck-suppress ignoredReturnValue
boost::math::llround(1.5);
// cppcheck-suppress ignoredReturnValue
boost::endian::endian_reverse(1);
}
void uninitvar()
{
int intUninit1;
int intUninit2;
// cppcheck-suppress uninitvar
boost::endian::endian_reverse_inplace(intUninit1);
// cppcheck-suppress uninitvar
(void)boost::math::round(intUninit2);
}
void throwexception(int * buf)
{
if (!buf)
boost::throw_exception(std::bad_alloc());
*buf = 0;
}
void throwexception2(int * buf)
{
if (!buf)
BOOST_THROW_EXCEPTION(std::bad_alloc());
*buf = 0;
}
void macros()
{
#define DECL(z, n, text) text ## n = n;
BOOST_PP_REPEAT(5, DECL, int x)
BOOST_SCOPED_ENUM_DECLARE_BEGIN(future_errc) {
// cppcheck-suppress valueFlowBailoutIncompleteVar
no_state
}
BOOST_SCOPED_ENUM_DECLARE_END(future_errc)
}
void containerOutOfBounds_scoped_array(std::size_t n) // #12356
{
boost::scoped_array<int> d(new int[n] {});
for (std::size_t i = 0; i < n; i++)
if (d[i]) {}
}
void lock_guard_finiteLifetime(boost::mutex& m)
{
// cppcheck-suppress unusedScopedObject
boost::lock_guard<boost::mutex>{ m };
}
BOOST_AUTO_TEST_SUITE(my_auto_test_suite)
BOOST_AUTO_TEST_CASE(test_message_macros)
{
bool my_bool = false;
BOOST_WARN_MESSAGE(my_bool, "warn");
BOOST_CHECK_MESSAGE(my_bool, "check");
BOOST_REQUIRE_MESSAGE(my_bool, "require");
BOOST_WARN_MESSAGE(my_bool, "my_bool was: " << my_bool);
}
using test_types_w_tuples = std::tuple<int, long, unsigned char>;
BOOST_AUTO_TEST_CASE_TEMPLATE(my_tuple_test, T, test_types_w_tuples)
{
// cppcheck-suppress valueFlowBailoutIncompleteVar
BOOST_TEST(sizeof(T) == 4U);
}
BOOST_AUTO_TEST_SUITE_END() | null |
1,037 | cpp | cppcheck | kde.cpp | test/cfg/kde.cpp | null |
// Test library configuration for kde.cfg
//
// Usage:
// $ cppcheck --check-library --library=kde --enable=style,information --inconclusive --error-exitcode=1 --inline-suppr test/cfg/kde.cpp
// =>
// No warnings about bad library configuration, unmatched suppressions, etc. exitcode=0
//
#include <cstdio>
#include <KDE/KGlobal>
#include <KDE/KConfigGroup>
#include <klocalizedstring.h>
class k_global_static_testclass1 {};
K_GLOBAL_STATIC(k_global_static_testclass1, k_global_static_testinstance1);
void valid_code(const KConfigGroup& cfgGroup)
{
const k_global_static_testclass1 * pk_global_static_testclass1 = k_global_static_testinstance1;
printf("%p", pk_global_static_testclass1);
bool entryTest = cfgGroup.readEntry("test", false);
if (entryTest) {}
}
void ignoredReturnValue(const KConfigGroup& cfgGroup)
{
// cppcheck-suppress ignoredReturnValue
cfgGroup.readEntry("test", "default");
// cppcheck-suppress ignoredReturnValue
cfgGroup.readEntry("test");
}
void i18n_test()
{
(void)i18n("Text");
(void)xi18n("Text");
(void)ki18n("Text");
(void)i18nc("Text", "Context");
(void)xi18nc("Text", "Context");
(void)ki18nc("Text", "Context");
}
| null |
1,038 | cpp | cppcheck | mfc.cpp | test/cfg/mfc.cpp | null |
// Test library configuration for mfc.cfg
#include <afxwin.h>
class MyClass1 : public CObject {
DECLARE_DYNAMIC(MyClass1)
public:
MyClass1() {}
};
IMPLEMENT_DYNAMIC(MyClass1, CObject)
class MyClass2 : public CObject {
DECLARE_DYNCREATE(MyClass2)
public:
MyClass2() {}
};
IMPLEMENT_DYNCREATE(MyClass2, CObject)
class MyClass3 : public CObject {
DECLARE_SERIAL(MyClass3)
public:
MyClass3() {}
};
IMPLEMENT_SERIAL(MyClass3, CObject, 42)
| null |
1,039 | cpp | cppcheck | qt.cpp | test/cfg/qt.cpp | null |
// Test library configuration for qt.cfg
//
// Usage:
// $ cppcheck --check-library --library=qt --enable=style,information --inconclusive --error-exitcode=1 --inline-suppr test/cfg/qt.cpp
// =>
// No warnings about bad library configuration, unmatched suppressions, etc. exitcode=0
//
// cppcheck-suppress-file valueFlowBailout
#include <QObject>
#include <QString>
#include <QVector>
#include <QStack>
#include <QByteArray>
#include <QList>
#include <QLinkedList>
#include <QMap>
#include <QMultiMap>
#include <QQueue>
#include <QSet>
#include <QtPlugin>
#include <QFile>
#include <QCoreApplication>
#include <QLoggingCategory>
#include <QTest>
#include <QRect>
#include <QRectF>
#include <QSize>
#include <QSizeF>
#include <QPoint>
#include <QPointF>
#include <QRegion>
#include <QTransform>
#include <cstdio>
int ignoredReturnValue_QSize_height(const QSize &s)
{
// cppcheck-suppress ignoredReturnValue
s.height();
return s.height();
}
int ignoredReturnValue_QSize_width(const QSize &s)
{
// cppcheck-suppress ignoredReturnValue
s.width();
return s.width();
}
void unusedVariable_QTransform()
{
// cppcheck-suppress unusedVariable
QTransform a;
}
void unreadVariable_QRegion(const int x, const QRegion::RegionType type, const QPolygon &polygon, const QBitmap &bm, const QRegion ®ion, const Qt::FillRule fillRule)
{
// cppcheck-suppress unusedVariable
QRegion a;
// cppcheck-suppress unreadVariable
QRegion b{};
// cppcheck-suppress unreadVariable
QRegion c{x,x,x,x};
// cppcheck-suppress unreadVariable
QRegion d{x,x,x,x, type};
// cppcheck-suppress unreadVariable
QRegion e{polygon, fillRule};
// cppcheck-suppress unreadVariable
QRegion f{bm};
// cppcheck-suppress unreadVariable
QRegion g{region};
}
void unreadVariable_QPoint(const QPoint &s)
{
// cppcheck-suppress unusedVariable
QPoint a;
// cppcheck-suppress unreadVariable
QPoint b{};
// cppcheck-suppress unreadVariable
QPoint c{4, 2};
// cppcheck-suppress unreadVariable
QPoint d(4, 2);
// cppcheck-suppress unreadVariable
QPoint e(s);
}
void unreadVariable_QPointF(const QPointF &s)
{
// cppcheck-suppress unusedVariable
QPointF a;
// cppcheck-suppress unreadVariable
QPointF b{};
// cppcheck-suppress unreadVariable
QPointF c{4.2, 4.2};
// cppcheck-suppress unreadVariable
QPointF d(4.2, 4.2);
// cppcheck-suppress unreadVariable
QPointF e(s);
}
void unreadVariable_QSizeF(const QSize &s)
{
// cppcheck-suppress unusedVariable
QSizeF a;
// cppcheck-suppress unreadVariable
QSizeF b{};
// cppcheck-suppress unreadVariable
QSizeF c{4.2, 4.2};
// cppcheck-suppress unreadVariable
QSizeF d(4.2, 4.2);
// cppcheck-suppress unreadVariable
QSizeF e(s);
}
void unreadVariable_QSize(const QSize &s)
{
// cppcheck-suppress unusedVariable
QSize a;
// cppcheck-suppress unreadVariable
QSize b{};
// cppcheck-suppress unreadVariable
QSize c{4, 2};
// cppcheck-suppress unreadVariable
QSize d(4, 2);
// cppcheck-suppress unreadVariable
QSize e(s);
}
void unreadVariable_QRect(const QPoint &topLeft, const QSize &size, const QPoint &bottomRight, const int x) {
// cppcheck-suppress unusedVariable
QRect a;
// cppcheck-suppress unreadVariable
QRect b{};
// cppcheck-suppress unreadVariable
QRect c(0, 0, 100, 50);
// cppcheck-suppress unreadVariable
QRect d(x, x, x, x);
// cppcheck-suppress unreadVariable
QRect e(topLeft, size);
// cppcheck-suppress unreadVariable
QRect f(topLeft, bottomRight);
}
void unreadVariable_QRectF(const QPointF &topLeft, const QSizeF &size, const QPointF &bottomRight, const QRectF &rect, const qreal x) {
// cppcheck-suppress unusedVariable
QRectF a;
// cppcheck-suppress unreadVariable
QRectF b{};
// cppcheck-suppress unreadVariable
QRectF c(0.0, 0.0, 100.0, 50.0);
// cppcheck-suppress unreadVariable
QRectF d(x, x, x, x);
// cppcheck-suppress unreadVariable
QRectF e(topLeft, size);
// cppcheck-suppress unreadVariable
QRectF f(topLeft, bottomRight);
// cppcheck-suppress unreadVariable
QRectF g(rect);
}
void QString1(QString s)
{
for (int i = 0; i <= s.size(); ++i) {
// cppcheck-suppress stlOutOfBounds
s[i] = 'x';
}
}
bool QString2()
{
QString s;
// cppcheck-suppress knownConditionTrueFalse
return s.size();
}
QString::iterator QString3()
{
QString qstring1;
QString qstring2;
// cppcheck-suppress mismatchingContainers
for (QString::iterator it = qstring1.begin(); it != qstring2.end(); ++it)
{}
QString::iterator it = qstring1.begin();
// cppcheck-suppress returnDanglingLifetime
return it;
}
void QString4()
{
// cppcheck-suppress unusedVariable
QString qs;
}
// cppcheck-suppress passedByValue
bool QString5(QString s) { // #10710
return s.isEmpty();
}
// cppcheck-suppress passedByValue
QStringList QString6(QString s) {
return QStringList{ "*" + s + "*" };
}
// cppcheck-suppress passedByValue
bool QString7(QString s, const QString& l) {
return l.startsWith(s);
}
void QString_split(const char* name) { // #12998
// cppcheck-suppress valueFlowBailoutIncompleteVar // FIXME
QStringList qsl = QString(name).split(';', Qt::SkipEmptyParts);
if (qsl.isEmpty()) {}
}
namespace NTestStd // #12355
{
using namespace std;
QString QString_std(QString s)
{
s.replace("abc", "def");
return s;
}
}
void QByteArray1(QByteArray byteArrayArg)
{
for (int i = 0; i <= byteArrayArg.size(); ++i) {
// cppcheck-suppress stlOutOfBounds
byteArrayArg[i] = 'x';
}
// cppcheck-suppress containerOutOfBoundsIndexExpression
byteArrayArg[byteArrayArg.length()] = 'a';
// cppcheck-suppress containerOutOfBoundsIndexExpression
byteArrayArg[byteArrayArg.count()] = 'b';
// cppcheck-suppress containerOutOfBoundsIndexExpression
printf("val: %c\n", byteArrayArg[byteArrayArg.size()]);
QByteArray byteArray1{'a', 'b'};
(void)byteArray1[1];
// cppcheck-suppress ignoredReturnValue
byteArray1.at(1);
}
void QList1(QList<int> intListArg)
{
for (int i = 0; i <= intListArg.size(); ++i) {
// cppcheck-suppress stlOutOfBounds
intListArg[i] = 1;
}
// cppcheck-suppress containerOutOfBoundsIndexExpression
intListArg[intListArg.length()] = 5;
// cppcheck-suppress containerOutOfBoundsIndexExpression
intListArg[intListArg.count()] = 10;
// cppcheck-suppress containerOutOfBoundsIndexExpression
printf("val: %d\n", intListArg[intListArg.size()]);
QList<QString> qstringList1{"one", "two"};
(void)qstringList1[1];
QList<QString> qstringList2 = {"one", "two"};
(void)qstringList2[1];
qstringList2.clear();
// cppcheck-suppress containerOutOfBounds
(void)qstringList2[1];
QList<QString> qstringList3;
qstringList3 << "one" << "two";
(void)qstringList3[1];
// FIXME: The following should have a containerOutOfBounds suppression #9242
(void)qstringList3[3];
// cppcheck-suppress ignoredReturnValue
qstringList3.startsWith("one");
// cppcheck-suppress ignoredReturnValue
qstringList3.endsWith("one");
// cppcheck-suppress ignoredReturnValue
qstringList3.count();
// cppcheck-suppress ignoredReturnValue
qstringList3.length();
// cppcheck-suppress ignoredReturnValue
qstringList3.size();
// cppcheck-suppress ignoredReturnValue
qstringList3.at(5);
// cppcheck-suppress invalidFunctionArg
(void)qstringList3.at(-5);
QList<QString> qstringList4;
// cppcheck-suppress containerOutOfBounds
(void)qstringList4[0];
qstringList4.append("a");
(void)qstringList4[0];
qstringList4.clear();
// cppcheck-suppress containerOutOfBounds
(void)qstringList4[0];
}
QList<int> QList2() { // #10556
QList<int> v;
for (int i = 0; i < 4; ++i)
{
v.append(i);
(void)v.at(i);
}
return v;
}
QList<int>::iterator QList3()
{
QList<int> qlist1;
QList<int> qlist2;
// cppcheck-suppress mismatchingContainers
for (QList<int>::iterator it = qlist1.begin(); it != qlist2.end(); ++it)
{}
QList<int>::iterator it = qlist1.begin();
// cppcheck-suppress returnDanglingLifetime
return it;
}
void QLinkedList1()
{
// cppcheck-suppress unreadVariable
QLinkedList<QString> qstringLinkedList1{"one", "two"};
QLinkedList<QString> qstringLinkedList2 = {"one", "two"};
qstringLinkedList2.clear();
QLinkedList<QString> qstringLinkedList3;
qstringLinkedList3 << "one" << "two";
// cppcheck-suppress ignoredReturnValue
qstringLinkedList3.startsWith("one");
// cppcheck-suppress ignoredReturnValue
qstringLinkedList3.endsWith("one");
// cppcheck-suppress ignoredReturnValue
qstringLinkedList3.count();
// cppcheck-suppress ignoredReturnValue
qstringLinkedList3.size();
QLinkedList<QString> qstringLinkedList4;
qstringLinkedList4.append("a");
qstringLinkedList4.clear();
}
QLinkedList<int>::iterator QLinkedList3()
{
QLinkedList<int> intQLinkedList1;
QLinkedList<int> intQLinkedList2;
// cppcheck-suppress mismatchingContainers
for (QLinkedList<int>::iterator it = intQLinkedList1.begin(); it != intQLinkedList2.end(); ++it)
{}
QLinkedList<int>::iterator it = intQLinkedList1.begin();
// cppcheck-suppress returnDanglingLifetime
return it;
}
void QStringList1(QStringList stringlistArg)
{
for (int i = 0; i <= stringlistArg.size(); ++i) {
// cppcheck-suppress stlOutOfBounds
stringlistArg[i] = "abc";
}
// cppcheck-suppress containerOutOfBoundsIndexExpression
stringlistArg[stringlistArg.length()] = "ab";
stringlistArg[stringlistArg.length() - 1] = "ab"; // could be valid
// cppcheck-suppress containerOutOfBoundsIndexExpression
stringlistArg[stringlistArg.count()] = "12";
stringlistArg[stringlistArg.count() - 1] = "12"; // could be valid
// cppcheck-suppress containerOutOfBoundsIndexExpression
(void)stringlistArg[stringlistArg.size()];
(void)stringlistArg[stringlistArg.size() - 1]; // could be valid
QStringList qstringlist1{"one", "two"};
(void)qstringlist1[1];
QStringList qstringlist2 = {"one", "two"};
(void)qstringlist2[1];
QStringList qstringlist3;
qstringlist3 << "one" << "two";
(void)qstringlist3[1];
// FIXME: The following should have a containerOutOfBounds suppression #9242
(void)qstringlist3[3];
// cppcheck-suppress ignoredReturnValue
qstringlist3.startsWith("one");
// cppcheck-suppress ignoredReturnValue
qstringlist3.endsWith("one");
// cppcheck-suppress ignoredReturnValue
qstringlist3.count();
// cppcheck-suppress ignoredReturnValue
qstringlist3.length();
// cppcheck-suppress ignoredReturnValue
qstringlist3.size();
// cppcheck-suppress ignoredReturnValue
qstringlist3.at(5);
// cppcheck-suppress invalidFunctionArg
(void)qstringlist3.at(-5);
}
QStringList::iterator QStringList2()
{
QStringList qstringlist1;
QStringList qstringlist2;
// cppcheck-suppress mismatchingContainers
for (QStringList::iterator it = qstringlist1.begin(); it != qstringlist2.end(); ++it)
{}
QStringList::iterator it = qstringlist1.begin();
// cppcheck-suppress returnDanglingLifetime
return it;
}
void QVector1(QVector<int> intVectorArg)
{
for (int i = 0; i <= intVectorArg.size(); ++i) {
// cppcheck-suppress stlOutOfBounds
intVectorArg[i] = 1;
}
// cppcheck-suppress containerOutOfBoundsIndexExpression
intVectorArg[intVectorArg.length()] = 5;
// cppcheck-suppress containerOutOfBoundsIndexExpression
intVectorArg[intVectorArg.count()] = 10;
// cppcheck-suppress containerOutOfBoundsIndexExpression
printf("val: %d\n", intVectorArg[intVectorArg.size()]);
QVector<QString> qstringVector1{"one", "two"};
(void)qstringVector1[1];
QVector<QString> qstringVector2 = {"one", "two"};
(void)qstringVector2[1];
QVector<QString> qstringVector3;
qstringVector3 << "one" << "two";
(void)qstringVector3[1];
// FIXME: The following should have a containerOutOfBounds suppression #9242
(void)qstringVector3[3];
// cppcheck-suppress ignoredReturnValue
qstringVector3.startsWith("one");
// cppcheck-suppress ignoredReturnValue
qstringVector3.endsWith("one");
// cppcheck-suppress ignoredReturnValue
qstringVector3.count();
// cppcheck-suppress ignoredReturnValue
qstringVector3.length();
// cppcheck-suppress ignoredReturnValue
qstringVector3.size();
// cppcheck-suppress ignoredReturnValue
qstringVector3.at(5);
// cppcheck-suppress invalidFunctionArg
(void)qstringVector3.at(-5);
}
QVector<int>::iterator QVector2()
{
QVector<int> qvector1;
QVector<int> qvector2;
// cppcheck-suppress mismatchingContainers
for (QVector<int>::iterator it = qvector1.begin(); it != qvector2.end(); ++it)
{}
QVector<int>::iterator it = qvector1.begin();
// cppcheck-suppress returnDanglingLifetime
return it;
}
// cppcheck-suppress passedByValue
void duplicateExpression_QString_Compare(QString style) //#8723
{
// cppcheck-suppress [duplicateExpression,valueFlowBailoutIncompleteVar]
if (style.compare( "x", Qt::CaseInsensitive ) == 0 || style.compare( "x", Qt::CaseInsensitive ) == 0)
{}
}
void QVector_uninit()
{
int i;
// cppcheck-suppress [uninitvar, unreadVariable]
QVector<int> v(i);
}
void QStack1(QStack<int> intStackArg)
{
for (int i = 0; i <= intStackArg.size(); ++i) {
// cppcheck-suppress stlOutOfBounds
intStackArg[i] = 1;
}
// cppcheck-suppress containerOutOfBoundsIndexExpression
intStackArg[intStackArg.length()] = 5;
// cppcheck-suppress containerOutOfBoundsIndexExpression
intStackArg[intStackArg.count()] = 10;
// cppcheck-suppress containerOutOfBoundsIndexExpression
printf("val: %d\n", intStackArg[intStackArg.size()]);
QStack<QString> qstringStack1;
qstringStack1.push("one");
qstringStack1.push("two");
(void)qstringStack1[1];
QStack<QString> qstringStack2;
qstringStack2 << "one" << "two";
(void)qstringStack2[1];
// FIXME: The following should have a containerOutOfBounds suppression #9242
(void)qstringStack2[3];
// cppcheck-suppress ignoredReturnValue
qstringStack2.startsWith("one");
// cppcheck-suppress ignoredReturnValue
qstringStack2.endsWith("one");
// cppcheck-suppress ignoredReturnValue
qstringStack2.count();
// cppcheck-suppress ignoredReturnValue
qstringStack2.length();
// cppcheck-suppress ignoredReturnValue
qstringStack2.size();
// cppcheck-suppress ignoredReturnValue
qstringStack2.at(5);
// cppcheck-suppress invalidFunctionArg
(void)qstringStack2.at(-5);
}
QStack<int>::iterator QStack2()
{
QStack<int> qstack1;
QStack<int> qstack2;
// cppcheck-suppress mismatchingContainers
for (QStack<int>::iterator it = qstack1.begin(); it != qstack2.end(); ++it)
{}
QStack<int>::iterator it = qstack1.begin();
// cppcheck-suppress returnDanglingLifetime
return it;
}
void QStack3()
{
QStack<int> intStack;
intStack.push(1);
// cppcheck-suppress ignoredReturnValue
intStack.top();
intStack.pop();
}
// Verify that Qt macros do not result in syntax errors, false positives or other issues.
class MacroTest1 : public QObject {
Q_OBJECT
Q_PLUGIN_METADATA(IID "com.foo.bar" FILE "test.json")
public:
explicit MacroTest1(QObject *parent = 0);
~MacroTest1();
};
class MacroTest2 {
Q_DECLARE_TR_FUNCTIONS(MacroTest2)
public:
MacroTest2();
~MacroTest2();
};
void MacroTest2_test()
{
QString str = MacroTest2::tr("hello");
QByteArray ba = str.toLatin1();
printf(ba.data());
#ifndef QT_NO_DEPRECATED
str = MacroTest2::trUtf8("test2");
ba = str.toLatin1();
printf(ba.data());
#endif
}
void MacroTest3()
{
QByteArray message = QByteArrayLiteral("Test1");
message += QByteArrayLiteral("Test2");
QVERIFY2(2 >= 0, message.constData());
}
// cppcheck-suppress constParameterReference
void validCode(int * pIntPtr, QString & qstrArg, double d)
{
Q_UNUSED(d)
if (QFile::exists("test")) {}
if (pIntPtr != Q_NULLPTR) {
*pIntPtr = 5;
}
if (pIntPtr && *pIntPtr == 1) {
forever {
}
} else if (pIntPtr && *pIntPtr == 2) {
Q_FOREVER {}
}
if (Q_LIKELY(pIntPtr)) {}
if (Q_UNLIKELY(!pIntPtr)) {}
printf(QT_TR_NOOP("Hi"));
// cppcheck-suppress valueFlowBailoutIncompleteVar
Q_DECLARE_LOGGING_CATEGORY(logging_category_test);
QT_FORWARD_DECLARE_CLASS(forwardDeclaredClass);
QT_FORWARD_DECLARE_STRUCT(forwardDeclaredStruct);
//#9650
QString qstr1(qstrArg);
if (qstr1.length() == 1) {} else {
qstr1.chop(1);
if (qstr1.length() == 1) {}
}
if (qstr1.length() == 1) {} else {
qstr1.remove(1);
if (qstr1.length() == 1) {}
}
}
void ignoredReturnValue()
{
// cppcheck-suppress ignoredReturnValue
QFile::exists("test");
QFile file1("test");
// cppcheck-suppress ignoredReturnValue
file1.exists();
}
void nullPointer(int * pIntPtr)
{
int * pNullPtr = Q_NULLPTR;
// cppcheck-suppress nullPointer
*pNullPtr = 1;
if (pIntPtr != Q_NULLPTR) {
*pIntPtr = 2;
} else {
// cppcheck-suppress nullPointerRedundantCheck
*pIntPtr = 3;
}
}
namespace {
class C : public QObject {
Q_OBJECT
public:
explicit C(QObject* parent = nullptr) : QObject(parent) {}
void signal() {}
};
class D : public QObject {
Q_OBJECT
public:
D() {
connect(new C(this), &C::signal, this, &D::slot);
}
void slot() {};
};
// findFunction11
class Fred : public QObject {
Q_OBJECT
private slots:
// cppcheck-suppress functionStatic
void foo();
};
void Fred::foo() {}
// bitfields14
class X {
signals:
};
// simplifyQtSignalsSlots1
class Counter1 : public QObject {
Q_OBJECT
public:
Counter1() {
m_value = 0;
}
int value() const {
return m_value;
}
public slots:
void setValue(int value);
signals:
void valueChanged(int newValue);
private:
int m_value;
};
void Counter1::setValue(int value) {
if (value != m_value) {
m_value = value;
emit valueChanged(value);
}
}
class Counter2 : public QObject {
Q_OBJECT
public:
Counter2() {
m_value = 0;
}
int value() const {
return m_value;
}
public Q_SLOTS:
void setValue(int value);
Q_SIGNALS:
void valueChanged(int newValue);
private:
int m_value;
};
void Counter2::setValue(int value) {
if (value != m_value) {
m_value = value;
emit valueChanged(value);
}
}
class MyObject1 : public QObject {
MyObject1() {}
~MyObject1() {}
public slots:
signals:
// cppcheck-suppress functionStatic
void test() {}
};
class MyObject2 : public QObject {
Q_OBJECT
public slots:
};
// simplifyQtSignalsSlots2
namespace Foo { class Bar; }
class Foo::Bar : public QObject { private slots: };
// Q_PROPERTY with templates inducing a ',' should not produce a preprocessorErrorDirective
class AssocProperty : public QObject {
public:
Q_PROPERTY(QHash<QString, int> hash READ hash WRITE setHash)
};
}
struct SEstimateSize {
inline const QString& get() const {
return m;
}
QString m;
};
class QString;
void dontCrashEstimateSize(const SEstimateSize& s) {
// cppcheck-suppress redundantCopyLocalConst
QString q = s.get();
if (!q.isNull()) {}
}
bool knownConditionTrueFalse_QString_count(const QString& s) // #11036
{
if (!s.isEmpty() && s.count("abc") == 0)
return false;
return true;
}
void unusedVariable_qtContainers() // #10689
{
// cppcheck-suppress unusedVariable
QMap<int, int> qm;
// cppcheck-suppress unusedVariable
QSet<int> qs;
// cppcheck-suppress unusedVariable
QMultiMap<int, int> qmm;
// cppcheck-suppress unusedVariable
QQueue<int> qq;
// cppcheck-suppress unusedVariable
QLatin1String ql1s;
}
void unreadVariable_QMapIterator(QMap<QString, QObject*>& m)
{
auto it = m.find("abc"); // #12662
if (it != m.end()) {
// cppcheck-suppress checkLibraryFunction // TODO
delete it.value();
// cppcheck-suppress checkLibraryFunction
it.value() = new QObject();
}
}
void constVariablePointer_QVector(QVector<int*>& qv, int* p)
{
qv.push_back(p); // #12661
}
const QString& unassignedVariable_static_QString() // #12935
{
static QString qs;
return qs;
}
struct BQObject_missingOverride { // #13406
Q_OBJECT
};
struct DQObject_missingOverride : BQObject_missingOverride {
Q_OBJECT
}; | null |
1,040 | cpp | cppcheck | test-stacktrace.cpp | test/signal/test-stacktrace.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#include "config.h"
#ifdef USE_UNIX_BACKTRACE_SUPPORT
#include "stacktrace.h"
#include <cstdio>
// static functions are omitted from trace
/*static*/ void my_func_2() // NOLINT(misc-use-internal-linkage)
{
print_stacktrace(stdout, 0, true, -1, true);
}
/*static*/ void my_func() // NOLINT(misc-use-internal-linkage)
{
my_func_2();
}
#endif
int main()
{
#ifdef USE_UNIX_BACKTRACE_SUPPORT
my_func();
return 0;
#else
return 1;
#endif
}
| null |
1,041 | cpp | cppcheck | test-signalhandler.cpp | test/signal/test-signalhandler.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#include "config.h"
#if defined(USE_UNIX_SIGNAL_HANDLING)
#include "signalhandler.h"
#include <cassert>
#include <cfenv>
#include <cstdio>
#include <cstdlib>
#include <cstring>
// static functions are omitted from trace
/*static*/ NORETURN void my_assert() // NOLINT(misc-use-internal-linkage)
{
assert(false);
}
/*static*/ NORETURN void my_abort() // NOLINT(misc-use-internal-linkage)
{
abort();
}
/*static*/ void my_segv() // NOLINT(misc-use-internal-linkage)
{
// cppcheck-suppress nullPointer
++*(int*)nullptr;
}
/*static*/ void my_fpe() // NOLINT(misc-use-internal-linkage)
{
#if !defined(__APPLE__)
feenableexcept(FE_ALL_EXCEPT); // TODO: check result
#endif
std::feraiseexcept(FE_UNDERFLOW | FE_DIVBYZERO); // TODO: check result
// TODO: to generate this via code
}
#endif
int main(int argc, const char * const argv[])
{
#if defined(USE_UNIX_SIGNAL_HANDLING)
if (argc != 2)
return 1;
register_signal_handler(stdout);
if (strcmp(argv[1], "assert") == 0)
my_assert();
else if (strcmp(argv[1], "abort") == 0)
my_abort();
else if (strcmp(argv[1], "fpe") == 0)
my_fpe();
else if (strcmp(argv[1], "segv") == 0)
my_segv();
return 0;
#else
(void)argc;
(void)argv;
return 1;
#endif
}
| null |
1,042 | cpp | cppcheck | samplemodel.cpp | test/cli/QML-Samples-TableView/samplemodel.cpp | null | #include "samplemodel.h"
#include <QDebug>
#include <QRandomGenerator>
SampleModel::SampleModel(QObject *parent) : QAbstractListModel(parent)
{}
int SampleModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent)
return _data.size();
}
QVariant SampleModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
if (index.row() < 0 || index.row() > _data.count() - 1)
return QVariant();
auto row = _data.at(index.row());
switch (role) {
case IdRole:
return index.row();
case NameRole:
return row.first;
case GradeRole:
return row.second;
}
return QVariant();
}
QHash<int, QByteArray> SampleModel::roleNames() const
{
return {
{IdRole, "id"},
{NameRole, "name"},
{GradeRole, "grade"}
};
}
void SampleModel::fillSampleData(int size)
{
QString abs = "qwertyuiopasdfghjklzxcvbnm";
QRandomGenerator r;
for (auto i = 0; i < size; i++) {
Row row;
auto nameLen = r.bounded(3, 8);
QString name;
for (int c = 0; c < nameLen; ++c)
name.append(abs.at(r.bounded(0, abs.size() - 1)));
row.first = name;
row.second = r.bounded(0, 20);
_data.append(row);
}
qDebug() << _data.size() << "item(s) added as sample data";
beginInsertRows(QModelIndex(), 0, _data.size() - 1);
endInsertRows();
}
| null |
1,043 | cpp | cppcheck | samplemodel.h | test/cli/QML-Samples-TableView/samplemodel.h | null | #ifndef SAMPLEMODEL_H
#define SAMPLEMODEL_H
#include <QAbstractListModel>
class SampleModel : public QAbstractListModel
{
Q_OBJECT
typedef QPair<QString, int> Row;
QList<Row> _data;
public:
enum Role {
IdRole = Qt::UserRole + 1,
NameRole,
GradeRole
};
SampleModel(QObject *parent = nullptr);
int rowCount(const QModelIndex &parent) const;
QVariant data(const QModelIndex &index, int role) const;
QHash<int, QByteArray> roleNames() const;
public slots:
void fillSampleData(int size);
};
#endif // SAMPLEMODEL_H
| null |
1,044 | cpp | cppcheck | main.cpp | test/cli/QML-Samples-TableView/main.cpp | null | #include <QtGui/QGuiApplication>
#include <QtQml/QQmlApplicationEngine>
#include "samplemodel.h"
int main(int argc, char *argv[])
{
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
qmlRegisterType<SampleModel>("Test", 1, 0, "SampleModel");
const QUrl url(QStringLiteral("qrc:/main.qml"));
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
engine.load(url);
return app.exec();
}
| null |
1,045 | cpp | cppcheck | B.cpp | test/cli/proj-inline-suppress-unusedFunction/B.cpp | null | #include "B.hpp"
B::B() {}
// cppcheck-suppress unusedFunction
void B::unusedFunctionTest() {}
| null |
1,046 | cpp | cppcheck | A.cpp | test/cli/proj-inline-suppress-unusedFunction/A.cpp | null | #include "B.hpp"
int main()
{
B b();
return 0;
}
| null |
1,047 | cpp | cppcheck | odr1.cpp | test/cli/whole-program/odr1.cpp | null | #include "odr.h"
#include <iostream>
// cppcheck-suppress ctuOneDefinitionRuleViolation
class C : public Base
{
public:
void f() override {
std::cout << "1";
}
};
Base *c1_create()
{
return new C();
}
| null |
1,048 | cpp | cppcheck | odr2.cpp | test/cli/whole-program/odr2.cpp | null | #include "odr.h"
#include <iostream>
class C : public Base
{
public:
void f() override {
std::cout << "2";
}
};
Base *c2_create()
{
return new C();
}
| null |
1,049 | cpp | cppcheck | odr.h | test/cli/whole-program/odr.h | null | class Base {
public:
virtual void f() = 0;
};
extern Base *c1_create();
extern Base *c2_create(); | null |
1,050 | cpp | cppcheck | TestClass.h | test/cli/shared-items-project/Shared/TestClass.h | null | #pragma once
namespace Shared
{
class TestClass
{
public:
explicit TestClass();
virtual ~TestClass();
};
} // namespace Shared
| null |
1,051 | cpp | cppcheck | TestClass.cpp | test/cli/shared-items-project/Shared/TestClass.cpp | null | #include "TestClass.h"
using namespace Shared;
TestClass::TestClass()
{}
TestClass::~TestClass()
{}
| null |
1,052 | cpp | cppcheck | MainFile.cpp | test/cli/shared-items-project/Main/MainFile.cpp | null | #include <TestClass.h>
int main(void)
{
Shared::TestClass test{};
return 0;
} | null |
1,053 | cpp | cppcheck | 1.h | test/cli/proj-inline-suppress/1.h | null |
// cppcheck-suppress zerodiv
const int x = 10000 / 0;
| null |
1,054 | cpp | cppcheck | 3.cpp | test/cli/proj-inline-suppress/3.cpp | null | // From forum: https://sourceforge.net/p/cppcheck/discussion/general/thread/e67653efdb/
void foo()
{ // cppcheck-suppress zerodiv
int x = 10000 / 0;
}
| null |
1,055 | cpp | cppcheck | template.cpp | test/cli/proj-inline-suppress/template.cpp | null | namespace {
template<typename T>
T f() {
return T();
}
}
// cppcheck-suppress unusedFunction
int g(int i) {
if (i == 0)
return f<char>();
if (i == 1)
return f<short>();
return f<int>();
} | null |
1,056 | cpp | cppcheck | unusedFunctionUnmatched.cpp | test/cli/proj-inline-suppress/unusedFunctionUnmatched.cpp | null | // cppcheck-suppress unusedFunction
void f() {
// cppcheck-suppress unusedFunction
// cppcheck-suppress uninitvar
}
| null |
1,057 | cpp | cppcheck | 3.h | test/cli/unusedFunction/3.h | null | void f3_1();
void f3_2();
void f3_3(); | null |
1,058 | cpp | cppcheck | cppcheckexecutorseh.cpp | cli/cppcheckexecutorseh.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#include "cppcheckexecutorseh.h"
#ifdef USE_WINDOWS_SEH
#include "cppcheckexecutor.h"
#include "utils.h"
#include <windows.h>
#include <dbghelp.h>
#include <tchar.h>
namespace {
const ULONG maxnamelength = 512;
struct IMAGEHLP_SYMBOL64_EXT : public IMAGEHLP_SYMBOL64 {
TCHAR nameExt[maxnamelength]; // actually no need to worry about character encoding here
};
typedef BOOL (WINAPI *fpStackWalk64)(DWORD, HANDLE, HANDLE, LPSTACKFRAME64, PVOID, PREAD_PROCESS_MEMORY_ROUTINE64, PFUNCTION_TABLE_ACCESS_ROUTINE64, PGET_MODULE_BASE_ROUTINE64, PTRANSLATE_ADDRESS_ROUTINE64);
fpStackWalk64 pStackWalk64;
typedef DWORD64 (WINAPI *fpSymGetModuleBase64)(HANDLE, DWORD64);
fpSymGetModuleBase64 pSymGetModuleBase64;
typedef BOOL (WINAPI *fpSymGetSymFromAddr64)(HANDLE, DWORD64, PDWORD64, PIMAGEHLP_SYMBOL64);
fpSymGetSymFromAddr64 pSymGetSymFromAddr64;
typedef BOOL (WINAPI *fpSymGetLineFromAddr64)(HANDLE, DWORD64, PDWORD, PIMAGEHLP_LINE64);
fpSymGetLineFromAddr64 pSymGetLineFromAddr64;
typedef DWORD (WINAPI *fpUnDecorateSymbolName)(const TCHAR*, PTSTR, DWORD, DWORD);
fpUnDecorateSymbolName pUnDecorateSymbolName;
typedef PVOID (WINAPI *fpSymFunctionTableAccess64)(HANDLE, DWORD64);
fpSymFunctionTableAccess64 pSymFunctionTableAccess64;
typedef BOOL (WINAPI *fpSymInitialize)(HANDLE, PCSTR, BOOL);
fpSymInitialize pSymInitialize;
HMODULE hLibDbgHelp;
// avoid explicit dependency on Dbghelp.dll
bool loadDbgHelp()
{
hLibDbgHelp = ::LoadLibraryW(L"Dbghelp.dll");
if (!hLibDbgHelp)
return false;
pStackWalk64 = (fpStackWalk64) ::GetProcAddress(hLibDbgHelp, "StackWalk64");
pSymGetModuleBase64 = (fpSymGetModuleBase64) ::GetProcAddress(hLibDbgHelp, "SymGetModuleBase64");
pSymGetSymFromAddr64 = (fpSymGetSymFromAddr64) ::GetProcAddress(hLibDbgHelp, "SymGetSymFromAddr64");
pSymGetLineFromAddr64 = (fpSymGetLineFromAddr64)::GetProcAddress(hLibDbgHelp, "SymGetLineFromAddr64");
pSymFunctionTableAccess64 = (fpSymFunctionTableAccess64)::GetProcAddress(hLibDbgHelp, "SymFunctionTableAccess64");
pSymInitialize = (fpSymInitialize) ::GetProcAddress(hLibDbgHelp, "SymInitialize");
pUnDecorateSymbolName = (fpUnDecorateSymbolName)::GetProcAddress(hLibDbgHelp, "UnDecorateSymbolName");
return true;
}
void printCallstack(FILE* outputFile, PEXCEPTION_POINTERS ex)
{
if (!loadDbgHelp())
return;
const HANDLE hProcess = GetCurrentProcess();
const HANDLE hThread = GetCurrentThread();
pSymInitialize(
hProcess,
nullptr,
TRUE
);
CONTEXT context = *(ex->ContextRecord);
STACKFRAME64 stack= {0};
stack.AddrPC.Mode = AddrModeFlat;
stack.AddrStack.Mode = AddrModeFlat;
stack.AddrFrame.Mode = AddrModeFlat;
#if defined(_M_IX86)
stack.AddrPC.Offset = context.Eip;
stack.AddrStack.Offset = context.Esp;
stack.AddrFrame.Offset = context.Ebp;
#elif defined(_M_AMD64)
stack.AddrPC.Offset = context.Rip;
stack.AddrStack.Offset = context.Rsp;
stack.AddrFrame.Offset = context.Rsp;
#elif defined(_M_ARM64)
stack.AddrPC.Offset = context.Pc;
stack.AddrStack.Offset = context.Sp;
stack.AddrFrame.Offset = context.Fp;
#else
#error Platform not supported!
#endif
IMAGEHLP_SYMBOL64_EXT symbol;
symbol.SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);
symbol.MaxNameLength = maxnamelength;
DWORD64 displacement = 0;
int beyond_main=-1; // emergency exit, see below
for (ULONG frame = 0; ; frame++) {
BOOL result = pStackWalk64
(
#if defined(_M_IX86)
IMAGE_FILE_MACHINE_I386,
#elif defined(_M_AMD64)
IMAGE_FILE_MACHINE_AMD64,
#elif defined(_M_ARM64)
IMAGE_FILE_MACHINE_ARM64,
#endif
hProcess,
hThread,
&stack,
&context,
nullptr,
pSymFunctionTableAccess64,
pSymGetModuleBase64,
nullptr
);
if (!result) // official end...
break;
pSymGetSymFromAddr64(hProcess, (ULONG64)stack.AddrPC.Offset, &displacement, &symbol);
TCHAR undname[maxnamelength]= {0};
pUnDecorateSymbolName((const TCHAR*)symbol.Name, (PTSTR)undname, (DWORD)getArrayLength(undname), UNDNAME_COMPLETE);
if (beyond_main>=0)
++beyond_main;
if (_tcscmp(undname, _T("main"))==0)
beyond_main=0;
fprintf(outputFile,
"%lu. 0x%08I64X in ",
frame, (ULONG64)stack.AddrPC.Offset);
fputs((const char *)undname, outputFile);
fputc('\n', outputFile);
if (0==stack.AddrReturn.Offset || beyond_main>2) // StackWalk64() sometimes doesn't reach any end...
break;
}
FreeLibrary(hLibDbgHelp);
hLibDbgHelp=nullptr;
}
void writeMemoryErrorDetails(FILE* outputFile, PEXCEPTION_POINTERS ex, const char* description)
{
fputs(description, outputFile);
fprintf(outputFile, " (instruction: 0x%p) ", ex->ExceptionRecord->ExceptionAddress);
// Using %p for ULONG_PTR later on, so it must have size identical to size of pointer
// This is not the universally portable solution but good enough for Win32/64
C_ASSERT(sizeof(void*) == sizeof(ex->ExceptionRecord->ExceptionInformation[1]));
switch (ex->ExceptionRecord->ExceptionInformation[0]) {
case 0:
fprintf(outputFile, "reading from 0x%p",
reinterpret_cast<void*>(ex->ExceptionRecord->ExceptionInformation[1]));
break;
case 1:
fprintf(outputFile, "writing to 0x%p",
reinterpret_cast<void*>(ex->ExceptionRecord->ExceptionInformation[1]));
break;
case 8:
fprintf(outputFile, "data execution prevention at 0x%p",
reinterpret_cast<void*>(ex->ExceptionRecord->ExceptionInformation[1]));
break;
default:
break;
}
}
/*
* Any evaluation of the exception needs to be done here!
*/
int filterException(FILE *outputFile, int code, PEXCEPTION_POINTERS ex)
{
fputs("Internal error: ", outputFile);
switch (ex->ExceptionRecord->ExceptionCode) {
case EXCEPTION_ACCESS_VIOLATION:
writeMemoryErrorDetails(outputFile, ex, "Access violation");
break;
case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
fputs("Out of array bounds", outputFile);
break;
case EXCEPTION_BREAKPOINT:
fputs("Breakpoint", outputFile);
break;
case EXCEPTION_DATATYPE_MISALIGNMENT:
fputs("Misaligned data", outputFile);
break;
case EXCEPTION_FLT_DENORMAL_OPERAND:
fputs("Denormalized floating-point value", outputFile);
break;
case EXCEPTION_FLT_DIVIDE_BY_ZERO:
fputs("Floating-point divide-by-zero", outputFile);
break;
case EXCEPTION_FLT_INEXACT_RESULT:
fputs("Inexact floating-point value", outputFile);
break;
case EXCEPTION_FLT_INVALID_OPERATION:
fputs("Invalid floating-point operation", outputFile);
break;
case EXCEPTION_FLT_OVERFLOW:
fputs("Floating-point overflow", outputFile);
break;
case EXCEPTION_FLT_STACK_CHECK:
fputs("Floating-point stack overflow", outputFile);
break;
case EXCEPTION_FLT_UNDERFLOW:
fputs("Floating-point underflow", outputFile);
break;
case EXCEPTION_GUARD_PAGE:
fputs("Page-guard access", outputFile);
break;
case EXCEPTION_ILLEGAL_INSTRUCTION:
fputs("Illegal instruction", outputFile);
break;
case EXCEPTION_IN_PAGE_ERROR:
writeMemoryErrorDetails(outputFile, ex, "Invalid page access");
break;
case EXCEPTION_INT_DIVIDE_BY_ZERO:
fputs("Integer divide-by-zero", outputFile);
break;
case EXCEPTION_INT_OVERFLOW:
fputs("Integer overflow", outputFile);
break;
case EXCEPTION_INVALID_DISPOSITION:
fputs("Invalid exception dispatcher", outputFile);
break;
case EXCEPTION_INVALID_HANDLE:
fputs("Invalid handle", outputFile);
break;
case EXCEPTION_NONCONTINUABLE_EXCEPTION:
fputs("Non-continuable exception", outputFile);
break;
case EXCEPTION_PRIV_INSTRUCTION:
fputs("Invalid instruction", outputFile);
break;
case EXCEPTION_SINGLE_STEP:
fputs("Single instruction step", outputFile);
break;
case EXCEPTION_STACK_OVERFLOW:
fputs("Stack overflow", outputFile);
break;
default:
fprintf(outputFile, "Unknown exception (%d)\n",
code);
break;
}
fputc('\n', outputFile);
printCallstack(outputFile, ex);
fflush(outputFile);
return EXCEPTION_EXECUTE_HANDLER;
}
}
/**
* Signal/SEH handling
* Has to be clean for using with SEH on windows, i.e. no construction of C++ object instances is allowed!
* TODO Check for multi-threading issues!
*
*/
int check_wrapper_seh(CppCheckExecutor& executor, int (CppCheckExecutor::*f)(const Settings&) const, const Settings& settings)
{
FILE * const outputFile = settings.exceptionOutput;
__try {
return (&executor->*f)(settings);
} __except (filterException(outputFile, GetExceptionCode(), GetExceptionInformation())) {
fputs("Please report this to the cppcheck developers!\n", outputFile);
return -1;
}
}
#endif
| null |
1,059 | cpp | cppcheck | cmdlineparser.h | cli/cmdlineparser.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#ifndef CMDLINE_PARSER_H
#define CMDLINE_PARSER_H
#include <cstddef>
#include <cstdint>
#include <list>
#include <string>
#include <vector>
#include "cmdlinelogger.h"
#include "filesettings.h"
#include "utils.h"
class Settings;
struct Suppressions;
class Library;
/// @addtogroup CLI
/// @{
/**
* @brief The command line parser.
* The command line parser parses options and parameters user gives to
* cppcheck command line.
*
* The parser takes a pointer to Settings instance which it will update
* based on options user has given. Couple of options are handled as
* class internal options.
*/
class CmdLineParser {
public:
/**
* The constructor.
* @param logger The logger instance to log messages through
* @param settings Settings instance that will be modified according to
* options user has given.
* @param suppressions Suppressions instance that keeps the suppressions
*/
CmdLineParser(CmdLineLogger &logger, Settings &settings, Suppressions &suppressions);
enum class Result : std::uint8_t { Success, Exit, Fail };
/**
* @brief Parse command line args and fill settings and file lists
* from there.
*
* @param argc argc from main()
* @param argv argv from main()
* @return false when errors are found in the input
*/
bool fillSettingsFromArgs(int argc, const char* const argv[]);
/**
* Parse given command line.
* @return true if command line was ok, false if there was an error.
*/
Result parseFromArgs(int argc, const char* const argv[]);
/**
* Return the path names user gave to command line.
*/
const std::vector<std::string>& getPathNames() const {
return mPathNames;
}
/**
* Return the files user gave to command line.
*/
const std::list<FileWithDetails>& getFiles() const {
return mFiles;
}
/**
* Return the file settings read from command line.
*/
const std::list<FileSettings>& getFileSettings() const {
return mFileSettings;
}
/**
* Return a list of paths user wants to ignore.
*/
const std::vector<std::string>& getIgnoredPaths() const {
return mIgnoredPaths;
}
/**
* Get Cppcheck version
*/
std::string getVersion() const;
protected:
/**
* Print help text to the console.
*/
void printHelp() const;
private:
bool isCppcheckPremium() const;
template<typename T>
bool parseNumberArg(const char* const arg, std::size_t offset, T& num, bool mustBePositive = false)
{
T tmp;
std::string err;
if (!strToInt(arg + offset, tmp, &err)) {
mLogger.printError("argument to '" + std::string(arg, offset) + "' is not valid - " + err + ".");
return false;
}
if (mustBePositive && tmp < 0) {
mLogger.printError("argument to '" + std::string(arg, offset) + "' needs to be a positive integer.");
return false;
}
num = tmp;
return true;
}
/**
* Tries to load a library and prints warning/error messages
* @return false, if an error occurred (except unknown XML elements)
*/
bool tryLoadLibrary(Library& destination, const std::string& basepath, const char* filename, bool debug);
/**
* @brief Load libraries
* @param settings Settings
* @return Returns true if successful
*/
bool loadLibraries(Settings& settings);
/**
* @brief Load addons
* @param settings Settings
* @return Returns true if successful
*/
bool loadAddons(Settings& settings);
bool loadCppcheckCfg();
CmdLineLogger &mLogger;
std::vector<std::string> mPathNames;
std::list<FileWithDetails> mFiles;
std::list<FileSettings> mFileSettings;
std::vector<std::string> mIgnoredPaths;
Settings &mSettings;
Suppressions &mSuppressions;
std::string mVSConfig;
};
/// @}
#endif // CMDLINE_PARSER_H
| null |
1,060 | cpp | cppcheck | executor.cpp | cli/executor.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#include "executor.h"
#include "color.h"
#include "errorlogger.h"
#include "library.h"
#include "settings.h"
#include "suppressions.h"
#include <cassert>
#include <sstream>
#include <utility>
struct FileSettings;
Executor::Executor(const std::list<FileWithDetails> &files, const std::list<FileSettings>& fileSettings, const Settings &settings, SuppressionList &suppressions, ErrorLogger &errorLogger)
: mFiles(files), mFileSettings(fileSettings), mSettings(settings), mSuppressions(suppressions), mErrorLogger(errorLogger)
{
// the two inputs may only be used exclusively
assert(!(!files.empty() && !fileSettings.empty()));
}
// TODO: this logic is duplicated in CppCheck::reportErr()
bool Executor::hasToLog(const ErrorMessage &msg)
{
if (!mSettings.library.reportErrors(msg.file0))
return false;
if (!mSuppressions.isSuppressed(msg, {}))
{
// TODO: there should be no need for verbose and default messages here
std::string errmsg = msg.toString(mSettings.verbose);
if (errmsg.empty())
return false;
std::lock_guard<std::mutex> lg(mErrorListSync);
if (mErrorList.emplace(std::move(errmsg)).second) {
return true;
}
}
return false;
}
void Executor::reportStatus(std::size_t fileindex, std::size_t filecount, std::size_t sizedone, std::size_t sizetotal)
{
if (filecount > 1) {
std::ostringstream oss;
const unsigned long percentDone = (sizetotal > 0) ? (100 * sizedone) / sizetotal : 0;
oss << fileindex << '/' << filecount
<< " files checked " << percentDone
<< "% done";
mErrorLogger.reportOut(oss.str(), Color::FgBlue);
}
}
| null |
1,061 | cpp | cppcheck | executor.h | cli/executor.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#ifndef EXECUTOR_H
#define EXECUTOR_H
#include <cstddef>
#include <list>
#include <mutex>
#include <string>
#include <unordered_set>
class Settings;
class ErrorLogger;
class ErrorMessage;
class SuppressionList;
struct FileSettings;
class FileWithDetails;
/// @addtogroup CLI
/// @{
/**
* This class will take a list of filenames and settings and check then
* all files using threads.
*/
class Executor {
public:
Executor(const std::list<FileWithDetails> &files, const std::list<FileSettings>& fileSettings, const Settings &settings, SuppressionList &suppressions, ErrorLogger &errorLogger);
virtual ~Executor() = default;
Executor(const Executor &) = delete;
Executor& operator=(const Executor &) = delete;
virtual unsigned int check() = 0;
/**
* Information about how many files have been checked
*
* @param fileindex This many files have been checked.
* @param filecount This many files there are in total.
* @param sizedone The sum of sizes of the files checked.
* @param sizetotal The total sizes of the files.
*/
void reportStatus(std::size_t fileindex, std::size_t filecount, std::size_t sizedone, std::size_t sizetotal);
protected:
/**
* @brief Check if message is being suppressed and unique.
* @param msg the message to check
* @return true if message is not suppressed and unique
*/
bool hasToLog(const ErrorMessage &msg);
const std::list<FileWithDetails> &mFiles;
const std::list<FileSettings>& mFileSettings;
const Settings &mSettings;
SuppressionList &mSuppressions;
ErrorLogger &mErrorLogger;
private:
std::mutex mErrorListSync;
// TODO: store hashes instead of the full messages
std::unordered_set<std::string> mErrorList;
};
/// @}
#endif // EXECUTOR_H
| null |
1,062 | cpp | cppcheck | signalhandler.h | cli/signalhandler.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#ifndef SIGNALHANDLER_H
#define SIGNALHANDLER_H
#include "config.h"
#if defined(USE_UNIX_SIGNAL_HANDLING)
#include <cstdio>
void register_signal_handler(FILE* output);
#endif // USE_UNIX_SIGNAL_HANDLING
#endif // SIGNALHANDLER_H
| null |
1,063 | cpp | cppcheck | filelister.h | cli/filelister.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#ifndef filelisterH
#define filelisterH
#include <list>
#include <set>
#include <string>
class PathMatch;
class FileWithDetails;
/// @addtogroup CLI
/// @{
/** @brief Cross-platform FileLister */
class FileLister {
public:
/**
* @brief Recursively add source files to a map.
* Add source files from given directory and all subdirectries to the
* given map. Only files with accepted extensions
* (*.c;*.cpp;*.cxx;*.c++;*.cc;*.txx) are added.
* @param files output list that associates the size of each file with its name
* @param path root path
* @param ignored ignored paths
* @return On success, an empty string is returned. On error, a error message is returned.
*/
static std::string recursiveAddFiles(std::list<FileWithDetails> &files, const std::string &path, const PathMatch& ignored) {
const std::set<std::string> extra;
return recursiveAddFiles(files, path, extra, ignored);
}
/**
* @brief Recursively add source files to a map.
* Add source files from given directory and all subdirectries to the
* given map. Only files with accepted extensions
* (*.c;*.cpp;*.cxx;*.c++;*.cc;*.txx) are added.
* @param files output list that associates the size of each file with its name
* @param path root path
* @param extra Extra file extensions
* @param ignored ignored paths
* @return On success, an empty string is returned. On error, a error message is returned.
*/
static std::string recursiveAddFiles(std::list<FileWithDetails> &files, const std::string &path, const std::set<std::string> &extra, const PathMatch& ignored);
/**
* @brief (Recursively) add source files to a map.
* Add source files from given directory and all subdirectries to the
* given map. Only files with accepted extensions
* (*.c;*.cpp;*.cxx;*.c++;*.cc;*.txx) are added.
* @param files output list that associates the size of each file with its name
* @param path root path
* @param extra Extra file extensions
* @param recursive Enable recursion
* @param ignored ignored paths
* @return On success, an empty string is returned. On error, a error message is returned.
*/
static std::string addFiles(std::list<FileWithDetails> &files, const std::string &path, const std::set<std::string> &extra, bool recursive, const PathMatch& ignored);
};
/// @}
#endif // #ifndef filelisterH
| null |
1,064 | cpp | cppcheck | processexecutor.h | cli/processexecutor.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#ifndef PROCESSEXECUTOR_H
#define PROCESSEXECUTOR_H
#include "cppcheck.h"
#include "executor.h"
#include <cstddef>
#include <list>
#include <string>
class Settings;
class ErrorLogger;
class SuppressionList;
struct FileSettings;
class FileWithDetails;
/// @addtogroup CLI
/// @{
/**
* This class will take a list of filenames and settings and check then
* all files using threads.
*/
class ProcessExecutor : public Executor {
public:
ProcessExecutor(const std::list<FileWithDetails> &files, const std::list<FileSettings>& fileSettings, const Settings &settings, SuppressionList &suppressions, ErrorLogger &errorLogger, CppCheck::ExecuteCmdFn executeCommand);
ProcessExecutor(const ProcessExecutor &) = delete;
ProcessExecutor& operator=(const ProcessExecutor &) = delete;
unsigned int check() override;
private:
/**
* Read from the pipe, parse and handle what ever is in there.
* @return False in case of an recoverable error - will exit process on others
*/
bool handleRead(int rpipe, unsigned int &result, const std::string& filename);
/**
* @brief Check load average condition
* @param nchildren - count of currently ran children
* @return true - if new process can be started
*/
bool checkLoadAverage(size_t nchildren);
/**
* @brief Reports internal errors related to child processes
* @param msg The error message
*/
void reportInternalChildErr(const std::string &childname, const std::string &msg);
CppCheck::ExecuteCmdFn mExecuteCommand;
};
/// @}
#endif // PROCESSEXECUTOR_H
| null |
1,065 | cpp | cppcheck | cmdlinelogger.h | cli/cmdlinelogger.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#ifndef CMD_LINE_LOGGER_H
#define CMD_LINE_LOGGER_H
#include <string>
class CmdLineLogger
{
public:
virtual ~CmdLineLogger() = default;
/** print a regular message */
virtual void printMessage(const std::string &message) = 0;
/** print an error message */
virtual void printError(const std::string &message) = 0;
/** print to the output */
virtual void printRaw(const std::string &message) = 0;
};
#endif // CMD_LINE_LOGGER_H
| null |
1,066 | cpp | cppcheck | threadexecutor.h | cli/threadexecutor.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#ifndef THREADEXECUTOR_H
#define THREADEXECUTOR_H
#include "cppcheck.h"
#include "executor.h"
#include <list>
class Settings;
class ErrorLogger;
class SuppressionList;
struct FileSettings;
class FileWithDetails;
/// @addtogroup CLI
/// @{
/**
* This class will take a list of filenames and settings and check then
* all files using threads.
*/
class ThreadExecutor : public Executor {
friend class SyncLogForwarder;
public:
ThreadExecutor(const std::list<FileWithDetails> &files, const std::list<FileSettings>& fileSettings, const Settings &settings, SuppressionList &suppressions, ErrorLogger &errorLogger, CppCheck::ExecuteCmdFn executeCommand);
ThreadExecutor(const ThreadExecutor &) = delete;
ThreadExecutor& operator=(const ThreadExecutor &) = delete;
unsigned int check() override;
CppCheck::ExecuteCmdFn mExecuteCommand;
};
/// @}
#endif // THREADEXECUTOR_H
| null |
1,067 | cpp | cppcheck | processexecutor.cpp | cli/processexecutor.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#include "processexecutor.h"
#if !defined(WIN32) && !defined(__MINGW32__)
#include "config.h"
#include "cppcheck.h"
#include "errorlogger.h"
#include "errortypes.h"
#include "filesettings.h"
#include "settings.h"
#include "suppressions.h"
#include "timer.h"
#include <algorithm>
#include <numeric>
#include <cassert>
#include <cerrno>
#include <csignal>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <list>
#include <map>
#include <sstream>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <utility>
#include <fcntl.h>
#ifdef __SVR4 // Solaris
#include <sys/loadavg.h>
#endif
#if defined(__linux__)
#include <sys/prctl.h>
#endif
enum class Color : std::uint8_t;
// NOLINTNEXTLINE(misc-unused-using-decls) - required for FD_ZERO
using std::memset;
ProcessExecutor::ProcessExecutor(const std::list<FileWithDetails> &files, const std::list<FileSettings>& fileSettings, const Settings &settings, SuppressionList &suppressions, ErrorLogger &errorLogger, CppCheck::ExecuteCmdFn executeCommand)
: Executor(files, fileSettings, settings, suppressions, errorLogger)
, mExecuteCommand(std::move(executeCommand))
{
assert(mSettings.jobs > 1);
}
namespace {
class PipeWriter : public ErrorLogger {
public:
enum PipeSignal : std::uint8_t {REPORT_OUT='1',REPORT_ERROR='2', CHILD_END='5'};
explicit PipeWriter(int pipe) : mWpipe(pipe) {}
void reportOut(const std::string &outmsg, Color c) override {
writeToPipe(REPORT_OUT, static_cast<char>(c) + outmsg);
}
void reportErr(const ErrorMessage &msg) override {
writeToPipe(REPORT_ERROR, msg.serialize());
}
void writeEnd(const std::string& str) const {
writeToPipe(CHILD_END, str);
}
private:
// TODO: how to log file name in error?
void writeToPipeInternal(PipeSignal type, const void* data, std::size_t to_write) const
{
const ssize_t bytes_written = write(mWpipe, data, to_write);
if (bytes_written <= 0) {
const int err = errno;
std::cerr << "#### ThreadExecutor::writeToPipeInternal() error for type " << type << ": " << std::strerror(err) << std::endl;
std::exit(EXIT_FAILURE);
}
// TODO: write until everything is written
if (bytes_written != to_write) {
std::cerr << "#### ThreadExecutor::writeToPipeInternal() error for type " << type << ": insufficient data written (expected: " << to_write << " / got: " << bytes_written << ")" << std::endl;
std::exit(EXIT_FAILURE);
}
}
void writeToPipe(PipeSignal type, const std::string &data) const
{
{
const auto t = static_cast<char>(type);
writeToPipeInternal(type, &t, 1);
}
const auto len = static_cast<unsigned int>(data.length());
{
static constexpr std::size_t l_size = sizeof(unsigned int);
writeToPipeInternal(type, &len, l_size);
}
writeToPipeInternal(type, data.c_str(), len);
}
const int mWpipe;
};
}
bool ProcessExecutor::handleRead(int rpipe, unsigned int &result, const std::string& filename)
{
std::size_t bytes_to_read;
ssize_t bytes_read;
char type = 0;
bytes_to_read = sizeof(char);
bytes_read = read(rpipe, &type, bytes_to_read);
if (bytes_read <= 0) {
if (errno == EAGAIN)
return true;
// TODO: log details about failure
// need to increment so a missing pipe (i.e. premature exit of forked process) results in an error exitcode
++result;
return false;
}
if (bytes_read != bytes_to_read) {
std::cerr << "#### ThreadExecutor::handleRead(" << filename << ") error (type): insufficient data read (expected: " << bytes_to_read << " / got: " << bytes_read << ")" << std::endl;
std::exit(EXIT_FAILURE);
}
if (type != PipeWriter::REPORT_OUT && type != PipeWriter::REPORT_ERROR && type != PipeWriter::CHILD_END) {
std::cerr << "#### ThreadExecutor::handleRead(" << filename << ") invalid type " << int(type) << std::endl;
std::exit(EXIT_FAILURE);
}
unsigned int len = 0;
bytes_to_read = sizeof(len);
bytes_read = read(rpipe, &len, bytes_to_read);
if (bytes_read <= 0) {
const int err = errno;
std::cerr << "#### ThreadExecutor::handleRead(" << filename << ") error (len) for type " << int(type) << ": " << std::strerror(err) << std::endl;
std::exit(EXIT_FAILURE);
}
if (bytes_read != bytes_to_read) {
std::cerr << "#### ThreadExecutor::handleRead(" << filename << ") error (len) for type" << int(type) << ": insufficient data read (expected: " << bytes_to_read << " / got: " << bytes_read << ")" << std::endl;
std::exit(EXIT_FAILURE);
}
std::string buf(len, '\0');
char *data_start = &buf[0];
bytes_to_read = len;
do {
bytes_read = read(rpipe, data_start, bytes_to_read);
if (bytes_read <= 0) {
const int err = errno;
std::cerr << "#### ThreadExecutor::handleRead(" << filename << ") error (buf) for type" << int(type) << ": " << std::strerror(err) << std::endl;
std::exit(EXIT_FAILURE);
}
bytes_to_read -= bytes_read;
data_start += bytes_read;
} while (bytes_to_read != 0);
bool res = true;
if (type == PipeWriter::REPORT_OUT) {
// the first character is the color
const auto c = static_cast<Color>(buf[0]);
// TODO: avoid string copy
mErrorLogger.reportOut(buf.substr(1), c);
} else if (type == PipeWriter::REPORT_ERROR) {
ErrorMessage msg;
try {
msg.deserialize(buf);
} catch (const InternalError& e) {
std::cerr << "#### ThreadExecutor::handleRead(" << filename << ") internal error: " << e.errorMessage << std::endl;
std::exit(EXIT_FAILURE);
}
if (hasToLog(msg))
mErrorLogger.reportErr(msg);
} else if (type == PipeWriter::CHILD_END) {
result += std::stoi(buf);
res = false;
}
return res;
}
bool ProcessExecutor::checkLoadAverage(size_t nchildren)
{
#if defined(__QNX__) || defined(__HAIKU__) // getloadavg() is unsupported on Qnx, Haiku.
(void)nchildren;
return true;
#else
if (!nchildren || !mSettings.loadAverage) {
return true;
}
double sample(0);
if (getloadavg(&sample, 1) != 1) {
// disable load average checking on getloadavg error
return true;
}
if (sample < mSettings.loadAverage) {
return true;
}
return false;
#endif
}
unsigned int ProcessExecutor::check()
{
unsigned int fileCount = 0;
unsigned int result = 0;
const std::size_t totalfilesize = std::accumulate(mFiles.cbegin(), mFiles.cend(), std::size_t(0), [](std::size_t v, const FileWithDetails& p) {
return v + p.size();
});
std::list<int> rpipes;
std::map<pid_t, std::string> childFile;
std::map<int, std::string> pipeFile;
std::size_t processedsize = 0;
std::list<FileWithDetails>::const_iterator iFile = mFiles.cbegin();
std::list<FileSettings>::const_iterator iFileSettings = mFileSettings.cbegin();
for (;;) {
// Start a new child
const size_t nchildren = childFile.size();
if ((iFile != mFiles.cend() || iFileSettings != mFileSettings.cend()) && nchildren < mSettings.jobs && checkLoadAverage(nchildren)) {
int pipes[2];
if (pipe(pipes) == -1) {
std::cerr << "#### ThreadExecutor::check, pipe() failed: "<< std::strerror(errno) << std::endl;
std::exit(EXIT_FAILURE);
}
const int flags = fcntl(pipes[0], F_GETFL, 0);
if (flags < 0) {
std::cerr << "#### ThreadExecutor::check, fcntl(F_GETFL) failed: "<< std::strerror(errno) << std::endl;
std::exit(EXIT_FAILURE);
}
if (fcntl(pipes[0], F_SETFL, flags) < 0) {
std::cerr << "#### ThreadExecutor::check, fcntl(F_SETFL) failed: "<< std::strerror(errno) << std::endl;
std::exit(EXIT_FAILURE);
}
const pid_t pid = fork();
if (pid < 0) {
// Error
std::cerr << "#### ThreadExecutor::check, Failed to create child process: "<< std::strerror(errno) << std::endl;
std::exit(EXIT_FAILURE);
} else if (pid == 0) {
#if defined(__linux__)
prctl(PR_SET_PDEATHSIG, SIGHUP);
#endif
close(pipes[0]);
PipeWriter pipewriter(pipes[1]);
CppCheck fileChecker(pipewriter, false, mExecuteCommand);
fileChecker.settings() = mSettings;
unsigned int resultOfCheck = 0;
if (iFileSettings != mFileSettings.end()) {
resultOfCheck = fileChecker.check(*iFileSettings);
if (fileChecker.settings().clangTidy)
fileChecker.analyseClangTidy(*iFileSettings);
} else {
// Read file from a file
resultOfCheck = fileChecker.check(*iFile);
// TODO: call analyseClangTidy()?
}
pipewriter.writeEnd(std::to_string(resultOfCheck));
std::exit(EXIT_SUCCESS);
}
close(pipes[1]);
rpipes.push_back(pipes[0]);
if (iFileSettings != mFileSettings.end()) {
childFile[pid] = iFileSettings->filename() + ' ' + iFileSettings->cfg;
pipeFile[pipes[0]] = iFileSettings->filename() + ' ' + iFileSettings->cfg;
++iFileSettings;
} else {
childFile[pid] = iFile->path();
pipeFile[pipes[0]] = iFile->path();
++iFile;
}
}
if (!rpipes.empty()) {
fd_set rfds;
FD_ZERO(&rfds);
for (std::list<int>::const_iterator rp = rpipes.cbegin(); rp != rpipes.cend(); ++rp)
FD_SET(*rp, &rfds);
timeval tv; // for every second polling of load average condition
tv.tv_sec = 1;
tv.tv_usec = 0;
const int r = select(*std::max_element(rpipes.cbegin(), rpipes.cend()) + 1, &rfds, nullptr, nullptr, &tv);
if (r > 0) {
std::list<int>::const_iterator rp = rpipes.cbegin();
while (rp != rpipes.cend()) {
if (FD_ISSET(*rp, &rfds)) {
std::string name;
const std::map<int, std::string>::const_iterator p = pipeFile.find(*rp);
if (p != pipeFile.cend()) {
name = p->second;
}
const bool readRes = handleRead(*rp, result, name);
if (!readRes) {
std::size_t size = 0;
if (p != pipeFile.cend()) {
pipeFile.erase(p);
const auto fs = std::find_if(mFiles.cbegin(), mFiles.cend(), [&name](const FileWithDetails& entry) {
return entry.path() == name;
});
if (fs != mFiles.end()) {
size = fs->size();
}
}
fileCount++;
processedsize += size;
if (!mSettings.quiet)
Executor::reportStatus(fileCount, mFiles.size() + mFileSettings.size(), processedsize, totalfilesize);
close(*rp);
rp = rpipes.erase(rp);
} else
++rp;
} else
++rp;
}
}
}
if (!childFile.empty()) {
int stat = 0;
const pid_t child = waitpid(0, &stat, WNOHANG);
if (child > 0) {
std::string childname;
const std::map<pid_t, std::string>::const_iterator c = childFile.find(child);
if (c != childFile.cend()) {
childname = c->second;
childFile.erase(c);
}
if (WIFEXITED(stat)) {
const int exitstatus = WEXITSTATUS(stat);
if (exitstatus != EXIT_SUCCESS) {
std::ostringstream oss;
oss << "Child process exited with " << exitstatus;
reportInternalChildErr(childname, oss.str());
}
} else if (WIFSIGNALED(stat)) {
std::ostringstream oss;
oss << "Child process crashed with signal " << WTERMSIG(stat);
reportInternalChildErr(childname, oss.str());
}
}
}
if (iFile == mFiles.end() && iFileSettings == mFileSettings.end() && rpipes.empty() && childFile.empty()) {
// All done
break;
}
}
// TODO: wee need to get the timing information from the subprocess
if (mSettings.showtime == SHOWTIME_MODES::SHOWTIME_SUMMARY || mSettings.showtime == SHOWTIME_MODES::SHOWTIME_TOP5_SUMMARY)
CppCheck::printTimerResults(mSettings.showtime);
return result;
}
void ProcessExecutor::reportInternalChildErr(const std::string &childname, const std::string &msg)
{
std::list<ErrorMessage::FileLocation> locations;
locations.emplace_back(childname, 0, 0);
const ErrorMessage errmsg(std::move(locations),
emptyString,
Severity::error,
"Internal error: " + msg,
"cppcheckError",
Certainty::normal);
if (!mSuppressions.isSuppressed(errmsg, {}))
mErrorLogger.reportErr(errmsg);
}
#endif // !WIN32
| null |
1,068 | cpp | cppcheck | filelister.cpp | cli/filelister.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#include "filelister.h"
#include "filesettings.h"
#include "path.h"
#include "pathmatch.h"
#include "utils.h"
#include <cstring>
#include <iterator>
#include <memory>
#ifdef _WIN32
///////////////////////////////////////////////////////////////////////////////
////// This code is WIN32 systems /////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
#include <windows.h>
#include <shlwapi.h>
// Here is the catch: cppcheck core is Ansi code (using char type).
// When compiling Unicode targets WinAPI automatically uses *W Unicode versions
// of called functions. Thus, we explicitly call *A versions of the functions.
static std::string addFiles2(std::list<FileWithDetails>&files, const std::string &path, const std::set<std::string> &extra, bool recursive, const PathMatch& ignored)
{
const std::string cleanedPath = Path::toNativeSeparators(path);
// basedir is the base directory which is used to form pathnames.
// It always has a trailing backslash available for concatenation.
std::string basedir;
// searchPattern is the search string passed into FindFirst and FindNext.
std::string searchPattern = cleanedPath;
// The user wants to check all files in a dir
const bool checkAllFilesInDir = Path::isDirectory(cleanedPath);
if (checkAllFilesInDir) {
const char c = cleanedPath.back();
switch (c) {
case '\\':
searchPattern += '*';
basedir = cleanedPath;
break;
case '*':
basedir = cleanedPath.substr(0, cleanedPath.length() - 1);
break;
default:
searchPattern += "\\*";
if (cleanedPath != ".")
basedir = cleanedPath + '\\';
}
} else {
const std::string::size_type pos = cleanedPath.find_last_of('\\');
if (std::string::npos != pos) {
basedir = cleanedPath.substr(0, pos + 1);
}
}
WIN32_FIND_DATAA ffd;
HANDLE hFind = FindFirstFileA(searchPattern.c_str(), &ffd);
if (INVALID_HANDLE_VALUE == hFind) {
const DWORD err = GetLastError();
if (err == ERROR_FILE_NOT_FOUND) {
// no files matched
return "";
}
return "finding files failed. Search pattern: '" + searchPattern + "'. (error: " + std::to_string(err) + ")";
}
std::unique_ptr<void, decltype(&FindClose)> hFind_deleter(hFind, FindClose);
do {
if (ffd.cFileName[0] != '.' && ffd.cFileName[0] != '\0')
{
const char* ansiFfd = ffd.cFileName;
if (std::strchr(ansiFfd,'?')) {
ansiFfd = ffd.cAlternateFileName;
}
const std::string fname(basedir + ansiFfd);
if ((ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) {
// File
if ((!checkAllFilesInDir || Path::acceptFile(fname, extra)) && !ignored.match(fname)) {
std::string nativename = Path::fromNativeSeparators(fname);
// Limitation: file sizes are assumed to fit in a 'size_t'
#ifdef _WIN64
const std::size_t filesize = (static_cast<std::size_t>(ffd.nFileSizeHigh) << 32) | ffd.nFileSizeLow;
#else
const std::size_t filesize = ffd.nFileSizeLow;
#endif
files.emplace_back(std::move(nativename), filesize);
}
} else {
// Directory
if (recursive) {
if (!ignored.match(fname)) {
std::list<FileWithDetails> filesSorted;
std::string err = addFiles2(filesSorted, fname, extra, recursive, ignored);
if (!err.empty())
return err;
// files inside directories need to be sorted as the filesystem doesn't provide a stable order
filesSorted.sort([](const FileWithDetails& a, const FileWithDetails& b) {
return a.path() < b.path();
});
files.insert(files.end(), std::make_move_iterator(filesSorted.begin()), std::make_move_iterator(filesSorted.end()));
}
}
}
}
if (!FindNextFileA(hFind, &ffd)) {
const DWORD err = GetLastError();
// no more files matched
if (err != ERROR_NO_MORE_FILES)
return "failed to get next file (error: " + std::to_string(err) + ")";
break;
}
} while (true);
return "";
}
std::string FileLister::addFiles(std::list<FileWithDetails> &files, const std::string &path, const std::set<std::string> &extra, bool recursive, const PathMatch& ignored)
{
if (path.empty())
return "no path specified";
std::list<FileWithDetails> filesSorted;
std::string err = addFiles2(filesSorted, path, extra, recursive, ignored);
// files need to be sorted as the filesystems dosn't provide a stable order
filesSorted.sort([](const FileWithDetails& a, const FileWithDetails& b) {
return a.path() < b.path();
});
files.insert(files.end(), std::make_move_iterator(filesSorted.begin()), std::make_move_iterator(filesSorted.end()));
return err;
}
#else
///////////////////////////////////////////////////////////////////////////////
////// This code is POSIX-style systems ///////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
#if defined(__CYGWIN__)
#undef __STRICT_ANSI__
#endif
#include <dirent.h>
#include <sys/stat.h>
#include <cerrno>
static std::string addFiles2(std::list<FileWithDetails> &files,
const std::string &path,
const std::set<std::string> &extra,
bool recursive,
const PathMatch& ignored
)
{
if (ignored.match(path))
return "";
struct stat file_stat;
if (stat(path.c_str(), &file_stat) == -1)
return ""; // TODO: return error?
if ((file_stat.st_mode & S_IFMT) != S_IFDIR)
{
files.emplace_back(path, file_stat.st_size);
return "";
}
// process directory entry
DIR * dir = opendir(path.c_str());
if (!dir) {
const int err = errno;
return "could not open directory '" + path + "' (errno: " + std::to_string(err) + ")";
}
std::unique_ptr<DIR, decltype(&closedir)> dir_deleter(dir, closedir);
std::string new_path = path;
new_path += '/';
while (const dirent* dir_result = readdir(dir)) {
if ((std::strcmp(dir_result->d_name, ".") == 0) ||
(std::strcmp(dir_result->d_name, "..") == 0))
continue;
new_path.erase(path.length() + 1);
new_path += dir_result->d_name;
#if defined(_DIRENT_HAVE_D_TYPE) || defined(_BSD_SOURCE)
const bool path_is_directory = (dir_result->d_type == DT_DIR || (dir_result->d_type == DT_UNKNOWN && Path::isDirectory(new_path)));
#else
const bool path_is_directory = Path::isDirectory(new_path);
#endif
if (path_is_directory) {
if (recursive && !ignored.match(new_path)) {
std::string err = addFiles2(files, new_path, extra, recursive, ignored);
if (!err.empty()) {
return err;
}
}
} else {
if (Path::acceptFile(new_path, extra) && !ignored.match(new_path)) {
if (stat(new_path.c_str(), &file_stat) == -1) {
const int err = errno;
return "could not stat file '" + new_path + "' (errno: " + std::to_string(err) + ")";
}
files.emplace_back(new_path, file_stat.st_size);
}
}
}
return "";
}
std::string FileLister::addFiles(std::list<FileWithDetails> &files, const std::string &path, const std::set<std::string> &extra, bool recursive, const PathMatch& ignored)
{
if (path.empty())
return "no path specified";
std::string corrected_path = path;
if (endsWith(corrected_path, '/'))
corrected_path.erase(corrected_path.end() - 1);
std::list<FileWithDetails> filesSorted;
std::string err = addFiles2(filesSorted, corrected_path, extra, recursive, ignored);
// files need to be sorted as the filesystems dosn't provide a stable order
filesSorted.sort([](const FileWithDetails& a, const FileWithDetails& b) {
return a.path() < b.path();
});
files.insert(files.end(), std::make_move_iterator(filesSorted.begin()), std::make_move_iterator(filesSorted.end()));
return err;
}
#endif
std::string FileLister::recursiveAddFiles(std::list<FileWithDetails> &files, const std::string &path, const std::set<std::string> &extra, const PathMatch& ignored)
{
return addFiles(files, path, extra, true, ignored);
}
| null |
1,069 | cpp | cppcheck | cppcheckexecutor.h | cli/cppcheckexecutor.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#ifndef CPPCHECKEXECUTOR_H
#define CPPCHECKEXECUTOR_H
#include "filesettings.h"
#include <list>
#include <string>
#include <vector>
class Settings;
class ErrorLogger;
class SuppressionList;
/**
* This class works as an example of how CppCheck can be used in external
* programs without very little knowledge of the internal parts of the
* program itself. If you wish to use cppcheck e.g. as a part of IDE,
* just rewrite this class for your needs and possibly use other methods
* from CppCheck class instead the ones used here.
*/
class CppCheckExecutor {
public:
friend class TestSuppressions;
/**
* Constructor
*/
CppCheckExecutor() = default;
CppCheckExecutor(const CppCheckExecutor &) = delete;
CppCheckExecutor& operator=(const CppCheckExecutor&) = delete;
/**
* Starts the checking.
*
* @param argc from main()
* @param argv from main()
* @return EXIT_FAILURE if arguments are invalid or no input files
* were found.
* If errors are found and --error-exitcode is used,
* given value is returned instead of default 0.
* If no errors are found, 0 is returned.
*/
int check(int argc, const char* const argv[]);
private:
/**
* Execute a shell command and read the output from it. Returns exitcode of the executed command,.
*/
static int executeCommand(std::string exe, std::vector<std::string> args, std::string redirect, std::string &output_);
protected:
static bool reportSuppressions(const Settings &settings, const SuppressionList& suppressions, bool unusedFunctionCheckEnabled, const std::list<FileWithDetails> &files, const std::list<FileSettings>& fileSettings, ErrorLogger& errorLogger);
/**
* Wrapper around check_internal
* - installs optional platform dependent signal handling
*
* @param settings the settings
**/
int check_wrapper(const Settings& settings);
/**
* Starts the checking.
*
* @param settings the settings
* @return EXIT_FAILURE if arguments are invalid or no input files
* were found.
* If errors are found and --error-exitcode is used,
* given value is returned instead of default 0.
* If no errors are found, 0 is returned.
*/
int check_internal(const Settings& settings) const;
/**
* Filename associated with size of file
*/
std::list<FileWithDetails> mFiles;
std::list<FileSettings> mFileSettings;
};
#endif // CPPCHECKEXECUTOR_H
| null |
1,070 | cpp | cppcheck | singleexecutor.cpp | cli/singleexecutor.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#include "singleexecutor.h"
#include "cppcheck.h"
#include "filesettings.h"
#include "settings.h"
#include "timer.h"
#include <cassert>
#include <cstddef>
#include <list>
#include <numeric>
class ErrorLogger;
SingleExecutor::SingleExecutor(CppCheck &cppcheck, const std::list<FileWithDetails> &files, const std::list<FileSettings>& fileSettings, const Settings &settings, SuppressionList &suppressions, ErrorLogger &errorLogger)
: Executor(files, fileSettings, settings, suppressions, errorLogger)
, mCppcheck(cppcheck)
{
assert(mSettings.jobs == 1);
}
// TODO: markup handling is not performed with multiple jobs
unsigned int SingleExecutor::check()
{
unsigned int result = 0;
const std::size_t totalfilesize = std::accumulate(mFiles.cbegin(), mFiles.cend(), std::size_t(0), [](std::size_t v, const FileWithDetails& f) {
return v + f.size();
});
std::size_t processedsize = 0;
unsigned int c = 0;
for (std::list<FileWithDetails>::const_iterator i = mFiles.cbegin(); i != mFiles.cend(); ++i) {
result += mCppcheck.check(*i);
processedsize += i->size();
++c;
if (!mSettings.quiet)
reportStatus(c, mFiles.size(), processedsize, totalfilesize);
// TODO: call analyseClangTidy()?
}
// filesettings
// check all files of the project
for (const FileSettings &fs : mFileSettings) {
result += mCppcheck.check(fs);
++c;
if (!mSettings.quiet)
reportStatus(c, mFileSettings.size(), c, mFileSettings.size());
if (mSettings.clangTidy)
mCppcheck.analyseClangTidy(fs);
}
if (mCppcheck.analyseWholeProgram())
result++;
if (mSettings.showtime == SHOWTIME_MODES::SHOWTIME_SUMMARY || mSettings.showtime == SHOWTIME_MODES::SHOWTIME_TOP5_SUMMARY)
CppCheck::printTimerResults(mSettings.showtime);
return result;
}
| null |
1,071 | cpp | cppcheck | precompiled.h | cli/precompiled.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#pragma once
// IWYU pragma: begin_keep
#include "config.h"
#include "cppcheck.h"
#include "settings.h"
// IWYU pragma: end_keep
| null |
1,072 | cpp | cppcheck | cppcheckexecutor.cpp | cli/cppcheckexecutor.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#include "cppcheckexecutor.h"
#include "analyzerinfo.h"
#include "checkersreport.h"
#include "cmdlinelogger.h"
#include "cmdlineparser.h"
#include "color.h"
#include "config.h"
#include "cppcheck.h"
#include "errorlogger.h"
#include "errortypes.h"
#include "filesettings.h"
#include "json.h"
#include "settings.h"
#include "singleexecutor.h"
#include "suppressions.h"
#include "utils.h"
#if defined(HAS_THREADING_MODEL_THREAD)
#include "threadexecutor.h"
#endif
#if defined(HAS_THREADING_MODEL_FORK)
#include "processexecutor.h"
#endif
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <cstdio>
#include <cstdlib> // EXIT_SUCCESS and EXIT_FAILURE
#include <ctime>
#include <fstream>
#include <iostream>
#include <list>
#include <set>
#include <sstream>
#include <unordered_set>
#include <utility>
#include <vector>
#ifdef USE_UNIX_SIGNAL_HANDLING
#include "signalhandler.h"
#endif
#ifdef USE_WINDOWS_SEH
#include "cppcheckexecutorseh.h"
#endif
#ifdef _WIN32
#include <windows.h>
#endif
#if !defined(WIN32) && !defined(__MINGW32__)
#include <sys/wait.h> // WIFEXITED and friends
#endif
namespace {
class SarifReport {
public:
void addFinding(ErrorMessage msg) {
mFindings.push_back(std::move(msg));
}
picojson::array serializeRules() const {
picojson::array ret;
std::set<std::string> ruleIds;
for (const auto& finding : mFindings) {
// github only supports findings with locations
if (finding.callStack.empty())
continue;
if (ruleIds.insert(finding.id).second) {
picojson::object rule;
rule["id"] = picojson::value(finding.id);
// rule.shortDescription.text
picojson::object shortDescription;
shortDescription["text"] = picojson::value(finding.shortMessage());
rule["shortDescription"] = picojson::value(shortDescription);
// rule.fullDescription.text
picojson::object fullDescription;
fullDescription["text"] = picojson::value(finding.verboseMessage());
rule["fullDescription"] = picojson::value(fullDescription);
// rule.help.text
picojson::object help;
help["text"] = picojson::value(finding.verboseMessage()); // FIXME provide proper help text
rule["help"] = picojson::value(help);
// rule.properties.precision, rule.properties.problem.severity
picojson::object properties;
properties["precision"] = picojson::value(sarifPrecision(finding));
double securitySeverity = 0;
if (finding.severity == Severity::error && !ErrorLogger::isCriticalErrorId(finding.id))
securitySeverity = 9.9; // We see undefined behavior
//else if (finding.severity == Severity::warning)
// securitySeverity = 5.1; // We see potential undefined behavior
if (securitySeverity > 0.5) {
properties["security-severity"] = picojson::value(securitySeverity);
const picojson::array tags{picojson::value("security")};
properties["tags"] = picojson::value(tags);
}
rule["properties"] = picojson::value(properties);
ret.emplace_back(rule);
}
}
return ret;
}
static picojson::array serializeLocations(const ErrorMessage& finding) {
picojson::array ret;
for (const auto& location : finding.callStack) {
picojson::object physicalLocation;
picojson::object artifactLocation;
artifactLocation["uri"] = picojson::value(location.getfile(false));
physicalLocation["artifactLocation"] = picojson::value(artifactLocation);
picojson::object region;
region["startLine"] = picojson::value(static_cast<int64_t>(location.line));
region["startColumn"] = picojson::value(static_cast<int64_t>(location.column));
region["endLine"] = region["startLine"];
region["endColumn"] = region["startColumn"];
physicalLocation["region"] = picojson::value(region);
picojson::object loc;
loc["physicalLocation"] = picojson::value(physicalLocation);
ret.emplace_back(loc);
}
return ret;
}
picojson::array serializeResults() const {
picojson::array results;
for (const auto& finding : mFindings) {
// github only supports findings with locations
if (finding.callStack.empty())
continue;
picojson::object res;
res["level"] = picojson::value(sarifSeverity(finding));
res["locations"] = picojson::value(serializeLocations(finding));
picojson::object message;
message["text"] = picojson::value(finding.shortMessage());
res["message"] = picojson::value(message);
res["ruleId"] = picojson::value(finding.id);
results.emplace_back(res);
}
return results;
}
picojson::value serializeRuns(const std::string& productName, const std::string& version) const {
picojson::object driver;
driver["name"] = picojson::value(productName);
driver["semanticVersion"] = picojson::value(version);
driver["informationUri"] = picojson::value("https://cppcheck.sourceforge.io");
driver["rules"] = picojson::value(serializeRules());
picojson::object tool;
tool["driver"] = picojson::value(driver);
picojson::object run;
run["tool"] = picojson::value(tool);
run["results"] = picojson::value(serializeResults());
picojson::array runs{picojson::value(run)};
return picojson::value(runs);
}
std::string serialize(std::string productName) const {
const auto nameAndVersion = Settings::getNameAndVersion(productName);
productName = nameAndVersion.first.empty() ? "Cppcheck" : nameAndVersion.first;
std::string version = nameAndVersion.first.empty() ? CppCheck::version() : nameAndVersion.second;
if (version.find(' ') != std::string::npos)
version.erase(version.find(' '), std::string::npos);
picojson::object doc;
doc["version"] = picojson::value("2.1.0");
doc["$schema"] = picojson::value("https://docs.oasis-open.org/sarif/sarif/v2.1.0/errata01/os/schemas/sarif-schema-2.1.0.json");
doc["runs"] = serializeRuns(productName, version);
return picojson::value(doc).serialize(true);
}
private:
static std::string sarifSeverity(const ErrorMessage& errmsg) {
if (ErrorLogger::isCriticalErrorId(errmsg.id))
return "error";
switch (errmsg.severity) {
case Severity::error:
case Severity::warning:
case Severity::style:
case Severity::portability:
case Severity::performance:
return "warning";
case Severity::information:
case Severity::internal:
case Severity::debug:
case Severity::none:
return "note";
}
return "note";
}
static std::string sarifPrecision(const ErrorMessage& errmsg) {
if (errmsg.certainty == Certainty::inconclusive)
return "medium";
return "high";
}
std::vector<ErrorMessage> mFindings;
};
class CmdLineLoggerStd : public CmdLineLogger
{
public:
CmdLineLoggerStd() = default;
void printMessage(const std::string &message) override
{
printRaw("cppcheck: " + message);
}
void printError(const std::string &message) override
{
printMessage("error: " + message);
}
void printRaw(const std::string &message) override
{
std::cout << message << std::endl;
}
};
class StdLogger : public ErrorLogger
{
public:
explicit StdLogger(const Settings& settings)
: mSettings(settings)
{
if (!mSettings.outputFile.empty()) {
mErrorOutput = new std::ofstream(settings.outputFile);
}
}
~StdLogger() override {
if (mSettings.outputFormat == Settings::OutputFormat::sarif) {
reportErr(mSarifReport.serialize(mSettings.cppcheckCfgProductName));
}
delete mErrorOutput;
}
StdLogger(const StdLogger&) = delete;
StdLogger& operator=(const SingleExecutor &) = delete;
void resetLatestProgressOutputTime() {
mLatestProgressOutputTime = std::time(nullptr);
}
/**
* Helper function to print out errors. Appends a line change.
* @param errmsg String printed to error stream
*/
void reportErr(const std::string &errmsg);
/**
* @brief Write the checkers report
*/
void writeCheckersReport();
bool hasCriticalErrors() const {
return !mCriticalErrors.empty();
}
const std::string& getCtuInfo() const {
return mCtuInfo;
}
private:
/**
* Information about progress is directed here. This should be
* called by the CppCheck class only.
*
* @param outmsg Progress message e.g. "Checking main.cpp..."
*/
void reportOut(const std::string &outmsg, Color c = Color::Reset) override;
/** xml output of errors */
void reportErr(const ErrorMessage &msg) override;
void reportProgress(const std::string &filename, const char stage[], std::size_t value) override;
/**
* Pointer to current settings; set while check() is running for reportError().
*/
const Settings& mSettings;
/**
* Used to filter out duplicate error messages.
*/
// TODO: store hashes instead of the full messages
std::unordered_set<std::string> mShownErrors;
/**
* Report progress time
*/
std::time_t mLatestProgressOutputTime{};
/**
* Error output
*/
std::ofstream* mErrorOutput{};
/**
* Checkers that has been executed
*/
std::set<std::string> mActiveCheckers;
/**
* List of critical errors
*/
std::string mCriticalErrors;
/**
* CTU information
*/
std::string mCtuInfo;
/**
* SARIF report generator
*/
SarifReport mSarifReport;
};
}
int CppCheckExecutor::check(int argc, const char* const argv[])
{
Settings settings;
CmdLineLoggerStd logger;
CmdLineParser parser(logger, settings, settings.supprs);
if (!parser.fillSettingsFromArgs(argc, argv)) {
return EXIT_FAILURE;
}
if (Settings::terminated()) {
return EXIT_SUCCESS;
}
settings.loadSummaries();
mFiles = parser.getFiles();
mFileSettings = parser.getFileSettings();
settings.setMisraRuleTexts(executeCommand);
const int ret = check_wrapper(settings);
return ret;
}
int CppCheckExecutor::check_wrapper(const Settings& settings)
{
#ifdef USE_WINDOWS_SEH
if (settings.exceptionHandling)
return check_wrapper_seh(*this, &CppCheckExecutor::check_internal, settings);
#elif defined(USE_UNIX_SIGNAL_HANDLING)
if (settings.exceptionHandling)
register_signal_handler(settings.exceptionOutput);
#endif
return check_internal(settings);
}
bool CppCheckExecutor::reportSuppressions(const Settings &settings, const SuppressionList& suppressions, bool unusedFunctionCheckEnabled, const std::list<FileWithDetails> &files, const std::list<FileSettings>& fileSettings, ErrorLogger& errorLogger) {
const auto& suppr = suppressions.getSuppressions();
if (std::any_of(suppr.begin(), suppr.end(), [](const SuppressionList::Suppression& s) {
return s.errorId == "unmatchedSuppression" && s.fileName.empty() && s.lineNumber == SuppressionList::Suppression::NO_LINE;
}))
return false;
bool err = false;
if (settings.useSingleJob()) {
// the two inputs may only be used exclusively
assert(!(!files.empty() && !fileSettings.empty()));
for (std::list<FileWithDetails>::const_iterator i = files.cbegin(); i != files.cend(); ++i) {
err |= SuppressionList::reportUnmatchedSuppressions(
suppressions.getUnmatchedLocalSuppressions(*i, unusedFunctionCheckEnabled), errorLogger);
}
for (std::list<FileSettings>::const_iterator i = fileSettings.cbegin(); i != fileSettings.cend(); ++i) {
err |= SuppressionList::reportUnmatchedSuppressions(
suppressions.getUnmatchedLocalSuppressions(i->file, unusedFunctionCheckEnabled), errorLogger);
}
}
err |= SuppressionList::reportUnmatchedSuppressions(suppressions.getUnmatchedGlobalSuppressions(unusedFunctionCheckEnabled), errorLogger);
return err;
}
/*
* That is a method which gets called from check_wrapper
* */
int CppCheckExecutor::check_internal(const Settings& settings) const
{
StdLogger stdLogger(settings);
if (settings.reportProgress >= 0)
stdLogger.resetLatestProgressOutputTime();
if (settings.xml) {
stdLogger.reportErr(ErrorMessage::getXMLHeader(settings.cppcheckCfgProductName, settings.xml_version));
}
if (!settings.buildDir.empty()) {
std::list<std::string> fileNames;
for (std::list<FileWithDetails>::const_iterator i = mFiles.cbegin(); i != mFiles.cend(); ++i)
fileNames.emplace_back(i->path());
AnalyzerInformation::writeFilesTxt(settings.buildDir, fileNames, settings.userDefines, mFileSettings);
}
if (!settings.checkersReportFilename.empty())
std::remove(settings.checkersReportFilename.c_str());
CppCheck cppcheck(stdLogger, true, executeCommand);
cppcheck.settings() = settings; // this is a copy
auto& suppressions = cppcheck.settings().supprs.nomsg;
unsigned int returnValue = 0;
if (settings.useSingleJob()) {
// Single process
SingleExecutor executor(cppcheck, mFiles, mFileSettings, settings, suppressions, stdLogger);
returnValue = executor.check();
} else {
#if defined(HAS_THREADING_MODEL_THREAD)
if (settings.executor == Settings::ExecutorType::Thread) {
ThreadExecutor executor(mFiles, mFileSettings, settings, suppressions, stdLogger, CppCheckExecutor::executeCommand);
returnValue = executor.check();
}
#endif
#if defined(HAS_THREADING_MODEL_FORK)
if (settings.executor == Settings::ExecutorType::Process) {
ProcessExecutor executor(mFiles, mFileSettings, settings, suppressions, stdLogger, CppCheckExecutor::executeCommand);
returnValue = executor.check();
}
#endif
}
returnValue |= cppcheck.analyseWholeProgram(settings.buildDir, mFiles, mFileSettings, stdLogger.getCtuInfo());
if (settings.severity.isEnabled(Severity::information) || settings.checkConfiguration) {
const bool err = reportSuppressions(settings, suppressions, settings.checks.isEnabled(Checks::unusedFunction), mFiles, mFileSettings, stdLogger);
if (err && returnValue == 0)
returnValue = settings.exitCode;
}
if (!settings.checkConfiguration) {
cppcheck.tooManyConfigsError(emptyString,0U);
}
stdLogger.writeCheckersReport();
if (settings.xml) {
stdLogger.reportErr(ErrorMessage::getXMLFooter(settings.xml_version));
}
if (settings.safety && stdLogger.hasCriticalErrors())
return EXIT_FAILURE;
if (returnValue)
return settings.exitCode;
return EXIT_SUCCESS;
}
void StdLogger::writeCheckersReport()
{
const bool summary = mSettings.safety || mSettings.severity.isEnabled(Severity::information);
const bool xmlReport = mSettings.xml && mSettings.xml_version == 3;
const bool textReport = !mSettings.checkersReportFilename.empty();
if (!summary && !xmlReport && !textReport)
return;
CheckersReport checkersReport(mSettings, mActiveCheckers);
const auto& suppressions = mSettings.supprs.nomsg.getSuppressions();
const bool summarySuppressed = std::any_of(suppressions.cbegin(), suppressions.cend(), [](const SuppressionList::Suppression& s) {
return s.errorId == "checkersReport";
});
if (summary && !summarySuppressed) {
ErrorMessage msg;
msg.severity = Severity::information;
msg.id = "checkersReport";
const int activeCheckers = checkersReport.getActiveCheckersCount();
const int totalCheckers = checkersReport.getAllCheckersCount();
std::string what;
if (mCriticalErrors.empty())
what = std::to_string(activeCheckers) + "/" + std::to_string(totalCheckers);
else
what = "There was critical errors";
if (!xmlReport && !textReport)
what += " (use --checkers-report=<filename> to see details)";
msg.setmsg("Active checkers: " + what);
reportErr(msg);
}
if (textReport) {
std::ofstream fout(mSettings.checkersReportFilename);
if (fout.is_open())
fout << checkersReport.getReport(mCriticalErrors);
}
if (xmlReport) {
reportErr(" </errors>\n");
reportErr(checkersReport.getXmlReport(mCriticalErrors));
}
}
#ifdef _WIN32
// fix trac ticket #439 'Cppcheck reports wrong filename for filenames containing 8-bit ASCII'
static inline std::string ansiToOEM(const std::string &msg, bool doConvert)
{
if (doConvert) {
const unsigned msglength = msg.length();
// convert ANSI strings to OEM strings in two steps
std::vector<WCHAR> wcContainer(msglength);
std::string result(msglength, '\0');
// ansi code page characters to wide characters
MultiByteToWideChar(CP_ACP, 0, msg.data(), msglength, wcContainer.data(), msglength);
// wide characters to oem codepage characters
WideCharToMultiByte(CP_OEMCP, 0, wcContainer.data(), msglength, &result[0], msglength, nullptr, nullptr);
return result; // hope for return value optimization
}
return msg;
}
#else
// no performance regression on non-windows systems
#define ansiToOEM(msg, doConvert) (msg)
#endif
void StdLogger::reportErr(const std::string &errmsg)
{
if (mErrorOutput)
*mErrorOutput << errmsg << std::endl;
else {
std::cerr << ansiToOEM(errmsg, !mSettings.xml) << std::endl;
}
}
void StdLogger::reportOut(const std::string &outmsg, Color c)
{
if (c == Color::Reset)
std::cout << ansiToOEM(outmsg, true) << std::endl;
else
std::cout << c << ansiToOEM(outmsg, true) << Color::Reset << std::endl;
}
// TODO: remove filename parameter?
void StdLogger::reportProgress(const std::string &filename, const char stage[], const std::size_t value)
{
(void)filename;
if (!mLatestProgressOutputTime)
return;
// Report progress messages every x seconds
const std::time_t currentTime = std::time(nullptr);
if (currentTime >= (mLatestProgressOutputTime + mSettings.reportProgress))
{
mLatestProgressOutputTime = currentTime;
// format a progress message
std::ostringstream ostr;
ostr << "progress: "
<< stage
<< ' ' << value << '%';
// Report progress message
reportOut(ostr.str());
}
}
void StdLogger::reportErr(const ErrorMessage &msg)
{
if (msg.severity == Severity::internal && (msg.id == "logChecker" || endsWith(msg.id, "-logChecker"))) {
const std::string& checker = msg.shortMessage();
mActiveCheckers.emplace(checker);
return;
}
if (msg.severity == Severity::internal && msg.id == "ctuinfo") {
mCtuInfo += msg.shortMessage() + "\n";
return;
}
if (ErrorLogger::isCriticalErrorId(msg.id) && mCriticalErrors.find(msg.id) == std::string::npos) {
if (!mCriticalErrors.empty())
mCriticalErrors += ", ";
mCriticalErrors += msg.id;
if (msg.severity == Severity::internal)
mCriticalErrors += " (suppressed)";
}
if (msg.severity == Severity::internal)
return;
// TODO: we generate a different message here then we log below
// TODO: there should be no need for verbose and default messages here
// Alert only about unique errors
if (!mShownErrors.insert(msg.toString(mSettings.verbose)).second)
return;
if (mSettings.outputFormat == Settings::OutputFormat::sarif)
mSarifReport.addFinding(msg);
else if (mSettings.xml)
reportErr(msg.toXML());
else
reportErr(msg.toString(mSettings.verbose, mSettings.templateFormat, mSettings.templateLocation));
}
/**
* Execute a shell command and read the output from it. Returns true if command terminated successfully.
*/
// cppcheck-suppress passedByValueCallback - used as callback so we need to preserve the signature
// NOLINTNEXTLINE(performance-unnecessary-value-param) - used as callback so we need to preserve the signature
int CppCheckExecutor::executeCommand(std::string exe, std::vector<std::string> args, std::string redirect, std::string &output_)
{
output_.clear();
#ifdef _WIN32
// Extra quoutes are needed in windows if filename has space
if (exe.find(" ") != std::string::npos)
exe = "\"" + exe + "\"";
#endif
std::string joinedArgs;
for (const std::string &arg : args) {
if (!joinedArgs.empty())
joinedArgs += " ";
if (arg.find(' ') != std::string::npos)
joinedArgs += '"' + arg + '"';
else
joinedArgs += arg;
}
const std::string cmd = exe + " " + joinedArgs + " " + redirect;
#ifdef _WIN32
FILE* p = _popen(cmd.c_str(), "r");
#else
FILE *p = popen(cmd.c_str(), "r");
#endif
//std::cout << "invoking command '" << cmd << "'" << std::endl;
if (!p) {
// TODO: how to provide to caller?
//const int err = errno;
//std::cout << "popen() errno " << std::to_string(err) << std::endl;
return -1;
}
char buffer[1024];
while (fgets(buffer, sizeof(buffer), p) != nullptr)
output_ += buffer;
#ifdef _WIN32
const int res = _pclose(p);
#else
const int res = pclose(p);
#endif
if (res == -1) { // error occurred
// TODO: how to provide to caller?
//const int err = errno;
//std::cout << "pclose() errno " << std::to_string(err) << std::endl;
return res;
}
#if !defined(WIN32) && !defined(__MINGW32__)
if (WIFEXITED(res)) {
return WEXITSTATUS(res);
}
if (WIFSIGNALED(res)) {
return WTERMSIG(res);
}
#endif
return res;
}
| null |
1,073 | cpp | cppcheck | stacktrace.h | cli/stacktrace.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#ifndef STACKTRACE_H
#define STACKTRACE_H
#include "config.h"
#ifdef USE_UNIX_BACKTRACE_SUPPORT
#include <cstdio>
/*
* Try to print the callstack.
* That is very sensitive to the operating system, hardware, compiler and runtime.
* The code is not meant for production environment!
* One reason is named first: it's using functions not whitelisted for usage in a signal handler function.
*
* @param output the descriptor to write the trace to
* @param start_idx the frame index to start with
* @param demangling controls demangling of symbols
* @param maxdepth the maximum number of frames to list (32 at most or if -1)
* @param omit_above_own omit top frames which are above our own code (i.e. libc symbols)
*/
void print_stacktrace(FILE* output, int start_idx, bool demangling, int maxdepth, bool omit_above_own);
#endif
#endif // STACKTRACE_H
| null |
1,074 | cpp | cppcheck | cmdlineparser.cpp | cli/cmdlineparser.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#include "cmdlineparser.h"
#include "addoninfo.h"
#include "check.h"
#include "color.h"
#include "config.h"
#include "cppcheck.h"
#include "errorlogger.h"
#include "errortypes.h"
#include "filelister.h"
#include "filesettings.h"
#include "importproject.h"
#include "library.h"
#include "path.h"
#include "pathmatch.h"
#include "platform.h"
#include "settings.h"
#include "standards.h"
#include "suppressions.h"
#include "timer.h"
#include "utils.h"
#include <algorithm>
#include <cassert>
#include <climits>
#include <cstdio>
#include <cstdlib> // EXIT_FAILURE
#include <cstring>
#include <fstream>
#include <iostream>
#include <iterator>
#include <list>
#include <set>
#include <sstream>
#include <unordered_set>
#include <utility>
#ifdef HAVE_RULES
// xml is used for rules
#include "xml.h"
#endif
static bool addFilesToList(const std::string& fileList, std::vector<std::string>& pathNames)
{
std::istream *files;
std::ifstream infile;
if (fileList == "-") { // read from stdin
files = &std::cin;
} else {
infile.open(fileList);
if (!infile.is_open())
return false;
files = &infile;
}
std::string fileName;
// cppcheck-suppress accessMoved - FP
while (std::getline(*files, fileName)) { // next line
// cppcheck-suppress accessMoved - FP
if (!fileName.empty()) {
pathNames.emplace_back(std::move(fileName));
}
}
return true;
}
static bool addIncludePathsToList(const std::string& fileList, std::list<std::string>& pathNames)
{
std::ifstream files(fileList);
if (files) {
std::string pathName;
// cppcheck-suppress accessMoved - FP
while (std::getline(files, pathName)) { // next line
if (!pathName.empty()) {
pathName = Path::removeQuotationMarks(std::move(pathName));
pathName = Path::fromNativeSeparators(std::move(pathName));
// If path doesn't end with / or \, add it
if (!endsWith(pathName, '/'))
pathName += '/';
pathNames.emplace_back(std::move(pathName));
}
}
return true;
}
return false;
}
static bool addPathsToSet(const std::string& fileName, std::set<std::string>& set)
{
std::list<std::string> templist;
if (!addIncludePathsToList(fileName, templist))
return false;
set.insert(templist.cbegin(), templist.cend());
return true;
}
namespace {
class XMLErrorMessagesLogger : public ErrorLogger
{
void reportOut(const std::string & outmsg, Color /*c*/ = Color::Reset) override
{
std::cout << outmsg << std::endl;
}
void reportErr(const ErrorMessage &msg) override
{
reportOut(msg.toXML());
}
void reportProgress(const std::string & /*filename*/, const char /*stage*/[], const std::size_t /*value*/) override
{}
};
}
CmdLineParser::CmdLineParser(CmdLineLogger &logger, Settings &settings, Suppressions &suppressions)
: mLogger(logger)
, mSettings(settings)
, mSuppressions(suppressions)
{}
bool CmdLineParser::fillSettingsFromArgs(int argc, const char* const argv[])
{
const Result result = parseFromArgs(argc, argv);
switch (result) {
case Result::Success:
break;
case Result::Exit:
Settings::terminate();
return true;
case Result::Fail:
return false;
}
// Libraries must be loaded before FileLister is executed to ensure markup files will be
// listed properly.
if (!loadLibraries(mSettings))
return false;
if (!loadAddons(mSettings))
return false;
// Check that all include paths exist
{
for (std::list<std::string>::const_iterator iter = mSettings.includePaths.cbegin();
iter != mSettings.includePaths.cend();
) {
const std::string path(Path::toNativeSeparators(*iter));
if (Path::isDirectory(path))
++iter;
else {
// TODO: this bypasses the template format and other settings
// If the include path is not found, warn user and remove the non-existing path from the list.
if (mSettings.severity.isEnabled(Severity::information))
std::cout << "(information) Couldn't find path given by -I '" << path << '\'' << std::endl;
iter = mSettings.includePaths.erase(iter);
}
}
}
// Output a warning for the user if he tries to exclude headers
const std::vector<std::string>& ignored = getIgnoredPaths();
const bool warn = std::any_of(ignored.cbegin(), ignored.cend(), [](const std::string& i) {
return Path::isHeader(i);
});
if (warn) {
mLogger.printMessage("filename exclusion does not apply to header (.h and .hpp) files.");
mLogger.printMessage("Please use --suppress for ignoring results from the header files.");
}
const std::vector<std::string>& pathnamesRef = getPathNames();
const std::list<FileSettings>& fileSettingsRef = getFileSettings();
// the inputs can only be used exclusively - CmdLineParser should already handle this
assert(!(!pathnamesRef.empty() && !fileSettingsRef.empty()));
if (!fileSettingsRef.empty()) {
// TODO: de-duplicate
std::list<FileSettings> fileSettings;
if (!mSettings.fileFilters.empty()) {
// filter only for the selected filenames from all project files
std::copy_if(fileSettingsRef.cbegin(), fileSettingsRef.cend(), std::back_inserter(fileSettings), [&](const FileSettings &fs) {
return matchglobs(mSettings.fileFilters, fs.filename());
});
if (fileSettings.empty()) {
mLogger.printError("could not find any files matching the filter.");
return false;
}
}
else {
fileSettings = fileSettingsRef;
}
mFileSettings.clear();
// sort the markup last
std::copy_if(fileSettings.cbegin(), fileSettings.cend(), std::back_inserter(mFileSettings), [&](const FileSettings &fs) {
return !mSettings.library.markupFile(fs.filename()) || !mSettings.library.processMarkupAfterCode(fs.filename());
});
std::copy_if(fileSettings.cbegin(), fileSettings.cend(), std::back_inserter(mFileSettings), [&](const FileSettings &fs) {
return mSettings.library.markupFile(fs.filename()) && mSettings.library.processMarkupAfterCode(fs.filename());
});
if (mFileSettings.empty()) {
mLogger.printError("could not find or open any of the paths given.");
return false;
}
}
if (!pathnamesRef.empty()) {
std::list<FileWithDetails> filesResolved;
// TODO: this needs to be inlined into PathMatch as it depends on the underlying filesystem
#if defined(_WIN32)
// For Windows we want case-insensitive path matching
const bool caseSensitive = false;
#else
const bool caseSensitive = true;
#endif
// Execute recursiveAddFiles() to each given file parameter
// TODO: verbose log which files were ignored?
const PathMatch matcher(ignored, caseSensitive);
for (const std::string &pathname : pathnamesRef) {
const std::string err = FileLister::recursiveAddFiles(filesResolved, Path::toNativeSeparators(pathname), mSettings.library.markupExtensions(), matcher);
if (!err.empty()) {
// TODO: bail out?
mLogger.printMessage(err);
}
}
if (filesResolved.empty()) {
mLogger.printError("could not find or open any of the paths given.");
// TODO: PathMatch should provide the information if files were ignored
if (!ignored.empty())
mLogger.printMessage("Maybe all paths were ignored?");
return false;
}
// de-duplicate files
{
auto it = filesResolved.begin();
while (it != filesResolved.end()) {
const std::string& name = it->path();
// TODO: log if duplicated files were dropped
filesResolved.erase(std::remove_if(std::next(it), filesResolved.end(), [&](const FileWithDetails& entry) {
return entry.path() == name;
}), filesResolved.end());
++it;
}
}
std::list<FileWithDetails> files;
if (!mSettings.fileFilters.empty()) {
std::copy_if(filesResolved.cbegin(), filesResolved.cend(), std::inserter(files, files.end()), [&](const FileWithDetails& entry) {
return matchglobs(mSettings.fileFilters, entry.path());
});
if (files.empty()) {
mLogger.printError("could not find any files matching the filter.");
return false;
}
}
else {
files = std::move(filesResolved);
}
// sort the markup last
std::copy_if(files.cbegin(), files.cend(), std::inserter(mFiles, mFiles.end()), [&](const FileWithDetails& entry) {
return !mSettings.library.markupFile(entry.path()) || !mSettings.library.processMarkupAfterCode(entry.path());
});
std::copy_if(files.cbegin(), files.cend(), std::inserter(mFiles, mFiles.end()), [&](const FileWithDetails& entry) {
return mSettings.library.markupFile(entry.path()) && mSettings.library.processMarkupAfterCode(entry.path());
});
if (mFiles.empty()) {
mLogger.printError("could not find or open any of the paths given.");
return false;
}
}
return true;
}
// TODO: normalize/simplify/native all path parameters
// TODO: error out on all missing given files/paths
CmdLineParser::Result CmdLineParser::parseFromArgs(int argc, const char* const argv[])
{
mSettings.exename = Path::getCurrentExecutablePath(argv[0]);
// default to --check-level=normal from CLI for now
mSettings.setCheckLevel(Settings::CheckLevel::normal);
if (argc <= 1) {
printHelp();
return Result::Exit;
}
// check for exclusive options
for (int i = 1; i < argc; i++) {
// documentation..
if (std::strcmp(argv[i], "--doc") == 0) {
std::ostringstream doc;
// Get documentation..
for (const Check * it : Check::instances()) {
const std::string& name(it->name());
const std::string info(it->classInfo());
if (!name.empty() && !info.empty())
doc << "## " << name << " ##\n"
<< info << "\n";
}
mLogger.printRaw(doc.str());
return Result::Exit;
}
// print all possible error messages..
if (std::strcmp(argv[i], "--errorlist") == 0) {
if (!loadCppcheckCfg())
return Result::Fail;
{
XMLErrorMessagesLogger xmlLogger;
std::cout << ErrorMessage::getXMLHeader(mSettings.cppcheckCfgProductName, 2);
CppCheck::getErrorMessages(xmlLogger);
std::cout << ErrorMessage::getXMLFooter(2) << std::endl;
}
return Result::Exit;
}
// Print help
if (std::strcmp(argv[i], "-h") == 0 || std::strcmp(argv[i], "--help") == 0) {
printHelp();
return Result::Exit;
}
if (std::strcmp(argv[i], "--version") == 0) {
if (!loadCppcheckCfg())
return Result::Fail;
const std::string version = getVersion();
mLogger.printRaw(version);
return Result::Exit;
}
}
bool def = false;
bool maxconfigs = false;
ImportProject project;
bool executorAuto = true;
for (int i = 1; i < argc; i++) {
if (argv[i][0] == '-') {
// User define
if (std::strncmp(argv[i], "-D", 2) == 0) {
std::string define;
// "-D define"
if (std::strcmp(argv[i], "-D") == 0) {
++i;
if (i >= argc || argv[i][0] == '-') {
mLogger.printError("argument to '-D' is missing.");
return Result::Fail;
}
define = argv[i];
}
// "-Ddefine"
else {
define = 2 + argv[i];
}
// No "=", append a "=1"
if (define.find('=') == std::string::npos)
define += "=1";
if (!mSettings.userDefines.empty())
mSettings.userDefines += ";";
mSettings.userDefines += define;
def = true;
}
// -E
else if (std::strcmp(argv[i], "-E") == 0) {
mSettings.preprocessOnly = true;
mSettings.quiet = true;
}
// Include paths
else if (std::strncmp(argv[i], "-I", 2) == 0) {
std::string path;
// "-I path/"
if (std::strcmp(argv[i], "-I") == 0) {
++i;
if (i >= argc || argv[i][0] == '-') {
mLogger.printError("argument to '-I' is missing.");
return Result::Fail;
}
path = argv[i];
}
// "-Ipath/"
else {
path = 2 + argv[i];
}
path = Path::removeQuotationMarks(std::move(path));
path = Path::fromNativeSeparators(std::move(path));
// If path doesn't end with / or \, add it
if (!endsWith(path,'/'))
path += '/';
mSettings.includePaths.emplace_back(std::move(path));
}
// User undef
else if (std::strncmp(argv[i], "-U", 2) == 0) {
std::string undef;
// "-U undef"
if (std::strcmp(argv[i], "-U") == 0) {
++i;
if (i >= argc || argv[i][0] == '-') {
mLogger.printError("argument to '-U' is missing.");
return Result::Fail;
}
undef = argv[i];
}
// "-Uundef"
else {
undef = 2 + argv[i];
}
mSettings.userUndefs.insert(std::move(undef));
}
else if (std::strncmp(argv[i], "--addon=", 8) == 0)
mSettings.addons.emplace(argv[i]+8);
else if (std::strncmp(argv[i],"--addon-python=", 15) == 0)
mSettings.addonPython.assign(argv[i]+15);
// Check configuration
else if (std::strcmp(argv[i], "--check-config") == 0)
mSettings.checkConfiguration = true;
// Check level
else if (std::strncmp(argv[i], "--check-level=", 14) == 0) {
Settings::CheckLevel level = Settings::CheckLevel::normal;
const std::string level_s(argv[i] + 14);
if (level_s == "reduced")
level = Settings::CheckLevel::reduced;
else if (level_s == "normal")
level = Settings::CheckLevel::normal;
else if (level_s == "exhaustive")
level = Settings::CheckLevel::exhaustive;
else {
mLogger.printError("unknown '--check-level' value '" + level_s + "'.");
return Result::Fail;
}
mSettings.setCheckLevel(level);
}
// Check library definitions
else if (std::strcmp(argv[i], "--check-library") == 0) {
mSettings.checkLibrary = true;
}
else if (std::strncmp(argv[i], "--check-version=", 16) == 0) {
if (!loadCppcheckCfg())
return Result::Fail;
const std::string actualVersion = getVersion();
const std::string wantedVersion = argv[i] + 16;
if (actualVersion != wantedVersion) {
mLogger.printError("--check-version check failed. Aborting.");
return Result::Fail;
}
}
else if (std::strncmp(argv[i], "--checkers-report=", 18) == 0)
mSettings.checkersReportFilename = argv[i] + 18;
else if (std::strncmp(argv[i], "--checks-max-time=", 18) == 0) {
if (!parseNumberArg(argv[i], 18, mSettings.checksMaxTime, true))
return Result::Fail;
}
else if (std::strcmp(argv[i], "--clang") == 0) {
mSettings.clang = true;
}
else if (std::strncmp(argv[i], "--clang=", 8) == 0) {
mSettings.clang = true;
mSettings.clangExecutable = argv[i] + 8;
}
else if (std::strncmp(argv[i], "--config-exclude=",17) ==0) {
mSettings.configExcludePaths.insert(Path::fromNativeSeparators(argv[i] + 17));
}
else if (std::strncmp(argv[i], "--config-excludes-file=", 23) == 0) {
// open this file and read every input file (1 file name per line)
const std::string cfgExcludesFile(23 + argv[i]);
if (!addPathsToSet(cfgExcludesFile, mSettings.configExcludePaths)) {
mLogger.printError("unable to open config excludes file at '" + cfgExcludesFile + "'");
return Result::Fail;
}
}
else if (std::strncmp(argv[i], "--cppcheck-build-dir=", 21) == 0) {
std::string path = Path::fromNativeSeparators(argv[i] + 21);
if (path.empty()) {
mLogger.printError("no path has been specified for --cppcheck-build-dir");
return Result::Fail;
}
mSettings.buildDir = std::move(path);
if (endsWith(mSettings.buildDir, '/'))
mSettings.buildDir.pop_back();
}
else if (std::strcmp(argv[i], "--cpp-header-probe") == 0) {
mSettings.cppHeaderProbe = true;
}
// Show --debug output after the first simplifications
else if (std::strcmp(argv[i], "--debug") == 0 ||
std::strcmp(argv[i], "--debug-normal") == 0)
mSettings.debugnormal = true;
// Show debug warnings for lookup for configuration files
else if (std::strcmp(argv[i], "--debug-lookup") == 0)
mSettings.debuglookup = true;
else if (std::strncmp(argv[i], "--debug-lookup=", 15) == 0) {
const std::string lookup = argv[i] + 15;
if (lookup == "all")
mSettings.debuglookup = true;
else if (lookup == "addon")
mSettings.debuglookupAddon = true;
else if (lookup == "config")
mSettings.debuglookupConfig = true;
else if (lookup == "library")
mSettings.debuglookupLibrary = true;
else if (lookup == "platform")
mSettings.debuglookupPlatform = true;
else
{
mLogger.printError("unknown lookup '" + lookup + "'");
return Result::Fail;
}
}
// Flag used for various purposes during debugging
else if (std::strcmp(argv[i], "--debug-simplified") == 0)
mSettings.debugSimplified = true;
// Show template information
else if (std::strcmp(argv[i], "--debug-template") == 0)
mSettings.debugtemplate = true;
// Show debug warnings
else if (std::strcmp(argv[i], "--debug-warnings") == 0)
mSettings.debugwarnings = true;
else if (std::strncmp(argv[i], "--disable=", 10) == 0) {
const std::string errmsg = mSettings.removeEnabled(argv[i] + 10);
if (!errmsg.empty()) {
mLogger.printError(errmsg);
return Result::Fail;
}
}
// dump cppcheck data
else if (std::strcmp(argv[i], "--dump") == 0)
mSettings.dump = true;
else if (std::strncmp(argv[i], "--enable=", 9) == 0) {
const std::string enable_arg = argv[i] + 9;
const std::string errmsg = mSettings.addEnabled(enable_arg);
if (!errmsg.empty()) {
mLogger.printError(errmsg);
return Result::Fail;
}
// when "style" is enabled, also enable "warning", "performance" and "portability"
if (enable_arg.find("style") != std::string::npos) {
mSettings.addEnabled("warning");
mSettings.addEnabled("performance");
mSettings.addEnabled("portability");
}
}
// --error-exitcode=1
else if (std::strncmp(argv[i], "--error-exitcode=", 17) == 0) {
if (!parseNumberArg(argv[i], 17, mSettings.exitCode))
return Result::Fail;
}
// Exception handling inside cppcheck client
else if (std::strcmp(argv[i], "--exception-handling") == 0) {
#if defined(USE_WINDOWS_SEH) || defined(USE_UNIX_SIGNAL_HANDLING)
mSettings.exceptionHandling = true;
#else
mLogger.printError("Option --exception-handling is not supported since Cppcheck has not been built with any exception handling enabled.");
return Result::Fail;
#endif
}
// Exception handling inside cppcheck client
else if (std::strncmp(argv[i], "--exception-handling=", 21) == 0) {
#if defined(USE_WINDOWS_SEH) || defined(USE_UNIX_SIGNAL_HANDLING)
const std::string exceptionOutfilename = argv[i] + 21;
if (exceptionOutfilename != "stderr" && exceptionOutfilename != "stdout") {
mLogger.printError("invalid '--exception-handling' argument");
return Result::Fail;
}
mSettings.exceptionHandling = true;
mSettings.exceptionOutput = (exceptionOutfilename == "stderr") ? stderr : stdout;
#else
mLogger.printError("Option --exception-handling is not supported since Cppcheck has not been built with any exception handling enabled.");
return Result::Fail;
#endif
}
else if (std::strncmp(argv[i], "--executor=", 11) == 0) {
const std::string type = 11 + argv[i];
if (type == "auto") {
executorAuto = true;
mSettings.executor = Settings::defaultExecutor();
}
else if (type == "thread") {
#if defined(HAS_THREADING_MODEL_THREAD)
executorAuto = false;
mSettings.executor = Settings::ExecutorType::Thread;
#else
mLogger.printError("executor type 'thread' cannot be used as Cppcheck has not been built with a respective threading model.");
return Result::Fail;
#endif
}
else if (type == "process") {
#if defined(HAS_THREADING_MODEL_FORK)
executorAuto = false;
mSettings.executor = Settings::ExecutorType::Process;
#else
mLogger.printError("executor type 'process' cannot be used as Cppcheck has not been built with a respective threading model.");
return Result::Fail;
#endif
}
else {
mLogger.printError("unknown executor: '" + type + "'.");
return Result::Fail;
}
}
// Filter errors
else if (std::strncmp(argv[i], "--exitcode-suppressions=", 24) == 0) {
// exitcode-suppressions=filename.txt
std::string filename = 24 + argv[i];
std::ifstream f(filename);
if (!f.is_open()) {
mLogger.printError("couldn't open the file: \"" + filename + "\".");
return Result::Fail;
}
const std::string errmsg(mSuppressions.nofail.parseFile(f));
if (!errmsg.empty()) {
mLogger.printError(errmsg);
return Result::Fail;
}
}
// use a file filter
else if (std::strncmp(argv[i], "--file-filter=", 14) == 0) {
const char *filter = argv[i] + 14;
if (std::strcmp(filter, "-") == 0) {
if (!addFilesToList(filter, mSettings.fileFilters)) {
mLogger.printError("Failed: --file-filter=-");
return Result::Fail;
}
} else {
mSettings.fileFilters.emplace_back(filter);
}
}
// file list specified
else if (std::strncmp(argv[i], "--file-list=", 12) == 0) {
// open this file and read every input file (1 file name per line)
const std::string fileList = argv[i] + 12;
if (!addFilesToList(fileList, mPathNames)) {
mLogger.printError("couldn't open the file: \"" + fileList + "\".");
return Result::Fail;
}
}
// Force checking of files that have "too many" configurations
else if (std::strcmp(argv[i], "-f") == 0 || std::strcmp(argv[i], "--force") == 0)
mSettings.force = true;
else if (std::strcmp(argv[i], "--fsigned-char") == 0)
mSettings.platform.defaultSign = 's';
else if (std::strcmp(argv[i], "--funsigned-char") == 0)
mSettings.platform.defaultSign = 'u';
// Ignored paths
else if (std::strncmp(argv[i], "-i", 2) == 0) {
std::string path;
// "-i path/"
if (std::strcmp(argv[i], "-i") == 0) {
++i;
if (i >= argc || argv[i][0] == '-') {
mLogger.printError("argument to '-i' is missing.");
return Result::Fail;
}
path = argv[i];
}
// "-ipath/"
else {
path = 2 + argv[i];
}
if (!path.empty()) {
path = Path::removeQuotationMarks(std::move(path));
path = Path::simplifyPath(std::move(path));
// TODO: this only works when it exists
if (Path::isDirectory(path)) {
// If directory name doesn't end with / or \, add it
if (!endsWith(path, '/'))
path += '/';
}
mIgnoredPaths.emplace_back(std::move(path));
}
}
else if (std::strncmp(argv[i], "--include=", 10) == 0) {
mSettings.userIncludes.emplace_back(Path::fromNativeSeparators(argv[i] + 10));
}
else if (std::strncmp(argv[i], "--includes-file=", 16) == 0) {
// open this file and read every input file (1 file name per line)
const std::string includesFile(16 + argv[i]);
if (!addIncludePathsToList(includesFile, mSettings.includePaths)) {
mLogger.printError("unable to open includes file at '" + includesFile + "'");
return Result::Fail;
}
}
// Inconclusive checking
else if (std::strcmp(argv[i], "--inconclusive") == 0)
mSettings.certainty.enable(Certainty::inconclusive);
// Enables inline suppressions.
else if (std::strcmp(argv[i], "--inline-suppr") == 0)
mSettings.inlineSuppressions = true;
// Checking threads
else if (std::strncmp(argv[i], "-j", 2) == 0) {
std::string numberString;
// "-j 3"
if (std::strcmp(argv[i], "-j") == 0) {
++i;
if (i >= argc || argv[i][0] == '-') {
mLogger.printError("argument to '-j' is missing.");
return Result::Fail;
}
numberString = argv[i];
}
// "-j3"
else
numberString = argv[i]+2;
unsigned int tmp;
std::string err;
if (!strToInt(numberString, tmp, &err)) {
mLogger.printError("argument to '-j' is not valid - " + err + ".");
return Result::Fail;
}
if (tmp == 0) {
// TODO: implement get CPU logical core count and use that.
// Usually, -j 0 would mean "use all available cores," but
// if we get a 0, we just stall and don't do any work.
mLogger.printError("argument for '-j' must be greater than 0.");
return Result::Fail;
}
if (tmp > 1024) {
// Almost nobody has 1024 logical cores, but somebody out
// there does.
mLogger.printError("argument for '-j' is allowed to be 1024 at max.");
return Result::Fail;
}
mSettings.jobs = tmp;
}
else if (std::strncmp(argv[i], "-l", 2) == 0) {
#ifdef HAS_THREADING_MODEL_FORK
std::string numberString;
// "-l 3"
if (std::strcmp(argv[i], "-l") == 0) {
++i;
if (i >= argc || argv[i][0] == '-') {
mLogger.printError("argument to '-l' is missing.");
return Result::Fail;
}
numberString = argv[i];
}
// "-l3"
else
numberString = argv[i]+2;
int tmp;
std::string err;
if (!strToInt(numberString, tmp, &err)) {
mLogger.printError("argument to '-l' is not valid - " + err + ".");
return Result::Fail;
}
mSettings.loadAverage = tmp;
#else
mLogger.printError("Option -l cannot be used as Cppcheck has not been built with fork threading model.");
return Result::Fail;
#endif
}
// Enforce language (--language=, -x)
else if (std::strncmp(argv[i], "--language=", 11) == 0 || std::strcmp(argv[i], "-x") == 0) {
std::string str;
if (argv[i][2]) {
str = argv[i]+11;
} else {
i++;
if (i >= argc || argv[i][0] == '-') {
mLogger.printError("no language given to '-x' option.");
return Result::Fail;
}
str = argv[i];
}
if (str == "c")
mSettings.enforcedLang = Standards::Language::C;
else if (str == "c++")
mSettings.enforcedLang = Standards::Language::CPP;
else {
mLogger.printError("unknown language '" + str + "' enforced.");
return Result::Fail;
}
}
// --library
else if (std::strncmp(argv[i], "--library=", 10) == 0) {
std::list<std::string> libs = splitString(argv[i] + 10, ',');
for (auto& l : libs) {
if (l.empty()) {
mLogger.printError("empty library specified.");
return Result::Fail;
}
mSettings.libraries.emplace_back(std::move(l));
}
}
// Set maximum number of #ifdef configurations to check
else if (std::strncmp(argv[i], "--max-configs=", 14) == 0) {
int tmp;
if (!parseNumberArg(argv[i], 14, tmp))
return Result::Fail;
if (tmp < 1) {
mLogger.printError("argument to '--max-configs=' must be greater than 0.");
return Result::Fail;
}
mSettings.maxConfigs = tmp;
mSettings.force = false;
maxconfigs = true;
}
// max ctu depth
else if (std::strncmp(argv[i], "--max-ctu-depth=", 16) == 0) {
int temp = 0;
if (!parseNumberArg(argv[i], 16, temp))
return Result::Fail;
if (temp > 10) {
mLogger.printMessage("--max-ctu-depth is being capped at 10. This limitation will be removed in a future Cppcheck version.");
temp = 10;
}
mSettings.maxCtuDepth = temp;
}
else if (std::strncmp(argv[i], "--max-template-recursion=", 25) == 0) {
int temp = 0;
if (!parseNumberArg(argv[i], 25, temp))
return Result::Fail;
mSettings.maxTemplateRecursion = temp;
}
// undocumented option for usage in Python tests to indicate that no build dir should be injected
else if (std::strcmp(argv[i], "--no-cppcheck-build-dir") == 0) {
mSettings.buildDir.clear();
}
else if (std::strcmp(argv[i], "--no-cpp-header-probe") == 0) {
mSettings.cppHeaderProbe = false;
}
// Write results in file
else if (std::strncmp(argv[i], "--output-file=", 14) == 0)
mSettings.outputFile = Path::simplifyPath(argv[i] + 14);
else if (std::strncmp(argv[i], "--output-format=", 16) == 0) {
const std::string format = argv[i] + 16;
if (format == "sarif")
mSettings.outputFormat = Settings::OutputFormat::sarif;
else if (format == "xml")
mSettings.outputFormat = Settings::OutputFormat::xml;
else {
mLogger.printError("argument to '--output-format=' must be 'sarif' or 'xml'.");
return Result::Fail;
}
mSettings.xml = (mSettings.outputFormat == Settings::OutputFormat::xml);
}
// Experimental: limit execution time for extended valueflow analysis. basic valueflow analysis
// is always executed.
else if (std::strncmp(argv[i], "--performance-valueflow-max-time=", 33) == 0) {
if (!parseNumberArg(argv[i], 33, mSettings.vfOptions.maxTime, true))
return Result::Fail;
}
else if (std::strncmp(argv[i], "--performance-valueflow-max-if-count=", 37) == 0) {
if (!parseNumberArg(argv[i], 37, mSettings.vfOptions.maxIfCount, true))
return Result::Fail;
}
else if (std::strncmp(argv[i], "--performance-valueflow-max-iterations=", 39) == 0) {
if (!parseNumberArg(argv[i], 39, mSettings.vfOptions.maxIterations, true))
return Result::Fail;
}
// Specify platform
else if (std::strncmp(argv[i], "--platform=", 11) == 0) {
const std::string platform(11+argv[i]);
std::string errstr;
const std::vector<std::string> paths = {argv[0]};
if (!mSettings.platform.set(platform, errstr, paths, mSettings.debuglookup || mSettings.debuglookupPlatform)) {
mLogger.printError(errstr);
return Result::Fail;
}
// TODO: remove
// these are loaded via external files and thus have Settings::PlatformFile set instead.
// override the type so they behave like the regular platforms.
if (platform == "unix32-unsigned")
mSettings.platform.type = Platform::Type::Unix32;
else if (platform == "unix64-unsigned")
mSettings.platform.type = Platform::Type::Unix64;
}
// Write results in results.plist
else if (std::strncmp(argv[i], "--plist-output=", 15) == 0) {
mSettings.outputFormat = Settings::OutputFormat::plist;
mSettings.plistOutput = Path::simplifyPath(argv[i] + 15);
if (mSettings.plistOutput.empty())
mSettings.plistOutput = ".";
const std::string plistOutput = Path::toNativeSeparators(mSettings.plistOutput);
if (!Path::isDirectory(plistOutput)) {
std::string message("plist folder does not exist: '");
message += plistOutput;
message += "'.";
mLogger.printError(message);
return Result::Fail;
}
if (!endsWith(mSettings.plistOutput,'/'))
mSettings.plistOutput += '/';
}
// Special Cppcheck Premium options
else if ((std::strncmp(argv[i], "--premium=", 10) == 0 || std::strncmp(argv[i], "--premium-", 10) == 0) && isCppcheckPremium()) {
// valid options --premium=..
const std::set<std::string> valid{
"autosar",
"cert-c-2016",
"cert-c++-2016",
"cert-cpp-2016",
"misra-c-2012",
"misra-c-2023",
"misra-c++-2008",
"misra-cpp-2008",
"misra-c++-2023",
"misra-cpp-2023",
"bughunting",
"safety"};
// valid options --premium-..=
const std::set<std::string> valid2{
"cert-c-int-precision",
"license-file"
};
if (std::strcmp(argv[i], "--premium=safety-off") == 0) {
mSettings.safety = false;
continue;
}
if (std::strcmp(argv[i], "--premium=safety") == 0)
mSettings.safety = true;
if (!mSettings.premiumArgs.empty())
mSettings.premiumArgs += " ";
const std::string p(argv[i] + 10);
const std::string p2(p.find('=') != std::string::npos ? p.substr(0, p.find('=')) : "");
if (!valid.count(p) && !valid2.count(p2)) {
mLogger.printError("invalid --premium option '" + (p2.empty() ? p : p2) + "'.");
return Result::Fail;
}
mSettings.premiumArgs += "--" + p;
if (p == "misra-c-2012" || p == "misra-c-2023")
mSettings.addons.emplace("misra");
if (startsWith(p, "autosar") || startsWith(p, "cert") || startsWith(p, "misra")) {
// All checkers related to the coding standard should be enabled. The coding standards
// do not all undefined behavior or portability issues.
mSettings.addEnabled("warning");
mSettings.addEnabled("portability");
}
}
// --project
else if (std::strncmp(argv[i], "--project=", 10) == 0) {
if (project.projectType != ImportProject::Type::NONE)
{
mLogger.printError("multiple --project options are not supported.");
return Result::Fail;
}
mSettings.checkAllConfigurations = false; // Can be overridden with --max-configs or --force
std::string projectFile = argv[i]+10;
ImportProject::Type projType = project.import(projectFile, &mSettings);
project.projectType = projType;
if (projType == ImportProject::Type::CPPCHECK_GUI) {
for (const std::string &lib : project.guiProject.libraries)
mSettings.libraries.emplace_back(lib);
const auto& excludedPaths = project.guiProject.excludedPaths;
std::copy(excludedPaths.cbegin(), excludedPaths.cend(), std::back_inserter(mIgnoredPaths));
std::string platform(project.guiProject.platform);
// keep existing platform from command-line intact
if (!platform.empty()) {
std::string errstr;
const std::vector<std::string> paths = {projectFile, argv[0]};
if (!mSettings.platform.set(platform, errstr, paths, mSettings.debuglookup || mSettings.debuglookupPlatform)) {
mLogger.printError(errstr);
return Result::Fail;
}
}
const auto& projectFileGui = project.guiProject.projectFile;
if (!projectFileGui.empty()) {
// read underlying project
projectFile = projectFileGui;
projType = project.import(projectFileGui, &mSettings);
}
}
if (projType == ImportProject::Type::VS_SLN || projType == ImportProject::Type::VS_VCXPROJ) {
if (project.guiProject.analyzeAllVsConfigs == "false")
project.selectOneVsConfig(mSettings.platform.type);
mSettings.libraries.emplace_back("windows");
}
if (projType == ImportProject::Type::MISSING) {
mLogger.printError("failed to open project '" + projectFile + "'. The file does not exist.");
return Result::Fail;
}
if (projType == ImportProject::Type::UNKNOWN) {
mLogger.printError("failed to load project '" + projectFile + "'. The format is unknown.");
return Result::Fail;
}
if (projType == ImportProject::Type::FAILURE) {
mLogger.printError("failed to load project '" + projectFile + "'. An error occurred.");
return Result::Fail;
}
}
// --project-configuration
else if (std::strncmp(argv[i], "--project-configuration=", 24) == 0) {
mVSConfig = argv[i] + 24;
// TODO: provide error when this does nothing
if (!mVSConfig.empty() && (project.projectType == ImportProject::Type::VS_SLN || project.projectType == ImportProject::Type::VS_VCXPROJ))
project.ignoreOtherConfigs(mVSConfig);
}
// Only print something when there are errors
else if (std::strcmp(argv[i], "-q") == 0 || std::strcmp(argv[i], "--quiet") == 0)
mSettings.quiet = true;
// Output relative paths
else if (std::strcmp(argv[i], "-rp") == 0 || std::strcmp(argv[i], "--relative-paths") == 0)
mSettings.relativePaths = true;
else if (std::strncmp(argv[i], "-rp=", 4) == 0 || std::strncmp(argv[i], "--relative-paths=", 17) == 0) {
mSettings.relativePaths = true;
if (argv[i][argv[i][3]=='='?4:17] != 0) {
std::string paths = argv[i]+(argv[i][3]=='='?4:17);
for (;;) {
const std::string::size_type pos = paths.find(';');
if (pos == std::string::npos) {
mSettings.basePaths.emplace_back(Path::fromNativeSeparators(paths));
break;
}
mSettings.basePaths.emplace_back(Path::fromNativeSeparators(paths.substr(0, pos)));
paths.erase(0, pos + 1);
}
} else {
mLogger.printError("no paths specified for the '" + std::string(argv[i]) + "' option.");
return Result::Fail;
}
}
// Report progress
else if (std::strcmp(argv[i], "--report-progress") == 0) {
mSettings.reportProgress = 10;
}
else if (std::strncmp(argv[i], "--report-progress=", 18) == 0) {
int tmp;
if (!parseNumberArg(argv[i], 18, tmp, true))
return Result::Fail;
mSettings.reportProgress = tmp;
}
// Rule given at command line
else if (std::strncmp(argv[i], "--rule=", 7) == 0) {
#ifdef HAVE_RULES
Settings::Rule rule;
rule.pattern = 7 + argv[i];
if (rule.pattern.empty()) {
mLogger.printError("no rule pattern provided.");
return Result::Fail;
}
mSettings.rules.emplace_back(std::move(rule));
#else
mLogger.printError("Option --rule cannot be used as Cppcheck has not been built with rules support.");
return Result::Fail;
#endif
}
// Rule file
else if (std::strncmp(argv[i], "--rule-file=", 12) == 0) {
#ifdef HAVE_RULES
// TODO: improved error handling - wrong root node, etc.
// TODO: consume unused "version" attribute
const std::string ruleFile = argv[i] + 12;
tinyxml2::XMLDocument doc;
const tinyxml2::XMLError err = doc.LoadFile(ruleFile.c_str());
if (err == tinyxml2::XML_SUCCESS) {
const tinyxml2::XMLElement *node = doc.FirstChildElement();
// check if it is a single or multi rule configuration
if (node && strcmp(node->Value(), "rules") == 0)
node = node->FirstChildElement("rule");
for (; node && strcmp(node->Value(), "rule") == 0; node = node->NextSiblingElement()) {
Settings::Rule rule;
for (const tinyxml2::XMLElement *subnode = node->FirstChildElement(); subnode; subnode = subnode->NextSiblingElement()) {
const char * const subname = subnode->Name();
const char * const subtext = subnode->GetText();
if (std::strcmp(subname, "tokenlist") == 0) {
rule.tokenlist = empty_if_null(subtext);
}
else if (std::strcmp(subname, "pattern") == 0) {
rule.pattern = empty_if_null(subtext);
}
else if (std::strcmp(subname, "message") == 0) {
for (const tinyxml2::XMLElement *msgnode = subnode->FirstChildElement(); msgnode; msgnode = msgnode->NextSiblingElement()) {
const char * const msgname = msgnode->Name();
const char * const msgtext = msgnode->GetText();
if (std::strcmp(msgname, "severity") == 0) {
rule.severity = severityFromString(empty_if_null(msgtext));
}
else if (std::strcmp(msgname, "id") == 0) {
rule.id = empty_if_null(msgtext);
}
else if (std::strcmp(msgname, "summary") == 0) {
rule.summary = empty_if_null(msgtext);
}
else {
mLogger.printError("unable to load rule-file '" + ruleFile + "' - unknown element '" + msgname + "' encountered in 'message'.");
return Result::Fail;
}
}
}
else {
mLogger.printError("unable to load rule-file '" + ruleFile + "' - unknown element '" + subname + "' encountered in 'rule'.");
return Result::Fail;
}
}
if (rule.pattern.empty()) {
mLogger.printError("unable to load rule-file '" + ruleFile + "' - a rule is lacking a pattern.");
return Result::Fail;
}
if (rule.id.empty()) {
mLogger.printError("unable to load rule-file '" + ruleFile + "' - a rule is lacking an id.");
return Result::Fail;
}
if (rule.tokenlist.empty()) {
mLogger.printError("unable to load rule-file '" + ruleFile + "' - a rule is lacking a tokenlist.");
return Result::Fail;
}
if (rule.tokenlist != "normal" && rule.tokenlist != "define" && rule.tokenlist != "raw") {
mLogger.printError("unable to load rule-file '" + ruleFile + "' - a rule is using the unsupported tokenlist '" + rule.tokenlist + "'.");
return Result::Fail;
}
if (rule.severity == Severity::none) {
mLogger.printError("unable to load rule-file '" + ruleFile + "' - a rule has an invalid severity.");
return Result::Fail;
}
mSettings.rules.emplace_back(std::move(rule));
}
} else {
mLogger.printError("unable to load rule-file '" + ruleFile + "' (" + tinyxml2::XMLDocument::ErrorIDToName(err) + ").");
return Result::Fail;
}
#else
mLogger.printError("Option --rule-file cannot be used as Cppcheck has not been built with rules support.");
return Result::Fail;
#endif
}
// Safety certified behavior
else if (std::strcmp(argv[i], "--safety") == 0)
mSettings.safety = true;
// show timing information..
else if (std::strncmp(argv[i], "--showtime=", 11) == 0) {
const std::string showtimeMode = argv[i] + 11;
if (showtimeMode == "file")
mSettings.showtime = SHOWTIME_MODES::SHOWTIME_FILE;
else if (showtimeMode == "file-total")
mSettings.showtime = SHOWTIME_MODES::SHOWTIME_FILE_TOTAL;
else if (showtimeMode == "summary")
mSettings.showtime = SHOWTIME_MODES::SHOWTIME_SUMMARY;
else if (showtimeMode == "top5") {
mSettings.showtime = SHOWTIME_MODES::SHOWTIME_TOP5_FILE;
mLogger.printMessage("--showtime=top5 is deprecated and will be removed in Cppcheck 2.14. Please use --showtime=top5_file or --showtime=top5_summary instead.");
}
else if (showtimeMode == "top5_file")
mSettings.showtime = SHOWTIME_MODES::SHOWTIME_TOP5_FILE;
else if (showtimeMode == "top5_summary")
mSettings.showtime = SHOWTIME_MODES::SHOWTIME_TOP5_SUMMARY;
else if (showtimeMode == "none")
mSettings.showtime = SHOWTIME_MODES::SHOWTIME_NONE;
else if (showtimeMode.empty()) {
mLogger.printError("no mode provided for --showtime");
return Result::Fail;
}
else {
mLogger.printError("unrecognized --showtime mode: '" + showtimeMode + "'. Supported modes: file, file-total, summary, top5, top5_file, top5_summary.");
return Result::Fail;
}
}
// --std
else if (std::strncmp(argv[i], "--std=", 6) == 0) {
const std::string std = argv[i] + 6;
if (!mSettings.standards.setStd(std)) {
mLogger.printError("unknown --std value '" + std + "'");
return Result::Fail;
}
}
else if (std::strncmp(argv[i], "--suppress=", 11) == 0) {
const std::string suppression = argv[i]+11;
const std::string errmsg(mSuppressions.nomsg.addSuppressionLine(suppression));
if (!errmsg.empty()) {
mLogger.printError(errmsg);
return Result::Fail;
}
}
// Filter errors
else if (std::strncmp(argv[i], "--suppressions-list=", 20) == 0) {
std::string filename = argv[i]+20;
std::ifstream f(filename);
if (!f.is_open()) {
std::string message("couldn't open the file: \"");
message += filename;
message += "\".";
if (std::count(filename.cbegin(), filename.cend(), ',') > 0 ||
std::count(filename.cbegin(), filename.cend(), '.') > 1) {
// If user tried to pass multiple files (we can only guess that)
// e.g. like this: --suppressions-list=a.txt,b.txt
// print more detailed error message to tell user how he can solve the problem
message += "\nIf you want to pass two files, you can do it e.g. like this:";
message += "\n cppcheck --suppressions-list=a.txt --suppressions-list=b.txt file.cpp";
}
mLogger.printError(message);
return Result::Fail;
}
const std::string errmsg(mSuppressions.nomsg.parseFile(f));
if (!errmsg.empty()) {
mLogger.printError(errmsg);
return Result::Fail;
}
}
else if (std::strncmp(argv[i], "--suppress-xml=", 15) == 0) {
const char * filename = argv[i] + 15;
const std::string errmsg(mSuppressions.nomsg.parseXmlFile(filename));
if (!errmsg.empty()) {
mLogger.printError(errmsg);
return Result::Fail;
}
}
// Output formatter
else if (std::strncmp(argv[i], "--template=", 11) == 0) {
mSettings.templateFormat = argv[i] + 11;
// TODO: bail out when no template is provided?
if (mSettings.templateFormat == "gcc") {
mSettings.templateFormat = "{bold}{file}:{line}:{column}: {magenta}warning:{default} {message} [{id}]{reset}\\n{code}";
mSettings.templateLocation = "{bold}{file}:{line}:{column}: {dim}note:{reset} {info}\\n{code}";
} else if (mSettings.templateFormat == "daca2") {
mSettings.daca = true;
mSettings.templateFormat = "{file}:{line}:{column}: {severity}:{inconclusive:inconclusive:} {message} [{id}]";
mSettings.templateLocation = "{file}:{line}:{column}: note: {info}";
} else if (mSettings.templateFormat == "vs")
mSettings.templateFormat = "{file}({line}): {severity}: {message}";
else if (mSettings.templateFormat == "edit")
mSettings.templateFormat = "{file} +{line}: {severity}: {message}";
else if (mSettings.templateFormat == "cppcheck1")
mSettings.templateFormat = "{callstack}: ({severity}{inconclusive:, inconclusive}) {message}";
else if (mSettings.templateFormat == "selfcheck") {
mSettings.templateFormat = "{file}:{line}:{column}: {severity}:{inconclusive:inconclusive:} {message} [{id}]\\n{code}";
mSettings.templateLocation = "{file}:{line}:{column}: note: {info}\\n{code}";
mSettings.daca = true;
} else if (mSettings.templateFormat == "simple") {
mSettings.templateFormat = "{file}:{line}:{column}: {severity}:{inconclusive:inconclusive:} {message} [{id}]";
mSettings.templateLocation = "";
}
// TODO: bail out when no placeholders are found?
}
else if (std::strncmp(argv[i], "--template-location=", 20) == 0) {
mSettings.templateLocation = argv[i] + 20;
// TODO: bail out when no template is provided?
// TODO: bail out when no placeholders are found?
}
else if (std::strncmp(argv[i], "--template-max-time=", 20) == 0) {
if (!parseNumberArg(argv[i], 20, mSettings.templateMaxTime))
return Result::Fail;
}
else if (std::strncmp(argv[i], "--typedef-max-time=", 19) == 0) {
if (!parseNumberArg(argv[i], 19, mSettings.typedefMaxTime))
return Result::Fail;
}
else if (std::strncmp(argv[i], "--valueflow-max-iterations=", 27) == 0) {
if (!parseNumberArg(argv[i], 27, mSettings.vfOptions.maxIterations))
return Result::Fail;
}
else if (std::strcmp(argv[i], "-v") == 0 || std::strcmp(argv[i], "--verbose") == 0)
mSettings.verbose = true;
// Write results in results.xml
else if (std::strcmp(argv[i], "--xml") == 0) {
mSettings.xml = true;
mSettings.outputFormat = Settings::OutputFormat::xml;
}
// Define the XML file version (and enable XML output)
else if (std::strncmp(argv[i], "--xml-version=", 14) == 0) {
int tmp;
if (!parseNumberArg(argv[i], 14, tmp))
return Result::Fail;
if (tmp != 2 && tmp != 3) {
// We only have xml version 2 and 3
mLogger.printError("'--xml-version' can only be 2 or 3.");
return Result::Fail;
}
mSettings.xml_version = tmp;
// Enable also XML if version is set
mSettings.xml = true;
mSettings.outputFormat = Settings::OutputFormat::xml;
}
else {
std::string message("unrecognized command line option: \"");
message += argv[i];
message += "\".";
mLogger.printError(message);
return Result::Fail;
}
}
else {
mPathNames.emplace_back(Path::fromNativeSeparators(Path::removeQuotationMarks(argv[i])));
}
}
if (!loadCppcheckCfg())
return Result::Fail;
// TODO: bail out?
if (!executorAuto && mSettings.useSingleJob())
mLogger.printMessage("'--executor' has no effect as only a single job will be used.");
// Default template format..
if (mSettings.templateFormat.empty()) {
mSettings.templateFormat = "{bold}{file}:{line}:{column}: {red}{inconclusive:{magenta}}{severity}:{inconclusive: inconclusive:}{default} {message} [{id}]{reset}\\n{code}";
if (mSettings.templateLocation.empty())
mSettings.templateLocation = "{bold}{file}:{line}:{column}: {dim}note:{reset} {info}\\n{code}";
}
// replace static parts of the templates
substituteTemplateFormatStatic(mSettings.templateFormat);
substituteTemplateLocationStatic(mSettings.templateLocation);
if (mSettings.force || maxconfigs)
mSettings.checkAllConfigurations = true;
if (mSettings.force)
mSettings.maxConfigs = INT_MAX;
else if ((def || mSettings.preprocessOnly) && !maxconfigs)
mSettings.maxConfigs = 1U;
if (mSettings.jobs > 1 && mSettings.buildDir.empty()) {
// TODO: bail out instead?
if (mSettings.checks.isEnabled(Checks::unusedFunction))
mLogger.printMessage("unusedFunction check requires --cppcheck-build-dir to be active with -j.");
// TODO: enable
//mLogger.printMessage("whole program analysis requires --cppcheck-build-dir to be active with -j.");
}
if (!mPathNames.empty() && project.projectType != ImportProject::Type::NONE) {
mLogger.printError("--project cannot be used in conjunction with source files.");
return Result::Fail;
}
if (!mSettings.buildDir.empty() && !Path::isDirectory(mSettings.buildDir)) {
mLogger.printError("Directory '" + mSettings.buildDir + "' specified by --cppcheck-build-dir argument has to be existent.");
return Result::Fail;
}
// Print error only if we have "real" command and expect files
if (mPathNames.empty() && project.guiProject.pathNames.empty() && project.fileSettings.empty()) {
// TODO: this message differs from the one reported in fillSettingsFromArgs()
mLogger.printError("no C or C++ source files found.");
return Result::Fail;
}
if (!project.guiProject.pathNames.empty())
mPathNames = project.guiProject.pathNames;
if (!project.fileSettings.empty()) {
project.ignorePaths(mIgnoredPaths);
if (project.fileSettings.empty()) {
mLogger.printError("no C or C++ source files found.");
mLogger.printMessage("all paths were ignored"); // TODO: log this differently?
return Result::Fail;
}
mFileSettings = project.fileSettings;
}
// Use paths _pathnames if no base paths for relative path output are given
if (mSettings.basePaths.empty() && mSettings.relativePaths)
mSettings.basePaths = mPathNames;
return Result::Success;
}
void CmdLineParser::printHelp() const
{
const std::string manualUrl(isCppcheckPremium() ?
"https://cppcheck.sourceforge.io/manual.pdf" :
"https://files.cppchecksolutions.com/manual.pdf");
std::ostringstream oss;
oss << "Cppcheck - A tool for static C/C++ code analysis\n"
"\n"
"Syntax:\n"
" cppcheck [OPTIONS] [files or paths]\n"
"\n"
"If a directory is given instead of a filename, *.cpp, *.cxx, *.cc, *.c++, *.c, *.ipp,\n"
"*.ixx, *.tpp, and *.txx files are checked recursively from the given directory.\n\n"
"Options:\n"
" --addon=<addon>\n"
" Execute addon. i.e. --addon=misra. If options must be\n"
" provided a json configuration is needed.\n"
" --addon-python=<python interpreter>\n"
" You can specify the python interpreter either in the\n"
" addon json files or through this command line option.\n"
" If not present, Cppcheck will try \"python3\" first and\n"
" then \"python\".\n"
" --cppcheck-build-dir=<dir>\n"
" Cppcheck work folder. Advantages:\n"
" * whole program analysis\n"
" * faster analysis; Cppcheck will reuse the results if\n"
" the hash for a file is unchanged.\n"
" * some useful debug information, i.e. commands used to\n"
" execute clang/clang-tidy/addons.\n"
" --check-config Check cppcheck configuration. The normal code\n"
" analysis is disabled by this flag.\n"
" --check-level=<level>\n"
" Configure how much valueflow analysis you want:\n"
" * reduced: Reduce valueflow to finish checking quickly.\n"
" * normal: Cppcheck uses some compromises in the analysis so\n"
" the checking will finish in reasonable time.\n"
" * exhaustive: deeper analysis that you choose when you can\n"
" wait.\n"
" The default choice is 'normal'.\n"
" --check-library Show information messages when library files have\n"
" incomplete info.\n"
" --checkers-report=<file>\n"
" Write a report of all the active checkers to the given file.\n"
" --clang=<path> Experimental: Use Clang parser instead of the builtin Cppcheck\n"
" parser. Takes the executable as optional parameter and\n"
" defaults to `clang`. Cppcheck will run the given Clang\n"
" executable, import the Clang AST and convert it into\n"
" Cppcheck data. After that the normal Cppcheck analysis is\n"
" used. You must have the executable in PATH if no path is\n"
" given.\n"
" --config-exclude=<dir>\n"
" Path (prefix) to be excluded from configuration\n"
" checking. Preprocessor configurations defined in\n"
" headers (but not sources) matching the prefix will not\n"
" be considered for evaluation.\n"
" --config-excludes-file=<file>\n"
" A file that contains a list of config-excludes\n"
" --disable=<id> Disable individual checks.\n"
" Please refer to the documentation of --enable=<id>\n"
" for further details.\n"
" --dump Dump xml data for each translation unit. The dump\n"
" files have the extension .dump and contain ast,\n"
" tokenlist, symboldatabase, valueflow.\n"
" -D<ID> Define preprocessor symbol. Unless --max-configs or\n"
" --force is used, Cppcheck will only check the given\n"
" configuration when -D is used.\n"
" Example: '-DDEBUG=1 -D__cplusplus'.\n"
" -E Print preprocessor output on stdout and don't do any\n"
" further processing.\n"
" --enable=<id> Enable additional checks. The available ids are:\n"
" * all\n"
" Enable all checks. It is recommended to only\n"
" use --enable=all when the whole program is\n"
" scanned, because this enables unusedFunction.\n"
" * warning\n"
" Enable warning messages\n"
" * style\n"
" Enable all coding style checks. All messages\n"
" with the severities 'style', 'warning',\n"
" 'performance' and 'portability' are enabled.\n"
" * performance\n"
" Enable performance messages\n"
" * portability\n"
" Enable portability messages\n"
" * information\n"
" Enable information messages\n"
" * unusedFunction\n"
" Check for unused functions. It is recommended\n"
" to only enable this when the whole program is\n"
" scanned.\n"
" * missingInclude\n"
" Warn if there are missing includes.\n"
" Several ids can be given if you separate them with\n"
" commas. See also --std\n"
" --error-exitcode=<n> If errors are found, integer [n] is returned instead of\n"
" the default '0'. '" << EXIT_FAILURE << "' is returned\n"
" if arguments are not valid or if no input files are\n"
" provided. Note that your operating system can modify\n"
" this value, e.g. '256' can become '0'.\n"
" --errorlist Print a list of all the error messages in XML format.\n"
" --exitcode-suppressions=<file>\n"
" Used when certain messages should be displayed but\n"
" should not cause a non-zero exitcode.\n"
" --file-filter=<str> Analyze only those files matching the given filter str\n"
" Can be used multiple times\n"
" Example: --file-filter=*bar.cpp analyzes only files\n"
" that end with bar.cpp.\n"
" --file-list=<file> Specify the files to check in a text file. Add one\n"
" filename per line. When file is '-,' the file list will\n"
" be read from standard input.\n"
" -f, --force Force checking of all configurations in files. If used\n"
" together with '--max-configs=', the last option is the\n"
" one that is effective.\n"
" --fsigned-char Treat char type as signed.\n"
" --funsigned-char Treat char type as unsigned.\n"
" -h, --help Print this help.\n"
" -I <dir> Give path to search for include files. Give several -I\n"
" parameters to give several paths. First given path is\n"
" searched for contained header files first. If paths are\n"
" relative to source files, this is not needed.\n"
" --includes-file=<file>\n"
" Specify directory paths to search for included header\n"
" files in a text file. Add one include path per line.\n"
" First given path is searched for contained header\n"
" files first. If paths are relative to source files,\n"
" this is not needed.\n"
" --include=<file>\n"
" Force inclusion of a file before the checked file.\n"
" -i <dir or file> Give a source file or source file directory to exclude\n"
" from the check. This applies only to source files so\n"
" header files included by source files are not matched.\n"
" Directory name is matched to all parts of the path.\n"
" --inconclusive Allow that Cppcheck reports even though the analysis is\n"
" inconclusive.\n"
" There are false positives with this option. Each result\n"
" must be carefully investigated before you know if it is\n"
" good or bad.\n"
" --inline-suppr Enable inline suppressions. Use them by placing one or\n"
" more comments, like: '// cppcheck-suppress warningId'\n"
" on the lines before the warning to suppress.\n"
" -j <jobs> Start <jobs> threads to do the checking simultaneously.\n"
" -l <load> Specifies that no new threads should be started if\n"
" there are other threads running and the load average is\n"
" at least <load>.\n"
" --language=<language>, -x <language>\n"
" Forces cppcheck to check all files as the given\n"
" language. Valid values are: c, c++\n"
" --library=<cfg> Load file <cfg> that contains information about types\n"
" and functions. With such information Cppcheck\n"
" understands your code better and therefore you\n"
" get better results. The std.cfg file that is\n"
" distributed with Cppcheck is loaded automatically.\n"
" For more information about library files, read the\n"
" manual.\n"
" --max-configs=<limit>\n"
" Maximum number of configurations to check in a file\n"
" before skipping it. Default is '12'. If used together\n"
" with '--force', the last option is the one that is\n"
" effective.\n"
" --max-ctu-depth=N Max depth in whole program analysis. The default value\n"
" is 2. A larger value will mean more errors can be found\n"
" but also means the analysis will be slower.\n"
" --output-file=<file> Write results to file, rather than standard error.\n"
" --output-format=<format>\n"
" Specify the output format. The available formats are:\n"
" * sarif\n"
" * xml\n"
" --platform=<type>, --platform=<file>\n"
" Specifies platform specific types and sizes. The\n"
" available builtin platforms are:\n"
" * unix32\n"
" 32 bit unix variant\n"
" * unix64\n"
" 64 bit unix variant\n"
" * win32A\n"
" 32 bit Windows ASCII character encoding\n"
" * win32W\n"
" 32 bit Windows UNICODE character encoding\n"
" * win64\n"
" 64 bit Windows\n"
" * avr8\n"
" 8 bit AVR microcontrollers\n"
" * elbrus-e1cp\n"
" Elbrus e1c+ architecture\n"
" * pic8\n"
" 8 bit PIC microcontrollers\n"
" Baseline and mid-range architectures\n"
" * pic8-enhanced\n"
" 8 bit PIC microcontrollers\n"
" Enhanced mid-range and high end (PIC18) architectures\n"
" * pic16\n"
" 16 bit PIC microcontrollers\n"
" * mips32\n"
" 32 bit MIPS microcontrollers\n"
" * native\n"
" Type sizes of host system are assumed, but no\n"
" further assumptions.\n"
" * unspecified\n"
" Unknown type sizes\n"
" --plist-output=<path>\n"
" Generate Clang-plist output files in folder.\n";
if (isCppcheckPremium()) {
oss <<
" --premium=<option>\n"
" Coding standards:\n"
" * autosar Autosar (partial)\n"
" * cert-c-2016 Cert C 2016 checking\n"
" * cert-c++-2016 Cert C++ 2016 checking\n"
" * misra-c-2012 Misra C 2012\n"
" * misra-c-2023 Misra C 2023\n"
" * misra-c++-2008 Misra C++ 2008\n"
" * misra-c++-2023 Misra C++ 2023\n"
" Other:\n"
" * bughunting Soundy analysis\n"
" * cert-c-int-precision=BITS Integer precision to use in Cert C analysis.\n"
" * safety Turn on safety certified behavior (ON by default)\n"
" * safety-off Turn off safety certified behavior\n";
}
oss <<
" --project=<file> Run Cppcheck on project. The <file> can be a Visual\n"
" Studio Solution (*.sln), Visual Studio Project\n"
" (*.vcxproj), compile database (compile_commands.json),\n"
" or Borland C++ Builder 6 (*.bpr). The files to analyse,\n"
" include paths, defines, platform and undefines in\n"
" the specified file will be used.\n"
" --project-configuration=<config>\n"
" If used together with a Visual Studio Solution (*.sln)\n"
" or Visual Studio Project (*.vcxproj) you can limit\n"
" the configuration cppcheck should check.\n"
" For example: '--project-configuration=Release|Win32'\n"
" -q, --quiet Do not show progress reports.\n"
" Note that this option is not mutually exclusive with --verbose.\n"
" -rp=<paths>, --relative-paths=<paths>\n"
" Use relative paths in output. When given, <paths> are\n"
" used as base. You can separate multiple paths by ';'.\n"
" Otherwise path where source files are searched is used.\n"
" We use string comparison to create relative paths, so\n"
" using e.g. ~ for home folder does not work. It is\n"
" currently only possible to apply the base paths to\n"
" files that are on a lower level in the directory tree.\n"
" --report-progress Report progress messages while checking a file (single job only).\n"
" --rule=<rule> Match regular expression.\n"
" --rule-file=<file> Use given rule file. For more information, see:\n"
" http://sourceforge.net/projects/cppcheck/files/Articles/\n"
" --showtime=<mode> Show timing information.\n"
" The available modes are:\n"
" * none\n"
" Show nothing (default)\n"
" * file\n"
" Show for each processed file\n"
" * file-total\n"
" Show total time only for each processed file\n"
" * summary\n"
" Show a summary at the end\n"
" * top5_file\n"
" Show the top 5 for each processed file\n"
" * top5_summary\n"
" Show the top 5 summary at the end\n"
" * top5\n"
" Alias for top5_file (deprecated)\n"
" --std=<id> Set standard.\n"
" The available options are:\n"
" * c89\n"
" C code is C89 compatible\n"
" * c99\n"
" C code is C99 compatible\n"
" * c11\n"
" C code is C11 compatible (default)\n"
" * c++03\n"
" C++ code is C++03 compatible\n"
" * c++11\n"
" C++ code is C++11 compatible\n"
" * c++14\n"
" C++ code is C++14 compatible\n"
" * c++17\n"
" C++ code is C++17 compatible\n"
" * c++20\n"
" C++ code is C++20 compatible (default)\n"
" --suppress=<spec> Suppress warnings that match <spec>. The format of\n"
" <spec> is:\n"
" [error id]:[filename]:[line]\n"
" The [filename] and [line] are optional. If [error id]\n"
" is a wildcard '*', all error ids match.\n"
" --suppressions-list=<file>\n"
" Suppress warnings listed in the file. Each suppression\n"
" is in the same format as <spec> above.\n"
" --suppress-xml=<file>\n"
" Suppress warnings listed in a xml file. XML file should\n"
" follow the manual.pdf format specified in section.\n"
" `6.4 XML suppressions` .\n"
" --template='<text>' Format the error messages. Available fields:\n"
" {file} file name\n"
" {line} line number\n"
" {column} column number\n"
" {callstack} show a callstack. Example:\n"
" [file.c:1] -> [file.c:100]\n"
" {inconclusive:text} if warning is inconclusive, text\n"
" is written\n"
" {severity} severity\n"
" {message} warning message\n"
" {id} warning id\n"
" {cwe} CWE id (Common Weakness Enumeration)\n"
" {code} show the real code\n"
" \\t insert tab\n"
" \\n insert newline\n"
" \\r insert carriage return\n"
" Example formats:\n"
" '{file}:{line},{severity},{id},{message}' or\n"
" '{file}({line}):({severity}) {message}' or\n"
" '{callstack} {message}'\n"
" Pre-defined templates: gcc (default), cppcheck1 (old default), vs, edit.\n"
// Note: template daca2 also exists, but is for internal use (cppcheck scripts).
" --template-location='<text>'\n"
" Format error message location. If this is not provided\n"
" then no extra location info is shown.\n"
" Available fields:\n"
" {file} file name\n"
" {line} line number\n"
" {column} column number\n"
" {info} location info\n"
" {code} show the real code\n"
" \\t insert tab\n"
" \\n insert newline\n"
" \\r insert carriage return\n"
" Example format (gcc-like):\n"
" '{file}:{line}:{column}: note: {info}\\n{code}'\n"
" -U<ID> Undefine preprocessor symbol. Use -U to explicitly\n"
" hide certain #ifdef <ID> code paths from checking.\n"
" Example: '-UDEBUG'\n"
" -v, --verbose Output more detailed error information.\n"
" Note that this option is not mutually exclusive with --quiet.\n"
" --version Print out version number.\n"
" --xml Write results in xml format to error stream (stderr).\n"
"\n"
"Example usage:\n"
" # Recursively check the current folder. Print the progress on the screen and\n"
" # write errors to a file:\n"
" cppcheck . 2> err.txt\n"
"\n"
" # Recursively check ../myproject/ and don't print progress:\n"
" cppcheck --quiet ../myproject/\n"
"\n"
" # Check test.cpp, enable all checks:\n"
" cppcheck --enable=all --inconclusive --library=posix test.cpp\n"
"\n"
" # Check f.cpp and search include files from inc1/ and inc2/:\n"
" cppcheck -I inc1/ -I inc2/ f.cpp\n"
"\n"
"For more information:\n"
" " << manualUrl << "\n"
"\n"
"Many thanks to the 3rd party libraries we use:\n"
" * tinyxml2 -- loading project/library/ctu files.\n"
" * picojson -- loading compile database.\n"
" * pcre -- rules.\n"
" * qt -- used in GUI\n";
mLogger.printRaw(oss.str());
}
std::string CmdLineParser::getVersion() const {
if (!mSettings.cppcheckCfgProductName.empty())
return mSettings.cppcheckCfgProductName;
const char * const extraVersion = CppCheck::extraVersion();
if (*extraVersion != '\0')
return std::string("Cppcheck ") + CppCheck::version() + " ("+ extraVersion + ')';
return std::string("Cppcheck ") + CppCheck::version();
}
bool CmdLineParser::isCppcheckPremium() const {
if (mSettings.cppcheckCfgProductName.empty())
Settings::loadCppcheckCfg(mSettings, mSettings.supprs, mSettings.debuglookup || mSettings.debuglookupConfig);
return startsWith(mSettings.cppcheckCfgProductName, "Cppcheck Premium");
}
bool CmdLineParser::tryLoadLibrary(Library& destination, const std::string& basepath, const char* filename, bool debug)
{
const Library::Error err = destination.load(basepath.c_str(), filename, debug);
if (err.errorcode == Library::ErrorCode::UNKNOWN_ELEMENT)
mLogger.printMessage("Found unknown elements in configuration file '" + std::string(filename) + "': " + err.reason); // TODO: print as errors
else if (err.errorcode != Library::ErrorCode::OK) {
std::string msg = "Failed to load library configuration file '" + std::string(filename) + "'. ";
switch (err.errorcode) {
case Library::ErrorCode::OK:
break;
case Library::ErrorCode::FILE_NOT_FOUND:
msg += "File not found";
break;
case Library::ErrorCode::BAD_XML:
msg += "Bad XML";
break;
case Library::ErrorCode::UNKNOWN_ELEMENT:
msg += "Unexpected element";
break;
case Library::ErrorCode::MISSING_ATTRIBUTE:
msg +="Missing attribute";
break;
case Library::ErrorCode::BAD_ATTRIBUTE_VALUE:
msg += "Bad attribute value";
break;
case Library::ErrorCode::UNSUPPORTED_FORMAT:
msg += "File is of unsupported format version";
break;
case Library::ErrorCode::DUPLICATE_PLATFORM_TYPE:
msg += "Duplicate platform type";
break;
case Library::ErrorCode::PLATFORM_TYPE_REDEFINED:
msg += "Platform type redefined";
break;
case Library::ErrorCode::DUPLICATE_DEFINE:
msg += "Duplicate define";
break;
}
if (!err.reason.empty())
msg += " '" + err.reason + "'";
mLogger.printMessage(msg); // TODO: print as errors
return false;
}
return true;
}
bool CmdLineParser::loadLibraries(Settings& settings)
{
if (!tryLoadLibrary(settings.library, settings.exename, "std.cfg", settings.debuglookup || settings.debuglookupLibrary)) {
const std::string msg("Failed to load std.cfg. Your Cppcheck installation is broken, please re-install.");
#ifdef FILESDIR
const std::string details("The Cppcheck binary was compiled with FILESDIR set to \""
FILESDIR "\" and will therefore search for "
"std.cfg in " FILESDIR "/cfg.");
#else
const std::string cfgfolder(Path::fromNativeSeparators(Path::getPathFromFilename(settings.exename)) + "cfg");
const std::string details("The Cppcheck binary was compiled without FILESDIR set. Either the "
"std.cfg should be available in " + cfgfolder + " or the FILESDIR "
"should be configured.");
#endif
mLogger.printRaw(msg + " " + details); // TODO: do not print as raw?
return false;
}
bool result = true;
for (const auto& lib : settings.libraries) {
if (!tryLoadLibrary(settings.library, settings.exename, lib.c_str(), settings.debuglookup || settings.debuglookupLibrary)) {
result = false;
}
}
return result;
}
bool CmdLineParser::loadAddons(Settings& settings)
{
bool result = true;
for (const std::string &addon: settings.addons) {
AddonInfo addonInfo;
const std::string failedToGetAddonInfo = addonInfo.getAddonInfo(addon, settings.exename, settings.debuglookup || settings.debuglookupAddon);
if (!failedToGetAddonInfo.empty()) {
mLogger.printRaw(failedToGetAddonInfo); // TODO: do not print as raw
result = false;
continue;
}
settings.addonInfos.emplace_back(std::move(addonInfo));
}
return result;
}
bool CmdLineParser::loadCppcheckCfg()
{
if (!mSettings.cppcheckCfgProductName.empty())
return true;
const std::string cfgErr = Settings::loadCppcheckCfg(mSettings, mSuppressions, mSettings.debuglookup || mSettings.debuglookupConfig);
if (!cfgErr.empty()) {
mLogger.printError("could not load cppcheck.cfg - " + cfgErr);
return false;
}
return true;
}
| null |
1,075 | cpp | cppcheck | main.cpp | cli/main.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
/**
*
* @mainpage Cppcheck
* @version 2.16.99
*
* @section overview_sec Overview
* Cppcheck is a simple tool for static analysis of C/C++ code.
*
* When you write a checker you have access to:
* - %Token list - the tokenized code
* - Syntax tree - Syntax tree of each expression
* - %SymbolDatabase - Information about all types/variables/functions/etc
* in the current translation unit
* - Library - Configuration of functions/types
* - Value flow analysis - Data flow analysis that determine possible values for each token
*
* Use --debug-normal on the command line to see debug output for the token list
* and the syntax tree. If both --debug-normal and --verbose is used, the symbol
* database is also written.
*
* The checks are written in C++.
*
* @section detailed_overview_sec Detailed overview
* This happens when you execute cppcheck from the command line:
* -# CppCheckExecutor::check this function executes the Cppcheck
* -# CmdLineParser::parseFromArgs parse command line arguments
* - The Settings class is used to maintain settings
* - Use FileLister and command line arguments to get files to check
* -# ThreadExecutor create more instances of CppCheck if needed
* -# CppCheck::check is called for each file. It checks a single file
* -# Preprocess the file (through Preprocessor)
* - Comments are removed
* - Macros are expanded
* -# Tokenize the file (see Tokenizer)
* -# Run the runChecks of all check classes.
*
* When errors are found, they are reported back to the CppCheckExecutor through the ErrorLogger interface.
*/
#include "cppcheckexecutor.h"
#ifdef NDEBUG
#include "errortypes.h"
#include <cstdlib>
#include <exception>
#include <iostream>
#endif
/**
* Main function of cppcheck
*
* @param argc Passed to CppCheck::parseFromArgs()
* @param argv Passed to CppCheck::parseFromArgs()
* @return What CppCheckExecutor::check() returns.
*/
int main(int argc, char* argv[])
{
// MS Visual C++ memory leak debug tracing
#if defined(_MSC_VER) && defined(_DEBUG)
_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
#endif
CppCheckExecutor exec;
// *INDENT-OFF*
#ifdef NDEBUG
try {
#endif
return exec.check(argc, argv);
#ifdef NDEBUG
} catch (const InternalError& e) {
std::cout << e.errorMessage << std::endl;
} catch (const std::exception& error) {
std::cout << error.what() << std::endl;
} catch (...) {
std::cout << "Unknown exception" << std::endl;
}
return EXIT_FAILURE;
#endif
// *INDENT-ON*
}
| null |
1,076 | cpp | cppcheck | cppcheckexecutorseh.h | cli/cppcheckexecutorseh.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#ifndef CPPCHECKEXECUTORSEH_H
#define CPPCHECKEXECUTORSEH_H
#include "config.h" // IWYU pragma: keep
#ifdef USE_WINDOWS_SEH
class CppCheckExecutor;
class Settings;
int check_wrapper_seh(CppCheckExecutor& executor, int (CppCheckExecutor::*f)(const Settings&) const, const Settings& settings);
#endif
#endif // CPPCHECKEXECUTORSEH_H
| null |
1,077 | cpp | cppcheck | signalhandler.cpp | cli/signalhandler.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#include "signalhandler.h"
#if defined(USE_UNIX_SIGNAL_HANDLING)
#ifdef USE_UNIX_BACKTRACE_SUPPORT
#include "stacktrace.h"
#endif
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
//#include <features.h> // __USE_DYNAMIC_STACK_SIZE
#include <map>
#include <string>
#include <sys/types.h>
#include <unistd.h>
#include <utility>
#if defined(__linux__) && defined(REG_ERR)
#include <sys/syscall.h>
#endif
#if defined(__APPLE__)
# define _XOPEN_SOURCE // ucontext.h APIs can only be used on Mac OSX >= 10.7 if _XOPEN_SOURCE is defined
# include <ucontext.h>
# undef _XOPEN_SOURCE
#elif !defined(__OpenBSD__) && !defined(__HAIKU__)
# include <ucontext.h>
#endif
// TODO: __USE_DYNAMIC_STACK_SIZE is dependent on the features.h include and not a built-in compiler define, so it might be problematic to depend on it
#ifdef __USE_DYNAMIC_STACK_SIZE
static constexpr size_t MYSTACKSIZE = (16*1024)+32768; // wild guess about a reasonable buffer
#else
static constexpr size_t MYSTACKSIZE = 16*1024+SIGSTKSZ; // wild guess about a reasonable buffer
#endif
static char mytstack[MYSTACKSIZE]= {0}; // alternative stack for signal handler
static bool bStackBelowHeap=false; // lame attempt to locate heap vs. stack address space. See CppCheckExecutor::check_wrapper()
static FILE* signalOutput = stdout; // TODO: get rid of this
/**
* \param[in] ptr address to be examined.
* \return true if address is supposed to be on stack (contrary to heap). If ptr is 0 false will be returned.
* If unknown better return false.
*/
static bool IsAddressOnStack(const void* ptr)
{
if (nullptr==ptr)
return false;
char a;
if (bStackBelowHeap)
return ptr < &a;
return ptr > &a;
}
/* (declare this list here, so it may be used in signal handlers in addition to main())
* A list of signals available in ISO C
* Check out http://pubs.opengroup.org/onlinepubs/009695399/basedefs/signal.h.html
* For now we only want to detect abnormal behaviour for a few selected signals:
*/
#define DECLARE_SIGNAL(x) std::make_pair(x, #x)
using Signalmap_t = std::map<int, std::string>;
static const Signalmap_t listofsignals = {
DECLARE_SIGNAL(SIGABRT),
DECLARE_SIGNAL(SIGBUS),
DECLARE_SIGNAL(SIGFPE),
DECLARE_SIGNAL(SIGILL),
DECLARE_SIGNAL(SIGINT),
DECLARE_SIGNAL(SIGQUIT),
DECLARE_SIGNAL(SIGSEGV),
DECLARE_SIGNAL(SIGSYS),
// don't care: SIGTERM
DECLARE_SIGNAL(SIGUSR1),
//DECLARE_SIGNAL(SIGUSR2) no usage currently
};
#undef DECLARE_SIGNAL
/*
* Entry pointer for signal handlers
* It uses functions which are not safe to be called from a signal handler,
* (http://pubs.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html#tag_15_04 has a whitelist)
* but when ending up here something went terribly wrong anyway.
* And all which is left is just printing some information and terminate.
*/
// cppcheck-suppress constParameterCallback
static void CppcheckSignalHandler(int signo, siginfo_t * info, void * context)
{
int type = -1;
pid_t killid;
// TODO: separate these two defines
#if defined(__linux__) && defined(REG_ERR)
const auto* const uc = reinterpret_cast<const ucontext_t*>(context);
killid = (pid_t) syscall(SYS_gettid);
if (uc) {
type = (int)uc->uc_mcontext.gregs[REG_ERR] & 2;
}
#else
(void)context;
killid = getpid();
#endif
const Signalmap_t::const_iterator it=listofsignals.find(signo);
const char * const signame = (it==listofsignals.end()) ? "unknown" : it->second.c_str();
bool unexpectedSignal=true; // unexpected indicates program failure
bool terminate=true; // exit process/thread
const bool isAddressOnStack = IsAddressOnStack(info->si_addr);
FILE * const output = signalOutput;
switch (signo) {
case SIGABRT:
fputs("Internal error: cppcheck received signal ", output);
fputs(signame, output);
fputs(
#ifdef NDEBUG
" - abort\n",
#else
" - abort or assertion\n",
#endif
output);
break;
case SIGBUS:
fputs("Internal error: cppcheck received signal ", output);
fputs(signame, output);
switch (info->si_code) {
case BUS_ADRALN: // invalid address alignment
fputs(" - BUS_ADRALN", output);
break;
case BUS_ADRERR: // nonexistent physical address
fputs(" - BUS_ADRERR", output);
break;
case BUS_OBJERR: // object-specific hardware error
fputs(" - BUS_OBJERR", output);
break;
#ifdef BUS_MCEERR_AR
case BUS_MCEERR_AR: // Hardware memory error consumed on a machine check;
fputs(" - BUS_MCEERR_AR", output);
break;
#endif
#ifdef BUS_MCEERR_AO
case BUS_MCEERR_AO: // Hardware memory error detected in process but not consumed
fputs(" - BUS_MCEERR_AO", output);
break;
#endif
default:
break;
}
fprintf(output, " (at 0x%lx).\n",
(unsigned long)info->si_addr);
break;
case SIGFPE:
fputs("Internal error: cppcheck received signal ", output);
fputs(signame, output);
switch (info->si_code) {
case FPE_INTDIV: // integer divide by zero
fputs(" - FPE_INTDIV", output);
break;
case FPE_INTOVF: // integer overflow
fputs(" - FPE_INTOVF", output);
break;
case FPE_FLTDIV: // floating-point divide by zero
fputs(" - FPE_FLTDIV", output);
break;
case FPE_FLTOVF: // floating-point overflow
fputs(" - FPE_FLTOVF", output);
break;
case FPE_FLTUND: // floating-point underflow
fputs(" - FPE_FLTUND", output);
break;
case FPE_FLTRES: // floating-point inexact result
fputs(" - FPE_FLTRES", output);
break;
case FPE_FLTINV: // floating-point invalid operation
fputs(" - FPE_FLTINV", output);
break;
case FPE_FLTSUB: // subscript out of range
fputs(" - FPE_FLTSUB", output);
break;
default:
break;
}
fprintf(output, " (at 0x%lx).\n",
(unsigned long)info->si_addr);
break;
case SIGILL:
fputs("Internal error: cppcheck received signal ", output);
fputs(signame, output);
switch (info->si_code) {
case ILL_ILLOPC: // illegal opcode
fputs(" - ILL_ILLOPC", output);
break;
case ILL_ILLOPN: // illegal operand
fputs(" - ILL_ILLOPN", output);
break;
case ILL_ILLADR: // illegal addressing mode
fputs(" - ILL_ILLADR", output);
break;
case ILL_ILLTRP: // illegal trap
fputs(" - ILL_ILLTRP", output);
break;
case ILL_PRVOPC: // privileged opcode
fputs(" - ILL_PRVOPC", output);
break;
case ILL_PRVREG: // privileged register
fputs(" - ILL_PRVREG", output);
break;
case ILL_COPROC: // coprocessor error
fputs(" - ILL_COPROC", output);
break;
case ILL_BADSTK: // internal stack error
fputs(" - ILL_BADSTK", output);
break;
default:
break;
}
fprintf(output, " (at 0x%lx).%s\n",
(unsigned long)info->si_addr,
(isAddressOnStack)?" Stackoverflow?":"");
break;
case SIGINT:
unexpectedSignal=false; // legal usage: interrupt application via CTRL-C
fputs("cppcheck received signal ", output);
fputs(signame, output);
fputs(".\n", output);
break;
case SIGSEGV:
fputs("Internal error: cppcheck received signal ", output);
fputs(signame, output);
switch (info->si_code) {
case SEGV_MAPERR: // address not mapped to object
fputs(" - SEGV_MAPERR", output);
break;
case SEGV_ACCERR: // invalid permissions for mapped object
fputs(" - SEGV_ACCERR", output);
break;
default:
break;
}
fprintf(output, " (%sat 0x%lx).%s\n",
// cppcheck-suppress knownConditionTrueFalse ; FP
(type==-1)? "" :
(type==0) ? "reading " : "writing ",
(unsigned long)info->si_addr,
(isAddressOnStack)?" Stackoverflow?":""
);
break;
case SIGUSR1:
fputs("cppcheck received signal ", output);
fputs(signame, output);
fputs(".\n", output);
terminate=false;
break;
default:
fputs("Internal error: cppcheck received signal ", output);
fputs(signame, output);
fputs(".\n", output);
break;
}
#ifdef USE_UNIX_BACKTRACE_SUPPORT
// flush otherwise the trace might be printed earlier
fflush(output);
print_stacktrace(output, 1, true, -1, true);
#endif
if (unexpectedSignal) {
fputs("\nPlease report this to the cppcheck developers!\n", output);
}
fflush(output);
if (terminate) {
// now let things proceed, shutdown and hopefully dump core for post-mortem analysis
struct sigaction act;
memset(&act, 0, sizeof(act));
act.sa_handler=SIG_DFL;
sigaction(signo, &act, nullptr);
kill(killid, signo);
}
}
void register_signal_handler(FILE * const output)
{
signalOutput = output;
// determine stack vs. heap
char stackVariable;
char *heapVariable=static_cast<char*>(malloc(1));
bStackBelowHeap = &stackVariable < heapVariable;
free(heapVariable);
// set up alternative stack for signal handler
stack_t segv_stack;
segv_stack.ss_sp = mytstack;
segv_stack.ss_flags = 0;
segv_stack.ss_size = MYSTACKSIZE;
if (sigaltstack(&segv_stack, nullptr) != 0) {
// TODO: log errno
fputs("could not set alternate signal stack context.\n", output);
std::exit(EXIT_FAILURE);
}
// install signal handler
struct sigaction act;
memset(&act, 0, sizeof(act));
act.sa_flags=SA_SIGINFO|SA_ONSTACK;
act.sa_sigaction=CppcheckSignalHandler;
for (std::map<int, std::string>::const_iterator sig=listofsignals.cbegin(); sig!=listofsignals.cend(); ++sig) {
sigaction(sig->first, &act, nullptr);
}
}
#endif
| null |
1,078 | cpp | cppcheck | stacktrace.cpp | cli/stacktrace.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#include "stacktrace.h"
#ifdef USE_UNIX_BACKTRACE_SUPPORT
#include "utils.h"
#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <cxxabi.h>
#include <execinfo.h>
void print_stacktrace(FILE* output, int start_idx, bool demangling, int maxdepth, bool omit_above_own)
{
// 32 vs. 64bit
#define ADDRESSDISPLAYLENGTH ((sizeof(long)==8)?12:8)
void *callstackArray[32]= {nullptr}; // the less resources the better...
const int currentdepth = backtrace(callstackArray, (int)getArrayLength(callstackArray));
// set offset to 1 to omit the printing function itself
int offset=start_idx+1; // some entries on top are within our own exception handling code or libc
if (maxdepth<0)
maxdepth=currentdepth-offset;
else
maxdepth = std::min(maxdepth, currentdepth);
char **symbolStringList = backtrace_symbols(callstackArray, currentdepth);
if (!symbolStringList) {
fputs("Callstack could not be obtained\n", output);
return;
}
fputs("Callstack:\n", output);
bool own_code = false;
char demangle_buffer[2048]= {0};
for (int i = offset; i < maxdepth; ++i) {
const char * const symbolString = symbolStringList[i];
// skip all leading libc symbols so the first symbol is our code
if (omit_above_own && !own_code) {
if (strstr(symbolString, "/libc.so.6") != nullptr)
continue;
own_code = true;
offset = i; // make sure the numbering is continous if we omit frames
}
char * realnameString = nullptr;
const char * const firstBracketName = strchr(symbolString, '(');
const char * const firstBracketAddress = strchr(symbolString, '[');
const char * const secondBracketAddress = strchr(firstBracketAddress, ']');
const char * const beginAddress = firstBracketAddress+3;
const int addressLen = int(secondBracketAddress-beginAddress);
const int padLen = (ADDRESSDISPLAYLENGTH-addressLen);
if (demangling && firstBracketName) {
const char * const plus = strchr(firstBracketName, '+');
if (plus && (plus>(firstBracketName+1))) {
char input_buffer[1024]= {0};
strncpy(input_buffer, firstBracketName+1, plus-firstBracketName-1);
size_t length = getArrayLength(demangle_buffer);
int status=0;
// We're violating the specification - passing stack address instead of malloc'ed heap.
// Benefit is that no further heap is required, while there is sufficient stack...
realnameString = abi::__cxa_demangle(input_buffer, demangle_buffer, &length, &status); // non-NULL on success
}
}
const int ordinal=i-offset;
fprintf(output, "#%-2d 0x",
ordinal);
if (padLen>0)
fprintf(output, "%0*d",
padLen, 0);
if (realnameString) {
fprintf(output, "%.*s in %s\n",
(int)(secondBracketAddress-firstBracketAddress-3), firstBracketAddress+3,
realnameString);
} else {
fprintf(output, "%.*s in %.*s\n",
(int)(secondBracketAddress-firstBracketAddress-3), firstBracketAddress+3,
(int)(firstBracketAddress-symbolString), symbolString);
}
}
// NOLINTNEXTLINE(bugprone-multi-level-implicit-pointer-conversion) - code matches the documented usage
free(symbolStringList);
#undef ADDRESSDISPLAYLENGTH
}
#endif // USE_UNIX_BACKTRACE_SUPPORT
| null |
1,079 | cpp | cppcheck | singleexecutor.h | cli/singleexecutor.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#ifndef SINGLEEXECUTOR_H
#define SINGLEEXECUTOR_H
#include "executor.h"
#include <list>
class ErrorLogger;
class Settings;
class CppCheck;
class SuppressionList;
struct FileSettings;
class FileWithDetails;
class SingleExecutor : public Executor
{
public:
SingleExecutor(CppCheck &cppcheck, const std::list<FileWithDetails> &files, const std::list<FileSettings>& fileSettings, const Settings &settings, SuppressionList &suppressions, ErrorLogger &errorLogger);
SingleExecutor(const SingleExecutor &) = delete;
SingleExecutor& operator=(const SingleExecutor &) = delete;
unsigned int check() override;
private:
CppCheck &mCppcheck;
};
#endif // SINGLEEXECUTOR_H
| null |
1,080 | cpp | cppcheck | threadexecutor.cpp | cli/threadexecutor.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#include "threadexecutor.h"
#include "config.h"
#include "cppcheck.h"
#include "errorlogger.h"
#include "filesettings.h"
#include "settings.h"
#include "timer.h"
#include <cassert>
#include <cstdint>
#include <cstdlib>
#include <future>
#include <iostream>
#include <list>
#include <numeric>
#include <mutex>
#include <string>
#include <system_error>
#include <utility>
#include <vector>
ThreadExecutor::ThreadExecutor(const std::list<FileWithDetails> &files, const std::list<FileSettings>& fileSettings, const Settings &settings, SuppressionList &suppressions, ErrorLogger &errorLogger, CppCheck::ExecuteCmdFn executeCommand)
: Executor(files, fileSettings, settings, suppressions, errorLogger)
, mExecuteCommand(std::move(executeCommand))
{
assert(mSettings.jobs > 1);
}
class SyncLogForwarder : public ErrorLogger
{
public:
explicit SyncLogForwarder(ThreadExecutor &threadExecutor, ErrorLogger &errorLogger)
: mThreadExecutor(threadExecutor), mErrorLogger(errorLogger) {}
void reportOut(const std::string &outmsg, Color c) override
{
std::lock_guard<std::mutex> lg(mReportSync);
mErrorLogger.reportOut(outmsg, c);
}
void reportErr(const ErrorMessage &msg) override {
if (!mThreadExecutor.hasToLog(msg))
return;
std::lock_guard<std::mutex> lg(mReportSync);
mErrorLogger.reportErr(msg);
}
void reportStatus(std::size_t fileindex, std::size_t filecount, std::size_t sizedone, std::size_t sizetotal) {
std::lock_guard<std::mutex> lg(mReportSync);
mThreadExecutor.reportStatus(fileindex, filecount, sizedone, sizetotal);
}
private:
std::mutex mReportSync;
ThreadExecutor &mThreadExecutor;
ErrorLogger &mErrorLogger;
};
class ThreadData
{
public:
ThreadData(ThreadExecutor &threadExecutor, ErrorLogger &errorLogger, const Settings &settings, const std::list<FileWithDetails> &files, const std::list<FileSettings> &fileSettings, CppCheck::ExecuteCmdFn executeCommand)
: mFiles(files), mFileSettings(fileSettings), mSettings(settings), mExecuteCommand(std::move(executeCommand)), logForwarder(threadExecutor, errorLogger)
{
mItNextFile = mFiles.begin();
mItNextFileSettings = mFileSettings.begin();
mTotalFiles = mFiles.size() + mFileSettings.size();
mTotalFileSize = std::accumulate(mFiles.cbegin(), mFiles.cend(), std::size_t(0), [](std::size_t v, const FileWithDetails& p) {
return v + p.size();
});
}
bool next(const FileWithDetails *&file, const FileSettings *&fs, std::size_t &fileSize) {
std::lock_guard<std::mutex> l(mFileSync);
if (mItNextFile != mFiles.end()) {
file = &(*mItNextFile);
fs = nullptr;
fileSize = mItNextFile->size();
++mItNextFile;
return true;
}
if (mItNextFileSettings != mFileSettings.end()) {
file = nullptr;
fs = &(*mItNextFileSettings);
fileSize = 0;
++mItNextFileSettings;
return true;
}
return false;
}
unsigned int check(ErrorLogger &errorLogger, const FileWithDetails *file, const FileSettings *fs) const {
CppCheck fileChecker(errorLogger, false, mExecuteCommand);
fileChecker.settings() = mSettings; // this is a copy
unsigned int result;
if (fs) {
// file settings..
result = fileChecker.check(*fs);
if (fileChecker.settings().clangTidy)
fileChecker.analyseClangTidy(*fs);
} else {
// Read file from a file
result = fileChecker.check(*file);
// TODO: call analyseClangTidy()?
}
return result;
}
void status(std::size_t fileSize) {
std::lock_guard<std::mutex> l(mFileSync);
mProcessedSize += fileSize;
mProcessedFiles++;
if (!mSettings.quiet)
logForwarder.reportStatus(mProcessedFiles, mTotalFiles, mProcessedSize, mTotalFileSize);
}
private:
const std::list<FileWithDetails> &mFiles;
std::list<FileWithDetails>::const_iterator mItNextFile;
const std::list<FileSettings> &mFileSettings;
std::list<FileSettings>::const_iterator mItNextFileSettings;
std::size_t mProcessedFiles{};
std::size_t mTotalFiles{};
std::size_t mProcessedSize{};
std::size_t mTotalFileSize{};
std::mutex mFileSync;
const Settings &mSettings;
CppCheck::ExecuteCmdFn mExecuteCommand;
public:
SyncLogForwarder logForwarder;
};
static unsigned int STDCALL threadProc(ThreadData *data)
{
unsigned int result = 0;
const FileWithDetails *file;
const FileSettings *fs;
std::size_t fileSize;
while (data->next(file, fs, fileSize)) {
result += data->check(data->logForwarder, file, fs);
data->status(fileSize);
}
return result;
}
unsigned int ThreadExecutor::check()
{
std::vector<std::future<unsigned int>> threadFutures;
threadFutures.reserve(mSettings.jobs);
ThreadData data(*this, mErrorLogger, mSettings, mFiles, mFileSettings, mExecuteCommand);
for (unsigned int i = 0; i < mSettings.jobs; ++i) {
try {
threadFutures.emplace_back(std::async(std::launch::async, &threadProc, &data));
}
catch (const std::system_error &e) {
std::cerr << "#### ThreadExecutor::check exception :" << e.what() << std::endl;
exit(EXIT_FAILURE);
}
}
unsigned int result = std::accumulate(threadFutures.begin(), threadFutures.end(), 0U, [](unsigned int v, std::future<unsigned int>& f) {
return v + f.get();
});
if (mSettings.showtime == SHOWTIME_MODES::SHOWTIME_SUMMARY || mSettings.showtime == SHOWTIME_MODES::SHOWTIME_TOP5_SUMMARY)
CppCheck::printTimerResults(mSettings.showtime);
return result;
}
| null |
1,081 | cpp | cppcheck | democlient.cpp | democlient/democlient.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 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/>.
*/
#include "cppcheck.h"
#include "errorlogger.h"
#include "errortypes.h"
#include "filesettings.h"
#include "settings.h"
#include "version.h"
#include <algorithm>
#include <ctime>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <string>
enum class Color : std::uint8_t;
static void unencode(const char *src, char *dest)
{
for (; *src; src++, dest++) {
if (*src == '+')
*dest = ' ';
else if (*src == '%') {
unsigned int code;
if (std::sscanf(src+1, "%2x", &code) != 1)
code = '?';
*dest = code;
src += 2;
} else
*dest = *src;
}
*dest = '\0';
}
static FILE *logfile = nullptr;
class CppcheckExecutor : public ErrorLogger {
private:
const std::time_t stoptime;
CppCheck cppcheck;
public:
CppcheckExecutor()
: ErrorLogger()
, stoptime(std::time(nullptr)+2U)
, cppcheck(*this, false, nullptr) {
cppcheck.settings().addEnabled("all");
cppcheck.settings().certainty.enable(Certainty::inconclusive);
}
void run(const char code[]) {
cppcheck.check(FileWithDetails("test.cpp"), code);
}
void reportOut(const std::string & /*outmsg*/, Color /*c*/) override {}
void reportErr(const ErrorMessage &msg) override {
const std::string s = msg.toString(true);
std::cout << s << std::endl;
if (logfile != nullptr)
std::fprintf(logfile, "%s\n", s.c_str());
}
void reportProgress(const std::string& /*filename*/,
const char /*stage*/[],
const std::size_t /*value*/) override {
if (std::time(nullptr) >= stoptime) {
std::cout << "Time to analyse the code exceeded 2 seconds. Terminating.\n\n";
Settings::terminate();
}
}
};
int main()
{
std::cout << "Content-type: text/html\r\n\r\n"
<< "<!DOCTYPE html>\n";
char data[4096] = {0};
const char *query_string = std::getenv("QUERY_STRING");
if (query_string)
std::strncpy(data, query_string, sizeof(data)-2);
const char *lenstr = std::getenv("CONTENT_LENGTH");
if (lenstr) {
int len = std::min(1 + std::atoi(lenstr), (int)(sizeof(data) - 2));
std::fgets(data, len, stdin);
}
if (data[4000] != '\0') {
std::cout << "<html><body>For performance reasons the code must be shorter than 1000 chars.</body></html>";
return EXIT_SUCCESS;
}
const char *pdata = data;
if (std::strncmp(pdata, "code=", 5)==0)
pdata += 5;
char code[4096] = {0};
unencode(pdata, code);
logfile = std::fopen("democlient.log", "at");
if (logfile != nullptr)
std::fprintf(logfile, "===========================================================\n%s\n", code);
std::cout << "<html><body>Cppcheck " CPPCHECK_VERSION_STRING "<pre>";
CppcheckExecutor cppcheckExecutor;
cppcheckExecutor.run(code);
std::fclose(logfile);
std::cout << "</pre>Done!</body></html>";
return EXIT_SUCCESS;
}
| null |
1,082 | cpp | custom_tests | custom_tests_1.cpp | custom/custom_tests_1.cpp | custom/custom_tests_1.cpp |
#include "CppUTest/TestHarness.h"
#include "my_math_function.h"
#include "CppUTest/CommandLineTestRunner.h"
TEST_GROUP(MyMathFunctions) {};
TEST(MyMathFunctions, AddPositiveNumbers) {
CHECK_EQUAL(5, add(2, 3));
CHECK_EQUAL(10, add(5, 5));
CHECK_EQUAL(100, add(50, 50));
}
int main(int argc, char** argv) {
return CommandLineTestRunner::RunAllTests(argc, argv);
}
|
#include "CppUTest/TestHarness.h"
#include "my_math_function.h"
#include "CppUTest/CommandLineTestRunner.h"
TEST_GROUP(MyMathFunctions) {};
TEST(MyMathFunctions, AddPositiveNumbers) {
CHECK_EQUAL(5, add(2, 3));
CHECK_EQUAL(10, add(5, 5));
CHECK_EQUAL(100, add(50, 50));
}
int main(int argc, char** argv) {
return CommandLineTestRunner::RunAllTests(argc, argv);
}
|
1,083 | cpp | custom_tests | custom_tests_2.cpp | custom/custom_tests_2.cpp | custom/custom_tests_2.cpp |
#include <CppUTest/CommandLineTestRunner.h>
#include "main.h"
// A mock function to replace GPIO behavior
void mock_HAL_GPIO_TogglePin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin) {
// Mock behavior: simply log the pin toggled (you can implement tracking here)
}
extern "C" {
int some_function_from_main() {
return 42;
}
void HAL_GPIO_TogglePin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin) {
mock_HAL_GPIO_TogglePin(GPIOx, GPIO_Pin);
}
}
TEST_GROUP(LedBlinkGroup) {
void setup() {}
void teardown() {}
};
TEST(LedBlinkGroup, TestFunction1) {
int result = some_function_from_main();
CHECK_EQUAL(42, result);
}
TEST(LedBlinkGroup, TestGPIOFunctionality) {
HAL_GPIO_TogglePin(GPIOB, GPIO_PIN_4);
}
int main(int argc, char** argv) {
return CommandLineTestRunner::RunAllTests(argc, argv);
}
|
#include <CppUTest/CommandLineTestRunner.h>
#include "main.h"
// A mock function to replace GPIO behavior
void mock_HAL_GPIO_TogglePin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin) {
// Mock behavior: simply log the pin toggled (you can implement tracking here)
}
extern "C" {
int some_function_from_main() {
return 42;
}
void HAL_GPIO_TogglePin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin) {
mock_HAL_GPIO_TogglePin(GPIOx, GPIO_Pin);
}
}
TEST_GROUP(LedBlinkGroup) {
void setup() {}
void teardown() {}
};
TEST(LedBlinkGroup, TestFunction1) {
int result = some_function_from_main();
CHECK_EQUAL(42, result);
}
TEST(LedBlinkGroup, TestGPIOFunctionality) {
HAL_GPIO_TogglePin(GPIOB, GPIO_PIN_4);
}
int main(int argc, char** argv) {
return CommandLineTestRunner::RunAllTests(argc, argv);
}
|
1,084 | cpp | custom_tests | custom_tests_3.cpp | custom/custom_tests_3.cpp | custom/custom_tests_3.cpp |
#include "CppUTest/TestHarness.h"
#include "CppUTestExt/MockSupport.h"
// Mocked function
double SquareRoot_sqrt(double number) {
return mock().actualCall("SquareRoot_sqrt")
.withParameter("number", number)
.returnDoubleValue();
}
// Function under test
double Pythagorean_hypotenuse(double x, double y) {
double sum_of_squares = x * x + y * y;
return SquareRoot_sqrt(sum_of_squares);
}
TEST_GROUP(Pythagorean) {
void teardown() {
mock().clear();
}
};
TEST(Pythagorean, CalculatesHypotenuse) {
mock().expectOneCall("SquareRoot_sqrt")
.withParameter("number", 25.0)
.andReturnValue(5.0);
double result = Pythagorean_hypotenuse(3.0, 4.0);
DOUBLES_EQUAL(5.0, result, 0.01);
}
|
#include "CppUTest/TestHarness.h"
#include "CppUTestExt/MockSupport.h"
// Mocked function
double SquareRoot_sqrt(double number) {
return mock().actualCall("SquareRoot_sqrt")
.withParameter("number", number)
.returnDoubleValue();
}
// Function under test
double Pythagorean_hypotenuse(double x, double y) {
double sum_of_squares = x * x + y * y;
return SquareRoot_sqrt(sum_of_squares);
}
TEST_GROUP(Pythagorean) {
void teardown() {
mock().clear();
}
};
TEST(Pythagorean, CalculatesHypotenuse) {
mock().expectOneCall("SquareRoot_sqrt")
.withParameter("number", 25.0)
.andReturnValue(5.0);
double result = Pythagorean_hypotenuse(3.0, 4.0);
DOUBLES_EQUAL(5.0, result, 0.01);
}
|
1,085 | cpp | custom_tests | custom_tests_4.cpp | custom/custom_tests_4.cpp | custom/custom_tests_4.cpp |
#include "CppUTest/TestHarness.h"
extern "C" {
#include "LedDriver.h"
#include "RuntimeErrorStub.h"
}
TEST_GROUP(LedDriver) {
uint16_t virtualLeds;
void setup() {
virtualLeds = 0;
LedDriver_Create(&virtualLeds);
}
void teardown() {
LedDriver_Destroy();
}
};
TEST(LedDriver, LedsAreOffAfterCreate) {
virtualLeds = 0xffff;
LedDriver_Create(&virtualLeds);
LONGS_EQUAL(0, virtualLeds);
}
TEST(LedDriver, TurnOnLedOne) {
LedDriver_TurnOn(1);
LONGS_EQUAL(1, virtualLeds);
}
TEST(LedDriver, TurnOffLedOne) {
LedDriver_TurnOn(1);
LedDriver_TurnOff(1);
LONGS_EQUAL(0, virtualLeds);
}
TEST(LedDriver, TurnOnMultipleLeds) {
LedDriver_TurnOn(9);
LedDriver_TurnOn(8);
LONGS_EQUAL(0x180, virtualLeds);
}
TEST(LedDriver, TurnOffAnyLed) {
LedDriver_TurnAllOn();
LedDriver_TurnOff(8);
LONGS_EQUAL(0xff7f, virtualLeds);
}
TEST(LedDriver, LedMemoryIsNotReadable) {
virtualLeds = 0xffff;
LedDriver_TurnOn(8);
LONGS_EQUAL(0x80, virtualLeds);
}
TEST(LedDriver, UpperAndLowerBounds) {
LedDriver_TurnOn(1);
LedDriver_TurnOn(16);
LONGS_EQUAL(0x8001, virtualLeds);
}
TEST(LedDriver, OutOfBoundsTurnOnDoesNoHarm) {
LedDriver_TurnOn(-1);
LedDriver_TurnOn(0);
LedDriver_TurnOn(17);
LedDriver_TurnOn(3141);
LONGS_EQUAL(0, virtualLeds);
}
TEST(LedDriver, OutOfBoundsTurnOffDoesNoHarm) {
LedDriver_TurnAllOn();
LedDriver_TurnOff(-1);
LedDriver_TurnOff(0);
LedDriver_TurnOff(17);
LedDriver_TurnOff(3141);
LONGS_EQUAL(0xffff, virtualLeds);
}
IGNORE_TEST(LedDriver, OutOfBoundsToDo) {
// demo shows how to IGNORE a test
}
TEST(LedDriver, OutOfBoundsProducesRuntimeError) {
LedDriver_TurnOn(-1);
STRCMP_EQUAL("LED Driver: out-of-bounds LED", RuntimeErrorStub_GetLastError());
}
TEST(LedDriver, IsOn) {
CHECK_EQUAL(FALSE, LedDriver_IsOn(1));
LedDriver_TurnOn(1);
CHECK_EQUAL(TRUE, LedDriver_IsOn(1));
}
TEST(LedDriver, IsOff) {
CHECK_EQUAL(TRUE, LedDriver_IsOff(12));
LedDriver_TurnOn(12);
CHECK_EQUAL(FALSE, LedDriver_IsOff(12));
}
TEST(LedDriver, OutOfBoundsLedsAreAlwaysOff) {
CHECK_EQUAL(TRUE, LedDriver_IsOff(0));
CHECK_EQUAL(TRUE, LedDriver_IsOff(17));
CHECK_EQUAL(FALSE, LedDriver_IsOn(0));
CHECK_EQUAL(FALSE, LedDriver_IsOn(17));
}
TEST(LedDriver, AllOn) {
LedDriver_TurnAllOn();
LONGS_EQUAL(0xffff, virtualLeds);
}
TEST(LedDriver, AllOff) {
LedDriver_TurnAllOn();
LedDriver_TurnAllOff();
LONGS_EQUAL(0, virtualLeds);
}
|
#include "CppUTest/TestHarness.h"
extern "C" {
#include "LedDriver.h"
#include "RuntimeErrorStub.h"
}
TEST_GROUP(LedDriver) {
uint16_t virtualLeds;
void setup() {
virtualLeds = 0;
LedDriver_Create(&virtualLeds);
}
void teardown() {
LedDriver_Destroy();
}
};
TEST(LedDriver, LedsAreOffAfterCreate) {
virtualLeds = 0xffff;
LedDriver_Create(&virtualLeds);
LONGS_EQUAL(0, virtualLeds);
}
TEST(LedDriver, TurnOnLedOne) {
LedDriver_TurnOn(1);
LONGS_EQUAL(1, virtualLeds);
}
TEST(LedDriver, TurnOffLedOne) {
LedDriver_TurnOn(1);
LedDriver_TurnOff(1);
LONGS_EQUAL(0, virtualLeds);
}
TEST(LedDriver, TurnOnMultipleLeds) {
LedDriver_TurnOn(9);
LedDriver_TurnOn(8);
LONGS_EQUAL(0x180, virtualLeds);
}
TEST(LedDriver, TurnOffAnyLed) {
LedDriver_TurnAllOn();
LedDriver_TurnOff(8);
LONGS_EQUAL(0xff7f, virtualLeds);
}
TEST(LedDriver, LedMemoryIsNotReadable) {
virtualLeds = 0xffff;
LedDriver_TurnOn(8);
LONGS_EQUAL(0x80, virtualLeds);
}
TEST(LedDriver, UpperAndLowerBounds) {
LedDriver_TurnOn(1);
LedDriver_TurnOn(16);
LONGS_EQUAL(0x8001, virtualLeds);
}
TEST(LedDriver, OutOfBoundsTurnOnDoesNoHarm) {
LedDriver_TurnOn(-1);
LedDriver_TurnOn(0);
LedDriver_TurnOn(17);
LedDriver_TurnOn(3141);
LONGS_EQUAL(0, virtualLeds);
}
TEST(LedDriver, OutOfBoundsTurnOffDoesNoHarm) {
LedDriver_TurnAllOn();
LedDriver_TurnOff(-1);
LedDriver_TurnOff(0);
LedDriver_TurnOff(17);
LedDriver_TurnOff(3141);
LONGS_EQUAL(0xffff, virtualLeds);
}
IGNORE_TEST(LedDriver, OutOfBoundsToDo) {
// demo shows how to IGNORE a test
}
TEST(LedDriver, OutOfBoundsProducesRuntimeError) {
LedDriver_TurnOn(-1);
STRCMP_EQUAL("LED Driver: out-of-bounds LED", RuntimeErrorStub_GetLastError());
}
TEST(LedDriver, IsOn) {
CHECK_EQUAL(FALSE, LedDriver_IsOn(1));
LedDriver_TurnOn(1);
CHECK_EQUAL(TRUE, LedDriver_IsOn(1));
}
TEST(LedDriver, IsOff) {
CHECK_EQUAL(TRUE, LedDriver_IsOff(12));
LedDriver_TurnOn(12);
CHECK_EQUAL(FALSE, LedDriver_IsOff(12));
}
TEST(LedDriver, OutOfBoundsLedsAreAlwaysOff) {
CHECK_EQUAL(TRUE, LedDriver_IsOff(0));
CHECK_EQUAL(TRUE, LedDriver_IsOff(17));
CHECK_EQUAL(FALSE, LedDriver_IsOn(0));
CHECK_EQUAL(FALSE, LedDriver_IsOn(17));
}
TEST(LedDriver, AllOn) {
LedDriver_TurnAllOn();
LONGS_EQUAL(0xffff, virtualLeds);
}
TEST(LedDriver, AllOff) {
LedDriver_TurnAllOn();
LedDriver_TurnAllOff();
LONGS_EQUAL(0, virtualLeds);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.