blob: 7cc1804a063a9d986c8ed786535220cf87333af6 (
plain)
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
|
#include "formula.h"
subExceptionDef( ParseException );
Formula::Formula()
{
}
Formula::~Formula()
{
}
double Formula::run( const char *sFormula )
{
sBuf.write( sFormula, strlen( sFormula ) );
sBuf.setPos( 0 );
nState = 0;
for(;;)
{
tLook = nextToken();
if( tLook.nSym == symEOS )
break;
state();
}
printf("\n");
return 0.0;
}
void Formula::state()
{
switch( nState )
{
case 0: // initial expr
switch( tLook.nSym )
{
case symNumber:
push();
nState = 1;
break;
}
break;
case 1: // binary operator
switch( tLook.nSym )
{
case symAdd:
case symSubtract:
push();
nState = 2;
break;
case symMultiply:
case symDivide:
push();
nState = 3;
break;
}
break;
case 2: // add/subtract
break;
}
}
void Formula::push()
{
printToken( tLook );
sToken.push( tLook );
}
Formula::Token Formula::nextToken()
{
char cbuf;
for(;;)
{
if( sBuf.isEOS() )
return Token( symEOS );
sBuf.read( &cbuf, 1 );
switch( cbuf )
{
case '+':
return Token( symAdd );
case '-':
return Token( symSubtract );
case '*':
return Token( symMultiply );
case '/':
return Token( symDivide );
case '(':
return Token( symOpenParen );
case ')':
return Token( symCloseParen );
case ' ':
case '\t':
case '\n':
case '\r':
break;
default:
if( cbuf == '.' || (cbuf >= '0' && cbuf <= '9') )
{
char num[50];
int nPos = 0;
bool bDot = false;
for(;;)
{
num[nPos++] = cbuf;
if( cbuf == '.' )
{
if( bDot == false )
bDot = true;
else
throw ParseException(
"Numbers cannot have more than one "
". in them."
);
}
sBuf.read( &cbuf, 1 );
if( (cbuf != '.' && (cbuf < '0' || cbuf > '9')) ||
sBuf.isEOS() )
{
if( !sBuf.isEOS() ) sBuf.seek( -1 );
num[nPos] = '\0';
return Token( symNumber, strtod( num, NULL ) );
}
}
}
break;
}
}
}
void Formula::printToken( Token &tok )
{
switch( tok.nSym )
{
case symEOS: printf("[EOS] "); break;
case symAdd: printf("+ "); break;
case symSubtract: printf("- "); break;
case symMultiply: printf("* "); break;
case symDivide: printf("/ "); break;
case symOpenParen: printf("( "); break;
case symCloseParen: printf(") "); break;
case symNumber: printf("%f ", tok.val.num ); break;
default: printf("??? "); break;
}
}
|