mupInit()
by calling mupRelease(hParser)
.
parser_handle hParser; hParser = mupInit(); // Create a new handle // use the parser... mupRelease(hParser); // Release an existing parser handleInternally a handle is nothing more than a pointer to a parser object casted to a void pointer.
new
and delete
for initialization and deinitialization.)
mu::Parser parser;
const char
pointing to the expression.
mupSetExpr(hParser, szLine);
See also: example2/example2.c.
std::string
containing the expression as the
only parameter.
parser.SetExpr(line);
See also: example1/example1.cpp; src/muParserTest.cpp.
Expression evaluation is done by calling the mupEval()
function in the DLL version or the
Eval()
member function of a parser object. When evaluating an expression for the first time
the parser evaluates the expression string directly and creates a bytecode during this first time evaluation.
Every sucessive call to Eval()
will evaluate the bytecode directly unless you call a function
that will silently reset the parser to string parse mode. Some functions invalidate the bytecode due to
possible changes in callback function pointers or variable addresses. By doing so they effectively cause a
recreation of the bytecode during the next call to Eval()
.
Internally there are different evaluation functions. One for parsing from a string, the other for
parsing from bytecode (and a third one used only if the expression can be simplified to a constant).
Initially, Eval()
will call the string parsing function which is slow due to all the
necessary syntax checking, variable lookup, and bytecode creation. Once this
function succeeds, Eval()
will change its internal parse function pointer to either
the bytecode parsing function or the const result function which are significantly (approx. 1000 times)
faster. You don't have to worry about this, it's done automatically, just keep in mind that the
first time evaluation of an expression is significantly slower than any successive call to
Eval()
.
double fVal; fVal = mupEval(hParser);See also: example2/example2.c.
double fVal; try { fVal = parser.Eval(); } catch (Parser::exception_type &e) { std::cout << e.GetMsg() << endl; }See also: example1/example1.cpp.
If the expression contains multiple separated subexpressions the return value of Eval()
/
mupEval()
is the result of the last subexpression. If you need all of the results
use the Eval overload described in the next section.
muParser accepts expressions that are made up of several subexpressions delimited by the function argument separator. For instance take a look at the following expression:
sin(x),y+x,x*x
It is made up of three expression separated by commas hence it will create three return values.
(Assuming the comma is defined as the argument separator). The number of return values as well
as their value can be queried with an overload of the Eval
function. This overload
takes a reference to an integer value for storing the total number of return values and returns
a pointer to an array of value_type
holding the actual values with the first value
at the botton of the array and the last at the top.
int nNum, i; muFloat_t *v = mupEvalMulti(hParser, &nNum); for (i=0; i<nNum; ++i) { printf("v[i]=%2.2f\n", v[i]); }
int nNum; value_type *v = parser.Eval(nNum); for (int i=0; i<nNum; ++i) { std::cout << v[i] << "\n"; }See also: example1/example1.cpp.
The function GetNumResults()
can be used in order to finf out whether a given expression has produced
multiple return values.
The basic idea behind the bulkmode is to minimize the overhead of function calls and loops when using muParser inside of large loops. Each loop turn requires a distinct set of variables and setting these variables followed by calling the evaluation function can by slow if the loop is implemented in a managed language. This overhead can be minimized by precalculating the variable values and calling just a single evaluation function. In reality the bulkmode doesn't make much of a difference when used in C++ but it brings a significant increase in performance when used in .NET applications. If muParser was compiled with OpenMP support the calculation load will be spread among all available CPU cores. When using the bulk mode variable pointers submitted to the DefineVar function must be arrays instead of single variables. All variable arrays must have the same size and each array index represents a distinct set of variables to be used in the expression.
Although the bulk mode does work with standard callback functions it may sometimes be necessary to have additional informations inside a callback function. Especially Informations like the index of the current variable set and the index of the thread performing the calculation may be crucial to the evaluation process. To facilitate this need a special set of callback functions was added.
void CalcBulk() { int nBulkSize = 200, i; // allocate the arrays for variables and return values muFloat_t *x = (muFloat_t*)malloc(nBulkSize * sizeof(muFloat_t)); muFloat_t *y = (muFloat_t*)malloc(nBulkSize * sizeof(muFloat_t)); muFloat_t *r = (muFloat_t*)malloc(nBulkSize * sizeof(muFloat_t)); // initialize the parser and variables muParserHandle_t hParser = mupCreate(muBASETYPE_FLOAT); for (i=0; i<nBulkSize; ++i) { x[i] = i; y[i] = i; r[i] = 0; } // Set up variables and functions and evaluate the expression mupDefineVar(hParser, "x", x); mupDefineVar(hParser, "y", y); mupDefineBulkFun1(hParser, "bulktest", BulkTest); mupSetExpr(hParser, "bulktest(x+y)"); mupEvalBulk(hParser, r, nBulkSize); if (mupError(hParser)) { printf("\nError:\n"); printf("------\n"); printf("Message: %s\n", mupGetErrorMsg(hParser) ); printf("Token: %s\n", mupGetErrorToken(hParser) ); printf("Position: %d\n", mupGetErrorPos(hParser) ); printf("Errc: %d\n", mupGetErrorCode(hParser) ); return; } // Output the result for (i=0; i<nBulkSize; ++i) { printf("%d: bulkfun(%2.2f + %2.2f) = %2.2f\n", i, x[i], y[i], r[i]); } free(x); free(y); free(r); }
mu::muParser
directly you can skip this
section. (The DLL version uses the default implementation internally.)
mupDefineNameChars(hParser, "0123456789_" "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ"); mupDefineOprtChars(hParser, "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "+-*^/?<>=#!$%&|~'_"); mupDefineInfixOprtChars(hParser, "/+-*^?<>=#!$%&|~'_");
parser.DefineNameChars("0123456789_" "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ"); parser.DefineOprtChars("abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "+-*^/?<>=#!$%&|~'_"); parser.DefineInfixOprtChars("/+-*^?<>=#!$%&|~'_");See also: ParserLib/muParser.cpp; ParserLib/muParserInt.cpp.
DefineVar
function or implicit by the parser. Implicit declaration will call a variable factory function provided by the user. The parser is never the owner of its variables. So you must take care of their destruction in case of dynamic allocation. The general idea is to bind every parser variable to a C++ variable. For this reason, you have to make sure the C++ variable stays valid as long as you process a formula that needs it. Only variables of type double
are supported.
![]() |
Defining new Variables will reset the parser bytecode. Do not use this function just for changing the values of variables! It would dramatically reduce the parser performance! Once the parser knows the address of the variable there is no need to explicitely call a function for changing the value. Since the parser knows the address it knows the value too so simply change the C++ variable in your code directly! |
double fVal=0; mupDefineVar(hParser, "a", &fVal);See also: example2/example2.c.
double fVal=0; parser.DefineVar("a", &fVal);See also: example1/example1.cpp; src/muParserTest.cpp.
double* (*facfun_type)(const char*, void*)The first argument to a factory function is the name of the variable found by the parser. The second is a pointer to user defined data. This pointer can be used to provide a pointer to a class that implements the actual factory. By doing this it is possible to use custom factory classes depending on the variable name.
![]() | Be aware of name conflicts! Please notice that recognizing the name of an undefined variable is the last step during parser token detection. If the potential variable name starts with identifiers that could be interpreted as a function or operator it will be detected as such most likely resulting in an syntax error. |
double* AddVariable(const char *a_szName, void *pUserData) { static double afValBuf[100]; static int iVal = 0; std::cout << "Generating new variable \"" << a_szName << "\" (slots left: " << 99-iVal << ")" << endl; // you could also do: // MyFactory *pFactory = (MyFactory*)pUserData; // pFactory->CreateNewVariable(a_szName); afValBuf[iVal++] = 0; if (iVal>=99) throw mu::Parser::exception_type("Variable buffer overflow."); return &afValBuf[iVal]; }See also: example1/example1.cpp. In order to add a variable factory use the
SetVarFactory
functions. The first parameter
is a pointer to the static factory function, the second parameter is optional and represents a pointer
to user defined data. Without a variable factory each undefined variable will cause an undefined token error. Factory
functions can be used to query the values of newly created variables directly from a
database. If you emit errors from a factory function be sure to throw an exception of
type ParserBase::exception_type
all other exceptions will be caught internally
and result in an internal error.
mupSetVarFactory(hParser, AddVariable, pUserData);
See also: example2/example2.c.
parser.SetVarFactory(AddVariable, pUserData);
See also: example1/example1.cpp.
double
or string
. Constness
refers to the bytecode. Constants will be stored by their value in the bytecode, not by a reference to
their address. Thus accessing them is faster. They may be optimized away if this is possible.
Defining new constants or changing old ones will reset the parser to string parsing mode thus resetting
the bytecode.
0-9, a-z, A-Z, _
, and they may not start with a number. Violating this rule will raise a parser error.
// Define value constants _pi mupDefineConst(hParser, "_pi", (double)PARSER_CONST_PI); // Define a string constant named strBuf mupDefineStrConst("strBuf", "hello world");See also: example2/example2.c.
// Define value constant _pi parser.DefineConst("_pi", (double)PARSER_CONST_PI); // Define a string constant named strBuf parser.DefineStrConst("strBuf", "hello world");See also: example1/example1.cpp; src/muParserTest.cpp.
The parser allows the definition of a wide variety of different callback functions. Functions with a fixed number of up to ten numeric arguments, functions with a variable number of numeric arguments and functions taking a sinlge string argument plus up to two numeric values. In order to define a parser function you need to specify its name, a pointer to a static callback function and an optional flag indicating if the function is volatile. Volatile functions are functions that do not always return the same result for the same arguments. They can not be optimized.
The static callback functions must have of either one of the following types:
// For fixed number of arguments value_type (*fun_type1)(value_type); value_type (*fun_type2)(value_type, value_type); value_type (*fun_type3)(value_type, value_type, value_type); value_type (*fun_type4)(value_type, value_type, value_type, value_type); value_type (*fun_type5)(value_type, value_type, value_type, value_type, value_type); // ... and so on to up to 10 parameters // for a variable number of arguments // first arg: pointer to the arguments // second arg: number of arguments value_type (*multfun_type)(const value_type*, int); // for functions taking a single string plus up to two numeric values value_type (*strfun_type1)(const char_type*); value_type (*strfun_type2)(const char_type*, value_type); value_type (*strfun_type3)(const char_type*, value_type, value_type);
// Add functions taking string parameters that cant be optimized mupDefineStrFun1(hParser, "StrFun1", pStrCallback1, false); mupDefineStrFun2(hParser, "StrFun2", pStrCallback2, false); mupDefineStrFun3(hParser, "StrFun3", pStrCallback3, false); // Add an function with a fixed number of arguments mupDefineFun1(hParser, "fun1", pCallback1, false); mupDefineFun2(hParser, "fun2", pCallback2, false); mupDefineFun3(hParser, "fun3", pCallback3, false); mupDefineFun4(hParser, "fun4", pCallback4, false); mupDefineFun5(hParser, "fun5", pCallback5, false); // Define a function with variable number of arguments mupDefineMultFun(hParser, "MultFun", pMultCallback);See also: example2/example2.c.
parser.DefineFun("FunName", pCallback, false)See also: example1/example1.cpp; src/muParser.cpp; src/muParserInt.cpp.
a! = a*(a-1)...*2*1
). Another application for postfix operators is their use as multipliers
that can be used for implementing units."!(a<9)"
.fun_type1
like the following:
value_type MyCallback(value_type fVal) { return fVal/1000.0; }For defining postfix operators and infix operators you need a valid parser instance, an identifier string, and an optional third parameter marking the operator as volatile (non optimizable).
// Define an infix operator mupDefineInfixOprt(hParser, "!", MyCallback); // Define a postfix operators mupDefinePostfixOprt(hParser, "M", MyCallback);See also:example2/example2.c.
// Define an infix operator parser.DefineInfixOprt("!", MyCallback); // Define a postfix operators parser.DefinePostfixOprt("m", MyCallback);See also:example1/example1.cpp; src/muParserTest.cpp.
shl
or shr
, the "shift left" and "shift right" operators for integer numbers.
In order to add user defined operators you need to assign a name, a callback function of type fun_type2
and a priority for each new binary operator. You are not allowed to overload built in operators, this would result in an error being raised! For instance lets consider the
following callback function which should be assigned to a binary operator:
value_type MyAddFun(value_type v1, value_type v2) { return v1+v2; }For the definintion of binary operators you need at least 4 parameters. The first is a valid parser handle, the second is the identifier of the operator, the third is the operator callback function, the fourth is the operator priority and the optional fifth parameter is a flag of type
bool
marking the operator
as volatile. (The examples below omit the last flag.)
Having defined a proper operator callback function you can add the binary operator with the following code:
mupDefineOprt(hParser, "add", MyAddFun, 0);See also:example2/example2.c.
parser.DefineOprt("add", MyAddFun, 0);See also:example1/example1.cpp; src/muParserTest.cpp. The priority value must be greater or equal than zero (lowest possible priority). It controls the operator precedence in the formula. For instance if you want to calculate the formula
1+2*3^4
in a mathemetically correct sense you have to make sure that Addition has a lower priority than multiplication which in turn has a lower priority than the power operator. The most likely cases are that you assign an operator with a low priority of 0 (like and
, or
, xor
) or a high priority that is larger than 6. (The priority of the power operator (^
).)
By assigning Priority values already used by built in operators you might introduce unwanted side effects. To avoid this and make the order of calculation clear you must use brackets in these cases. Otherwise the order will be determined by the Formula parsing direction which is from left to right.
shl
equals priority of an addition; The order of the execution is from left to right.
1 + 2 shl 1 => (1 + 2) shl 1 2 shl 1 + 1 => (s shl 1) + 1Example B: Priority of
shl
is higher than the one of the addition; shl
is executed first.
1 + 2 shl 1 => 1 + (2 shl 1) 2 shl 1 + 1 => (2 shl 1) + 1If you encounter such conflicts or simply dont need the built in operators these can easily be deactivated using the
EnableBuiltInOprt(bool)
function. If you call this function you must add binary operators manually. After all without any operators you won't be able to parse anything useful. User defined operators come with approximately 10% decrease in parsing speed compared to built in operators. There is no way to avoid that. They cause an overhead when calling theeir callback functions. (This is the reason why there are built in operators)
// disable all built in operators parser.EnableBuiltInOprt(false);
mupGetVarNum(...)
with
mupGetExprVarNum(...)
and mupGetVar(...)
with mupGetExprVar(...)
in the following example. Due to the use of an temporary internal static buffer for storing the variable
name in the DLL version this DLL-function is not thread safe.
// Get the number of variables int iNumVar = mupGetVarNum(a_hParser); // Query the variables for (int i=0; i < iNumVar; ++i) { const char_type *szName = 0; double *pVar = 0; mupGetVar(a_hParser, i, &szName, &pVar); std::cout << "Name: " << szName << " Address: [0x" << pVar << "]\n"; }See also: example2/example2.c.
parser.GetVar()
with
parser.GetUsedVar()
in the following example.
// Get the map with the variables mu::Parser::varmap_type variables = parser.GetVar(); cout << "Number: " << (int)variables.size() << "\n"; // Get the number of variables mu::Parser::varmap_type::const_iterator item = variables.begin(); // Query the variables for (; item!=variables.end(); ++item) { cout << "Name: " << item->first << " Address: [0x" << item->second << "]\n"; }See also: example1/example1.cpp.
int iNumVar = mupGetConstNum(a_hParser); for (int i=0; i < iNumVar; ++i) { const char_type *szName = 0; double fVal = 0; mupGetConst(a_hParser, i, &szName, fVal); std::cout << " " << szName << " = " << fVal << "\n"; }See also: example2/example2.c.
GetConst()
member function that returns a map structure
with all defined constants. The following code snippet shows how to use it:
mu::Parser::valmap_type cmap = parser.GetConst(); if (cmap.size()) { mu::Parser::valmap_type::const_iterator item = cmap.begin(); for (; item!=cmap.end(); ++item) cout << " " << item->first << " = " << item->second << "\n"; }See also: example1/example1.cpp.
bool (*identfun_type)(const char_type*, int&, value_type&);
If the parser reaches an a position during string parsing that could host a value token it tries to interpret it as such. If that fails the parser sucessively calls all internal value recognition callbacks in order to give them a chance to make sense out of what has been found. If all of them fail the parser continues to check if it is a Variable or another kind of token.
In order to perform the task of value recognition these functions take a const char
pointer, a reference to int
and a reference
to double
as their arguments.
The const char
pointer points to the current formula position. The second
argument is the index of that position. This value must be increased by the length of the
value entry if one has been found. In that case the value must be written to the third
argument which is of type double
.
The next code snippet shows a sample implementation of a function that reads and
interprets binary values from the expression string. The code is taken from
muParserInt.cpp the implementation of a parser for integer numbers. Binary
numbers must be preceded with a #
(i.e. #1000101
).
bool ParserInt::IsBinVal(const char_type *a_szExpr, int &a_iPos, value_type &a_fVal) { if (a_szExpr[0]!='#') return false; unsigned iVal = 0, iBits = sizeof(iVal)*8; for (unsigned i=0; (a_szExpr[i+1]=='0'||a_szExpr[i+1]=='1')&& i<iBits; ++i) { iVal |= (int)(a_szExpr[i+1]=='1') << ((iBits-1)-i); } if (i==0) return false; if (i==iBits) throw exception_type("Binary to integer conversion error (overflow)."); a_fVal = (unsigned)(iVal >> (iBits-i) ); a_iPos += i+1; return true; }Once you have the callback you must add it to the parser. This can be done with:
mupAddValIdent(hParser, IsBinVal);
See also: example2/example2.c.
parser.AddValIdent(IsBinVal);
See also: ParserLib/muParserInt.cpp.
ClearVar
and
ClearConst
. Additionally variables can be removed by name using
RemoveVar
. Since the parser never owns the variables you must take care of
their release yourself (if they were dynamically allocated). If you need to browse all
the variables have a look at the chapter explaining how to
query parser variables.
// Remove all constants mupClearConst(hParser); // remove all variables mupClearVar(hParser); // remove a single variable by name mupRemoveVar(hParser, "a");See also: example2/example2.c
// Remove all constants parser.ClearConst(); // remove all variables parser.ClearVar(); // remove a single variable by name parser.RemoveVar("a");See also: example1/example1.cpp
mu::Parser::exception_type
and in the DLL
version they are normal functions.
These functions are:
exception.GetMsg() / mupGetErrorMsg()
- returns the error message.exception.GetExpr() / mupGetExpr()
- returns the current formula (if a formula is set)exception.GetToken() / mupGetErrorToken()
- returns the token associated with the error (if applicable)exception.GetPos() / mupGetErrorPos()
- returns the current formula position (if applicable)exception.GetCode() / mupGetErrorCode()
- returns the error code.
The following table lists the parser error codes.
The first column contains the enumeration values as defined in the enumeration mu::EErrorCodes
located in the file muParserError.h. Since they are only accessible from C++ the second column lists
their numeric code and the third column contains the error description.
Enumeration name | Value | Description |
ecUNEXPECTED_OPERATOR |
0 | Unexpected binary operator found |
ecUNASSIGNABLE_TOKEN |
1 | Token cant be identified |
ecUNEXPECTED_EOF |
2 | Unexpected end of formula. (Example: "2+sin(") |
ecUNEXPECTED_ARG_SEP |
3 | An unexpected argument separator has been found. (Example: "1,23") |
ecUNEXPECTED_ARG |
4 | An unexpected argument has been found |
ecUNEXPECTED_VAL |
5 | An unexpected value token has been found |
ecUNEXPECTED_VAR |
6 | An unexpected variable token has been found |
ecUNEXPECTED_PARENS |
7 | Unexpected parenthesis, opening or closing |
ecUNEXPECTED_STR |
8 | A string has been found at an inapropriate position |
ecSTRING_EXPECTED |
9 | A string function has been called with a different type of argument |
ecVAL_EXPECTED |
10 | A numerical function has been called with a non value type of argument |
ecMISSING_PARENS |
11 | Missing parens. (Example: "3*sin(3") |
ecUNEXPECTED_FUN |
12 | Unexpected function found. (Example: "sin(8)cos(9)") |
ecUNTERMINATED_STRING |
13 | unterminated string constant. (Example: "3*valueof("hello)") |
ecTOO_MANY_PARAMS |
14 | Too many function parameters |
ecTOO_FEW_PARAMS |
15 | Too few function parameters. (Example: "ite(1<2,2)") |
ecOPRT_TYPE_CONFLICT |
16 | binary operators may only be applied to value items of the same type |
ecSTR_RESULT |
17 | result is a string |
ecINVALID_NAME |
18 | Invalid function, variable or constant name. |
ecINVALID_BINOP_IDENT |
19 | Invalid binary operator identifier. |
ecINVALID_INFIX_IDENT |
20 | Invalid infix operator identifier. |
ecINVALID_POSTFIX_IDENT |
21 | Invalid postfix operator identifier. |
ecBUILTIN_OVERLOAD |
22 | Trying to overload builtin operator |
ecINVALID_FUN_PTR |
23 | Invalid callback function pointer |
ecINVALID_VAR_PTR |
24 | Invalid variable pointer |
ecEMPTY_EXPRESSION |
25 | The expression string is empty |
ecNAME_CONFLICT |
26 | Name conflict |
ecOPT_PRI |
27 | Invalid operator priority |
ecDOMAIN_ERROR |
28 | catch division by zero, sqrt(-1), log(0) (currently unused) |
ecDIV_BY_ZERO |
29 | Division by zero (currently unused) |
ecGENERIC |
30 | Error that does not fit any other code but is not an internal error |
ecLOCALE |
31 | Conflict with current locale |
ecUNEXPECTED_CONDITIONAL |
32 | Unexpected if then else operator |
ecMISSING_ELSE_CLAUSE |
33 | Missing else clause |
ecMISPLACED_COLON |
34 | Misplaced colon |
ecINTERNAL_ERROR |
35 | Internal error of any kind. |
mupError()
. Please note that by calling this function you will automatically reset the error flag!
// Callback function for errors void OnError() { cout << "Message: " << mupGetErrorMsg() << "\n"; cout << "Token: " << mupGetErrorToken() << "\n"; cout << "Position: " << mupGetErrorPos() << "\n"; cout << "Errc: " << mupGetErrorCode() << "\n"; } ... // Set a callback for error handling mupSetErrorHandler(OnError); // The next function could raise an error fVal = mupEval(hParser); // Test for the error flag if (!mupError()) cout << fVal << "\n";See also: example2/example2.c
Parser::exception_type
. This
class provides you with several member functions that allow querying the exact cause as well as
additional information for the error.
try { ... parser.Eval(); ... } catch(mu::Parser::exception_type &e) { cout << "Message: " << e.GetMsg() << "\n"; cout << "Formula: " << e.GetExpr() << "\n"; cout << "Token: " << e.GetToken() << "\n"; cout << "Position: " << e.GetPos() << "\n"; cout << "Errc: " << e.GetCode() << "\n"; }See also: example1/example1.cpp