kis_num_parser.cpp 15.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/*
 *  Copyright (c) 2016 Laurent Valentin Jospin <laurent.valentin@famillejospin.ch>
 *
 *  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_num_parser.h"

Boudewijn Rempt's avatar
Boudewijn Rempt committed
21
#include <qnumeric.h> // for qIsNaN
22 23 24 25 26
#include <qmath.h>
#include <QVector>
#include <QRegExp>
#include <QStringList>
#include <QVariant>
27
#include <QLocale>
28 29 30 31 32 33 34 35 36 37

#include <iostream>

using namespace std;

const QVector<char> opLevel1 = {'+', '-'};
const QVector<char> opLevel2 = {'*', '/'};

const QStringList supportedFuncs = {"", "cos", "sin", "tan", "acos", "asin", "atan", "exp", "ln", "log10", "abs"};

38
const QRegExp funcExpr("(-)?([a-zA-Z]*[0-9]*)?\\((.+)\\)");
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
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

/*!
luz paz's avatar
luz paz committed
100
 * \brief extractSubExprLevel1 extract from an expression the part of an expression that need to be treated recursively before computing level 1 operations (+, -).
101
 * \param expr The expression to treat, the part returned will be removed.
luz paz's avatar
luz paz committed
102
 * \param nextOp This reference, in case of success, will hold the first level operation identified as separator ('+' or '-')
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
 * \param noProblem A reference to a bool, set to true if there was no problem, false otherwise.
 * \return The first part of the expression that doesn't contain first level operations not nested within parenthesis.
 */
inline QString extractSubExprLevel1(QString & expr, char & nextOp, bool & noProblem){

    QString ret;

    int subCount = 0;

    bool lastMetIsNumber = false;

    for(int i = 0; i < expr.size(); i++){

    if (expr.at(i) == '(') {
        subCount++;
    }

    if (expr.at(i) == ')') {
        subCount--;
    }

    if (subCount < 0) {
        noProblem = false;
        return ret;
    }

    if(i == expr.size()-1 && subCount == 0){
        ret = expr;
        expr.clear();
        break;
    }

    if( (expr.at(i) == '+' || expr.at(i) == '-') &&
            subCount == 0) {

        if (expr.at(i) == '-' &&
                i < expr.size()-1) {

            bool cond = !expr.at(i+1).isSpace();

            if (cond && !lastMetIsNumber) {
                continue;
            }

        }

        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;
    }

    }

    noProblem = true;
    return ret;
}


/*!
luz paz's avatar
luz paz committed
171
 * \brief extractSubExprLevel2 extract from an expression the part of an expression that need to be treated recursively before computing level 2 operations (*, /).
172
 * \param expr The expression to treat, the part returned will be removed.
luz paz's avatar
luz paz committed
173
 * \param nextOp This reference, in case of success, will hold the first level operation identified as separator ('*' or '/')
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
 * \param noProblem A reference to a bool, set to true if there was no problem, false otherwise.
 * \return The first part of the expression that doesn't contain second level operations not nested within parenthesis.
 */
inline QString extractSubExprLevel2(QString & expr, char & nextOp, bool & noProblem){

    QString ret;

    int subCount = 0;

    for(int i = 0; i < expr.size(); i++){

    if (expr.at(i) == '(') {
        subCount++;
    }

    if (expr.at(i) == ')') {
        subCount--;
    }

    if (subCount < 0) {
        noProblem = false;
        return ret;
    }

    if(i == expr.size()-1 && subCount == 0){
        ret = expr;
        expr.clear();
        break;
    }

    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;

    }

    }

    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;

    QString exprDestructable = expr;

    char nextOp = '+';
    double result = 0.0;

    while (!exprDestructable.isEmpty()) {

        double sign = (nextOp == '-') ? -1 : 1;
        QString part = extractSubExprLevel1(exprDestructable, nextOp, noProblem);

        if (!noProblem) {
        return 0.0;
        }

        if (sign > 0) {
        result += treatLevel2(part, noProblem);
        } else {
        result -= treatLevel2(part, noProblem);
        }

        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;

    QString exprDestructable = expr;

    char nextOp = '*';

    QString part = extractSubExprLevel2(exprDestructable, nextOp, noProblem);

    double result = treatLevel3(part, noProblem);

    while (!exprDestructable.isEmpty()) {

        if (!noProblem) {
        return 0.0;
        }

        bool needToMultiply = (nextOp == '*');
        part = extractSubExprLevel2(exprDestructable, nextOp, noProblem);

        if (!noProblem) {
        return 0.0;
        }

        if (needToMultiply) {
        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 || indexPower + 1 >= expr.size()) {
        noProblem = false;
        return 0.0;
    }

    if (indexPower > -1) {

        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);
    }

431 432 433 434 435 436
    double val = QLocale().toDouble(expr, &noProblem);

    if(noProblem) {
        return val;
    }

437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
    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;

    QString exprDestructable = expr;

    char nextOp = '+';
    double result = 0.0;

    while (!exprDestructable.isEmpty()) {

    double sign = (nextOp == '-') ? -1 : 1;
    QString part = extractSubExprLevel1(exprDestructable, nextOp, noProblem);

    if( !noProblem) {
        return 0.0;
    }

    if (sign > 0) {
        result += treatLevel2Int(part, noProblem);
    } else {
        result -= treatLevel2Int(part, noProblem);
    }

    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 treatLevel2Int(const QString &expr, bool &noProblem)
{

    noProblem = true;

    QString exprDestructable = expr;

    char nextOp = '*';

    QString part = extractSubExprLevel2(exprDestructable, nextOp, noProblem);

    double result = treatFuncsInt(part, noProblem);

    while (!exprDestructable.isEmpty()) {

    if (!noProblem) {
        return 0.0;
    }

    bool needToMultiply = (nextOp == '*');
    part = extractSubExprLevel2(exprDestructable, nextOp, noProblem);

    if (!noProblem) {
        return 0.0;
    }

    if (needToMultiply) {
        result *= treatFuncsInt(part, noProblem);
    } else {

        double val = treatFuncsInt(part, noProblem);

Boudewijn Rempt's avatar
Boudewijn Rempt committed
523
        if(std::isinf(result/val) || qIsNaN(result/val)){
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
        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;

}