Home · All Namespaces · All Classes · Grouped Classes · Modules · Functions codeless banner

QExpressionEvaluator Class Reference
[QtBaseModule]

The QExpressionEvaluator class computes the results of arithmetic, logical and string based expressions. More...

    #include <QExpressionEvaluator>

Inherits QObject.

Public Types

Public Functions

Public Slots

Signals

Additional Inherited Members


Detailed Description

The QExpressionEvaluator class computes the results of arithmetic, logical and string based expressions.

Most interestingly, the expression evaluator has the ability to use values from the Qt Extended valuespace in its expressions and signal when the resulting expression changes through termsChanged().

Overview

It takes as input through setExpression() an expression such as "2 + 2" and calculates the result.

Here is an example of basic usage of the expression evaluator.

    QExpressionEvaluator ee;
    ee.setExpression("2 + 2");
    if(!ee.isValid()) { // check if syntax/semantics correct.
        qWarning("Syntax or semantic error in expression.");
    } else {
        if(!ee.evaluate()) { // evaluate the expression
            qWarning("Run-time error when evaluating expression"); // run-time error - type coercion or divide by zero.
        } else {
            QVariant result = ee.result();  // retrieve the result
            int x = result.toInt(); // x == 4
        }
    }

Details

The expression evaluator functionally operates in 2 phases. The first phase is the setup phase, where the specified expression is tokenized, parsed, semantically checked and byte code generated. The isValid() function returns whether this entire setup phase is successful ie. the specified expression is syntactually and semantically valid.

The second phase is the evaluation phase, where the generated bytecode from the first phase is executed to compute the result of the expression. The evaluate() function uses a virtual machine to execute the bytecode and store the resulting value. Run-time errors occur when an expression attempts to divide-by-zero or if an expression evaluator term cannot be coerced to a required type. The return value of evaluate() indicates whether there were any run-time errors. If evaluate() returns true, result() can then be called to retreive the calcuated result of the expression as a QVariant. You should cast the variant to the data type you expect.

Supported Data Types

The expression evaluator supports 5 data types: int, real, string and bool. real numbers are represented either using the C++ double data type, or by using fixed point calculations. C++ double is the default, but you probably want to use the fixed point format for user visible applications of the expression evaluator, such as a desktop calculator. This can be set using the setFloatingPointFormat() function.

Supported Operators

Table is in highest to lowest precedence.

OperatorDescription
( ) - !Brackets to control evaluation order of expression, unary minus, logical negation. eg. "2 * (3 + 4)" "-20" "!false"
* / %Arithmetic multiplication, division and modulus. eg. "2 * 3 / 3 % 3"
+ - .Arithmetic addition and subtraction. String concatenation. eg. "2 + 3 - 4" ""hello" . "world""
< > <= >=Logical comparison. eg "10.9 > = 10.8"
== !=Logical equality. eg. "true != false"
&&Logical AND eg. "true && true"
||Logical OR eg. "false || true"

Type Conversion

Operators in the expression evaluator work with operands of the same type ie. the '+' operator can only add two integer or two real numbers. However, a user may still mix data types and the operands will be coerced to the correct type for the operator.

Consider the expression: 2 + "2"

The '+' operator adds two number operands, but the RHS operand is a string. As the LHS is an integer, the expression evaluator tries to coerce the RHS string to an integer to meet the requirements of the '+' operator. In this case, the coercion would succeed and "2" would simply become an integer 2. The result of the expression would then be the integer 4.

If operands cannot be coerced to the required types for an operator, then for static coercion the setup phase fails and isValid() returns false and for run-time coercion evaluate() returns false.

Run-time coercion failures can occur for 2 reasons:

a term, eg. a key in the valuespace, does not return a value that can be coerced to the required type, or a return value of one side of the expression cannot be coerced to the required type. eg. 2 + ("2" . "@/value/in/valuespace") would fail at run-time because the RHS of '+' is a string, calculated at runtime, that cannot be coerced to an integer.

Below are the data type requirements of the expression evaluator's operators.

OperatorRequired operand typesReturn type
Basic arithmetic (* / + -)Alteast 1 double or integer./ always returns a real, others return real or integer depending on operands.
Modulus (%)Two integers.integer
String Concatentation (.)Atleast 1 string.string
Logical Comparison (< > <= >=)Atleast 1 double, integer or bool.bool
Other Logical (== != && || !)All types.bool

Valuespace integration

The expression evaluator has the ability to use values from the Qt Extended valuespace in its expressions.

    2 + @/Value/Space/Key

The above code would add 2 and the value for /Value/Space/Key in the valuespace.

The '@' character uniquely identifies the subsequent characters as a valuespace key to the expression evaluator.

In the above example, /Value/Space/Key must return data that can be converted to an integer. If conversion fails, a run-time error will occur and evaluate() will return false.

If a value in the valuespace changes, expressions which use that value will emit the termsChanged() signal.


Member Type Documentation

enum QExpressionEvaluator::FloatingPointFormat

Controls the floating point format used by the expression evaluator.

ConstantValueDescription
QExpressionEvaluator::Double0C++ double data type.
QExpressionEvaluator::FixedPoint1Fixed point arithmetic using an 8byte integer.


Member Function Documentation

QExpressionEvaluator::QExpressionEvaluator ( QObject * parent = 0 )

Constructs a QExpressionEvaluator. parent is passed to the QObject constructor.

QExpressionEvaluator::QExpressionEvaluator ( const QByteArray & expr, QObject * parent = 0 )

Constructs a QExpressionEvaluator.

expr is passed to setExpression(). parent is passed to the QObject constructor.

QExpressionEvaluator::~QExpressionEvaluator ()

Destroys the QExpressionEvaluator.

void QExpressionEvaluator::clear ()   [slot]

Clears the set expression and any associated data structures.

The expression becomes invalid ie. isValid() returns false.

bool QExpressionEvaluator::evaluate ()

Evaluates the expression specified through setExpression().

isValid() must return true before you call this function, otherwise it will abort().

Returns true if the expression was successfully evaluated, or false if a run-time error occured.

A run-time error can occur due to a coercion error or divide by zero.

If this function returns true, the result of the evaluation can be retrieved using result().

QByteArray QExpressionEvaluator::expression () const

Returns the current expression data the evaluator is operating on.

See also setExpression().

FloatingPointFormat QExpressionEvaluator::floatingPointFormat () const

Returns the current floating point format.

See also setFloatingPointFormat().

bool QExpressionEvaluator::isValid () const

Returns true if this expression is valid, otherwise false.

An expression is valid if it is not empty, it is syntactually and semantically correct, and a previous call to evaluate() did not result in a run-time error.

You must not call evaluate() unless this function returns true.

QVariant QExpressionEvaluator::result ()

Returns the result of the last call to evaluate() as a QVariant.

Returns an empty QVariant if evaluate() has not yet been called.

bool QExpressionEvaluator::setExpression ( const QByteArray & expr )   [slot]

Sets the expression for the evaluator to be expr

expr is parsed and semantically checked immediat

Returns true on success; otherwise returns false.

You should call isValid() after this function to determine whether the setup phase was completed successfully.

See also expression().

void QExpressionEvaluator::setFloatingPointFormat ( const FloatingPointFormat & fmt )

Sets the floating point format to be used by the expression evaluator to fmt.

The default is QExpressionEvaluator::Double, but setting QExpressionEvaluator::FixedPoint may give results appropriate for user level applications.

See also floatingPointFormat().

void QExpressionEvaluator::termsChanged ()   [signal]

Emitted when a pluggable term in the expression changes.


Copyright © 2009 Nokia Trademarks
Qt Extended 4.4.3