cppcheck/lib/token.cpp

1728 lines
50 KiB
C++
Raw Normal View History

2008-12-18 22:28:57 +01:00
/*
* Cppcheck - A tool for static C/C++ code analysis
2018-03-31 20:59:09 +02:00
* Copyright (C) 2007-2018 Cppcheck team.
2008-12-18 22:28:57 +01:00
*
* 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/>.
2008-12-18 22:28:57 +01:00
*/
#include "token.h"
2017-05-27 04:33:47 +02:00
#include "errorlogger.h"
2017-05-27 04:33:47 +02:00
#include "library.h"
#include "settings.h"
#include "symboldatabase.h"
#include "utils.h"
2017-05-27 04:33:47 +02:00
#include <cassert>
2017-05-27 04:33:47 +02:00
#include <cctype>
2008-12-18 22:28:57 +01:00
#include <cstring>
#include <iostream>
#include <map>
2017-05-27 04:33:47 +02:00
#include <set>
#include <stack>
2017-05-27 04:33:47 +02:00
#include <utility>
2018-06-17 17:20:16 +02:00
const std::list<ValueFlow::Value> Token::mEmptyValueList;
Fix crash bug #8579 (#1238) * Added declaration for deletePrevious function * Added definition for deletePrevious function * Fixed crash from deleteThis invalidating pointers The crash was caused by deleteThis() invalidating the pointer to a constant variable usage. This happened when a usage followed an assignment. This fixes bug #8579. * Added tokensFront to match tokensBack This means deletePrevious can set the list's front if necessary. * Initialised tokensFront in appropriate places * Switched to using default Token constructor * Switched to using Token default constructor * Switched to using default constructor for Token * Added missing argument to Token constructor * Changed to use default constructor for Tokens * Switched to using default constructor for Tokens * Switched to using default constructor for Token * Added new test for deleting front Token Also made sure to use the correct constructor for Token in other tests. * Syntax error * Replaced tokensFront and tokensBack with a struct This decreases the size of the Token class for performance purposes. * Replaced tokensFront and tokensBack with a struct * Added tokensFrontBack to destructor * Reworked to use TokensBackFront struct Also ran astyle. * Reworked to use TokenList's TokensFrontBack member * Reworked to use TokensFrontBack struct * Reworked to use TokensFrontBack struct * Reworked to work with TokensFrontBack struct * Removed unnecessary scope operator * Added missing parentheses * Fixed syntax error * Removed unnecessary constructor * Default constructor now 0-initialises everything This is safer for not using a temporary TokensFrontBack object, and doesn't use delegating constructors which aren't supported yet. * Fixed unsafe null check * Added missing explicit keyword * Fixing stylistic nits Removed default constructor as it has been superseded by the single-argument constructor with a default argument value. Renamed listEnds to tokensFrontBack. Fixed if statement that was supposed to be adding safety but would actually cause a crash if tokensFrontBack was null. * Fixing stylistic nits Removed default constructor and replaced it with a single-argument constructor with a default value. * Fixing stylistic nits Renamed _listEnds to _tokensFrontBack. * Fixing stylistic nits Renamed _listEnds to _tokensFrontBack.
2018-05-25 07:15:05 +02:00
Token::Token(TokensFrontBack *tokensFrontBack) :
mTokensFrontBack(tokensFrontBack),
2018-06-16 16:16:55 +02:00
mNext(nullptr),
mPrevious(nullptr),
2018-06-16 20:30:09 +02:00
mLink(nullptr),
2018-06-16 20:29:17 +02:00
mScope(nullptr),
2018-06-16 20:26:43 +02:00
mFunction(nullptr), // Initialize whole union
2018-06-16 16:38:50 +02:00
mVarId(0),
2018-06-16 16:43:54 +02:00
mFileIndex(0),
mLineNumber(0),
mColumn(0),
mProgressValue(0),
2018-06-16 16:40:02 +02:00
mTokType(eNone),
2018-06-16 16:14:34 +02:00
mFlags(0),
2018-06-16 21:43:44 +02:00
mBits(0),
mAstOperand1(nullptr),
mAstOperand2(nullptr),
mAstParent(nullptr),
2018-06-16 21:40:25 +02:00
mOriginalName(nullptr),
2018-06-16 21:42:40 +02:00
mValueType(nullptr),
2018-06-16 21:45:53 +02:00
mValues(nullptr)
2008-12-18 22:28:57 +01:00
{
}
Token::~Token()
2008-12-18 22:28:57 +01:00
{
2018-06-16 21:40:25 +02:00
delete mOriginalName;
2018-06-16 21:42:40 +02:00
delete mValueType;
2018-06-16 21:45:53 +02:00
delete mValues;
2008-12-18 22:28:57 +01:00
}
static const std::set<std::string> controlFlowKeywords = {
"goto",
"do",
"if",
"else",
"for",
"while",
"switch",
"case",
"break",
"continue",
"return"
};
void Token::update_property_info()
2008-12-18 22:28:57 +01:00
{
2018-06-16 23:03:15 +02:00
setFlag(fIsControlFlowKeyword, controlFlowKeywords.find(mStr) != controlFlowKeywords.end());
2018-06-16 23:03:15 +02:00
if (!mStr.empty()) {
if (mStr == "true" || mStr == "false")
2017-10-15 01:27:47 +02:00
tokType(eBoolean);
2018-06-16 23:03:15 +02:00
else if (std::isalpha((unsigned char)mStr[0]) || mStr[0] == '_' || mStr[0] == '$') { // Name
2018-06-16 16:38:50 +02:00
if (mVarId)
2017-10-15 01:27:47 +02:00
tokType(eVariable);
2018-06-16 16:40:02 +02:00
else if (mTokType != eVariable && mTokType != eFunction && mTokType != eType && mTokType != eKeyword)
2017-10-15 01:27:47 +02:00
tokType(eName);
2018-06-16 23:03:15 +02:00
} else if (std::isdigit((unsigned char)mStr[0]) || (mStr.length() > 1 && mStr[0] == '-' && std::isdigit((unsigned char)mStr[1])))
2017-10-15 01:27:47 +02:00
tokType(eNumber);
2018-06-16 23:03:15 +02:00
else if (mStr.length() > 1 && mStr[0] == '"' && endsWith(mStr,'"'))
2017-10-15 01:27:47 +02:00
tokType(eString);
2018-06-16 23:03:15 +02:00
else if (mStr.length() > 1 && mStr[0] == '\'' && endsWith(mStr,'\''))
2017-10-15 01:27:47 +02:00
tokType(eChar);
2018-06-16 23:03:15 +02:00
else if (mStr == "=" || mStr == "<<=" || mStr == ">>=" ||
(mStr.size() == 2U && mStr[1] == '=' && std::strchr("+-*/%&^|", mStr[0])))
2017-10-15 01:27:47 +02:00
tokType(eAssignmentOp);
2018-06-16 23:03:15 +02:00
else if (mStr.size() == 1 && mStr.find_first_of(",[]()?:") != std::string::npos)
2017-10-15 01:27:47 +02:00
tokType(eExtendedOp);
2018-06-16 23:03:15 +02:00
else if (mStr=="<<" || mStr==">>" || (mStr.size()==1 && mStr.find_first_of("+-*/%") != std::string::npos))
2017-10-15 01:27:47 +02:00
tokType(eArithmeticalOp);
2018-06-16 23:03:15 +02:00
else if (mStr.size() == 1 && mStr.find_first_of("&|^~") != std::string::npos)
2017-10-15 01:27:47 +02:00
tokType(eBitOp);
2018-06-16 23:03:15 +02:00
else if (mStr.size() <= 2 &&
(mStr == "&&" ||
mStr == "||" ||
mStr == "!"))
2017-10-15 01:27:47 +02:00
tokType(eLogicalOp);
2018-06-16 23:03:15 +02:00
else if (mStr.size() <= 2 && !mLink &&
(mStr == "==" ||
mStr == "!=" ||
mStr == "<" ||
mStr == "<=" ||
mStr == ">" ||
mStr == ">="))
2017-10-15 01:27:47 +02:00
tokType(eComparisonOp);
2018-06-16 23:03:15 +02:00
else if (mStr.size() == 2 &&
(mStr == "++" ||
mStr == "--"))
2017-10-15 01:27:47 +02:00
tokType(eIncDecOp);
2018-06-16 23:03:15 +02:00
else if (mStr.size() == 1 && (mStr.find_first_of("{}") != std::string::npos || (mLink && mStr.find_first_of("<>") != std::string::npos)))
2017-10-15 01:27:47 +02:00
tokType(eBracket);
else
2017-10-15 01:27:47 +02:00
tokType(eOther);
} else {
2017-10-15 01:27:47 +02:00
tokType(eNone);
}
update_property_isStandardType();
}
static const std::set<std::string> stdTypes = { "bool"
, "_Bool"
, "char"
, "double"
, "float"
, "int"
, "long"
, "short"
, "size_t"
, "void"
, "wchar_t"
};
void Token::update_property_isStandardType()
{
isStandardType(false);
2018-06-16 23:03:15 +02:00
if (mStr.size() < 3)
return;
2018-06-16 23:03:15 +02:00
if (stdTypes.find(mStr)!=stdTypes.end()) {
isStandardType(true);
2017-10-15 01:27:47 +02:00
tokType(eType);
}
}
bool Token::isUpperCaseName() const
{
if (!isName())
return false;
2018-06-16 23:03:15 +02:00
for (size_t i = 0; i < mStr.length(); ++i) {
if (std::islower(mStr[i]))
return false;
}
return true;
}
void Token::concatStr(std::string const& b)
{
2018-06-16 23:03:15 +02:00
mStr.erase(mStr.length() - 1);
mStr.append(b.begin() + 1, b.end());
update_property_info();
}
std::string Token::strValue() const
{
2018-06-16 16:40:02 +02:00
assert(mTokType == eString);
2018-06-16 23:03:15 +02:00
std::string ret(mStr.substr(1, mStr.length() - 2));
std::string::size_type pos = 0U;
while ((pos = ret.find('\\', pos)) != std::string::npos) {
ret.erase(pos,1U);
if (ret[pos] >= 'a') {
if (ret[pos] == 'n')
ret[pos] = '\n';
else if (ret[pos] == 'r')
ret[pos] = '\r';
else if (ret[pos] == 't')
ret[pos] = '\t';
}
if (ret[pos] == '0')
return ret.substr(0,pos);
pos++;
}
return ret;
}
void Token::deleteNext(unsigned long index)
2008-12-18 22:28:57 +01:00
{
2018-06-16 16:16:55 +02:00
while (mNext && index) {
Token *n = mNext;
// #8154 we are about to be unknown -> destroy the link to us
2018-06-16 20:30:09 +02:00
if (n->mLink && n->mLink->mLink == n)
n->mLink->link(nullptr);
2018-06-16 16:16:55 +02:00
mNext = n->next();
delete n;
--index;
}
2018-06-16 16:16:55 +02:00
if (mNext)
mNext->previous(this);
else if (mTokensFrontBack)
mTokensFrontBack->back = this;
Fix crash bug #8579 (#1238) * Added declaration for deletePrevious function * Added definition for deletePrevious function * Fixed crash from deleteThis invalidating pointers The crash was caused by deleteThis() invalidating the pointer to a constant variable usage. This happened when a usage followed an assignment. This fixes bug #8579. * Added tokensFront to match tokensBack This means deletePrevious can set the list's front if necessary. * Initialised tokensFront in appropriate places * Switched to using default Token constructor * Switched to using Token default constructor * Switched to using default constructor for Token * Added missing argument to Token constructor * Changed to use default constructor for Tokens * Switched to using default constructor for Tokens * Switched to using default constructor for Token * Added new test for deleting front Token Also made sure to use the correct constructor for Token in other tests. * Syntax error * Replaced tokensFront and tokensBack with a struct This decreases the size of the Token class for performance purposes. * Replaced tokensFront and tokensBack with a struct * Added tokensFrontBack to destructor * Reworked to use TokensBackFront struct Also ran astyle. * Reworked to use TokenList's TokensFrontBack member * Reworked to use TokensFrontBack struct * Reworked to use TokensFrontBack struct * Reworked to work with TokensFrontBack struct * Removed unnecessary scope operator * Added missing parentheses * Fixed syntax error * Removed unnecessary constructor * Default constructor now 0-initialises everything This is safer for not using a temporary TokensFrontBack object, and doesn't use delegating constructors which aren't supported yet. * Fixed unsafe null check * Added missing explicit keyword * Fixing stylistic nits Removed default constructor as it has been superseded by the single-argument constructor with a default argument value. Renamed listEnds to tokensFrontBack. Fixed if statement that was supposed to be adding safety but would actually cause a crash if tokensFrontBack was null. * Fixing stylistic nits Removed default constructor and replaced it with a single-argument constructor with a default value. * Fixing stylistic nits Renamed _listEnds to _tokensFrontBack. * Fixing stylistic nits Renamed _listEnds to _tokensFrontBack.
2018-05-25 07:15:05 +02:00
}
void Token::deletePrevious(unsigned long index)
{
2018-06-16 16:16:55 +02:00
while (mPrevious && index) {
Token *p = mPrevious;
Fix crash bug #8579 (#1238) * Added declaration for deletePrevious function * Added definition for deletePrevious function * Fixed crash from deleteThis invalidating pointers The crash was caused by deleteThis() invalidating the pointer to a constant variable usage. This happened when a usage followed an assignment. This fixes bug #8579. * Added tokensFront to match tokensBack This means deletePrevious can set the list's front if necessary. * Initialised tokensFront in appropriate places * Switched to using default Token constructor * Switched to using Token default constructor * Switched to using default constructor for Token * Added missing argument to Token constructor * Changed to use default constructor for Tokens * Switched to using default constructor for Tokens * Switched to using default constructor for Token * Added new test for deleting front Token Also made sure to use the correct constructor for Token in other tests. * Syntax error * Replaced tokensFront and tokensBack with a struct This decreases the size of the Token class for performance purposes. * Replaced tokensFront and tokensBack with a struct * Added tokensFrontBack to destructor * Reworked to use TokensBackFront struct Also ran astyle. * Reworked to use TokenList's TokensFrontBack member * Reworked to use TokensFrontBack struct * Reworked to use TokensFrontBack struct * Reworked to work with TokensFrontBack struct * Removed unnecessary scope operator * Added missing parentheses * Fixed syntax error * Removed unnecessary constructor * Default constructor now 0-initialises everything This is safer for not using a temporary TokensFrontBack object, and doesn't use delegating constructors which aren't supported yet. * Fixed unsafe null check * Added missing explicit keyword * Fixing stylistic nits Removed default constructor as it has been superseded by the single-argument constructor with a default argument value. Renamed listEnds to tokensFrontBack. Fixed if statement that was supposed to be adding safety but would actually cause a crash if tokensFrontBack was null. * Fixing stylistic nits Removed default constructor and replaced it with a single-argument constructor with a default value. * Fixing stylistic nits Renamed _listEnds to _tokensFrontBack. * Fixing stylistic nits Renamed _listEnds to _tokensFrontBack.
2018-05-25 07:15:05 +02:00
// #8154 we are about to be unknown -> destroy the link to us
2018-06-16 20:30:09 +02:00
if (p->mLink && p->mLink->mLink == p)
p->mLink->link(nullptr);
Fix crash bug #8579 (#1238) * Added declaration for deletePrevious function * Added definition for deletePrevious function * Fixed crash from deleteThis invalidating pointers The crash was caused by deleteThis() invalidating the pointer to a constant variable usage. This happened when a usage followed an assignment. This fixes bug #8579. * Added tokensFront to match tokensBack This means deletePrevious can set the list's front if necessary. * Initialised tokensFront in appropriate places * Switched to using default Token constructor * Switched to using Token default constructor * Switched to using default constructor for Token * Added missing argument to Token constructor * Changed to use default constructor for Tokens * Switched to using default constructor for Tokens * Switched to using default constructor for Token * Added new test for deleting front Token Also made sure to use the correct constructor for Token in other tests. * Syntax error * Replaced tokensFront and tokensBack with a struct This decreases the size of the Token class for performance purposes. * Replaced tokensFront and tokensBack with a struct * Added tokensFrontBack to destructor * Reworked to use TokensBackFront struct Also ran astyle. * Reworked to use TokenList's TokensFrontBack member * Reworked to use TokensFrontBack struct * Reworked to use TokensFrontBack struct * Reworked to work with TokensFrontBack struct * Removed unnecessary scope operator * Added missing parentheses * Fixed syntax error * Removed unnecessary constructor * Default constructor now 0-initialises everything This is safer for not using a temporary TokensFrontBack object, and doesn't use delegating constructors which aren't supported yet. * Fixed unsafe null check * Added missing explicit keyword * Fixing stylistic nits Removed default constructor as it has been superseded by the single-argument constructor with a default argument value. Renamed listEnds to tokensFrontBack. Fixed if statement that was supposed to be adding safety but would actually cause a crash if tokensFrontBack was null. * Fixing stylistic nits Removed default constructor and replaced it with a single-argument constructor with a default value. * Fixing stylistic nits Renamed _listEnds to _tokensFrontBack. * Fixing stylistic nits Renamed _listEnds to _tokensFrontBack.
2018-05-25 07:15:05 +02:00
2018-06-16 16:16:55 +02:00
mPrevious = p->previous();
Fix crash bug #8579 (#1238) * Added declaration for deletePrevious function * Added definition for deletePrevious function * Fixed crash from deleteThis invalidating pointers The crash was caused by deleteThis() invalidating the pointer to a constant variable usage. This happened when a usage followed an assignment. This fixes bug #8579. * Added tokensFront to match tokensBack This means deletePrevious can set the list's front if necessary. * Initialised tokensFront in appropriate places * Switched to using default Token constructor * Switched to using Token default constructor * Switched to using default constructor for Token * Added missing argument to Token constructor * Changed to use default constructor for Tokens * Switched to using default constructor for Tokens * Switched to using default constructor for Token * Added new test for deleting front Token Also made sure to use the correct constructor for Token in other tests. * Syntax error * Replaced tokensFront and tokensBack with a struct This decreases the size of the Token class for performance purposes. * Replaced tokensFront and tokensBack with a struct * Added tokensFrontBack to destructor * Reworked to use TokensBackFront struct Also ran astyle. * Reworked to use TokenList's TokensFrontBack member * Reworked to use TokensFrontBack struct * Reworked to use TokensFrontBack struct * Reworked to work with TokensFrontBack struct * Removed unnecessary scope operator * Added missing parentheses * Fixed syntax error * Removed unnecessary constructor * Default constructor now 0-initialises everything This is safer for not using a temporary TokensFrontBack object, and doesn't use delegating constructors which aren't supported yet. * Fixed unsafe null check * Added missing explicit keyword * Fixing stylistic nits Removed default constructor as it has been superseded by the single-argument constructor with a default argument value. Renamed listEnds to tokensFrontBack. Fixed if statement that was supposed to be adding safety but would actually cause a crash if tokensFrontBack was null. * Fixing stylistic nits Removed default constructor and replaced it with a single-argument constructor with a default value. * Fixing stylistic nits Renamed _listEnds to _tokensFrontBack. * Fixing stylistic nits Renamed _listEnds to _tokensFrontBack.
2018-05-25 07:15:05 +02:00
delete p;
--index;
}
2018-06-16 16:16:55 +02:00
if (mPrevious)
mPrevious->next(this);
else if (mTokensFrontBack)
mTokensFrontBack->front = this;
2008-12-18 22:28:57 +01:00
}
void Token::swapWithNext()
{
2018-06-16 16:16:55 +02:00
if (mNext) {
2018-06-16 23:03:15 +02:00
std::swap(mStr, mNext->mStr);
2018-06-16 16:40:02 +02:00
std::swap(mTokType, mNext->mTokType);
2018-06-16 16:16:55 +02:00
std::swap(mFlags, mNext->mFlags);
2018-06-16 16:38:50 +02:00
std::swap(mVarId, mNext->mVarId);
2018-06-16 16:43:54 +02:00
std::swap(mFileIndex, mNext->mFileIndex);
std::swap(mLineNumber, mNext->mLineNumber);
2018-06-16 20:30:09 +02:00
if (mNext->mLink)
mNext->mLink->mLink = this;
if (this->mLink)
this->mLink->mLink = mNext;
std::swap(mLink, mNext->mLink);
2018-06-16 20:29:17 +02:00
std::swap(mScope, mNext->mScope);
2018-06-16 20:26:43 +02:00
std::swap(mFunction, mNext->mFunction);
2018-06-16 21:40:25 +02:00
std::swap(mOriginalName, mNext->mOriginalName);
2018-06-16 21:45:53 +02:00
std::swap(mValues, mNext->mValues);
2018-06-16 21:42:40 +02:00
std::swap(mValueType, mNext->mValueType);
std::swap(mProgressValue, mNext->mProgressValue);
}
}
2017-08-25 23:30:04 +02:00
void Token::takeData(Token *fromToken)
{
2018-06-16 23:03:15 +02:00
mStr = fromToken->mStr;
2018-06-16 16:40:02 +02:00
tokType(fromToken->mTokType);
2018-06-16 16:14:34 +02:00
mFlags = fromToken->mFlags;
2018-06-16 16:38:50 +02:00
mVarId = fromToken->mVarId;
2018-06-16 16:43:54 +02:00
mFileIndex = fromToken->mFileIndex;
mLineNumber = fromToken->mLineNumber;
2018-06-16 20:30:09 +02:00
mLink = fromToken->mLink;
2018-06-16 20:29:17 +02:00
mScope = fromToken->mScope;
2018-06-16 20:26:43 +02:00
mFunction = fromToken->mFunction;
2018-06-16 21:40:25 +02:00
if (fromToken->mOriginalName) {
delete mOriginalName;
mOriginalName = fromToken->mOriginalName;
fromToken->mOriginalName = nullptr;
2017-08-25 23:30:04 +02:00
}
2018-06-16 21:45:53 +02:00
delete mValues;
mValues = fromToken->mValues;
fromToken->mValues = nullptr;
2018-06-16 21:42:40 +02:00
delete mValueType;
mValueType = fromToken->mValueType;
fromToken->mValueType = nullptr;
2018-06-16 20:30:09 +02:00
if (mLink)
mLink->link(this);
2017-08-25 23:30:04 +02:00
}
void Token::deleteThis()
{
2018-06-16 16:16:55 +02:00
if (mNext) { // Copy next to this and delete next
takeData(mNext);
mNext->link(nullptr); // mark as unlinked
deleteNext();
2018-06-16 16:16:55 +02:00
} else if (mPrevious && mPrevious->mPrevious) { // Copy previous to this and delete previous
takeData(mPrevious);
2018-06-16 16:16:55 +02:00
Token* toDelete = mPrevious;
mPrevious = mPrevious->mPrevious;
mPrevious->mNext = this;
delete toDelete;
2011-10-13 20:53:06 +02:00
} else {
// We are the last token in the list, we can't delete
// ourselves, so just make us empty
str("");
}
}
void Token::replace(Token *replaceThis, Token *start, Token *end)
{
// Fix the whole in the old location of start and end
if (start->previous())
start->previous()->next(end->next());
if (end->next())
end->next()->previous(start->previous());
// Move start and end to their new location
if (replaceThis->previous())
replaceThis->previous()->next(start);
if (replaceThis->next())
replaceThis->next()->previous(end);
start->previous(replaceThis->previous());
end->next(replaceThis->next());
if (end->mTokensFrontBack && end->mTokensFrontBack->back == end) {
while (end->next())
end = end->next();
end->mTokensFrontBack->back = end;
}
// Update mProgressValue, fileIndex and linenr
2012-01-22 00:02:55 +01:00
for (Token *tok = start; tok != end->next(); tok = tok->next())
tok->mProgressValue = replaceThis->mProgressValue;
// Delete old token, which is replaced
delete replaceThis;
}
const Token *Token::tokAt(int index) const
2008-12-18 22:28:57 +01:00
{
const Token *tok = this;
while (index > 0 && tok) {
tok = tok->next();
--index;
}
while (index < 0 && tok) {
tok = tok->previous();
++index;
2008-12-18 22:28:57 +01:00
}
return tok;
}
const Token *Token::linkAt(int index) const
{
const Token *tok = this->tokAt(index);
if (!tok) {
throw InternalError(this, "Internal error. Token::linkAt called with index outside the tokens range.");
}
return tok->link();
}
const std::string &Token::strAt(int index) const
2008-12-18 22:28:57 +01:00
{
const Token *tok = this->tokAt(index);
2018-06-16 23:03:15 +02:00
return tok ? tok->mStr : emptyString;
2008-12-18 22:28:57 +01:00
}
static int multiComparePercent(const Token *tok, const char*& haystack, unsigned int varid)
{
++haystack;
// Compare only the first character of the string for optimization reasons
switch (haystack[0]) {
case '\0':
case ' ':
case '|':
//simple '%' character
haystack += 1;
if (tok->isArithmeticalOp() && tok->str() == "%")
return 1;
break;
case 'v':
if (haystack[3] == '%') { // %var%
haystack += 4;
if (tok->varId() != 0)
return 1;
} else { // %varid%
if (varid == 0) {
throw InternalError(tok, "Internal error. Token::Match called with varid 0. Please report this to Cppcheck developers");
}
haystack += 6;
if (tok->varId() == varid)
return 1;
}
break;
case 't':
// Type (%type%)
{
haystack += 5;
if (tok->isName() && tok->varId() == 0 && !tok->isKeyword())
return 1;
}
break;
case 'a':
// Accept any token (%any%) or assign (%assign%)
{
if (haystack[3] == '%') { // %any%
haystack += 4;
return 1;
} else { // %assign%
haystack += 7;
if (tok->isAssignmentOp())
return 1;
}
}
break;
case 'n':
// Number (%num%) or name (%name%)
{
if (haystack[4] == '%') { // %name%
haystack += 5;
if (tok->isName())
return 1;
} else {
haystack += 4;
if (tok->isNumber())
return 1;
}
}
break;
case 'c': {
haystack += 1;
// Character (%char%)
if (haystack[0] == 'h') {
haystack += 4;
if (tok->tokType() == Token::eChar)
return 1;
}
// Const operator (%cop%)
else if (haystack[1] == 'p') {
haystack += 3;
if (tok->isConstOp())
return 1;
}
// Comparison operator (%comp%)
else {
haystack += 4;
if (tok->isComparisonOp())
return 1;
}
}
break;
case 's':
// String (%str%)
{
haystack += 4;
if (tok->tokType() == Token::eString)
return 1;
}
break;
case 'b':
// Bool (%bool%)
{
haystack += 5;
if (tok->isBoolean())
return 1;
}
break;
case 'o': {
++haystack;
if (haystack[1] == '%') {
// Op (%op%)
if (haystack[0] == 'p') {
haystack += 2;
if (tok->isOp())
return 1;
}
// Or (%or%)
else {
haystack += 2;
if (tok->tokType() == Token::eBitOp && tok->str() == "|")
return 1;
}
}
// Oror (%oror%)
else {
haystack += 4;
if (tok->tokType() == Token::eLogicalOp && tok->str() == "||")
return 1;
}
}
break;
default:
//unknown %cmd%, abort
2015-03-29 21:05:18 +02:00
throw InternalError(tok, "Unexpected command");
}
if (*haystack == '|')
haystack += 1;
else
return -1;
return 0xFFFF;
}
int Token::multiCompare(const Token *tok, const char *haystack, unsigned int varid)
2008-12-18 22:28:57 +01:00
{
const char *needle = tok->str().c_str();
const char *needlePointer = needle;
2012-03-25 11:51:59 +02:00
for (;;) {
if (needlePointer == needle && haystack[0] == '%' && haystack[1] != '|' && haystack[1] != '\0' && haystack[1] != ' ') {
2018-04-04 21:51:31 +02:00
const int ret = multiComparePercent(tok, haystack, varid);
if (ret < 2)
return ret;
2011-10-13 20:53:06 +02:00
} else if (*haystack == '|') {
if (*needlePointer == 0) {
// If needle is at the end, we have a match.
2008-12-18 22:28:57 +01:00
return 1;
}
2008-12-18 22:28:57 +01:00
needlePointer = needle;
++haystack;
} else if (*needlePointer == *haystack) {
if (*needlePointer == '\0')
return 1;
++needlePointer;
++haystack;
2011-10-13 20:53:06 +02:00
} else if (*haystack == ' ' || *haystack == '\0') {
if (needlePointer == needle)
return 0;
break;
2008-12-18 22:28:57 +01:00
}
// If haystack and needle don't share the same character,
// find next '|' character.
2011-10-13 20:53:06 +02:00
else {
needlePointer = needle;
2008-12-18 22:28:57 +01:00
2011-10-13 20:53:06 +02:00
do {
++haystack;
2011-10-13 20:53:06 +02:00
} while (*haystack != ' ' && *haystack != '|' && *haystack);
2008-12-18 22:28:57 +01:00
2011-10-13 20:53:06 +02:00
if (*haystack == ' ' || *haystack == '\0') {
return -1;
}
2008-12-18 22:28:57 +01:00
++haystack;
}
}
if (*needlePointer == '\0')
return 1;
2008-12-18 22:28:57 +01:00
return -1;
}
bool Token::simpleMatch(const Token *tok, const char pattern[])
{
if (!tok)
return false; // shortcut
const char *current = pattern;
const char *next = std::strchr(pattern, ' ');
if (!next)
2012-12-27 11:51:12 +01:00
next = pattern + std::strlen(pattern);
2011-10-13 20:53:06 +02:00
while (*current) {
2018-04-04 21:51:31 +02:00
const std::size_t length = next - current;
2018-06-16 23:03:15 +02:00
if (!tok || length != tok->mStr.length() || std::strncmp(current, tok->mStr.c_str(), length))
return false;
current = next;
2011-10-13 20:53:06 +02:00
if (*next) {
2012-12-27 11:51:12 +01:00
next = std::strchr(++current, ' ');
if (!next)
2012-12-27 11:51:12 +01:00
next = current + std::strlen(current);
}
tok = tok->next();
}
return true;
}
bool Token::firstWordEquals(const char *str, const char *word)
{
2011-10-13 20:53:06 +02:00
for (;;) {
if (*str != *word) {
return (*str == ' ' && *word == 0);
2011-10-13 20:53:06 +02:00
} else if (*str == 0)
break;
++str;
++word;
}
return true;
}
const char *Token::chrInFirstWord(const char *str, char c)
{
2011-10-13 20:53:06 +02:00
for (;;) {
if (*str == ' ' || *str == 0)
return nullptr;
if (*str == c)
return str;
++str;
}
}
bool Token::Match(const Token *tok, const char pattern[], unsigned int varid)
2008-12-18 22:28:57 +01:00
{
const char *p = pattern;
2011-10-13 20:53:06 +02:00
while (*p) {
2008-12-18 22:28:57 +01:00
// Skip spaces in pattern..
while (*p == ' ')
2009-01-01 23:22:28 +01:00
++p;
2008-12-18 22:28:57 +01:00
// No token => Success!
if (*p == '\0')
break;
2008-12-18 22:28:57 +01:00
2011-10-13 20:53:06 +02:00
if (!tok) {
// If we have no tokens, pattern "!!else" should return true
2012-11-25 15:13:41 +01:00
if (p[0] == '!' && p[1] == '!' && p[2] != '\0') {
2010-09-20 20:15:07 +02:00
while (*p && *p != ' ')
++p;
continue;
2011-10-13 20:53:06 +02:00
} else
return false;
}
2008-12-18 22:28:57 +01:00
// [.. => search for a one-character token..
if (p[0] == '[' && chrInFirstWord(p, ']')) {
if (tok->str().length() != 1)
return false;
2011-07-15 19:02:16 +02:00
const char *temp = p+1;
bool chrFound = false;
unsigned int count = 0;
2011-10-13 20:53:06 +02:00
while (*temp && *temp != ' ') {
if (*temp == ']') {
++count;
}
else if (*temp == tok->str()[0]) {
chrFound = true;
break;
}
++temp;
}
if (count > 1 && tok->str()[0] == ']')
chrFound = true;
if (!chrFound)
2008-12-18 22:28:57 +01:00
return false;
p = temp;
while (*p && *p != ' ')
++p;
2008-12-18 22:28:57 +01:00
}
// Parse "not" options. Token can be anything except the given one
else if (p[0] == '!' && p[1] == '!' && p[2] != '\0') {
p += 2;
if (firstWordEquals(p, tok->str().c_str()))
return false;
while (*p && *p != ' ')
++p;
}
2008-12-18 22:28:57 +01:00
// Parse multi options, such as void|int|char (accept token which is one of these 3)
else {
2018-04-04 21:51:31 +02:00
const int res = multiCompare(tok, p, varid);
2011-10-13 20:53:06 +02:00
if (res == 0) {
2008-12-18 22:28:57 +01:00
// Empty alternative matches, use the same token on next round
2010-09-20 20:15:07 +02:00
while (*p && *p != ' ')
++p;
2008-12-18 22:28:57 +01:00
continue;
2011-10-13 20:53:06 +02:00
} else if (res == -1) {
2008-12-18 22:28:57 +01:00
// No match
return false;
}
}
2010-09-20 20:15:07 +02:00
while (*p && *p != ' ')
++p;
2008-12-18 22:28:57 +01:00
tok = tok->next();
}
// The end of the pattern has been reached and nothing wrong has been found
return true;
}
std::size_t Token::getStrLength(const Token *tok)
{
2014-02-15 08:05:54 +01:00
assert(tok != nullptr);
2018-06-16 16:40:02 +02:00
assert(tok->mTokType == eString);
std::size_t len = 0;
std::string::const_iterator it = tok->str().begin() + 1U;
const std::string::const_iterator end = tok->str().end() - 1U;
while (it != end) {
if (*it == '\\') {
++it;
// string ends at '\0'
if (*it == '0')
return len;
}
if (*it == '\0')
return len;
++it;
++len;
}
return len;
}
std::size_t Token::getStrSize(const Token *tok)
{
assert(tok != nullptr && tok->tokType() == eString);
const std::string &str = tok->str();
unsigned int sizeofstring = 1U;
for (unsigned int i = 1U; i < str.size() - 1U; i++) {
if (str[i] == '\\')
++i;
++sizeofstring;
}
return sizeofstring;
}
2013-01-13 20:52:38 +01:00
std::string Token::getCharAt(const Token *tok, std::size_t index)
{
2014-02-15 08:05:54 +01:00
assert(tok != nullptr);
2013-01-13 20:52:38 +01:00
std::string::const_iterator it = tok->str().begin() + 1U;
const std::string::const_iterator end = tok->str().end() - 1U;
2013-01-13 20:52:38 +01:00
while (it != end) {
2013-01-13 20:52:38 +01:00
if (index == 0) {
if (*it == '\0')
return "\\0";
std::string ret(1, *it);
if (*it == '\\') {
++it;
ret += *it;
2013-01-13 20:52:38 +01:00
}
return ret;
}
if (*it == '\\')
++it;
++it;
2013-01-13 20:52:38 +01:00
--index;
}
assert(index == 0);
return "\\0";
}
void Token::move(Token *srcStart, Token *srcEnd, Token *newLocation)
{
/**[newLocation] -> b -> c -> [srcStart] -> [srcEnd] -> f */
// Fix the gap, which tokens to be moved will leave
srcStart->previous()->next(srcEnd->next());
srcEnd->next()->previous(srcStart->previous());
// Fix the tokens to be moved
srcEnd->next(newLocation->next());
srcStart->previous(newLocation);
// Fix the tokens at newLocation
newLocation->next()->previous(srcEnd);
newLocation->next(srcStart);
// Update _progressValue
for (Token *tok = srcStart; tok != srcEnd->next(); tok = tok->next())
tok->mProgressValue = newLocation->mProgressValue;
}
Token* Token::nextArgument() const
2011-10-23 11:23:48 +02:00
{
for (const Token* tok = this; tok; tok = tok->next()) {
if (tok->str() == ",")
return tok->next();
else if (tok->link() && Token::Match(tok, "(|{|[|<"))
tok = tok->link();
else if (Token::Match(tok, ")|;"))
return nullptr;
2011-10-23 11:23:48 +02:00
}
return nullptr;
2011-10-23 11:23:48 +02:00
}
Token* Token::nextArgumentBeforeCreateLinks2() const
{
for (const Token* tok = this; tok; tok = tok->next()) {
if (tok->str() == ",")
return tok->next();
else if (tok->link() && Token::Match(tok, "(|{|["))
tok = tok->link();
else if (tok->str() == "<") {
const Token* temp = tok->findClosingBracket();
if (temp)
tok = temp;
} else if (Token::Match(tok, ")|;"))
return nullptr;
}
return nullptr;
}
Token* Token::nextTemplateArgument() const
{
for (const Token* tok = this; tok; tok = tok->next()) {
if (tok->str() == ",")
return tok->next();
else if (tok->link() && Token::Match(tok, "(|{|[|<"))
tok = tok->link();
else if (Token::Match(tok, ">|;"))
return nullptr;
}
return nullptr;
}
2013-07-31 10:30:20 +02:00
const Token * Token::findClosingBracket() const
{
2018-06-16 23:03:15 +02:00
if (mStr != "<")
2018-01-01 12:22:04 +01:00
return nullptr;
const Token *closing = nullptr;
2013-07-31 10:30:20 +02:00
2018-01-01 12:22:04 +01:00
unsigned int depth = 0;
for (closing = this; closing != nullptr; closing = closing->next()) {
if (Token::Match(closing, "{|[|(")) {
closing = closing->link();
if (!closing)
return nullptr; // #6803
} else if (Token::Match(closing, "}|]|)|;"))
return nullptr;
else if (closing->str() == "<")
++depth;
else if (closing->str() == ">") {
if (--depth == 0)
return closing;
} else if (closing->str() == ">>") {
if (depth <= 2)
return closing;
depth -= 2;
}
}
2013-07-31 10:30:20 +02:00
return closing;
}
Token * Token::findClosingBracket()
{
// return value of const function
return const_cast<Token*>(const_cast<const Token*>(this)->findClosingBracket());
}
const Token * Token::findOpeningBracket() const
{
if (mStr != ">")
return nullptr;
const Token *opening = nullptr;
unsigned int depth = 0;
for (opening = this; opening != nullptr; opening = opening->previous()) {
if (Token::Match(opening, "}|]|)")) {
opening = opening->link();
if (!opening)
return nullptr;
} else if (Token::Match(opening, "{|{|(|;"))
return nullptr;
else if (opening->str() == ">")
++depth;
else if (opening->str() == "<") {
if (--depth == 0)
return opening;
}
}
return opening;
}
Token * Token::findOpeningBracket()
{
// return value of const function
return const_cast<Token*>(const_cast<const Token*>(this)->findOpeningBracket());
}
2008-12-18 22:28:57 +01:00
//---------------------------------------------------------------------------
const Token *Token::findsimplematch(const Token * const startTok, const char pattern[])
{
for (const Token* tok = startTok; tok; tok = tok->next()) {
if (Token::simpleMatch(tok, pattern))
return tok;
}
return nullptr;
}
const Token *Token::findsimplematch(const Token * const startTok, const char pattern[], const Token * const end)
{
for (const Token* tok = startTok; tok && tok != end; tok = tok->next()) {
if (Token::simpleMatch(tok, pattern))
return tok;
}
return nullptr;
}
const Token *Token::findmatch(const Token * const startTok, const char pattern[], const unsigned int varId)
{
for (const Token* tok = startTok; tok; tok = tok->next()) {
if (Token::Match(tok, pattern, varId))
return tok;
}
return nullptr;
}
const Token *Token::findmatch(const Token * const startTok, const char pattern[], const Token * const end, const unsigned int varId)
2010-07-26 16:46:37 +02:00
{
for (const Token* tok = startTok; tok && tok != end; tok = tok->next()) {
2010-07-26 16:46:37 +02:00
if (Token::Match(tok, pattern, varId))
return tok;
}
return nullptr;
2010-07-26 16:46:37 +02:00
}
void Token::insertToken(const std::string &tokenStr, const std::string &originalNameStr, bool prepend)
{
Token *newToken;
2018-06-16 23:03:15 +02:00
if (mStr.empty())
newToken = this;
else
newToken = new Token(mTokensFrontBack);
newToken->str(tokenStr);
if (!originalNameStr.empty())
newToken->originalName(originalNameStr);
if (newToken != this) {
2018-06-16 16:43:54 +02:00
newToken->mLineNumber = mLineNumber;
newToken->mFileIndex = mFileIndex;
newToken->mProgressValue = mProgressValue;
if (prepend) {
if (this->previous()) {
newToken->previous(this->previous());
newToken->previous()->next(newToken);
} else if (mTokensFrontBack) {
mTokensFrontBack->front = newToken;
}
this->previous(newToken);
newToken->next(this);
} else {
if (this->next()) {
newToken->next(this->next());
newToken->next()->previous(newToken);
} else if (mTokensFrontBack) {
mTokensFrontBack->back = newToken;
}
this->next(newToken);
newToken->previous(this);
}
}
2008-12-18 22:28:57 +01:00
}
void Token::eraseTokens(Token *begin, const Token *end)
2008-12-18 22:28:57 +01:00
{
if (!begin || begin == end)
2008-12-18 22:28:57 +01:00
return;
2011-10-13 20:53:06 +02:00
while (begin->next() && begin->next() != end) {
2008-12-18 22:28:57 +01:00
begin->deleteNext();
}
}
void Token::createMutualLinks(Token *begin, Token *end)
{
2014-02-15 08:05:54 +01:00
assert(begin != nullptr);
assert(end != nullptr);
assert(begin != end);
begin->link(end);
end->link(begin);
}
void Token::printOut(const char *title) const
2008-12-18 22:28:57 +01:00
{
if (title && title[0])
std::cout << "\n### " << title << " ###\n";
std::cout << stringifyList(true, true, true, true, true, nullptr, nullptr) << std::endl;
}
void Token::printOut(const char *title, const std::vector<std::string> &fileNames) const
{
if (title && title[0])
std::cout << "\n### " << title << " ###\n";
std::cout << stringifyList(true, true, true, true, true, &fileNames, nullptr) << std::endl;
2008-12-18 22:28:57 +01:00
}
void Token::stringify(std::ostream& os, bool varid, bool attributes, bool macro) const
{
if (attributes) {
if (isUnsigned())
os << "unsigned ";
else if (isSigned())
os << "signed ";
if (isComplex())
os << "_Complex ";
if (isLong()) {
2018-06-16 16:40:02 +02:00
if (mTokType == eString || mTokType == eChar)
os << "L";
else
os << "long ";
}
}
if (macro && isExpandedMacro())
os << "$";
2018-06-16 23:03:15 +02:00
if (isName() && mStr.find(' ') != std::string::npos) {
for (std::size_t i = 0U; i < mStr.size(); ++i) {
if (mStr[i] != ' ')
os << mStr[i];
}
2018-06-16 23:03:15 +02:00
} else if (mStr[0] != '\"' || mStr.find('\0') == std::string::npos)
os << mStr;
else {
2018-06-16 23:03:15 +02:00
for (std::size_t i = 0U; i < mStr.size(); ++i) {
if (mStr[i] == '\0')
os << "\\0";
else
2018-06-16 23:03:15 +02:00
os << mStr[i];
}
}
2018-06-16 16:38:50 +02:00
if (varid && mVarId != 0)
os << '@' << mVarId;
}
std::string Token::stringifyList(bool varid, bool attributes, bool linenumbers, bool linebreaks, bool files, const std::vector<std::string>* fileNames, const Token* end) const
{
if (this == end)
return "";
std::ostringstream ret;
2018-06-16 16:43:54 +02:00
unsigned int lineNumber = mLineNumber - (linenumbers ? 1U : 0U);
unsigned int fileInd = files ? ~0U : mFileIndex;
std::map<int, unsigned int> lineNumbers;
for (const Token *tok = this; tok != end; tok = tok->next()) {
bool fileChange = false;
2018-06-16 16:43:54 +02:00
if (tok->mFileIndex != fileInd) {
if (fileInd != ~0U) {
2018-06-16 16:43:54 +02:00
lineNumbers[fileInd] = tok->mFileIndex;
}
2018-06-16 16:43:54 +02:00
fileInd = tok->mFileIndex;
if (files) {
ret << "\n\n##file ";
2018-06-16 16:43:54 +02:00
if (fileNames && fileNames->size() > tok->mFileIndex)
ret << fileNames->at(tok->mFileIndex);
else
ret << fileInd;
2016-07-18 10:42:03 +02:00
ret << '\n';
}
2010-04-09 21:40:37 +02:00
lineNumber = lineNumbers[fileInd];
fileChange = true;
}
if (linebreaks && (lineNumber != tok->linenr() || fileChange)) {
2018-06-16 16:43:54 +02:00
if (lineNumber+4 < tok->linenr() && fileInd == tok->mFileIndex) {
ret << '\n' << lineNumber+1 << ":\n|\n";
ret << tok->linenr()-1 << ":\n";
ret << tok->linenr() << ": ";
2016-07-18 10:42:03 +02:00
} else if (this == tok && linenumbers) {
ret << tok->linenr() << ": ";
} else {
while (lineNumber < tok->linenr()) {
++lineNumber;
ret << '\n';
if (linenumbers) {
ret << lineNumber << ':';
if (lineNumber == tok->linenr())
ret << ' ';
}
}
}
2010-04-09 21:40:37 +02:00
lineNumber = tok->linenr();
}
tok->stringify(ret, varid, attributes, attributes); // print token
if (tok->next() != end && (!linebreaks || (tok->next()->linenr() <= tok->linenr() && tok->next()->fileIndex() == tok->fileIndex())))
ret << ' ';
}
2016-07-18 10:42:03 +02:00
if (linebreaks && (files || linenumbers))
ret << '\n';
return ret.str();
}
std::string Token::stringifyList(const Token* end, bool attributes) const
{
return stringifyList(false, attributes, false, false, false, nullptr, end);
}
std::string Token::stringifyList(bool varid) const
{
return stringifyList(varid, false, true, true, true, nullptr, nullptr);
}
void Token::astOperand1(Token *tok)
{
if (mAstOperand1)
mAstOperand1->mAstParent = nullptr;
// goto parent operator
if (tok) {
std::set<Token*> visitedParents;
while (tok->mAstParent) {
if (!visitedParents.insert(tok->mAstParent).second) // #6838/#6726/#8352 avoid hang on garbage code
throw InternalError(this, "Internal error. Token::astOperand1() cyclic dependency.");
tok = tok->mAstParent;
}
tok->mAstParent = this;
}
mAstOperand1 = tok;
}
void Token::astOperand2(Token *tok)
{
if (mAstOperand2)
mAstOperand2->mAstParent = nullptr;
// goto parent operator
if (tok) {
std::set<Token*> visitedParents;
while (tok->mAstParent) {
//std::cout << tok << " -> " << tok->mAstParent ;
if (!visitedParents.insert(tok->mAstParent).second) // #6838/#6726 avoid hang on garbage code
throw InternalError(this, "Internal error. Token::astOperand2() cyclic dependency.");
tok = tok->mAstParent;
}
tok->mAstParent = this;
}
mAstOperand2 = tok;
}
static const Token* goToLeftParenthesis(const Token* start, const Token* end)
{
// move start to lpar in such expression: '(*it).x'
int par = 0;
for (const Token *tok = start; tok && tok != end; tok = tok->next()) {
if (tok->str() == "(")
++par;
else if (tok->str() == ")") {
if (par == 0)
start = tok->link();
else
--par;
}
}
return start;
}
static const Token* goToRightParenthesis(const Token* start, const Token* end)
{
// move end to rpar in such expression: '2>(x+1)'
int par = 0;
for (const Token *tok = end; tok && tok != start; tok = tok->previous()) {
if (tok->str() == ")")
++par;
else if (tok->str() == "(") {
if (par == 0)
end = tok->link();
else
--par;
}
}
return end;
}
std::pair<const Token *, const Token *> Token::findExpressionStartEndTokens() const
{
const Token * const top = this;
const Token *start = top;
while (start->astOperand1() &&
(start->astOperand2() || !start->isUnaryPreOp() || Token::simpleMatch(start, "( )") || start->str() == "{"))
start = start->astOperand1();
const Token *end = top;
while (end->astOperand1() && (end->astOperand2() || end->isUnaryPreOp())) {
if (Token::Match(end,"(|[") &&
!(Token::Match(end, "( %type%") && !end->astOperand2())) {
end = end->link();
break;
}
end = end->astOperand2() ? end->astOperand2() : end->astOperand1();
}
start = goToLeftParenthesis(start, end);
end = goToRightParenthesis(start, end);
return std::pair<const Token *, const Token *>(start,end);
}
bool Token::isCalculation() const
{
if (!Token::Match(this, "%cop%|++|--"))
return false;
if (Token::Match(this, "*|&")) {
// dereference or address-of?
if (!this->astOperand2())
return false;
if (this->astOperand2()->str() == "[")
return false;
// type specification?
std::stack<const Token *> operands;
operands.push(this);
while (!operands.empty()) {
const Token *op = operands.top();
operands.pop();
if (op->isNumber() || op->varId() > 0)
return true;
if (op->astOperand1())
operands.push(op->astOperand1());
if (op->astOperand2())
operands.push(op->astOperand2());
else if (Token::Match(op, "*|&"))
return false;
}
// type specification => return false
return false;
}
return true;
}
bool Token::isUnaryPreOp() const
{
if (!astOperand1() || astOperand2())
return false;
if (!Token::Match(this, "++|--"))
return true;
2018-06-16 16:16:55 +02:00
const Token *tokbefore = mPrevious;
const Token *tokafter = mNext;
2015-10-26 13:29:47 +01:00
for (int distance = 1; distance < 10 && tokbefore; distance++) {
if (tokbefore == mAstOperand1)
return false;
if (tokafter == mAstOperand1)
return true;
2018-06-16 16:16:55 +02:00
tokbefore = tokbefore->mPrevious;
tokafter = tokafter->mPrevious;
}
return false; // <- guess
}
static std::string stringFromTokenRange(const Token* start, const Token* end)
{
std::ostringstream ret;
if (end)
2017-07-21 09:17:25 +02:00
end = end->next();
for (const Token *tok = start; tok && tok != end; tok = tok->next()) {
2017-07-21 09:17:25 +02:00
if (tok->isUnsigned())
ret << "unsigned ";
if (tok->isLong())
ret << (tok->isLiteral() ? "L" : "long ");
if (tok->originalName().empty() || tok->isUnsigned() || tok->isLong()) {
ret << tok->str();
} else
ret << tok->originalName();
if (Token::Match(tok, "%name%|%num% %name%|%num%"))
ret << ' ';
}
return ret.str();
}
std::string Token::expressionString() const
{
const auto tokens = findExpressionStartEndTokens();
return stringFromTokenRange(tokens.first, tokens.second);
}
2014-07-14 15:51:45 +02:00
static void astStringXml(const Token *tok, std::size_t indent, std::ostream &out)
{
const std::string strindent(indent, ' ');
2014-07-14 15:51:45 +02:00
out << strindent << "<token str=\"" << tok->str() << '\"';
if (tok->varId() > 0U)
out << " varId=\"" << MathLib::toString(tok->varId()) << '\"';
if (tok->variable())
out << " variable=\"" << tok->variable() << '\"';
if (tok->function())
out << " function=\"" << tok->function() << '\"';
if (!tok->values().empty())
out << " values=\"" << &tok->values() << '\"';
2014-07-14 15:51:45 +02:00
if (!tok->astOperand1() && !tok->astOperand2()) {
2014-07-14 15:51:45 +02:00
out << "/>" << std::endl;
}
2014-07-14 15:51:45 +02:00
else {
out << '>' << std::endl;
if (tok->astOperand1())
astStringXml(tok->astOperand1(), indent+2U, out);
if (tok->astOperand2())
astStringXml(tok->astOperand2(), indent+2U, out);
out << strindent << "</token>" << std::endl;
}
}
2014-07-14 15:51:45 +02:00
void Token::printAst(bool verbose, bool xml, std::ostream &out) const
{
2015-07-21 11:54:11 +02:00
std::set<const Token *> printed;
for (const Token *tok = this; tok; tok = tok->next()) {
if (!tok->mAstParent && tok->mAstOperand1) {
2015-07-21 11:54:11 +02:00
if (printed.empty() && !xml)
2014-07-14 15:51:45 +02:00
out << "\n\n##AST" << std::endl;
2015-07-21 11:54:11 +02:00
else if (printed.find(tok) != printed.end())
continue;
printed.insert(tok);
if (xml) {
2014-07-14 15:51:45 +02:00
out << "<ast scope=\"" << tok->scope() << "\" fileIndex=\"" << tok->fileIndex() << "\" linenr=\"" << tok->linenr() << "\">" << std::endl;
2015-07-21 11:54:11 +02:00
astStringXml(tok, 2U, out);
2014-07-14 15:51:45 +02:00
out << "</ast>" << std::endl;
} else if (verbose)
2015-07-21 11:54:11 +02:00
out << tok->astStringVerbose(0,0) << std::endl;
else
2015-07-21 11:54:11 +02:00
out << tok->astString(" ") << std::endl;
2014-01-18 09:58:32 +01:00
if (tok->str() == "(")
tok = tok->link();
}
}
}
2014-01-18 09:58:32 +01:00
static std::string indent(const unsigned int indent1, const unsigned int indent2)
{
std::string ret(indent1,' ');
for (unsigned int i = indent1; i < indent2; i += 2)
ret += "| ";
return ret;
}
std::string Token::astStringVerbose(const unsigned int indent1, const unsigned int indent2) const
{
std::string ret;
if (isExpandedMacro())
2016-01-01 13:54:07 +01:00
ret += '$';
2018-06-16 23:03:15 +02:00
ret += mStr;
2018-06-16 21:42:40 +02:00
if (mValueType)
ret += " \'" + mValueType->str() + '\'';
2016-01-01 13:54:07 +01:00
ret += '\n';
if (mAstOperand1) {
unsigned int i1 = indent1, i2 = indent2 + 2;
if (indent1==indent2 && !mAstOperand2)
i1 += 2;
ret += indent(indent1,indent2) + (mAstOperand2 ? "|-" : "`-") + mAstOperand1->astStringVerbose(i1,i2);
}
if (mAstOperand2) {
unsigned int i1 = indent1, i2 = indent2 + 2;
if (indent1==indent2)
i1 += 2;
ret += indent(indent1,indent2) + "`-" + mAstOperand2->astStringVerbose(i1,i2);
}
return ret;
}
2014-07-14 15:51:45 +02:00
void Token::printValueFlow(bool xml, std::ostream &out) const
2014-01-18 09:58:32 +01:00
{
2014-03-24 18:14:23 +01:00
unsigned int line = 0;
2014-07-14 15:51:45 +02:00
if (xml)
out << " <valueflow>" << std::endl;
else
out << "\n\n##Value flow" << std::endl;
2014-01-18 09:58:32 +01:00
for (const Token *tok = this; tok; tok = tok->next()) {
2018-06-16 21:45:53 +02:00
if (!tok->mValues)
2014-01-18 09:58:32 +01:00
continue;
2014-07-14 15:51:45 +02:00
if (xml)
2018-06-16 21:45:53 +02:00
out << " <values id=\"" << tok->mValues << "\">" << std::endl;
2014-07-14 15:51:45 +02:00
else if (line != tok->linenr())
out << "Line " << tok->linenr() << std::endl;
2014-01-18 09:58:32 +01:00
line = tok->linenr();
if (!xml) {
2018-06-16 21:45:53 +02:00
out << " " << tok->str() << (tok->mValues->front().isKnown() ? " always " : " possible ");
if (tok->mValues->size() > 1U)
out << '{';
}
for (const ValueFlow::Value &value : *tok->mValues) {
2014-07-14 15:51:45 +02:00
if (xml) {
out << " <value ";
switch (value.valueType) {
2016-11-13 22:59:56 +01:00
case ValueFlow::Value::INT:
if (tok->valueType() && tok->valueType()->sign == ValueType::UNSIGNED)
out << "intvalue=\"" << (MathLib::biguint)value.intvalue << '\"';
else
out << "intvalue=\"" << value.intvalue << '\"';
2016-11-13 22:59:56 +01:00
break;
case ValueFlow::Value::TOK:
out << "tokvalue=\"" << value.tokvalue << '\"';
2016-11-13 22:59:56 +01:00
break;
case ValueFlow::Value::FLOAT:
out << "floatvalue=\"" << value.floatValue << '\"';
2016-11-13 22:59:56 +01:00
break;
case ValueFlow::Value::MOVED:
out << "movedvalue=\"" << ValueFlow::Value::toString(value.moveKind) << '\"';
break;
case ValueFlow::Value::UNINIT:
out << "uninit=\"1\"";
break;
case ValueFlow::Value::CONTAINER_SIZE:
out << "container-size=\"" << value.intvalue << '\"';
break;
2018-11-14 06:14:04 +01:00
case ValueFlow::Value::LIFETIME:
out << "lifetime=\"" << value.tokvalue << '\"';
break;
2016-11-13 22:59:56 +01:00
}
if (value.condition)
out << " condition-line=\"" << value.condition->linenr() << '\"';
if (value.isKnown())
out << " known=\"true\"";
else if (value.isPossible())
out << " possible=\"true\"";
else if (value.isInconclusive())
out << " inconclusive=\"true\"";
2014-07-14 15:51:45 +02:00
out << "/>" << std::endl;
}
else {
if (&value != &tok->mValues->front())
out << ",";
switch (value.valueType) {
2016-11-13 22:59:56 +01:00
case ValueFlow::Value::INT:
if (tok->valueType() && tok->valueType()->sign == ValueType::UNSIGNED)
out << (MathLib::biguint)value.intvalue;
else
out << value.intvalue;
2016-11-13 22:59:56 +01:00
break;
case ValueFlow::Value::TOK:
out << value.tokvalue->str();
2016-11-13 22:59:56 +01:00
break;
case ValueFlow::Value::FLOAT:
out << value.floatValue;
2016-11-13 22:59:56 +01:00
break;
case ValueFlow::Value::MOVED:
out << ValueFlow::Value::toString(value.moveKind);
break;
case ValueFlow::Value::UNINIT:
out << "Uninit";
break;
case ValueFlow::Value::CONTAINER_SIZE:
out << "size=" << value.intvalue;
break;
2018-11-14 06:14:04 +01:00
case ValueFlow::Value::LIFETIME:
out << "lifetime=" << value.tokvalue->str();
break;
2016-11-13 22:59:56 +01:00
}
2014-07-14 15:51:45 +02:00
}
2014-01-18 09:58:32 +01:00
}
2014-07-14 15:51:45 +02:00
if (xml)
out << " </values>" << std::endl;
2018-06-16 21:45:53 +02:00
else if (tok->mValues->size() > 1U)
out << '}' << std::endl;
2014-07-14 15:51:45 +02:00
else
out << std::endl;
2014-01-18 09:58:32 +01:00
}
2014-07-14 15:51:45 +02:00
if (xml)
out << " </valueflow>" << std::endl;
2014-01-18 09:58:32 +01:00
}
const ValueFlow::Value * Token::getValueLE(const MathLib::bigint val, const Settings *settings) const
{
2018-06-16 21:45:53 +02:00
if (!mValues)
return nullptr;
const ValueFlow::Value *ret = nullptr;
std::list<ValueFlow::Value>::const_iterator it;
2018-06-16 21:45:53 +02:00
for (it = mValues->begin(); it != mValues->end(); ++it) {
2016-11-13 22:33:39 +01:00
if (it->isIntValue() && it->intvalue <= val) {
if (!ret || ret->isInconclusive() || (ret->condition && !it->isInconclusive()))
ret = &(*it);
if (!ret->isInconclusive() && !ret->condition)
break;
}
}
if (settings && ret) {
if (ret->isInconclusive() && !settings->inconclusive)
return nullptr;
if (ret->condition && !settings->isEnabled(Settings::WARNING))
return nullptr;
}
return ret;
}
const ValueFlow::Value * Token::getValueGE(const MathLib::bigint val, const Settings *settings) const
{
2018-06-16 21:45:53 +02:00
if (!mValues)
return nullptr;
const ValueFlow::Value *ret = nullptr;
std::list<ValueFlow::Value>::const_iterator it;
2018-06-16 21:45:53 +02:00
for (it = mValues->begin(); it != mValues->end(); ++it) {
2016-11-13 22:33:39 +01:00
if (it->isIntValue() && it->intvalue >= val) {
if (!ret || ret->isInconclusive() || (ret->condition && !it->isInconclusive()))
ret = &(*it);
if (!ret->isInconclusive() && !ret->condition)
break;
}
}
if (settings && ret) {
if (ret->isInconclusive() && !settings->inconclusive)
return nullptr;
if (ret->condition && !settings->isEnabled(Settings::WARNING))
return nullptr;
}
return ret;
}
const ValueFlow::Value * Token::getInvalidValue(const Token *ftok, unsigned int argnr, const Settings *settings) const
{
2018-06-16 21:45:53 +02:00
if (!mValues || !settings)
return nullptr;
const ValueFlow::Value *ret = nullptr;
std::list<ValueFlow::Value>::const_iterator it;
2018-06-16 21:45:53 +02:00
for (it = mValues->begin(); it != mValues->end(); ++it) {
2018-07-15 23:05:48 +02:00
if ((it->isIntValue() && !settings->library.isIntArgValid(ftok, argnr, it->intvalue)) ||
(it->isFloatValue() && !settings->library.isFloatArgValid(ftok, argnr, it->floatValue))) {
if (!ret || ret->isInconclusive() || (ret->condition && !it->isInconclusive()))
ret = &(*it);
if (!ret->isInconclusive() && !ret->condition)
break;
}
}
if (ret) {
if (ret->isInconclusive() && !settings->inconclusive)
return nullptr;
if (ret->condition && !settings->isEnabled(Settings::WARNING))
return nullptr;
}
return ret;
}
const Token *Token::getValueTokenMinStrSize() const
{
2018-06-16 21:45:53 +02:00
if (!mValues)
return nullptr;
const Token *ret = nullptr;
std::size_t minsize = ~0U;
std::list<ValueFlow::Value>::const_iterator it;
2018-06-16 21:45:53 +02:00
for (it = mValues->begin(); it != mValues->end(); ++it) {
2016-11-13 22:33:39 +01:00
if (it->isTokValue() && it->tokvalue && it->tokvalue->tokType() == Token::eString) {
const std::size_t size = getStrSize(it->tokvalue);
if (!ret || size < minsize) {
minsize = size;
ret = it->tokvalue;
}
}
}
return ret;
}
const Token *Token::getValueTokenMaxStrLength() const
{
2018-06-16 21:45:53 +02:00
if (!mValues)
return nullptr;
const Token *ret = nullptr;
std::size_t maxlength = 0U;
std::list<ValueFlow::Value>::const_iterator it;
2018-06-16 21:45:53 +02:00
for (it = mValues->begin(); it != mValues->end(); ++it) {
2016-11-13 22:33:39 +01:00
if (it->isTokValue() && it->tokvalue && it->tokvalue->tokType() == Token::eString) {
const std::size_t length = getStrLength(it->tokvalue);
if (!ret || length > maxlength) {
maxlength = length;
ret = it->tokvalue;
}
}
}
return ret;
}
static const Scope *getfunctionscope(const Scope *s)
{
while (s && s->type != Scope::eFunction)
s = s->nestedIn;
return s;
}
const Token *Token::getValueTokenDeadPointer() const
{
const Scope * const functionscope = getfunctionscope(this->scope());
std::list<ValueFlow::Value>::const_iterator it;
for (it = values().begin(); it != values().end(); ++it) {
// Is this a pointer alias?
2016-11-13 22:33:39 +01:00
if (!it->isTokValue() || (it->tokvalue && it->tokvalue->str() != "&"))
continue;
// Get variable
const Token *vartok = it->tokvalue->astOperand1();
if (!vartok || !vartok->isName() || !vartok->variable())
continue;
const Variable * const var = vartok->variable();
if (var->isStatic() || var->isReference())
continue;
if (!var->scope())
return nullptr; // #6804
2015-03-11 20:25:27 +01:00
if (var->scope()->type == Scope::eUnion && var->scope()->nestedIn == this->scope())
continue;
// variable must be in same function (not in subfunction)
if (functionscope != getfunctionscope(var->scope()))
continue;
// Is variable defined in this scope or upper scope?
const Scope *s = this->scope();
while ((s != nullptr) && (s != var->scope()))
s = s->nestedIn;
if (!s)
return it->tokvalue;
}
return nullptr;
}
bool Token::addValue(const ValueFlow::Value &value)
{
2018-06-16 21:45:53 +02:00
if (value.isKnown() && mValues) {
// Clear all other values of the same type since value is known
mValues->remove_if([&](const ValueFlow::Value & x) {
return x.valueType == value.valueType;
});
}
2018-06-16 21:45:53 +02:00
if (mValues) {
// Don't handle more than 10 values for performance reasons
// TODO: add setting?
2018-06-16 21:45:53 +02:00
if (mValues->size() >= 10U)
return false;
// if value already exists, don't add it again
std::list<ValueFlow::Value>::iterator it;
2018-06-16 21:45:53 +02:00
for (it = mValues->begin(); it != mValues->end(); ++it) {
// different intvalue => continue
if (it->intvalue != value.intvalue)
continue;
// different types => continue
if (it->valueType != value.valueType)
continue;
if ((value.isTokValue() || value.isLifetimeValue()) && (it->tokvalue != value.tokvalue) && (it->tokvalue->str() != value.tokvalue->str()))
continue;
// same value, but old value is inconclusive so replace it
if (it->isInconclusive() && !value.isInconclusive()) {
*it = value;
if (it->varId == 0)
2018-06-16 16:38:50 +02:00
it->varId = mVarId;
break;
}
// Same value already exists, don't add new value
return false;
}
// Add value
2018-06-16 21:45:53 +02:00
if (it == mValues->end()) {
ValueFlow::Value v(value);
if (v.varId == 0)
2018-06-16 16:38:50 +02:00
v.varId = mVarId;
if(v.isKnown() && v.isIntValue())
mValues->push_front(v);
else
mValues->push_back(v);
}
} else {
ValueFlow::Value v(value);
if (v.varId == 0)
2018-06-16 16:38:50 +02:00
v.varId = mVarId;
2018-06-16 21:45:53 +02:00
mValues = new std::list<ValueFlow::Value>(1, v);
}
return true;
}
void Token::assignProgressValues(Token *tok)
{
unsigned int total_count = 0;
for (Token *tok2 = tok; tok2; tok2 = tok2->next())
++total_count;
unsigned int count = 0;
for (Token *tok2 = tok; tok2; tok2 = tok2->next())
tok2->mProgressValue = count++ * 100 / total_count;
}
void Token::setValueType(ValueType *vt)
{
2018-06-16 21:42:40 +02:00
if (vt != mValueType) {
delete mValueType;
mValueType = vt;
}
}
void Token::type(const ::Type *t)
{
2018-06-16 20:25:54 +02:00
mType = t;
if (t) {
2017-10-15 01:27:47 +02:00
tokType(eType);
2018-06-16 20:25:54 +02:00
isEnumType(mType->isEnumType());
2018-06-16 16:40:02 +02:00
} else if (mTokType == eType)
2017-10-15 01:27:47 +02:00
tokType(eName);
}