bcParserCPP 2.8
Math Parser for C++
Public Types | Public Member Functions | Protected Types | Protected Member Functions | Friends
CMathParser< _CharT, _ValueT > Class Template Reference

CMathParser C++ template class parses and evaluates expressions given as string at runtime. More...

List of all members.

Public Types

typedef basic_string< _CharT > string_t
 String type used in variable, function names, and reporting messages.
typedef _ValueT ParserFunction (CMathParser< _CharT, _ValueT > *pParentParser, const _ValueT p[], const int count)
 ParserFunction type specifies the prototype of the functions that users can add to the list of available functions with N parameters to be used in an expression.
typedef ParserFunctionPParserFunction
typedef _ValueT VariableCallback (CMathParser< _CharT, _ValueT > *pParentParser, const string_t varName)
 VariableCallback is a callback function that is implemented by the user to provide the values for variables that are not predefined before parse operation.
typedef VariableCallbackPVariableCallback
typedef CParserException< _CharT > ParserException
 Errors are reported as ParserException.

Public Member Functions

 CMathParser ()
 Constructor to create a CMathParser instance.
virtual ~CMathParser ()
 Virtual destructor to free memory.
void Parse () throw (ParserException)
 Parse the expression.
BOOL IsFunction (string_t funcName)
 Returns TRUE if the given function name is already registered as a function.
BOOL IsVariable (string_t varName)
 Returns TRUE if the given variable name is already registered as a variable.
BOOL IsVariableUsed (string_t varName) throw (ParserException)
 Return TRUE if a given variable was used in the current expression.
BOOL IsFuncUsed (string_t funcName) throw (ParserException)
 Return TRUE if a given function is being used in the current expression.
void FreeParseTree ()
 Free the parse tree that was used to parse previous expression.
void Randomize ()
 Init random _ValueT generator for rnd built-in function.
void DeleteAllFuncs ()
 Delete all functions defined for the parser.
void DeleteAllVars ()
 Delete all defined variables.
void DeleteFunc (string_t funcName)
 Delete a function from defined functions list.
void DeleteVar (string_t varName)
 Delete an existing variable name.
void CreateVar (string_t varName, _ValueT varValue)
 Define a variable with initial value.
void CreateFunc (string_t newFuncName, int numParams, PParserFunction funcAddress) throw (ParserException)
 Create a user defined function with given name, number of params, function address to call.
virtual void CreateDefaultVars ()
 Create default built-in variables such as X, Y, PI.
virtual void CreateDefaultFuncs ()
 Create default functions.
_ValueT Evaluate () throw (ParserException)
 Evaluate the expression to it's value.
BOOL GetOptimizationOn ()
 Return current optimization setting.
void SetOptimizationOn (BOOL newVal)
 If OptimizationOn is set to TRUE, then the parser will eliminate expression sub-trees that evaluate to a constant expression so that they can be skipped in repeated evaluations.
void SetVariable (string_t varName, _ValueT varValue) throw (ParserException)
 Set the value of a variable.
_ValueT GetVariable (string_t varName)
 Get the current value of a variable.
_ValueT GetY ()
 Return value of variable Y.
void SetY (_ValueT newVal)
 Set value of variable Y.
_ValueT GetX ()
 Return value of variable X.
void SetX (_ValueT newVal)
 Set value of variable X.
_ValueT GetValue ()
 Parse the expression, evaluate it and return the result.
void SetExpression (string_t expr)
 Set the expression to parse.
string_t GetExpression ()
 Return the current expression string.
void SetVariableCallback (PVariableCallback callbackFunction)
 VariableCallback is a function that is implemented by the user to provide values for undefined variables.
PVariableCallback GetVariableCallback ()
 See SetVariableCallback.
vector< string_tGetDefinedFunctionNames ()
 Returns the list of currently defined functions as a vector of strings.
std::map< string_t, int > GetDefinedFunctionInfo ()
 Returns the list of currently defined functions (and their respective param counts) as a map of strings and ints.
vector< string_tGetDefinedVariableNames ()
 Returns the list of currently defined variables as a vector of strings.

Protected Types

typedef map< string_t, _ValueT
*, less< string_t > > 
TVarMap
typedef map< string_t,
FunctionEntry< PParserFunction >
*, less< string_t > > 
TFunctionMap

Protected Member Functions

int FindLastOper (const string_t &formula)
 In a given expression, find the last operation that needs to execute.
BOOL IsTwoParamFunc (const string_t &formula, string_t &paramLeft, string_t &paramRight, PParserFunction *funcAddr, int CurrChar)
 Determine if a given expression is a call to a function that takes two parameters.
BOOL IsOneParamFunc (const string_t &formula, string_t &param, PParserFunction *funcAddr, int CurrChar)
 Determine if a given expression is a call to a function that takes one parameters.
BOOL IsNParamFunc (const string_t &formula, vector< string_t > &params, PParserFunction *funcAddr)
 Is this expression a function that takes N parameters.
void CreateParseTree (const string_t expressionToParse, CNode< _ValueT > *&Node) throw (ParserException)
 Convert a string expression into a tree structure of CNode elements.
void Optimize (void)
 Optimize the expression.
BOOL IsFuncRegistered (const string_t name)
 Is the given function defined?

Friends

class COneParamNode< _CharT, _ValueT >
class CTwoParamNode< _CharT, _ValueT >
class CNParamNode< _CharT, _ValueT >
class CUnknownVarNode< _CharT, _ValueT >

Detailed Description

template<typename _CharT, typename _ValueT>
class CMathParser< _CharT, _ValueT >

CMathParser C++ template class parses and evaluates expressions given as string at runtime.

User can define variables, functions, set variable values, set a mathematical expression and request that it's value be computed. CMathParser will convert the string expression to an internal representation of a tree structure. If Optimization is turned on, it will walk the tree to convert non-parametric branches (branches whose values do not depend on variables) into a constant value. Once this is done successfully, the expression can be evaluated very quickly for different variable values.


Member Typedef Documentation

template<typename _CharT , typename _ValueT >
typedef _ValueT CMathParser< _CharT, _ValueT >::ParserFunction(CMathParser< _CharT, _ValueT > *pParentParser, const _ValueT p[], const int count)

ParserFunction type specifies the prototype of the functions that users can add to the list of available functions with N parameters to be used in an expression.

p[] array holds the value for each paramater. count is the number of paramaters (number of elements in p[]).

template<typename _CharT , typename _ValueT >
typedef basic_string<_CharT> CMathParser< _CharT, _ValueT >::string_t

String type used in variable, function names, and reporting messages.

It is nothing but a basic_string<> of std.

template<typename _CharT , typename _ValueT >
typedef _ValueT CMathParser< _CharT, _ValueT >::VariableCallback(CMathParser< _CharT, _ValueT > *pParentParser, const string_t varName)

VariableCallback is a callback function that is implemented by the user to provide the values for variables that are not predefined before parse operation.

Please see CMathParser::setVariableCallback(VariableCallback) for more information.


Constructor & Destructor Documentation

template<typename _CharT , typename _ValueT >
CMathParser< _CharT, _ValueT >::CMathParser ( ) [inline]

Constructor to create a CMathParser instance.

It initializes member variables and creates default functions and variables.


Member Function Documentation

template<typename _CharT , typename _ValueT >
virtual void CMathParser< _CharT, _ValueT >::CreateDefaultFuncs ( ) [inline, virtual]

Create default functions.

You can override CreateDefaultFuncs to define (or not define) a different set of functions.

Predefined functions that take one parameter are: SQR: Square function which can be used as SQR(X)

SIN: Sinus function which can be used as SIN(X), X is a real-type expression. Sin returns the sine of the angle X in radians.

COS: Cosinus function which can be used as COS(X), X is a real-type expression. COS returns the cosine of the angle X in radians.

ATAN: ArcTangent function which can be used as ATAN(X)

SINH: Sinus Hyperbolic function which can be used as SINH(X)

COSH: Cosinus Hyperbolic function which can be used as COSH(X)

COTAN: which can be used as COTAN(X)

TAN: which can be used as TAN(X)

EXP: which can be used as EXP(X)

LN: natural log, which can be used as LN(X)

LOG: 10 based log, which can be used as LOG(X)

SQRT: which can be used as SQRT(X)

ABS: absolute value, which can be used as ABS(X)

SIGN: SIGN(X) returns -1 if X<0; +1 if X>0, 0 if X=0; it can be used as SQR(X)

TRUNC: Discards the fractional part of a number. e.g. TRUNC(-3.2) is -3, TRUNC(3.2) is 3.

CEIL: CEIL(-3.2) = -3, CEIL(3.2) = 4

FLOOR: FLOOR(-3.2) = -4, FLOOR(3.2) = 3

RND: Random number generator.

RND(X) generates a random INTEGER number such that 0 <= Result < int(X). Call Parser.Randomize to initialize the random number generator with a random seed value before using RND function in your expression.

RANDOM: Random number generator.

RANDOM(X) generates a random floating point number such that 0 <= Result < X. Call Parser.Randomize to initialize the random number generator with a random seed value before using RANDOM function in your expression.

Predefined functions that take two parameters are:

INTPOW: The INTPOW function raises Base to an integral power. INTPOW(2, 3) = 8. Note that result of INTPOW(2, 3.4) = 8 as well.

POW: The Power function raises Base to any power. For fractional exponents or exponents greater than MaxInt, Base must be greater than 0.

LOGN: The LogN function returns the log base N of X. Example: LOGN(10, 100) = 2

MIN: MIN(2, 3, 4, 5) is 2.

MAX: MAX(2, 3, 1, 0) is 3.

IF: IF(1, 2, 3) is 2.

SUM: SUM(1, 2, 3, 4) is 10.

AVG: AVG(1, 2, 3, 4, 5) is 3.

template<typename _CharT , typename _ValueT >
virtual void CMathParser< _CharT, _ValueT >::CreateDefaultVars ( ) [inline, virtual]

Create default built-in variables such as X, Y, PI.

Override to define different set of variables.

template<typename _CharT , typename _ValueT >
void CMathParser< _CharT, _ValueT >::CreateFunc ( string_t  newFuncName,
int  numParams,
PParserFunction  funcAddress 
) throw (ParserException) [inline]

Create a user defined function with given name, number of params, function address to call.

The uppercase version of given function name can be used in the expressions. If the expression does not specify correct number of parameters, then a CMathParser::ParserException will be thrown during parsing. if number of parameters is specified as -1, then the function can take 1 or more number of parameters. Number of parameters will not be verified during parse operation. If invalid number of parameters are passed to a function, the function implementation itself can choose to throw exception during evaluate operation.

template<typename _CharT , typename _ValueT >
void CMathParser< _CharT, _ValueT >::DeleteFunc ( string_t  funcName) [inline]

Delete a function from defined functions list.

Ignore if not found.

template<typename _CharT , typename _ValueT >
void CMathParser< _CharT, _ValueT >::DeleteVar ( string_t  varName) [inline]

Delete an existing variable name.

If it does not exist, it is ignored.

template<typename _CharT , typename _ValueT >
_ValueT CMathParser< _CharT, _ValueT >::Evaluate ( ) throw (ParserException) [inline]

Evaluate the expression to it's value.

Throw CMathParser::ParserException if the expression can not be parsed.

template<typename _CharT , typename _ValueT >
int CMathParser< _CharT, _ValueT >::FindLastOper ( const string_t formula) [inline, protected]

In a given expression, find the last operation that needs to execute.

Return -1 if not found. For example: "SIN(X)" has no last operation. -1 will be returned. "SIN(X)+COS(Y)" has '+' as the last operation. This operation node, if it existing will be the root node for the expression tree that represents this formula.

template<typename _CharT , typename _ValueT >
void CMathParser< _CharT, _ValueT >::FreeParseTree ( ) [inline]

Free the parse tree that was used to parse previous expression.

This does not have to be called explicitly. This is only useful for an unusual case where a very big expression was parsed and tree takes alot of memory and you want to free it because you will not use the parser instance for a while. Otherwise, next expression parse will delete previous tree.

template<typename _CharT , typename _ValueT >
std::map<string_t, int> CMathParser< _CharT, _ValueT >::GetDefinedFunctionInfo ( ) [inline]

Returns the list of currently defined functions (and their respective param counts) as a map of strings and ints.

by Blake Madden.

template<typename _CharT , typename _ValueT >
BOOL CMathParser< _CharT, _ValueT >::GetOptimizationOn ( ) [inline]

Return current optimization setting.

If OptimizationOn is set to TRUE, then the parser will eliminate expression sub-trees that evaluate to a constant expression so that they can be skipped in repeated evaluations.

template<typename _CharT , typename _ValueT >
_ValueT CMathParser< _CharT, _ValueT >::GetVariable ( string_t  varName) [inline]

Get the current value of a variable.

Throws CMathParser::ParserException if variable is not defined yet.

template<typename _CharT , typename _ValueT >
_ValueT CMathParser< _CharT, _ValueT >::GetX ( ) [inline]

Return value of variable X.

Since X, and Y are commonly used in math expressions, CMathParser defines them by default. If you don't like X and Y, you can override CreateDefaultVars, or you can call DeleteAllVars() function.

template<typename _CharT , typename _ValueT >
_ValueT CMathParser< _CharT, _ValueT >::GetY ( ) [inline]

Return value of variable Y.

Since X, and Y are commonly used in math expressions, CMathParser defines them by default. If you don't like X and Y, you can override CreateDefaultVars, or you can call DeleteAllVars() function.

template<typename _CharT , typename _ValueT >
BOOL CMathParser< _CharT, _ValueT >::IsFuncUsed ( string_t  funcName) throw (ParserException) [inline]

Return TRUE if a given function is being used in the current expression.

Return FALSE if the expression is not using the function. Throw CMathParser::ParserException if the expression cannot be parsed.

template<typename _CharT , typename _ValueT >
BOOL CMathParser< _CharT, _ValueT >::IsOneParamFunc ( const string_t formula,
string_t param,
PParserFunction *  funcAddr,
int  CurrChar 
) [inline, protected]

Determine if a given expression is a call to a function that takes one parameters.

If so, tree structures representing child node will be returned as OUT parameter, too.

template<typename _CharT , typename _ValueT >
BOOL CMathParser< _CharT, _ValueT >::IsTwoParamFunc ( const string_t formula,
string_t paramLeft,
string_t paramRight,
PParserFunction *  funcAddr,
int  CurrChar 
) [inline, protected]

Determine if a given expression is a call to a function that takes two parameters.

If so, tree structures representing left and right nodes will be returned as OUT parameters, too.

template<typename _CharT , typename _ValueT >
BOOL CMathParser< _CharT, _ValueT >::IsVariableUsed ( string_t  varName) throw (ParserException) [inline]

Return TRUE if a given variable was used in the current expression.

Return FALSE if the expression does not contain this variable. Throw CMathParser::ParserException if the expression cannot be parsed.

template<typename _CharT , typename _ValueT >
void CMathParser< _CharT, _ValueT >::Parse ( ) throw (ParserException) [inline]

Parse the expression.

It is fast to parse the expression once, then loop to evaluate the expression multiple times by setting different variable values. throws CMathParser::ParserException on error.

template<typename _CharT , typename _ValueT >
void CMathParser< _CharT, _ValueT >::SetExpression ( string_t  expr) [inline]

Set the expression to parse.

The expression may contain : 1. variables such as X, Y, Z, TEMP, STRESS, STRAIN etc. 2. functions such as SIN(X), MIN(A,B), MYFUNC(D) 3. constants such as 2, 3, 50 4. scientific notation like: 3E+10 5. aithmetic operators: +,-,*,/,%(modulus),^(power) 6. logical operators : =,<,>,<>,>=,<=,!(not),&(and),|(or)

Example expressions are:

"X+Y/2" "SIN(X)+AVG(A,B,C)" "SUM(X,Y,Z,K,L)/5"

template<typename _CharT , typename _ValueT >
void CMathParser< _CharT, _ValueT >::SetVariable ( string_t  varName,
_ValueT  varValue 
) throw (ParserException) [inline]

Set the value of a variable.

This will define the variable if it is not defined yet.

template<typename _CharT , typename _ValueT >
void CMathParser< _CharT, _ValueT >::SetVariableCallback ( PVariableCallback  callbackFunction) [inline]

VariableCallback is a function that is implemented by the user to provide values for undefined variables.

If VariableCallback is set for the CMathParser instance, then the parser will tolerate undefined variables during parsing and it will invoke the user defined VariableCallback function to retrieve the variables values during evaluation. If VariableCallback is NULL, then the parser will require that all variables used in an expression are predefined before the parse operation. VariableCallback is useful in situations where the application domain is so large that defining every possible variable ahead of time is not possible. VariableCallback implementation should decide whether a variable name is valid and what it's value should be. If the variable name is not valid, then the VariableCallback should throw an exception and stop the expression evaluation. VariableCallback typedef for the function signature is as follows: typedef _ValueT VariableCallback(CMathParser<_CharT, _ValueT> *pParentParser, const string_t varName); The user defined function takes two parameters: 1. A pointer to the parser instance making this call. 2. The variable name as a string. Return value shall be the desired value for this variable name. If the variable is not valid, then an exception should be thrown. CMathParser::ParserException is a good canditate to throw in such case.

template<typename _CharT , typename _ValueT >
void CMathParser< _CharT, _ValueT >::SetX ( _ValueT  newVal) [inline]

Set value of variable X.

Since X, and Y are commonly used in math expressions, CMathParser defines them by default. If you don't like X and Y, you can override CreateDefaultVars, or you can call DeleteAllVars() function.

template<typename _CharT , typename _ValueT >
void CMathParser< _CharT, _ValueT >::SetY ( _ValueT  newVal) [inline]

Set value of variable Y.

Since X, and Y are commonly used in math expressions, CMathParser defines them by default. If you don't like X and Y, you can override CreateDefaultVars, or you can call DeleteAllVars() function.

 All Classes Functions Variables Typedefs Enumerations