10 #ifndef smtk_common_ExpressionGrammarImpl_h
11 #define smtk_common_ExpressionGrammarImpl_h
19 #include "smtk/CoreExports.h"
24 #include <tao/pegtl.hpp>
25 #include <tao/pegtl/contrib/abnf.hpp>
26 #include <tao/pegtl/contrib/parse_tree.hpp>
28 #ifdef ERROR_INVALID_FUNCTION
29 #undef ERROR_INVALID_FUNCTION
37 namespace expression_internal
40 using namespace tao::pegtl;
49 : one< '+', '-', '*', '/', '^' >
53 : seq< abnf::ALPHA, star< sor< ranges< 'a', 'z', 'A', 'Z', '0', '9'>, one< '-', '_' > > > >
57 : seq< abnf::ALPHA, star < sor< ranges< 'a', 'z', 'A', 'Z', '0', '9' >, one< '-', '_' > > > >
67 : opt< one < '+', '-' > >
71 : seq< one < 'e', 'E'>, opt< sign >, must< digits > >
75 : if_must< one< '.' >, opt< digits > >
79 : seq< sign, digits, opt< frac >, opt< exp > >
85 : if_must< function_name, star< ignored >, one< '(' >, star< ignored >, expression, star< ignored >, one< ')' > >
89 : if_must< one< '(' >, expression, one< ')' > >
93 : if_must< one< '{' >, symbol, one< '}' > >
97 : sor< number, paren, infix_function, subsymbol_reference >
101 : list< atomic, infix_operator, ignored >
105 must< star< ignored >, expression, star< ignored >, eof >
113 template<
typename Rule>
121 template<
typename ActionInput>
123 const ActionInput& in,
127 const SubsymbolVisitor& ,
128 InfixExpressionError& )
130 std::stringstream ss(in.string());
140 template<
typename ActionInput>
142 const ActionInput& in,
146 const SubsymbolVisitor& ,
147 InfixExpressionError& err)
149 std::string str = in.string();
150 const std::map<std::string, InfixOperator>::const_iterator it = b.ops().find(str);
151 if (it != b.ops().end())
159 err = InfixExpressionError::ERROR_UNKNOWN_OPERATOR;
160 throw parse_error(
"Invalid operator.", in);
168 template<
typename ActionInput>
170 const ActionInput& in,
174 const SubsymbolVisitor& ,
175 InfixExpressionError& err)
177 std::string str = in.string();
178 std::size_t openingParenIdx = str.find_first_of(
'(');
179 std::string functionName = str.substr(0, openingParenIdx);
181 const std::map<std::string, InfixFunction>::const_iterator it =
182 funcs.funcs().find(functionName);
183 if (it != funcs.funcs().end())
185 s.setFunctionForNextOpen(it->second.f);
189 err = InfixExpressionError::ERROR_UNKNOWN_FUNCTION;
190 throw parse_error(
"Invalid function.", in);
198 template<
typename ActionInput>
200 const ActionInput& in,
204 const SubsymbolVisitor& subFunc,
205 InfixExpressionError& err)
207 std::string str = in.string();
211 std::pair<double, bool> result = subFunc(str.substr(1, str.size() - 2));
215 if (!result.second || std::isnan(result.first) || std::isinf(result.first))
217 err = InfixExpressionError::ERROR_SUBEVALUATION_FAILED;
218 throw parse_error(
"Subexpression could not be evaluated.", in);
222 s.push(result.first);
234 const SubsymbolVisitor& ,
235 InfixExpressionError& )
248 const SubsymbolVisitor& ,
249 InfixExpressionError& )
260 #endif // smtk_common_ExpressionGrammarImpl_h