Calculator.h revision 10447
1#ifndef __LIBUTIL_CALCULATOR_H__
2#define __LIBUTIL_CALCULATOR_H__
3
4#include <sstream>
5
6#include "String.h"
7#include "Map.h"
8#include "Assert.h"
9
10namespace LibUtil
11{
12    using std::istringstream;
13
14    /*
15     *  program:
16     *      END                         // END is end-of-input
17     *      expr_list END
18     *
19     *  expr_list:
20     *      expression SEP expr_list    // SEP is semicolon
21     *      expression
22     *      print expression
23     *      print STRING
24     *      print STRING expression
25     *      print STRING expression SEP expr_list
26     *
27     *
28     *  expression:
29     *      expression + term
30     *      expression - term
31     *      term
32     *
33     *  term:
34     *      term / primary
35     *      term * primary
36     *      primary
37     *
38     *  primary:
39     *      NUMBER
40     *      NAME
41     *      NAME = expression
42     *      NAME string expression      // NAME is print
43     *      - primary
44     *      ( expression )
45     *
46     *  string:
47     *
48     **/
49
50    class Calculator
51    {
52        protected:
53            enum Token
54            {
55                NAME, NAME2, NUMBER, STRING, END,
56                PLUS = '+', MINUS = '-', MUL = '*', DIV = '/',
57                SEP = ';', ASSIGN = '=', LP = '(', RP = ')'
58            };
59
60        public:
61            Calculator();
62            virtual ~Calculator();
63
64        public:
65            void reset();
66            void evaluateString(const String& str_);
67
68        protected:
69            Token getToken(istringstream& ist_);
70            double prim(istringstream& ist_, bool is_get_);
71            double term(istringstream& ist_, bool is_get_);
72            double expr(istringstream& ist_, bool is_get_);
73            virtual double getEnvVar(const String& var_name_) const;
74
75        protected:
76            String m_reserved_chars_;
77            Map<double> m_var_;
78
79            Token m_curr_token_;
80            double m_value_number_;
81            String m_value_string_;
82    }; // class Calculator
83} // namespace LibUtil
84
85#endif // __LIBUTIL_CALCULATOR_H__
86
87