-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexprparser.cpp
126 lines (107 loc) · 2.05 KB
/
exprparser.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#include <QDebug>
#include "exprparser.h"
ExprParser::ExprParser(): str(), raw(nullptr) {}
void ExprParser::setSourceString(QString string)
{
str = string.toStdString();
raw = str.c_str();
}
char ExprParser::peek()
{
return *raw;
}
char ExprParser::get()
{
return *raw++;
}
bool ExprParser::isNum()
{
return (peek() >= '0' && peek() <= '9') || peek() == '.';
}
bool ExprParser::isAlpha()
{
return (peek() >= 'a' && peek() <= 'z')
|| (peek() >= 'A' && peek() <= 'Z')
|| peek() == '_';
}
double ExprParser::number()
{
QString buf;
while (isNum())
{
buf.append(get());
}
return buf.toDouble();
}
double ExprParser::var()
{
QString buf;
while (isAlpha())
{
buf.append(get());
}
while (isAlpha() || isNum())
{
buf.append(get());
}
qDebug() << "var" << buf;
// try for a function
if (peek() == '(')
{
qDebug() << "Func" << buf;
QList<double> args{};
args.append(expr());
while (peek() == ',')
{
get();
args.append(expr());
}
qDebug() << "Getting func" << buf;
return getFunc(buf, args);
}
return getVar(buf);
}
double ExprParser::factor()
{
if (isNum())
return number();
else if (isAlpha())
{
qDebug() << "Var!";
return var();
}
else if (peek() == '(')
{
get(); // (
double result = expr();
if (get() != ')')
throw ParsingError{};
return result;
}
else if (peek() == '-')
{
get();
return -expr();
}
return 0.0;
}
double ExprParser::term()
{
double res = factor();
while (peek() == '*' || peek() == '/')
if (get() == '*')
res *= factor();
else
res /= factor();
return res;
}
double ExprParser::expr()
{
double res = term();
while (peek() == '+' || peek() == '-')
if (get() == '+')
res += term();
else
res -= term();
return res;
}