IntroductionFeaturesBuild instructionsMath parser interfaceCurrent version |
The parser interfaceThe following section gives an overview of the public parser member functions as well as of the functions exported by the DLL version of the parser.Parser initialization / deinitialization[DLL interface]Create a new instance handle. You can create as many different instance handles as you like. Each will internally reference a different parser object. When using the DLL it is necessary to manually release any parser handle created bymupInit() by calling mupRelease(hParser) .
muParserHandle_t 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. [Parser class interface]Code for creating a new parser object. (In case of dynamic allocation usenew and delete
for initialization and deinitialization.)
mu::Parser parser;
Setting the expression[DLL interface]Setting the expression when using the DLL requires a valid parser handle and a pointer toconst char pointing to the expression.
mupSetExpr(hParser, szLine);
See also: example2/example2.c.
[Parser class interface]Setting the expression using the parser class requires astd::string containing the expression as the
only parameter.
parser.SetExpr(line);
See also: example1/example1.cpp; src/muParserTest.cpp.
Evaluating an expressionSingle return value
Expression evaluation is done by calling the
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, [DLL interface]double fVal; fVal = mupEval(hParser);See also: example2/example2.c. [Parser class interface]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 Multiple return valuesmuParser 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 [DLL interface]int nNum, i; muFloat_t *v = mupEvalMulti(hParser, &nNum); for (i=0; i<nNum; ++i) { printf("v[i]=%2.2f\n", v[i]); } [Parser class interface]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 Bulk mode evaluationsThe 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. [DLL interface]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); } Defining identifier character setsSometimes it is necessary to change the character sets that are used for token identifiers in order to avoid conflicts. The parser uses three different character sets.
mu::muParser directly you can skip this
section. (The DLL version uses the default implementation internally.)
[DLL interface]mupDefineNameChars(hParser, "0123456789_" "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ"); mupDefineOprtChars(hParser, "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "+-*^/?<>=#!$%&|~'_"); mupDefineInfixOprtChars(hParser, "/+-*^?<>=#!$%&|~'_"); [Parser class interface]parser.DefineNameChars("0123456789_" "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ"); parser.DefineOprtChars("abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "+-*^/?<>=#!$%&|~'_"); parser.DefineInfixOprtChars("/+-*^?<>=#!$%&|~'_");See also: ParserLib/muParser.cpp; ParserLib/muParserInt.cpp. Defining parser variablesCustom variables can be defined either explicit in the code by using theDefineVar 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.
Explicitely defining variablesExplicitely in this context means you have to do add the variables manually it in your application code. So you must know in advance which variables you intend to use. If this is not the case have a look at the section on Implicit creation of new variables.
[DLL interface]The first parameter is a valid parser handle, the second the variable name and the third a pointer to the associated C++ variable.double fVal=0; mupDefineVar(hParser, "a", &fVal);See also: example2/example2.c. [Parser class interface]The first parameter is the variable name and the second a pointer to the associated C++ variable.double fVal=0; parser.DefineVar("a", &fVal);See also: example1/example1.cpp; src/muParserTest.cpp. Implicit creation of new variablesImplicit declaration of new variables is only possible by setting a factory function. Implicit creation means that everytime the parser finds an unknown token at a position where a variable could be located it creates a new variable with that name automatically. The necessary factory function must be of type: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.
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.
[DLL interface]
mupSetVarFactory(hParser, AddVariable, pUserData);
See also: example2/example2.c.
[Parser class interface]
parser.SetVarFactory(AddVariable, pUserData);
See also: example1/example1.cpp.
Defining parser constantsParser constants can either be values of typedouble 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.
The Names of user defined constants may contain only the following characters: 0-9, a-z, A-Z, _ , and they may not start with a number. Violating this rule will raise a parser error.
[DLL interface]// 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. [Parser class interface]// 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. Querying parser variablesKeeping track of all variables can be a difficult task. For simplification the parser allows the user to query the variables defined in the parser. There are two different sets of variables that can be accessed:
[DLL interface]For querying the variables used in the expression exchangemupGetVarNum(...) 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 class interface]For querying the expression variables exchangeparser.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. Querying parser constantsQuerying parser constants is similar to querying variables and expression variables.[DLL interface]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.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. [Parser class interface]The parser class provides you with theGetConst() 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. Setting custom value recognition callbacksThe parser default implementation (muParser.cpp) scans expressions only for floating point values. Custom value recognition callbacks can be used in order to implement support for binary, hexadecimal or octal numbers. These functions are called during the string parsing and allow the user to scan portions of the original expressions for values. Their callback functions must be of the following type: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
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 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: [DLL interface]
mupAddValIdent(hParser, IsBinVal);
See also: example2/example2.c.
[Parser class interface]
parser.AddValIdent(IsBinVal);
See also: ParserLib/muParserInt.cpp.
Removing variables or constantsRemoving variables and constants can be done all at once usingClearVar 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.
[DLL interface]// Remove all constants mupClearConst(hParser); // remove all variables mupClearVar(hParser); // remove a single variable by name mupRemoveVar(hParser, "a");See also: example2/example2.c [Parser class interface]// Remove all constants parser.ClearConst(); // remove all variables parser.ClearVar(); // remove a single variable by name parser.RemoveVar("a");See also: example1/example1.cpp Error handlingIn case of an error both parser class and the parser DLL provide similar methods for querying the information associated with the error. In the parser class they are member functions of the associated exception classmu::Parser::exception_type and in the DLL
version they are normal functions.
These functions are:
The following table lists the parser error codes.
The first column contains the enumeration values as defined in the enumeration
[DLL interface]Since dynamic libraries with functions exported in C-style can't throw exceptions the DLL version provides the user with a callback mechanism to raise errors. Simply add a callback function that does the handling of errors. Additionally you can query the error flag withmupError() . 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 class interface]In case of an error the parser class raises an exception of typeParser::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
|