From e3a1789b3fa238c82f404222e84ac8a7a551af2c Mon Sep 17 00:00:00 2001 From: Paul Beckingham Date: Sun, 27 Apr 2014 10:07:11 -0700 Subject: [PATCH] Eval - Added support for compiled expressions that are compiled once and evaluated multiple times in different contexts. --- src/Eval.cpp | 35 +++++++++++++++++++++++++++++++++++ src/Eval.h | 3 +++ 2 files changed, 38 insertions(+) diff --git a/src/Eval.cpp b/src/Eval.cpp index 67fa6c8cc..a6e46c1a5 100644 --- a/src/Eval.cpp +++ b/src/Eval.cpp @@ -159,6 +159,41 @@ void Eval::evaluatePostfixExpression (const std::string& e, Variant& v) const evaluatePostfixStack (tokens, v); } +//////////////////////////////////////////////////////////////////////////////// +void Eval::compileExpression (const std::string& e) +{ + // Reduce e to a vector of tokens. + Lexer l (e); + l.ambiguity (_ambiguity); + std::string token; + Lexer::Type type; + while (l.token (token, type)) + { + _compiled.push_back (std::pair (token, type)); + if (_debug) + std::cout << "# token postfix '" << token << "' " << Lexer::type_name (type) << "\n"; + } + + // Parse for syntax checking and operator replacement. + infixParse (_compiled); + if (_debug) + { + std::vector >::iterator i; + for (i = _compiled.begin (); i != _compiled.end (); ++i) + std::cout << "# token infix '" << i->first << "' " << Lexer::type_name (i->second) << "\n"; + } + + // Convert infix --> postfix. + infixToPostfix (_compiled); +} + +//////////////////////////////////////////////////////////////////////////////// +void Eval::evaluateCompiledExpression (Variant& v) +{ + // Call the postfix evaluator. + evaluatePostfixStack (_compiled, v); +} + //////////////////////////////////////////////////////////////////////////////// void Eval::ambiguity (bool value) { diff --git a/src/Eval.h b/src/Eval.h index 11219894b..dbbb02c0e 100644 --- a/src/Eval.h +++ b/src/Eval.h @@ -44,6 +44,8 @@ public: void addSource (bool (*fn)(const std::string&, Variant&)); void evaluateInfixExpression (const std::string&, Variant&) const; void evaluatePostfixExpression (const std::string&, Variant&) const; + void compileExpression (const std::string&); + void evaluateCompiledExpression (Variant&); void ambiguity (bool); void debug (); @@ -69,6 +71,7 @@ private: std::vector _sources; bool _ambiguity; bool _debug; + std::vector > _compiled; };