From c208b397b798910df4ad129fb13d562b4450034e Mon Sep 17 00:00:00 2001 From: Mike Buland Date: Mon, 19 Feb 2007 05:15:23 +0000 Subject: The formula system works just fine, just no functions yet, but I don't need them for quite a while. --- src/formula.h | 59 +++++++++++++++++++++++++++++++++++++---------------------- 1 file changed, 37 insertions(+), 22 deletions(-) (limited to 'src/formula.h') diff --git a/src/formula.h b/src/formula.h index 1eccd36..939eb09 100644 --- a/src/formula.h +++ b/src/formula.h @@ -3,15 +3,19 @@ #include +#include #include #include "sbuffer.h" #include "exceptionbase.h" +#include "hash.h" subExceptionDecl( ParseException ); /** - * + * Implements a very simple formula parser that allows use of variables and + * custom functions. This is based on a simple calculator-type parser that + * executes as it processes, accounting for operator precedence and grouping. */ class Formula { @@ -19,7 +23,29 @@ public: Formula(); virtual ~Formula(); - double run( const char *sFormula ); + double run( char *sFormula ); + + typedef Hash varHash; + varHash hVars; + + typedef struct Func + { + double operator()( double x ) + { + return 0.0; + } + } Func; + + typedef Hash funcHash; + funcHash hFunc; + + typedef struct FuncSin : Func + { + double operator()( double x ) + { + return sin( x ); + } + } FuncSin; private: enum @@ -32,31 +58,20 @@ private: symOpenParen, symCloseParen, symNumber, - symVariable + symVariable, + symExponent, + symModulus }; - typedef struct Token - { - Token() {} - Token( uint8_t nSym ) : nSym( nSym ) { } - Token( uint8_t nSym, double dNum ) : nSym( nSym ) { val.num = dNum; } - uint8_t nSym; - union - { - double num; - } val; - } Token; + typedef uint8_t symType; - std::stack sToken; - Token tLook; - int nState; - SBuffer sBuf; + std::stack sOper; + std::stack sValue; private: - void push(); - void state(); - Token nextToken(); - void printToken( Token &tok ); + symType getPrec( symType nOper ); + symType nextToken( char **sBuf ); + void reduce( bool bCloseParen = false ); }; #endif -- cgit v1.2.3