#2031 Curve Calculator : Sort variable names by the order they first appear

This commit is contained in:
Magne Sjaastad 2017-10-23 13:31:57 +02:00
parent dd01863240
commit f61c83a659
3 changed files with 21 additions and 4 deletions

View File

@ -33,6 +33,8 @@
#include "cafPdmUiTextEditor.h"
#include <QMessageBox>
#include <algorithm>
@ -132,7 +134,12 @@ caf::PdmFieldHandle* RimCalculation::userDescriptionField()
bool RimCalculation::parseExpression()
{
QString leftHandSideVariableName = RimCalculation::findLeftHandSide(m_expression);
if (leftHandSideVariableName.isEmpty()) return false;
if (leftHandSideVariableName.isEmpty())
{
QMessageBox::warning(nullptr, "Expression Parser", "Failed to detect left hand side of equation");
return false;
}
std::vector<QString> variableNames = ExpressionParser::detectReferencedVariables(m_expression);

View File

@ -41,8 +41,8 @@ TEST(RicExpressionParserTest, DetectVariables)
std::vector<QString> variables = ExpressionParser::detectReferencedVariables(expr);
EXPECT_STREQ(variables[0].toStdString().data(), "a");
EXPECT_STREQ(variables[1].toStdString().data(), "c");
EXPECT_STREQ(variables[0].toStdString().data(), "c");
EXPECT_STREQ(variables[1].toStdString().data(), "a");
EXPECT_STREQ(variables[2].toStdString().data(), "x");
EXPECT_STREQ(variables[3].toStdString().data(), "y");
}

View File

@ -36,6 +36,8 @@ std::vector<QString> ExpressionParserImpl::detectReferencedVariables(const QStri
std::vector<std::string> variable_list;
exprtk::collect_variables(expression.toStdString(), variable_list);
std::vector<std::pair<int, QString>> indexAndNamePairs;
for (const auto& s : variable_list)
{
QString variableNameLowerCase = QString::fromStdString(s);
@ -45,9 +47,17 @@ std::vector<QString> ExpressionParserImpl::detectReferencedVariables(const QStri
int index = expression.indexOf(variableNameLowerCase, 0, Qt::CaseInsensitive);
if (index > -1)
{
referencedVariables.push_back(expression.mid(index, variableNameLowerCase.size()));
indexAndNamePairs.push_back(std::make_pair(index, expression.mid(index, variableNameLowerCase.size())));
}
}
// Sort the variable names in the order they first appear in the expression
std::sort(indexAndNamePairs.begin(), indexAndNamePairs.end());
for (const auto& indexAndName : indexAndNamePairs)
{
referencedVariables.push_back(indexAndName.second);
}
}
return referencedVariables;