muParser API -  1.35
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
muParserBase.h
Go to the documentation of this file.
1 /*
2  __________
3  _____ __ __\______ \_____ _______ ______ ____ _______
4  / \ | | \| ___/\__ \ \_ __ \/ ___/_/ __ \\_ __ \
5  | Y Y \| | /| | / __ \_| | \/\___ \ \ ___/ | | \/
6  |__|_| /|____/ |____| (____ /|__| /____ > \___ >|__|
7  \/ \/ \/ \/
8  Copyright (C) 2013 Ingo Berg
9 
10  Permission is hereby granted, free of charge, to any person obtaining a copy of this
11  software and associated documentation files (the "Software"), to deal in the Software
12  without restriction, including without limitation the rights to use, copy, modify,
13  merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
14  permit persons to whom the Software is furnished to do so, subject to the following conditions:
15 
16  The above copyright notice and this permission notice shall be included in all copies or
17  substantial portions of the Software.
18 
19  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
20  NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
22  DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24 */
25 #ifndef MU_PARSER_BASE_H
26 #define MU_PARSER_BASE_H
27 
28 //--- Standard includes ------------------------------------------------------------------------
29 #include <cmath>
30 #include <string>
31 #include <iostream>
32 #include <map>
33 #include <memory>
34 #include <locale>
35 #include <limits.h>
36 
37 //--- Parser includes --------------------------------------------------------------------------
38 #include "muParserDef.h"
39 #include "muParserStack.h"
40 #include "muParserTokenReader.h"
41 #include "muParserBytecode.h"
42 #include "muParserError.h"
43 
44 
45 namespace mu
46 {
47 /** \file
48  \brief This file contains the class definition of the muparser engine.
49 */
50 
51 //--------------------------------------------------------------------------------------------------
52 /** \brief Mathematical expressions parser (base parser engine).
53  \author (C) 2013 Ingo Berg
54 
55  This is the implementation of a bytecode based mathematical expressions parser.
56  The formula will be parsed from string and converted into a bytecode.
57  Future calculations will be done with the bytecode instead the formula string
58  resulting in a significant performance increase.
59  Complementary to a set of internally implemented functions the parser is able to handle
60  user defined functions and variables.
61 */
62 class ParserBase
63 {
64 friend class ParserTokenReader;
65 
66 private:
67 
68  /** \brief Typedef for the parse functions.
69 
70  The parse function do the actual work. The parser exchanges
71  the function pointer to the parser function depending on
72  which state it is in. (i.e. bytecode parser vs. string parser)
73  */
74  typedef value_type (ParserBase::*ParseFunction)() const;
75 
76  /** \brief Type used for storing an array of values. */
77  typedef std::vector<value_type> valbuf_type;
78 
79  /** \brief Type for a vector of strings. */
80  typedef std::vector<string_type> stringbuf_type;
81 
82  /** \brief Typedef for the token reader. */
84 
85  /** \brief Type used for parser tokens. */
87 
88  /** \brief Maximum number of threads spawned by OpenMP when using the bulk mode. */
89  static const int s_MaxNumOpenMPThreads = 16;
90 
91  public:
92 
93  /** \brief Type of the error class.
94 
95  Included for backwards compatibility.
96  */
98 
99  static void EnableDebugDump(bool bDumpCmd, bool bDumpStack);
100 
101  ParserBase();
102  ParserBase(const ParserBase &a_Parser);
103  ParserBase& operator=(const ParserBase &a_Parser);
104 
105  virtual ~ParserBase();
106 
107  value_type Eval() const;
108  value_type* Eval(int &nStackSize) const;
109  void Eval(value_type *results, int nBulkSize);
110 
111  int GetNumResults() const;
112 
113  void SetExpr(const string_type &a_sExpr);
114  void SetVarFactory(facfun_type a_pFactory, void *pUserData = NULL);
115 
116  void SetDecSep(char_type cDecSep);
117  void SetThousandsSep(char_type cThousandsSep = 0);
118  void ResetLocale();
119 
120  void EnableOptimizer(bool a_bIsOn=true);
121  void EnableBuiltInOprt(bool a_bIsOn=true);
122 
123  bool HasBuiltInOprt() const;
124  void AddValIdent(identfun_type a_pCallback);
125 
126  /** \fn void mu::ParserBase::DefineFun(const string_type &a_strName, fun_type0 a_pFun, bool a_bAllowOpt = true)
127  \brief Define a parser function without arguments.
128  \param a_strName Name of the function
129  \param a_pFun Pointer to the callback function
130  \param a_bAllowOpt A flag indicating this function may be optimized
131  */
132  template<typename T>
133  void DefineFun(const string_type &a_strName, T a_pFun, bool a_bAllowOpt = true)
134  {
135  AddCallback( a_strName, ParserCallback(a_pFun, a_bAllowOpt), m_FunDef, ValidNameChars() );
136  }
137 
138  void DefineOprt(const string_type &a_strName,
139  fun_type2 a_pFun,
140  unsigned a_iPri=0,
141  EOprtAssociativity a_eAssociativity = oaLEFT,
142  bool a_bAllowOpt = false);
143  void DefineConst(const string_type &a_sName, value_type a_fVal);
144  void DefineStrConst(const string_type &a_sName, const string_type &a_strVal);
145  void DefineVar(const string_type &a_sName, value_type *a_fVar);
146  void DefinePostfixOprt(const string_type &a_strFun, fun_type1 a_pOprt, bool a_bAllowOpt=true);
147  void DefineInfixOprt(const string_type &a_strName, fun_type1 a_pOprt, int a_iPrec=prINFIX, bool a_bAllowOpt=true);
148 
149  // Clear user defined variables, constants or functions
150  void ClearVar();
151  void ClearFun();
152  void ClearConst();
153  void ClearInfixOprt();
154  void ClearPostfixOprt();
155  void ClearOprt();
156 
157  void RemoveVar(const string_type &a_strVarName);
158  const varmap_type& GetUsedVar() const;
159  const varmap_type& GetVar() const;
160  const valmap_type& GetConst() const;
161  const string_type& GetExpr() const;
162  const funmap_type& GetFunDef() const;
163  string_type GetVersion(EParserVersionInfo eInfo = pviFULL) const;
164 
165  const char_type ** GetOprtDef() const;
166  void DefineNameChars(const char_type *a_szCharset);
167  void DefineOprtChars(const char_type *a_szCharset);
168  void DefineInfixOprtChars(const char_type *a_szCharset);
169 
170  const char_type* ValidNameChars() const;
171  const char_type* ValidOprtChars() const;
172  const char_type* ValidInfixOprtChars() const;
173 
174  void SetArgSep(char_type cArgSep);
175  char_type GetArgSep() const;
176 
177  void Error(EErrorCodes a_iErrc,
178  int a_iPos = (int)mu::string_type::npos,
179  const string_type &a_strTok = string_type() ) const;
180 
181  protected:
182 
183  void Init();
184 
185  virtual void InitCharSets() = 0;
186  virtual void InitFun() = 0;
187  virtual void InitConst() = 0;
188  virtual void InitOprt() = 0;
189 
190  virtual void OnDetectVar(string_type *pExpr, int &nStart, int &nEnd);
191 
192  static const char_type *c_DefaultOprt[];
193  static std::locale s_locale; ///< The locale used by the parser
194  static bool g_DbgDumpCmdCode;
195  static bool g_DbgDumpStack;
196 
197  /** \brief A facet class used to change decimal and thousands separator. */
198  template<class TChar>
199  class change_dec_sep : public std::numpunct<TChar>
200  {
201  public:
202 
203  explicit change_dec_sep(char_type cDecSep, char_type cThousandsSep = 0, int nGroup = 3)
204  :std::numpunct<TChar>()
205  ,m_nGroup(nGroup)
206  ,m_cDecPoint(cDecSep)
207  ,m_cThousandsSep(cThousandsSep)
208  {}
209 
210  protected:
211 
212  virtual char_type do_decimal_point() const
213  {
214  return m_cDecPoint;
215  }
216 
217  virtual char_type do_thousands_sep() const
218  {
219  return m_cThousandsSep;
220  }
221 
222  virtual std::string do_grouping() const
223  {
224  // fix for issue 4: https://code.google.com/p/muparser/issues/detail?id=4
225  // courtesy of Jens Bartsch
226  // original code:
227  // return std::string(1, (char)m_nGroup);
228  // new code:
229  return std::string(1, (char)(m_cThousandsSep > 0 ? m_nGroup : CHAR_MAX));
230  }
231 
232  private:
233 
234  int m_nGroup;
235  char_type m_cDecPoint;
236  char_type m_cThousandsSep;
237  };
238 
239  private:
240 
241  void Assign(const ParserBase &a_Parser);
242  void InitTokenReader();
243  void ReInit() const;
244 
245  void AddCallback( const string_type &a_strName,
246  const ParserCallback &a_Callback,
247  funmap_type &a_Storage,
248  const char_type *a_szCharSet );
249 
250  void ApplyRemainingOprt(ParserStack<token_type> &a_stOpt,
251  ParserStack<token_type> &a_stVal) const;
252  void ApplyBinOprt(ParserStack<token_type> &a_stOpt,
253  ParserStack<token_type> &a_stVal) const;
254 
255  void ApplyIfElse(ParserStack<token_type> &a_stOpt,
256  ParserStack<token_type> &a_stVal) const;
257 
258  void ApplyFunc(ParserStack<token_type> &a_stOpt,
259  ParserStack<token_type> &a_stVal,
260  int iArgCount) const;
261 
262  token_type ApplyStrFunc(const token_type &a_FunTok,
263  const std::vector<token_type> &a_vArg) const;
264 
265  int GetOprtPrecedence(const token_type &a_Tok) const;
266  EOprtAssociativity GetOprtAssociativity(const token_type &a_Tok) const;
267 
268  void CreateRPN() const;
269 
270  value_type ParseString() const;
271  value_type ParseCmdCode() const;
272  value_type ParseCmdCodeBulk(int nOffset, int nThreadID) const;
273 
274  void CheckName(const string_type &a_strName, const string_type &a_CharSet) const;
275  void CheckOprt(const string_type &a_sName,
276  const ParserCallback &a_Callback,
277  const string_type &a_szCharSet) const;
278 
279  void StackDump(const ParserStack<token_type > &a_stVal,
280  const ParserStack<token_type > &a_stOprt) const;
281 
282  /** \brief Pointer to the parser function.
283 
284  Eval() calls the function whose address is stored there.
285  */
286  mutable ParseFunction m_pParseFormula;
287  mutable ParserByteCode m_vRPN; ///< The Bytecode class.
288  mutable stringbuf_type m_vStringBuf; ///< String buffer, used for storing string function arguments
289  stringbuf_type m_vStringVarBuf;
290 
291  std::auto_ptr<token_reader_type> m_pTokenReader; ///< Managed pointer to the token reader object.
292 
293  funmap_type m_FunDef; ///< Map of function names and pointers.
294  funmap_type m_PostOprtDef; ///< Postfix operator callbacks
295  funmap_type m_InfixOprtDef; ///< unary infix operator.
296  funmap_type m_OprtDef; ///< Binary operator callbacks
297  valmap_type m_ConstDef; ///< user constants.
298  strmap_type m_StrVarDef; ///< user defined string constants
299  varmap_type m_VarDef; ///< user defind variables.
300 
301  bool m_bBuiltInOp; ///< Flag that can be used for switching built in operators on and off
302 
303  string_type m_sNameChars; ///< Charset for names
304  string_type m_sOprtChars; ///< Charset for postfix/ binary operator tokens
305  string_type m_sInfixOprtChars; ///< Charset for infix operator tokens
306 
307  mutable int m_nIfElseCounter; ///< Internal counter for keeping track of nested if-then-else clauses
308 
309  // items merely used for caching state information
310  mutable valbuf_type m_vStackBuffer; ///< This is merely a buffer used for the stack in the cmd parsing routine
311  mutable int m_nFinalResultIdx;
312 };
313 
314 } // namespace mu
315 
316 #endif
317 
void DefinePostfixOprt(const string_type &a_strFun, fun_type1 a_pOprt, bool a_bAllowOpt=true)
Add a user defined operator.
void DefineInfixOprtChars(const char_type *a_szCharset)
Define the set of valid characters to be used in names of infix operators.
Definition of the parser bytecode class.
void DefineNameChars(const char_type *a_szCharset)
Define the set of valid characters to be used in names of functions, variables, constants.
void DefineVar(const string_type &a_sName, value_type *a_fVar)
Add a user defined variable.
const funmap_type & GetFunDef() const
Return prototypes of all parser functions.
static std::locale s_locale
The locale used by the parser.
Definition: muParserBase.h:193
std::map< string_type, std::size_t > strmap_type
Type for assigning a string name to an index in the internal string table.
Definition: muParserDef.h:275
std::map< string_type, value_type * > varmap_type
Type used for storing variables.
Definition: muParserDef.h:269
static const char_type * c_DefaultOprt[]
Identifiers for built in binary operators.
Definition: muParserBase.h:192
void ClearConst()
Clear all user defined constants.
const char_type * ValidInfixOprtChars() const
Virtual function that defines the characters allowed in infix operator definitions.
void ClearOprt()
Clear all user defined binary operators.
void SetArgSep(char_type cArgSep)
Set argument separator.
const char_type * ValidOprtChars() const
Virtual function that defines the characters allowed in operator definitions.
void AddValIdent(identfun_type a_pCallback)
Add a value parsing function.
void SetDecSep(char_type cDecSep)
Set the decimal separator.
value_type Eval() const
Calculate the result.
Parser stack implementation.
Definition: muParserStack.h:53
bool HasBuiltInOprt() const
Query status of built in variables.
void ResetLocale()
Resets the locale.
std::map< string_type, ParserCallback > funmap_type
Container for Callback objects.
void ClearVar()
Clear all user defined variables.
void EnableOptimizer(bool a_bIsOn=true)
Enable or disable the formula optimization feature.
void DefineInfixOprt(const string_type &a_strName, fun_type1 a_pOprt, int a_iPrec=prINFIX, bool a_bAllowOpt=true)
Add a user defined operator.
void Error(EErrorCodes a_iErrc, int a_iPos=(int) mu::string_type::npos, const string_type &a_strTok=string_type()) const
Create an error containing the parse error position.
void SetVarFactory(facfun_type a_pFactory, void *pUserData=NULL)
Set a function that can create variable pointer for unknown expression variables. ...
const string_type & GetExpr() const
Retrieve the formula.
EOprtAssociativity
Parser operator precedence values.
Definition: muParserDef.h:215
void DefineOprtChars(const char_type *a_szCharset)
Define the set of valid characters to be used in names of binary operators and postfix operators...
const char_type * ValidNameChars() const
Virtual function that defines the characters allowed in name identifiers.
This file contains the parser token reader definition.
void SetThousandsSep(char_type cThousandsSep=0)
Sets the thousands operator.
std::map< string_type, value_type > valmap_type
Type used for storing constants.
Definition: muParserDef.h:272
void ClearPostfixOprt()
Clear all user defined postfix operators.
const valmap_type & GetConst() const
Return a map containing all parser constants.
void DefineFun(const string_type &a_strName, T a_pFun, bool a_bAllowOpt=true)
Define a parser function without arguments.
Definition: muParserBase.h:133
void DefineOprt(const string_type &a_strName, fun_type2 a_pFun, unsigned a_iPri=0, EOprtAssociativity a_eAssociativity=oaLEFT, bool a_bAllowOpt=false)
Define a binary operator.
Error class of the parser.
const varmap_type & GetVar() const
Return a map containing the used variables only.
MUP_BASETYPE value_type
The numeric datatype used by the parser.
Definition: muParserDef.h:247
A facet class used to change decimal and thousands separator.
Definition: muParserBase.h:199
void SetExpr(const string_type &a_sExpr)
Set the formula.
static void EnableDebugDump(bool bDumpCmd, bool bDumpStack)
Enable the dumping of bytecode and stack content on the console.
Namespace for mathematical applications.
Definition: muParser.cpp:49
string_type GetVersion(EParserVersionInfo eInfo=pviFULL) const
Returns the version of muparser.
void RemoveVar(const string_type &a_strVarName)
Remove a variable from internal storage.
const char_type ** GetOprtDef() const
Get the default symbols used for the built in operators.
This file defines the stack used by muparser.
string_type::value_type char_type
The character type used by the parser.
Definition: muParserDef.h:259
Token reader for the ParserBase class.
ParserBase & operator=(const ParserBase &a_Parser)
Assignment operator.
void DefineConst(const string_type &a_sName, value_type a_fVal)
Add a user defined constant.
void EnableBuiltInOprt(bool a_bIsOn=true)
Enable or disable the built in binary operators.
Bytecode implementation of the Math Parser.
MUP_STRING_TYPE string_type
The stringtype used by the parser.
Definition: muParserDef.h:253
ParserBase()
Constructor.
value_type(* fun_type1)(value_type)
Callback type used for functions with a single arguments.
Definition: muParserDef.h:286
ParserError exception_type
Type of the error class.
Definition: muParserBase.h:97
int(* identfun_type)(const char_type *sExpr, int *nPos, value_type *fVal)
Callback used for functions that identify values in a string.
Definition: muParserDef.h:361
void ClearFun()
Clear all functions.
void DefineStrConst(const string_type &a_sName, const string_type &a_strVal)
Define a new string constant.
char_type GetArgSep() const
Get the argument separator character.
value_type *(* facfun_type)(const char_type *, void *)
Callback used for variable creation factory functions.
Definition: muParserDef.h:364
value_type(* fun_type2)(value_type, value_type)
Callback type used for functions with two arguments.
Definition: muParserDef.h:289
EErrorCodes
Error codes.
Definition: muParserError.h:46
int GetNumResults() const
Return the number of results on the calculation stack.
void Init()
Initialize user defined functions.
Encapsulation of prototypes for a numerical parser function.
void ClearInfixOprt()
Clear the user defined Prefix operators.
Signs have a higher priority than ADD_SUB, but lower than power operator.
Definition: muParserDef.h:236
Mathematical expressions parser (base parser engine).
Definition: muParserBase.h:62
const varmap_type & GetUsedVar() const
Return a map containing the used variables only.
This file defines the error class used by the parser.
This file contains standard definitions used by the parser.