Skip to content

Commit

Permalink
fixed #6316 (Use std::to_string() in place of MathLib::toString() ...…
Browse files Browse the repository at this point in the history
…) - deleted default implementation of `Mathlib::toString()` (#5341)

It was also used inconsistently and seemed to imply there is some
special handling which wasn't the case. It was just an alias for
`std::to_string()` for non-`double` types. So there was no need for it.

---------

Co-authored-by: Robert Reif <[email protected]>
  • Loading branch information
firewave and IOBYTE committed Aug 17, 2023
1 parent d8b44df commit 3cf9100
Show file tree
Hide file tree
Showing 22 changed files with 81 additions and 94 deletions.
2 changes: 1 addition & 1 deletion lib/astutils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -341,7 +341,7 @@ static bool match(const Token *tok, const std::string &rhs)
{
if (tok->str() == rhs)
return true;
if (!tok->varId() && tok->hasKnownIntValue() && MathLib::toString(tok->values().front().intvalue) == rhs)
if (!tok->varId() && tok->hasKnownIntValue() && std::to_string(tok->values().front().intvalue) == rhs)
return true;
return false;
}
Expand Down
14 changes: 7 additions & 7 deletions lib/checkbufferoverrun.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ static int getMinFormatStringOutputLength(const std::vector<const Token*> &param
i_d_x_f_found = true;
parameterLength = 1;
if (inputArgNr < parameters.size() && parameters[inputArgNr]->hasKnownIntValue())
parameterLength = MathLib::toString(parameters[inputArgNr]->getKnownIntValue()).length();
parameterLength = std::to_string(parameters[inputArgNr]->getKnownIntValue()).length();

handleNextParameter = true;
break;
Expand Down Expand Up @@ -362,7 +362,7 @@ void CheckBufferOverrun::arrayIndex()
static std::string stringifyIndexes(const std::string& array, const std::vector<ValueFlow::Value>& indexValues)
{
if (indexValues.size() == 1)
return MathLib::toString(indexValues[0].intvalue);
return std::to_string(indexValues[0].intvalue);

std::ostringstream ret;
ret << array;
Expand All @@ -383,7 +383,7 @@ static std::string arrayIndexMessage(const Token* tok,
const Token* condition)
{
auto add_dim = [](const std::string &s, const Dimension &dim) {
return s + "[" + MathLib::toString(dim.num) + "]";
return s + "[" + std::to_string(dim.num) + "]";
};
const std::string array = std::accumulate(dimensions.cbegin(), dimensions.cend(), tok->astOperand1()->expressionString(), add_dim);

Expand Down Expand Up @@ -528,7 +528,7 @@ void CheckBufferOverrun::pointerArithmeticError(const Token *tok, const Token *i

std::string errmsg;
if (indexValue->condition)
errmsg = "Undefined behaviour, when '" + indexToken->expressionString() + "' is " + MathLib::toString(indexValue->intvalue) + " the pointer arithmetic '" + tok->expressionString() + "' is out of bounds.";
errmsg = "Undefined behaviour, when '" + indexToken->expressionString() + "' is " + std::to_string(indexValue->intvalue) + " the pointer arithmetic '" + tok->expressionString() + "' is out of bounds.";
else
errmsg = "Undefined behaviour, pointer arithmetic '" + tok->expressionString() + "' is out of bounds.";

Expand Down Expand Up @@ -992,13 +992,13 @@ bool CheckBufferOverrun::analyseWholeProgram1(const std::map<std::string, std::l
if (type == 1) {
errorId = "ctuArrayIndex";
if (unsafeUsage.value > 0)
errmsg = "Array index out of bounds; '" + unsafeUsage.myArgumentName + "' buffer size is " + MathLib::toString(functionCall->callArgValue) + " and it is accessed at offset " + MathLib::toString(unsafeUsage.value) + ".";
errmsg = "Array index out of bounds; '" + unsafeUsage.myArgumentName + "' buffer size is " + std::to_string(functionCall->callArgValue) + " and it is accessed at offset " + std::to_string(unsafeUsage.value) + ".";
else
errmsg = "Array index out of bounds; buffer '" + unsafeUsage.myArgumentName + "' is accessed at offset " + MathLib::toString(unsafeUsage.value) + ".";
errmsg = "Array index out of bounds; buffer '" + unsafeUsage.myArgumentName + "' is accessed at offset " + std::to_string(unsafeUsage.value) + ".";
cwe = (unsafeUsage.value > 0) ? CWE_BUFFER_OVERRUN : CWE_BUFFER_UNDERRUN;
} else {
errorId = "ctuPointerArith";
errmsg = "Pointer arithmetic overflow; '" + unsafeUsage.myArgumentName + "' buffer size is " + MathLib::toString(functionCall->callArgValue);
errmsg = "Pointer arithmetic overflow; '" + unsafeUsage.myArgumentName + "' buffer size is " + std::to_string(functionCall->callArgValue);
cwe = CWE_POINTER_ARITHMETIC_OVERFLOW;
}

Expand Down
2 changes: 1 addition & 1 deletion lib/checkclass.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2845,7 +2845,7 @@ void CheckClass::virtualFunctionCallInConstructorError(
}

reportError(errorPath, Severity::style, "virtualCallInConstructor",
"Virtual function '" + funcname + "' is called from " + scopeFunctionTypeName + " '" + constructorName + "' at line " + MathLib::toString(lineNumber) + ". Dynamic binding is not used.", CWE(0U), Certainty::normal);
"Virtual function '" + funcname + "' is called from " + scopeFunctionTypeName + " '" + constructorName + "' at line " + std::to_string(lineNumber) + ". Dynamic binding is not used.", CWE(0U), Certainty::normal);
}

void CheckClass::pureVirtualFunctionCallInConstructorError(
Expand Down
4 changes: 2 additions & 2 deletions lib/checkcondition.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1039,7 +1039,7 @@ static bool parseComparison(const Token *comp, bool &not1, std::string &op, std:
return false;
op = invertOperatorForOperandSwap(comp->str());
if (op1->enumerator() && op1->enumerator()->value_known)
value = MathLib::toString(op1->enumerator()->value);
value = std::to_string(op1->enumerator()->value);
else
value = op1->str();
expr = op2;
Expand All @@ -1048,7 +1048,7 @@ static bool parseComparison(const Token *comp, bool &not1, std::string &op, std:
return false;
op = comp->str();
if (op2->enumerator() && op2->enumerator()->value_known)
value = MathLib::toString(op2->enumerator()->value);
value = std::to_string(op2->enumerator()->value);
else
value = op2->str();
expr = op1;
Expand Down
2 changes: 1 addition & 1 deletion lib/checkother.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3518,7 +3518,7 @@ void CheckOther::funcArgNamesDifferent(const std::string & functionName, nonneg
std::list<const Token *> tokens = { declaration,definition };
reportError(tokens, Severity::style, "funcArgNamesDifferent",
"$symbol:" + functionName + "\n"
"Function '$symbol' argument " + MathLib::toString(index + 1) + " names different: declaration '" +
"Function '$symbol' argument " + std::to_string(index + 1) + " names different: declaration '" +
(declaration ? declaration->str() : std::string("A")) + "' definition '" +
(definition ? definition->str() : std::string("B")) + "'.", CWE628, Certainty::inconclusive);
}
Expand Down
12 changes: 6 additions & 6 deletions lib/checkstl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -203,14 +203,14 @@ void CheckStl::outOfBounds()
static std::string indexValueString(const ValueFlow::Value& indexValue, const std::string& containerName = emptyString)
{
if (indexValue.isIteratorStartValue())
return "at position " + MathLib::toString(indexValue.intvalue) + " from the beginning";
return "at position " + std::to_string(indexValue.intvalue) + " from the beginning";
if (indexValue.isIteratorEndValue())
return "at position " + MathLib::toString(-indexValue.intvalue) + " from the end";
std::string indexString = MathLib::toString(indexValue.intvalue);
return "at position " + std::to_string(-indexValue.intvalue) + " from the end";
std::string indexString = std::to_string(indexValue.intvalue);
if (indexValue.isSymbolicValue()) {
indexString = containerName + ".size()";
if (indexValue.intvalue != 0)
indexString += "+" + MathLib::toString(indexValue.intvalue);
indexString += "+" + std::to_string(indexValue.intvalue);
}
if (indexValue.bound == ValueFlow::Value::Bound::Lower)
return "greater or equal to " + indexString;
Expand Down Expand Up @@ -242,11 +242,11 @@ void CheckStl::outOfBoundsError(const Token *tok, const std::string &containerNa
errmsg = "Out of bounds access in expression '" + expression + "' because '$symbol' is empty.";
} else if (indexValue) {
if (containerSize->condition)
errmsg = ValueFlow::eitherTheConditionIsRedundant(containerSize->condition) + " or $symbol size can be " + MathLib::toString(containerSize->intvalue) + ". Expression '" + expression + "' cause access out of bounds.";
errmsg = ValueFlow::eitherTheConditionIsRedundant(containerSize->condition) + " or $symbol size can be " + std::to_string(containerSize->intvalue) + ". Expression '" + expression + "' cause access out of bounds.";
else if (indexValue->condition)
errmsg = ValueFlow::eitherTheConditionIsRedundant(indexValue->condition) + " or '" + index + "' can have the value " + indexValueString(*indexValue) + ". Expression '" + expression + "' cause access out of bounds.";
else
errmsg = "Out of bounds access in '" + expression + "', if '$symbol' size is " + MathLib::toString(containerSize->intvalue) + " and '" + index + "' is " + indexValueString(*indexValue);
errmsg = "Out of bounds access in '" + expression + "', if '$symbol' size is " + std::to_string(containerSize->intvalue) + " and '" + index + "' is " + indexValueString(*indexValue);
} else {
// should not happen
return;
Expand Down
4 changes: 2 additions & 2 deletions lib/cppcheck.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -807,7 +807,7 @@ unsigned int CppCheck::checkFile(const std::string& filename, const std::string
const std::list<Directive> &directives = preprocessor.getDirectives();
for (const Directive &dir : directives) {
if (dir.str.compare(0,8,"#define ") == 0 || dir.str.compare(0,9,"#include ") == 0)
code += "#line " + MathLib::toString(dir.linenr) + " \"" + dir.file + "\"\n" + dir.str + '\n';
code += "#line " + std::to_string(dir.linenr) + " \"" + dir.file + "\"\n" + dir.str + '\n';
}
Tokenizer tokenizer2(&mSettings, this);
std::istringstream istr2(code);
Expand Down Expand Up @@ -945,7 +945,7 @@ unsigned int CppCheck::checkFile(const std::string& filename, const std::string

} catch (const simplecpp::Output &o) {
// #error etc during preprocessing
configurationError.push_back((mCurrentConfig.empty() ? "\'\'" : mCurrentConfig) + " : [" + o.location.file() + ':' + MathLib::toString(o.location.line) + "] " + o.msg);
configurationError.push_back((mCurrentConfig.empty() ? "\'\'" : mCurrentConfig) + " : [" + o.location.file() + ':' + std::to_string(o.location.line) + "] " + o.msg);
--checkCount; // don't count invalid configurations
continue;

Expand Down
4 changes: 2 additions & 2 deletions lib/ctu.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ int CTU::maxCtuDepth = 2;

std::string CTU::getFunctionId(const Tokenizer *tokenizer, const Function *function)
{
return tokenizer->list.file(function->tokenDef) + ':' + MathLib::toString(function->tokenDef->linenr()) + ':' + MathLib::toString(function->tokenDef->column());
return tokenizer->list.file(function->tokenDef) + ':' + std::to_string(function->tokenDef->linenr()) + ':' + std::to_string(function->tokenDef->column());
}

CTU::FileInfo::Location::Location(const Tokenizer *tokenizer, const Token *tok)
Expand Down Expand Up @@ -579,7 +579,7 @@ std::list<ErrorMessage::FileLocation> CTU::FileInfo::getErrorPath(InvalidValueTy
}

ErrorMessage::FileLocation fileLoc(path[index]->location.fileName, path[index]->location.lineNumber, path[index]->location.column);
fileLoc.setinfo("Calling function " + path[index]->callFunctionName + ", " + MathLib::toString(path[index]->callArgNr) + getOrdinalText(path[index]->callArgNr) + " argument is " + value1);
fileLoc.setinfo("Calling function " + path[index]->callFunctionName + ", " + std::to_string(path[index]->callArgNr) + getOrdinalText(path[index]->callArgNr) + " argument is " + value1);
locationList.push_back(std::move(fileLoc));
}

Expand Down
16 changes: 8 additions & 8 deletions lib/errorlogger.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -240,8 +240,8 @@ std::string ErrorMessage::serialize() const
std::string oss;
serializeString(oss, id);
serializeString(oss, Severity::toString(severity));
serializeString(oss, MathLib::toString(cwe.id));
serializeString(oss, MathLib::toString(hash));
serializeString(oss, std::to_string(cwe.id));
serializeString(oss, std::to_string(hash));
serializeString(oss, file0);
if (certainty == Certainty::inconclusive) {
const std::string text("inconclusive");
Expand Down Expand Up @@ -461,7 +461,7 @@ std::string ErrorMessage::toXML() const
if (cwe.id)
printer.PushAttribute("cwe", cwe.id);
if (hash)
printer.PushAttribute("hash", MathLib::toString(hash).c_str());
printer.PushAttribute("hash", std::to_string(hash).c_str());
if (certainty == Certainty::inconclusive)
printer.PushAttribute("inconclusive", "true");

Expand Down Expand Up @@ -624,14 +624,14 @@ std::string ErrorMessage::toString(bool verbose, const std::string &templateForm
pos1 = result.find("{inconclusive:", pos1);
}
findAndReplace(result, "{severity}", Severity::toString(severity));
findAndReplace(result, "{cwe}", MathLib::toString(cwe.id));
findAndReplace(result, "{cwe}", std::to_string(cwe.id));
findAndReplace(result, "{message}", verbose ? mVerboseMessage : mShortMessage);
if (!callStack.empty()) {
if (result.find("{callstack}") != std::string::npos)
findAndReplace(result, "{callstack}", ErrorLogger::callStackToString(callStack));
findAndReplace(result, "{file}", callStack.back().getfile());
findAndReplace(result, "{line}", MathLib::toString(callStack.back().line));
findAndReplace(result, "{column}", MathLib::toString(callStack.back().column));
findAndReplace(result, "{line}", std::to_string(callStack.back().line));
findAndReplace(result, "{column}", std::to_string(callStack.back().column));
if (result.find("{code}") != std::string::npos) {
const std::string::size_type pos = result.find('\r');
const char *endl;
Expand Down Expand Up @@ -660,8 +660,8 @@ std::string ErrorMessage::toString(bool verbose, const std::string &templateForm
std::string text = templateLocation;

findAndReplace(text, "{file}", fileLocation.getfile());
findAndReplace(text, "{line}", MathLib::toString(fileLocation.line));
findAndReplace(text, "{column}", MathLib::toString(fileLocation.column));
findAndReplace(text, "{line}", std::to_string(fileLocation.line));
findAndReplace(text, "{column}", std::to_string(fileLocation.column));
findAndReplace(text, "{info}", fileLocation.getinfo().empty() ? mShortMessage : fileLocation.getinfo());
if (text.find("{code}") != std::string::npos) {
const std::string::size_type pos = text.find('\r');
Expand Down
16 changes: 8 additions & 8 deletions lib/mathlib.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1059,7 +1059,7 @@ std::string MathLib::add(const std::string & first, const std::string & second)
return (value(first) + value(second)).str();
#else
if (MathLib::isInt(first) && MathLib::isInt(second)) {
return toString(toLongNumber(first) + toLongNumber(second)) + intsuffix(first, second);
return std::to_string(toLongNumber(first) + toLongNumber(second)) + intsuffix(first, second);
}

double d1 = toDoubleNumber(first);
Expand All @@ -1081,7 +1081,7 @@ std::string MathLib::subtract(const std::string &first, const std::string &secon
return (value(first) - value(second)).str();
#else
if (MathLib::isInt(first) && MathLib::isInt(second)) {
return toString(toLongNumber(first) - toLongNumber(second)) + intsuffix(first, second);
return std::to_string(toLongNumber(first) - toLongNumber(second)) + intsuffix(first, second);
}

if (first == second)
Expand Down Expand Up @@ -1112,7 +1112,7 @@ std::string MathLib::divide(const std::string &first, const std::string &second)
throw InternalError(nullptr, "Internal Error: Division by zero");
if (a == std::numeric_limits<bigint>::min() && std::abs(b)<=1)
throw InternalError(nullptr, "Internal Error: Division overflow");
return toString(toLongNumber(first) / b) + intsuffix(first, second);
return std::to_string(toLongNumber(first) / b) + intsuffix(first, second);
}
if (isNullValue(second)) {
if (isNullValue(first))
Expand All @@ -1129,7 +1129,7 @@ std::string MathLib::multiply(const std::string &first, const std::string &secon
return (value(first) * value(second)).str();
#else
if (MathLib::isInt(first) && MathLib::isInt(second)) {
return toString(toLongNumber(first) * toLongNumber(second)) + intsuffix(first, second);
return std::to_string(toLongNumber(first) * toLongNumber(second)) + intsuffix(first, second);
}
return toString(toDoubleNumber(first) * toDoubleNumber(second));
#endif
Expand All @@ -1144,7 +1144,7 @@ std::string MathLib::mod(const std::string &first, const std::string &second)
const bigint b = toLongNumber(second);
if (b == 0)
throw InternalError(nullptr, "Internal Error: Division by zero");
return toString(toLongNumber(first) % b) + intsuffix(first, second);
return std::to_string(toLongNumber(first) % b) + intsuffix(first, second);
}
return toString(std::fmod(toDoubleNumber(first),toDoubleNumber(second)));
#endif
Expand All @@ -1169,13 +1169,13 @@ std::string MathLib::calculate(const std::string &first, const std::string &seco
return MathLib::mod(first, second);

case '&':
return MathLib::toString(MathLib::toLongNumber(first) & MathLib::toLongNumber(second)) + intsuffix(first,second);
return std::to_string(MathLib::toLongNumber(first) & MathLib::toLongNumber(second)) + intsuffix(first,second);

case '|':
return MathLib::toString(MathLib::toLongNumber(first) | MathLib::toLongNumber(second)) + intsuffix(first,second);
return std::to_string(MathLib::toLongNumber(first) | MathLib::toLongNumber(second)) + intsuffix(first,second);

case '^':
return MathLib::toString(MathLib::toLongNumber(first) ^ MathLib::toLongNumber(second)) + intsuffix(first,second);
return std::to_string(MathLib::toLongNumber(first) ^ MathLib::toLongNumber(second)) + intsuffix(first,second);

default:
throw InternalError(nullptr, std::string("Unexpected action '") + action + "' in MathLib::calculate(). Please report this to Cppcheck developers.");
Expand Down
6 changes: 2 additions & 4 deletions lib/mathlib.h
Original file line number Diff line number Diff line change
Expand Up @@ -74,9 +74,7 @@ class CPPCHECKLIB MathLib {
/** @brief for conversion of numeric literals - for atoi-like conversions please use strToInt() */
static biguint toULongNumber(const std::string & str);

template<class T> static std::string toString(T value) {
return std::to_string(value);
}
template<class T> static std::string toString(T value) = delete;
/** @brief for conversion of numeric literals */
static double toDoubleNumber(const std::string & str);

Expand Down Expand Up @@ -147,7 +145,7 @@ MathLib::value operator^(const MathLib::value &v1, const MathLib::value &v2);
MathLib::value operator<<(const MathLib::value &v1, const MathLib::value &v2);
MathLib::value operator>>(const MathLib::value &v1, const MathLib::value &v2);

template<> CPPCHECKLIB std::string MathLib::toString<double>(double value); // Declare specialization to avoid linker problems
template<> CPPCHECKLIB std::string MathLib::toString<double>(double value);

/// @}
//---------------------------------------------------------------------------
Expand Down
4 changes: 2 additions & 2 deletions lib/suppressions.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -356,11 +356,11 @@ std::string Suppressions::Suppression::getText() const
if (!fileName.empty())
ret += " fileName=" + fileName;
if (lineNumber != NO_LINE)
ret += " lineNumber=" + MathLib::toString(lineNumber);
ret += " lineNumber=" + std::to_string(lineNumber);
if (!symbolName.empty())
ret += " symbolName=" + symbolName;
if (hash > 0)
ret += " hash=" + MathLib::toString(hash);
ret += " hash=" + std::to_string(hash);
if (ret.compare(0,1," ")==0)
return ret.substr(1);
return ret;
Expand Down
2 changes: 1 addition & 1 deletion lib/symboldatabase.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7637,7 +7637,7 @@ void ValueType::setDebugPath(const Token* tok, SourceLocation ctx, SourceLocatio
std::string file = ctx.file_name();
if (file.empty())
return;
std::string s = Path::stripDirectoryPart(file) + ":" + MathLib::toString(ctx.line()) + ": " + ctx.function_name() +
std::string s = Path::stripDirectoryPart(file) + ":" + std::to_string(ctx.line()) + ": " + ctx.function_name() +
" => " + local.function_name();
debugPath.emplace_back(tok, std::move(s));
}
Expand Down
Loading

0 comments on commit 3cf9100

Please sign in to comment.