diff --git a/libs/ui/tests/kis_simplemathparsertest.cpp b/libs/ui/tests/kis_simplemathparsertest.cpp index e23de32f80..9277f97971 100644 --- a/libs/ui/tests/kis_simplemathparsertest.cpp +++ b/libs/ui/tests/kis_simplemathparsertest.cpp @@ -1,132 +1,134 @@ #include "kis_simplemathparsertest.h" #include "kis_numparser.h" #include #include KisSimpleMathParserTest::KisSimpleMathParserTest() : QObject() { } void KisSimpleMathParserTest::testDoubleComputation() { QStringList exprs = {"1", "2 + 3.4", "2 + -3.4", "2 - -3.4", "5-2", "7 + 2 - 5", "4.6 * 2 + 13", "4.6 / 2 + 3*3", "4.6 / 0.0 + 3*3", "-4.6 / 0.0 + 3*3", "-4.6 / -0.0 + 3*3", "4.6 / -0.0 + 3*3", "0.0 / 0.0 + 3*3", "2^3 - 4 * 1.5", "2^3.0 - 4 * 1.5", "cos(1)*2", "-cos(1)*2", "cos(1)^3*2", "cos(1)^3.0*2", "cos(1)*2 + sin(3)/2", - "cos(acos(-1)+1*3^2.0)*2 + sin(3)/2"}; + "cos(acos(-1)+1*3^2.0)*2 + sin(3)/2", + "cos(acos(-1)+1*3^2.0)^2 + sin(3)/2"}; QVector expected = {1, 2 + 3.4, 2 + -3.4, 2 - -3.4, 5-2, 7 + 2 - 5, 4.6 * 2 + 13, 4.6 / 2 + 3*3, 4.6 / 0.0 + 3*3, -4.6 / 0.0 + 3*3, -4.6 / -0.0 + 3*3, 4.6 / -0.0 + 3*3, 0.0 / 0.0 + 3*3, qPow(2,3) - 4 * 1.5, qPow(2,3.0) - 4 * 1.5, qCos(1.0/180*qAcos(-1))*2, -qCos(1.0/180*qAcos(-1))*2, qPow(qCos(1.0/180*qAcos(-1)),3)*2, qPow(qCos(1.0/180*qAcos(-1)),3.0)*2, qCos(1.0/180*qAcos(-1))*2 + qSin(3.0/180*qAcos(-1))/2, - qCos((qAcos(-1.0)*180/qAcos(-1)+1*qPow(3,2.0))/180*qAcos(-1))*2 + qSin(3.0/180*qAcos(-1))/2}; + qCos((qAcos(-1.0)*180/qAcos(-1)+1*qPow(3,2.0))/180*qAcos(-1))*2 + qSin(3.0/180*qAcos(-1))/2, + qPow(qCos((qAcos(-1.0)*180/qAcos(-1)+1*qPow(3,2.0))/180*qAcos(-1)),2) + qSin(3.0/180*qAcos(-1))/2}; for (int i = 0; i < expected.size(); i++) { double result = KisNumericParser::parseSimpleMathExpr(exprs[i]); bool test = result == expected[i] || qAbs(result - expected[i]) < 1e-12 || (isnan(result) && isnan(expected[i])); QVERIFY2(test, QString("Failed when %1 should equal %2 but evaluated to %3.").arg(exprs[i]).arg(expected[i]).arg(result).toStdString().c_str()); } } void KisSimpleMathParserTest::testIntComputation() { QStringList exprs = {"1", "2 + 3", "2 + -3", "2 - -3", "5-2", "7 + 2 - 5", "4/3", "12/3", "4*3"}; QVector expected = {1, 2 + 3, 2 + -3, 2 - -3, 5-2, 7 + 2 - 5, qRound(4.0/3.0), qRound(12.0/3.0), 4*3}; for (int i = 0; i < expected.size(); i++) { int result = KisNumericParser::parseIntegerMathExpr(exprs[i]); QCOMPARE(result, expected[i]); } } void KisSimpleMathParserTest::testIntFlooring() { QStringList exprs = {"4.5", "-4.5", "3.5 + 4.5", "2.8 - -3.5", "4.5/2.9", "7.6*3.2", "7.6*3.2 + 4.5" }; QVector expected = {qRound(4.5), qRound(-4.5), qRound(3.5 + 4.5), qRound(2.8 - -3.5), qRound(4.5/2.9), qRound(7.6*3.2), qRound(7.6*3.2 + 4.5) }; for (int i = 0; i < expected.size(); i++) { int result = KisNumericParser::parseIntegerMathExpr(exprs[i]); QCOMPARE(result, expected[i]); } } QTEST_APPLESS_MAIN(KisSimpleMathParserTest) diff --git a/libs/ui/utils/kis_numparser.cpp b/libs/ui/utils/kis_numparser.cpp index 8542761a30..2935bc571a 100644 --- a/libs/ui/utils/kis_numparser.cpp +++ b/libs/ui/utils/kis_numparser.cpp @@ -1,598 +1,565 @@ /* * Copyright (c) 2016 Laurent Valentin Jospin * * 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 2 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "kis_numparser.h" //#include #include #include #include #include #include +#include + using namespace std; const QVector opLevel1 = {'+', '-'}; const QVector opLevel2 = {'*', '/'}; const QStringList supportedFuncs = {"", "cos", "sin", "tan", "acos", "asin", "atan", "exp", "ln", "log10", "abs"}; const QRegExp funcExpr("(-)?([a-zA-Z]*)?\\((.+)\\)"); const QRegExp numberExpr("(-)?([0-9]+\\.?[0-9]*(e[0-9]*)?)"); const QRegExp funcExprInteger("(-)?\\((.+)\\)"); const QRegExp integerExpr("(-)?([0-9]+)"); //double functions double treatFuncs(QString const& expr, bool & noProblem); double treatLevel1(QString const& expr, bool & noProblem); double treatLevel2(QString const& expr, bool & noProblem); double treatLevel3(QString const& expr, bool & noProblem); //int functions double treatLevel1Int(QString const& expr, bool & noProblem); double treatLevel2Int(QString const& expr, bool & noProblem); double treatFuncsInt(QString const& expr, bool & noProblem); namespace KisNumericParser { /*! * \param expr the expression to parse * \param noProblem if provided, the value pointed to will be se to true is no problem appeared, false otherwise. * \return the numerical value the expression eval to (or 0 in case of error). */ double parseSimpleMathExpr(const QString &expr, bool *noProblem) { bool ok = true; //intermediate variable to pass by reference to the sublevel parser (if no pointer is provided). //then go down each 3 levels of operation priority. if (noProblem != nullptr) { return treatLevel1(expr, *noProblem); } return treatLevel1(expr, ok); } /*! * \param expr the expression to parse * \param noProblem if provided, the value pointed to will be se to true is no problem appeared, false otherwise. * \return the numerical value the expression eval to (or 0 in case of error). */ int parseIntegerMathExpr(QString const& expr, bool* noProblem) { bool ok = true; //intermediate variable to pass by reference to the sublevel parser (if no pointer is provided). if (noProblem != nullptr) { return qRound(treatLevel1Int(expr, *noProblem)); } return qRound(treatLevel1Int(expr, ok)); } } //namespace KisNumericParser. //intermediate functions /*! - * \brief cutLevel1 cut an expression into many subparts using the level1 operations (+-) outside of parenthesis as separator. Return some results by reference. - * \param expr The expression to cut. - * \param readyToTreat A reference to a string list to hold the subparts. - * \param op A list of operations stored as char ('+' and '-') and returned by reference. + * \brief extractSubExprLevel1 extract from an expression the part of an expression that need to be treated recursivly before computing level 1 operations (+, -). + * \param expr The expression to treat, the part returned will be removed. + * \param nextOp This reference, in case of sucess, will hold the first level operation identified as separator ('+' or '-') * \param noProblem A reference to a bool, set to true if there was no problem, false otherwise. - * - * The function won't cut the expression if the + or - operation is nested within parenthesis. The subexpression in the parenthesis will be treated recursivly later on. + * \return The first part of the expression that doesn't contain first level operations not nested within parenthesis. */ -inline void cutLevel1(QString const& expr, QStringList & readyToTreat, QVector & op, bool & noProblem) -{ +inline QString extractSubExprLevel1(QString & expr, char & nextOp, bool & noProblem){ - readyToTreat.clear(); - op.clear(); + QString ret; - int subCount = 0; - int lastPos = 0; + int subCount = 0; - bool lastMetIsNumber = false; + bool lastMetIsNumber = false; - for(int i = 0; i < expr.size(); i++){ + for(int i = 0; i < expr.size(); i++){ - if (expr.at(i) == '(') { - subCount++; - } + if (expr.at(i) == '(') { + subCount++; + } - if (expr.at(i) == ')') { - subCount--; - } + if (expr.at(i) == ')') { + subCount--; + } - if (subCount < 0) { - noProblem = false; - return; - } + if (subCount < 0) { + noProblem = false; + return ret; + } - if( (expr.at(i) == '+' || expr.at(i) == '-') && - subCount == 0) { + if(i == expr.size()-1 && subCount == 0){ + ret = expr; + expr.clear(); + break; + } - if (expr.at(i) == '-' && - i < expr.size()-1) { + if( (expr.at(i) == '+' || expr.at(i) == '-') && + subCount == 0) { - bool cond = !expr.at(i+1).isSpace(); + if (expr.at(i) == '-' && + i < expr.size()-1) { - if (cond && !lastMetIsNumber) { - continue; - } + bool cond = !expr.at(i+1).isSpace(); - } + if (cond && !lastMetIsNumber) { + continue; + } - readyToTreat.push_back(expr.mid(lastPos, i-lastPos).trimmed()); - lastPos = i+1; - op.push_back(expr.at(i).toLatin1()); + } - } + ret = expr.mid(0, i).trimmed(); + nextOp = expr.at(i).toLatin1(); + expr = expr.mid(i+1); + break; - if (expr.at(i).isDigit()) { - lastMetIsNumber = true; - } else if (expr.at(i) != '.' && - !expr.at(i).isSpace()) { - lastMetIsNumber = false; - } - } + } - readyToTreat.push_back(expr.mid(lastPos).trimmed()); + if (expr.at(i).isDigit()) { + lastMetIsNumber = true; + } else if (expr.at(i) != '.' && + !expr.at(i).isSpace()) { + lastMetIsNumber = false; + } + } + + noProblem = true; + return ret; } + /*! - * \brief cutLeve2 cut an expression into many subparts using the level2 operations (* and /) outside of parenthesis as separator. Return some results by reference. - * \param expr The expression to cut. - * \param readyToTreat A reference to a string list to hold the subparts. - * \param op A list of operations stored as char ('*' and '/') and returned by reference. + * \brief extractSubExprLevel2 extract from an expression the part of an expression that need to be treated recursivly before computing level 2 operations (*, /). + * \param expr The expression to treat, the part returned will be removed. + * \param nextOp This reference, in case of sucess, will hold the first level operation identified as separator ('*' or '/') * \param noProblem A reference to a bool, set to true if there was no problem, false otherwise. - * - * The function won't cut the expression if the * or / operation is nested within parenthesis. The subexpression in the parenthesis will be treated recursivly later on. + * \return The first part of the expression that doesn't contain second level operations not nested within parenthesis. */ -inline void cutLevel2(QString const& expr, QStringList & readyToTreat, QVector & op, bool & noProblem) -{ +inline QString extractSubExprLevel2(QString & expr, char & nextOp, bool & noProblem){ - readyToTreat.clear(); - op.clear(); + QString ret; - int subCount = 0; - int lastPos = 0; + int subCount = 0; - for (int i = 0; i < expr.size(); i++) { + for(int i = 0; i < expr.size(); i++){ - if (expr.at(i) == '(') { - subCount++; - } + if (expr.at(i) == '(') { + subCount++; + } - if (expr.at(i) == ')') { - subCount--; - } + if (expr.at(i) == ')') { + subCount--; + } - if (subCount < 0) { - noProblem = false; - return; - } + if (subCount < 0) { + noProblem = false; + return ret; + } - if ( (expr.at(i) == '*' || expr.at(i) == '/') && - subCount == 0) { + if(i == expr.size()-1 && subCount == 0){ + ret = expr; + expr.clear(); + break; + } - readyToTreat.push_back(expr.mid(lastPos, i-lastPos).trimmed()); - lastPos = i+1; - op.push_back(expr.at(i).toLatin1()); + if( (expr.at(i) == '*' || expr.at(i) == '/') && + subCount == 0) { - } - } + ret = expr.mid(0, i).trimmed(); + nextOp = expr.at(i).toLatin1(); + expr = expr.mid(i+1); + break; + + } + + } - readyToTreat.push_back(expr.mid(lastPos).trimmed()); + noProblem = true; + return ret; } /*! * \brief treatLevel1 treat an expression at the first level of recursion. * \param expr The expression to treat. * \param noProblem A reference to a bool set to true if no problem happened, false otherwise. * \return The value of the parsed expression or subexpression or 0 in case of error. */ double treatLevel1(const QString &expr, bool & noProblem) { noProblem = true; - QStringList readyToTreat; - QVector op; + QString exprDestructable = expr; - cutLevel1(expr, readyToTreat, op, noProblem); - if (!noProblem) { - return 0.0; - } + char nextOp = '+'; + double result = 0.0; - if (readyToTreat.contains("")) { - noProblem = false; - return 0.0; - } + while (!exprDestructable.isEmpty()) { - if (op.size() != readyToTreat.size()-1) { - noProblem = false; - return 0.0; - } + double sign = (nextOp == '-') ? -1 : 1; + QString part = extractSubExprLevel1(exprDestructable, nextOp, noProblem); - double result = 0.0; + if (!noProblem) { + return 0.0; + } - for (int i = 0; i < readyToTreat.size(); i++) { + if (sign > 0) { + result += treatLevel2(part, noProblem); + } else { + result -= treatLevel2(part, noProblem); + } - if (i == 0) { - result += treatLevel2(readyToTreat[i], noProblem); - } else { - if (op[i-1] == '+') { - result += treatLevel2(readyToTreat[i], noProblem); - } else if (op[i-1] == '-') { - result -= treatLevel2(readyToTreat[i], noProblem); - } - } - - if (noProblem == false) { - return 0.0; - } - } + if(!noProblem){ + return 0.0; + } + } return result; } /*! * \brief treatLevel2 treat a subexpression at the second level of recursion. * \param expr The subexpression to treat. * \param noProblem A reference to a bool set to true if no problem happened, false otherwise. * \return The value of the parsed subexpression or 0 in case of error. * * The expression should not contain first level operations not nested in parenthesis. */ double treatLevel2(QString const& expr, bool & noProblem) { noProblem = true; - QStringList readyToTreat; - QVector op; + QString exprDestructable = expr; - cutLevel2(expr, readyToTreat, op, noProblem); - if (!noProblem) { - return 0.0; - } + char nextOp = '*'; - if (readyToTreat.contains("")) { - noProblem = false; - return 0.0; - } + QString part = extractSubExprLevel2(exprDestructable, nextOp, noProblem); - if (op.size() != readyToTreat.size()-1) { - noProblem = false; - return 0.0; - } + double result = treatLevel3(part, noProblem); - double result = 0.0; + while (!exprDestructable.isEmpty()) { - for (int i = 0; i < readyToTreat.size(); i++) { + if (!noProblem) { + return 0.0; + } - if (i == 0) { - result += treatLevel3(readyToTreat[i], noProblem); - } else { - if (op[i-1] == '*') { - result *= treatLevel3(readyToTreat[i], noProblem); - } else if(op[i-1] == '/') { - //may become infinity or NAN. - result /= treatLevel3(readyToTreat[i], noProblem); - } - } + part = extractSubExprLevel2(exprDestructable, nextOp, noProblem); - if (noProblem == false) { - return 0.0; - } - } + if (!noProblem) { + return 0.0; + } - return result; + if (nextOp == '*') { + result *= treatLevel3(part, noProblem); + } else { + result /= treatLevel3(part, noProblem); + } + } + + return result; } /*! * \brief treatLevel3 treat a subexpression at the third level of recursion. * \param expr The subexpression to treat. * \param noProblem A reference to a bool set to true if no problem happened, false otherwise. * \return The value of the parsed subexpression or 0 in case of error. * * The expression should not contain first or second level operations not nested in parenthesis. */ double treatLevel3(const QString &expr, bool & noProblem) { noProblem = true; int indexPower = -1; int indexCount = 0; int subLevels = 0; for (int i = 0; i < expr.size(); i++) { if (expr.at(i) == '(') { subLevels++; } else if(expr.at(i) == ')') { subLevels--; if (subLevels < 0) { noProblem = false; return 0.0; } } else if (expr.at(i) == '^') { if (subLevels == 0) { indexPower = i; indexCount++; } } } - if (indexCount > 1) { + if (indexCount > 1 || indexPower + 1 >= expr.size()) { noProblem = false; return 0.0; } if (indexPower > -1) { - QStringList subExprs = expr.split('^'); + QStringList subExprs; + subExprs << expr.mid(0,indexPower); + subExprs << expr.mid(indexPower+1); bool noProb1 = true; bool noProb2 = true; double base = treatFuncs(subExprs[0], noProb1); double power = treatFuncs(subExprs[1], noProb2); return qPow(base, power); } else { return treatFuncs(expr, noProblem); } noProblem = false; return 0.0; } /*! * \brief treatFuncs treat the last level of recursion: parenthesis and functions. * \param expr The expression to parse. * \param noProblem A reference to a bool set to true if no problem happened, false otherwise. * \return The value of the parsed subexpression or 0 in case of error. * * The expression should not contain operators not nested anymore. The subexpressions within parenthesis will be treated by recalling the level 1 function. */ double treatFuncs(QString const& expr, bool & noProblem) { noProblem = true; QRegExp funcExp = funcExpr; //copy the expression in the current execution stack, to avoid errors for example when multiple thread call this function. QRegExp numExp = numberExpr; if (funcExp.exactMatch(expr.trimmed())) { int sign = funcExp.capturedTexts()[1].isEmpty() ? 1 : -1; QString func = funcExp.capturedTexts()[2].toLower(); QString subExpr = funcExp.capturedTexts()[3]; double val = treatLevel1(subExpr, noProblem); if (!noProblem) { return 0.0; } if (func.isEmpty()) { return sign*val; } if (!supportedFuncs.contains(func)) { noProblem = false; return 0.0; } //trigonometry is done in degree if (func == "cos") { val = qCos(val/180*qAcos(-1)); } else if (func == "sin") { val = qSin(val/180*qAcos(-1)); } else if (func == "tan") { val = qTan(val/180*qAcos(-1)); } else if(func == "acos") { val = qAcos(val)*180/qAcos(-1); } else if (func == "asin") { val = qAsin(val)*180/qAcos(-1); } else if (func == "atan") { val = qAtan(val)*180/qAcos(-1); } else if (func == "exp") { val = qExp(val); } else if (func == "ln") { val = qLn(val); } else if (func == "log10") { val = qLn(val)/qLn(10.0); } else if (func == "abs") { val = qAbs(val); } return sign*val; } else if(numExp.exactMatch(expr.trimmed())) { return expr.toDouble(&noProblem); } noProblem = false; return 0.0; } //int functions /*! * \brief treatLevel1 treat an expression at the first level of recursion. * \param expr The expression to treat. * \param noProblem A reference to a bool set to true if no problem happened, false otherwise. * \return The value of the parsed expression or subexpression or 0 in case of error. */ double treatLevel1Int(QString const& expr, bool & noProblem) { - noProblem = true; + noProblem = true; - QStringList readyToTreat; - QVector op; + QString exprDestructable = expr; - cutLevel1(expr, readyToTreat, op, noProblem); - if (!noProblem) { - return 0.0; - } + char nextOp = '+'; + double result = 0.0; - if (readyToTreat.contains("")) { - noProblem = false; - return 0; - } + while (!exprDestructable.isEmpty()) { - if (op.size() != readyToTreat.size()-1) { - noProblem = false; - return 0; - } - - double result = 0; + double sign = (nextOp == '-') ? -1 : 1; + QString part = extractSubExprLevel1(exprDestructable, nextOp, noProblem); - for (int i = 0; i < readyToTreat.size(); i++) { + if( !noProblem) { + return 0.0; + } - if (i == 0) { - result += treatLevel2Int(readyToTreat[i], noProblem); - } else { - if (op[i-1] == '+') { - result += treatLevel2Int(readyToTreat[i], noProblem); - } else if(op[i-1] == '-') { - result -= treatLevel2Int(readyToTreat[i], noProblem); - } - } + if (sign > 0) { + result += treatLevel2Int(part, noProblem); + } else { + result -= treatLevel2Int(part, noProblem); + } - if (noProblem == false) { - return 0; - } - } + if(!noProblem){ + return 0.0; + } + } - return result; + return result; } /*! * \brief treatLevel2 treat a subexpression at the second level of recursion. * \param expr The subexpression to treat. * \param noProblem A reference to a bool set to true if no problem happened, false otherwise. * \return The value of the parsed subexpression or 0 in case of error. * * The expression should not contain first level operations not nested in parenthesis. */ double treatLevel2Int(const QString &expr, bool &noProblem) { - noProblem = true; + noProblem = true; - QStringList readyToTreat; - QVector op; + QString exprDestructable = expr; - cutLevel2(expr, readyToTreat, op, noProblem); - if (!noProblem) { - return 0.0; - } + char nextOp = '*'; - if (readyToTreat.contains("")) { - noProblem = false; - return 0; - } + QString part = extractSubExprLevel2(exprDestructable, nextOp, noProblem); - if (op.size() != readyToTreat.size()-1) { - noProblem = false; - return 0; - } + double result = treatLevel3(part, noProblem); - double result = 0; + while (!exprDestructable.isEmpty()) { - for (int i = 0; i < readyToTreat.size(); i++) { + if (!noProblem) { + return 0.0; + } - if (i == 0) { - result += treatFuncsInt(readyToTreat[i], noProblem); - } else { - if (op[i-1] == '*') { - result *= treatFuncsInt(readyToTreat[i], noProblem); - } else if(op[i-1] == '/') { - int value = treatFuncsInt(readyToTreat[i], noProblem); + part = extractSubExprLevel2(exprDestructable, nextOp, noProblem); - //int int airthmetic it's impossible to divide by 0. - if (value == 0) { - noProblem = false; - return 0; - } + if (!noProblem) { + return 0.0; + } - result /= value; - } - } + if (nextOp == '*') { + result *= treatFuncsInt(part, noProblem); + } else { - if (noProblem == false) { - return 0; - } - } + double val = treatFuncsInt(part, noProblem); - return result; + if(std::isinf(result/val) || std::isnan(result/val)){ + noProblem = false; + return 0.0; + } + + result /= val; + } + } + + return result; } /*! * \brief treatFuncs treat the last level of recursion: parenthesis * \param expr The expression to parse. * \param noProblem A reference to a bool set to true if no problem happened, false otherwise. * \return The value of the parsed subexpression or 0 in case of error. * * The expression should not contain operators not nested anymore. The subexpressions within parenthesis will be treated by recalling the level 1 function. */ double treatFuncsInt(QString const& expr, bool & noProblem) { noProblem = true; QRegExp funcExpInteger = funcExprInteger; QRegExp integerExp = integerExpr; QRegExp numberExp = numberExpr; if (funcExpInteger.exactMatch(expr.trimmed())) { int sign = funcExpInteger.capturedTexts()[1].isEmpty() ? 1 : -1; QString subExpr = funcExpInteger.capturedTexts()[2]; double val = treatLevel1Int(subExpr, noProblem); if (!noProblem) { return 0; } return sign*val; } else if(numberExp.exactMatch(expr.trimmed())) { double value = QVariant(expr).toDouble(&noProblem); return value; } noProblem = false; return 0; }