-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMiniParser.cpp
More file actions
603 lines (531 loc) · 15.1 KB
/
MiniParser.cpp
File metadata and controls
603 lines (531 loc) · 15.1 KB
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
#include "MiniParser.hpp"
/*
Version History:
- 2006-04-08
initial release
- 2006-12-09:
added math functions (sin, cos, log, ln, exp, sqrt) and constants (PI)
improved error handling (removed an infinite loop)
- 2007-04-23:
made the grammar left associative to match natural arithmetic and C
*/
#include <iostream>
#include <sstream>
#include <map>
#include <cmath>
#include <cassert>
namespace
{
typedef MiniParserNode Node ;
// This is it!
Node* Parse( const std::string& str ) ;
}
class MiniParserNode
{
public:
typedef MiniParser::IDMap IDMap ;
typedef MiniParser::real real ;
static MiniParserNode* FromString( const std::string& str )
{
return Parse( str ) ;
}
virtual ~MiniParserNode() {}
virtual real eval( const IDMap& ids ) const = 0 ;
};
namespace
{
typedef MiniParserNode::real real ;
class NodeConstantValue : public Node
{
public:
NodeConstantValue( real val ) : mVal( val ) {}
real eval( const IDMap& ids ) const
{
return mVal ;
}
private:
real mVal ;
};
class NodeVariableValue : public Node
{
public:
NodeVariableValue( const std::string& var ) : mVar( var ) {}
real eval( const IDMap& ids ) const
{
IDMap::const_iterator var = ids.find( mVar ) ;
if( ids.end() == var )
{
std::cerr << "unknown variable: " << mVar << std::endl ;
return 0. ;
}
return var->second ;
}
private:
const std::string mVar ;
};
class NodePlus : public Node
{
public:
NodePlus( Node* lhs, Node* rhs ) : mLHS( lhs ), mRHS( rhs ) { assert( lhs && rhs ) ; }
~NodePlus() { delete mLHS ; delete mRHS ; }
real eval( const IDMap& ids ) const
{
return mLHS->eval( ids ) + mRHS->eval( ids ) ;
}
private:
Node* mLHS ;
Node* mRHS ;
};
class NodeMinus : public Node
{
public:
NodeMinus( Node* lhs, Node* rhs ) : mLHS( lhs ), mRHS( rhs ) { assert( lhs && rhs ) ; }
~NodeMinus() { delete mLHS ; delete mRHS ; }
real eval( const IDMap& ids ) const
{
return mLHS->eval( ids ) - mRHS->eval( ids ) ;
}
private:
Node* mLHS ;
Node* mRHS ;
};
class NodeTimes : public Node
{
public:
NodeTimes( Node* lhs, Node* rhs ) : mLHS( lhs ), mRHS( rhs ) { assert( lhs && rhs ) ; }
~NodeTimes() { delete mLHS ; delete mRHS ; }
real eval( const IDMap& ids ) const
{
return mLHS->eval( ids ) * mRHS->eval( ids ) ;
}
private:
Node* mLHS ;
Node* mRHS ;
};
class NodeDividedBy : public Node
{
public:
NodeDividedBy( Node* lhs, Node* rhs ) : mLHS( lhs ), mRHS( rhs ) { assert( lhs && rhs ) ; }
~NodeDividedBy() { delete mLHS ; delete mRHS ; }
real eval( const IDMap& ids ) const
{
return mLHS->eval( ids ) / mRHS->eval( ids ) ;
}
private:
Node* mLHS ;
Node* mRHS ;
};
class NodeModulus : public Node
{
public:
NodeModulus( Node* lhs, Node* rhs ) : mLHS( lhs ), mRHS( rhs ) { assert( lhs && rhs ) ; }
~NodeModulus() { delete mLHS ; delete mRHS ; }
real eval( const IDMap& ids ) const
{
return fmod( mLHS->eval( ids ), mRHS->eval( ids ) ) ;
}
private:
Node* mLHS ;
Node* mRHS ;
};
class NodePow : public Node
{
public:
NodePow( Node* lhs, Node* rhs ) : mLHS( lhs ), mRHS( rhs ) { assert( lhs && rhs ) ; }
~NodePow() { delete mLHS ; delete mRHS ; }
real eval( const IDMap& ids ) const
{
return pow( mLHS->eval( ids ), mRHS->eval( ids ) ) ;
}
private:
Node* mLHS ;
Node* mRHS ;
};
class NodeNegate : public Node
{
public:
NodeNegate( Node* node ) : mNode( node ) { assert( node ) ; }
~NodeNegate() { delete mNode ; }
real eval( const IDMap& ids ) const
{
return -mNode->eval( ids ) ;
}
private:
Node* mNode ;
};
class NodeSine : public Node
{
public:
NodeSine( Node* node ) : mNode( node ) { assert( node ) ; }
~NodeSine() { delete mNode ; }
real eval( const IDMap& ids ) const
{
return sin( mNode->eval( ids ) ) ;
}
private:
Node* mNode ;
};
class NodeCosine : public Node
{
public:
NodeCosine( Node* node ) : mNode( node ) { assert( node ) ; }
~NodeCosine() { delete mNode ; }
real eval( const IDMap& ids ) const
{
return cos( mNode->eval( ids ) ) ;
}
private:
Node* mNode ;
};
class NodeLog : public Node
{
public:
NodeLog( Node* node ) : mNode( node ) { assert( node ) ; }
~NodeLog() { delete mNode ; }
real eval( const IDMap& ids ) const
{
return log10( mNode->eval( ids ) ) ;
}
private:
Node* mNode ;
};
class NodeLN : public Node
{
public:
NodeLN( Node* node ) : mNode( node ) { assert( node ) ; }
~NodeLN() { delete mNode ; }
real eval( const IDMap& ids ) const
{
return log( mNode->eval( ids ) ) ;
}
private:
Node* mNode ;
};
class NodeExp : public Node
{
public:
NodeExp( Node* node ) : mNode( node ) { assert( node ) ; }
~NodeExp() { delete mNode ; }
real eval( const IDMap& ids ) const
{
return exp( mNode->eval( ids ) ) ;
}
private:
Node* mNode ;
};
class NodeSqrt : public Node
{
public:
NodeSqrt( Node* node ) : mNode( node ) { assert( node ) ; }
~NodeSqrt() { delete mNode ; }
real eval( const IDMap& ids ) const
{
return sqrt( mNode->eval( ids ) ) ;
}
private:
Node* mNode ;
};
class MiniTokenizer
{
public:
MiniTokenizer( std::istream& in ) : mIn( in ) { mIn >> std::ws ; advance() ; }
std::string eat() { std::string result = mPeek ; advance() ; return result ; }
const std::string& peek() { return mPeek ; }
bool eof() { return mIn.eof() ; }
private:
void advance()
{
if( eof() )
mPeek = "" ;
else
mIn >> mPeek >> std::ws ;
}
std::istream& mIn ;
std::string mPeek ;
};
void find_replace( std::string& in_this_string, const std::string& find, const std::string& replace )
{
std::string::size_type pos = 0 ;
while( std::string::npos != (pos = in_this_string.find( find, pos )) )
{
in_this_string.replace( pos, find.length(), replace ) ;
pos += replace.length() ;
}
}
Node* ParseValueNode( MiniTokenizer& mt ) ;
Node* Parse( const std::string& str )
{
std::string input = str ;
// Our simple tokenizer needs whitespace between all tokens.
find_replace( input, "(", " ( " ) ;
find_replace( input, ")", " ) " ) ;
find_replace( input, "+", " + " ) ;
find_replace( input, "-", " - " ) ;
find_replace( input, "*", " * " ) ;
find_replace( input, "/", " / " ) ;
find_replace( input, "%", " % " ) ;
find_replace( input, "^", " ^ " ) ;
// The exponentiation operator "**" gets turned into "* *" by the above
// find/replaces. Turn it back into "**".
find_replace( input, "* *", "**" ) ;
/*
// Operator precedence can be implemented with some parentheses.
// See: http://en.wikipedia.org/wiki/Operator-precedence_parser#Alternatives_to_Dijkstra.27s_Algorithm
// First in precedence is exponentiation.
find_replace( input, " ^ ", " ) ^ ( " );
find_replace( input, " ** ", " ) ** ( " );
// Then multiplication and division and modulus.
find_replace( input, " * ", " ) ) ) * ( ( ( " );
find_replace( input, " / ", " ) ) ) / ( ( ( " );
find_replace( input, " % ", " ) ) ) % ( ( ( " );
// Finally addition and subtraction.
find_replace( input, " + ", " ) ) ) ) + ( ( ( ( " );
// NOTE: Whoa, subtraction is complicated by its dual-use as unary minus, which has
// precedence after exponentiation but before multiplication/division/modulus.
// find_replace( input, " - ", " ) ) ) ) - ( ( ( ( " );
{
std::string& in_this_string = input;
const std::string find( " - " );
const std::string replace1( " ) ) ) ) - ( ( ( ( " );
const std::string replace2( " 0 ) ) - ( ( " );
// const std::string replace2( " - " );
std::string::size_type pos = 0 ;
while( std::string::npos != (pos = in_this_string.find( find, pos )) )
{
bool preceded_by_open_paren = true;
for( int i = pos-1; i >= 0; --i )
{
if( in_this_string[i] != ' ' && in_this_string[i] != '\r' && in_this_string[i] != '\n' && in_this_string[i] != '\t' && in_this_string[i] != '(' )
{
preceded_by_open_paren = false;
break;
}
}
if( preceded_by_open_paren )
{
in_this_string.replace( pos, find.length(), replace2 ) ;
pos += replace2.length() ;
}
else
{
in_this_string.replace( pos, find.length(), replace1 ) ;
pos += replace1.length() ;
}
}
}
// We need to parse an expression surrounded by four parentheses.
std::istringstream istr( "( ( ( ( ( " + input + " ) ) ) ) )" ) ;
std::cout << istr.str() << std::endl;
*/
std::istringstream istr( "( " + input + " )" ) ;
MiniTokenizer tt( istr ) ;
return ParseValueNode( tt ) ;
}
Node* ParseExpressionNode( MiniTokenizer& mt ) ;
Node* ParseValueNode( MiniTokenizer& mt )
{
std::string t = mt.eat() ;
if( t.size() == 0 )
{
std::cerr << "expression cut short" << std::endl ;
return new NodeConstantValue( 0. ) ;
}
assert( t.size() > 0 ) ;
if( t == "(" )
{
Node* result = ParseExpressionNode( mt ) ;
std::string rp = mt.eat() ;
if( ")" != rp )
{
std::cerr << "expression error: expected \")\"" << std::endl ;
delete result ;
return new NodeConstantValue( 0. ) ;
}
return result ;
}
else if( t == "-" )
{
return new NodeNegate( ParseValueNode( mt ) ) ;
}
else if( t[0] == '.' || (t[0] >= '0' && t[0] <= '9') )
{
std::istringstream ttof( t ) ;
real val ;
ttof >> val ;
if( !ttof )
{
std::cerr << "expecting a real number but received: " << t << std::endl ;
return new NodeConstantValue( 0. ) ;
}
else
{
return new NodeConstantValue( val ) ;
}
}
else if( t == "sin" )
{
if( mt.peek() != "(" )
{
std::cerr << "built-in function " << t << " must be followed by parentheses." << std::endl ;
return new NodePlus( new NodeConstantValue( 0. ), ParseExpressionNode( mt ) ) ;
}
return new NodeSine( ParseValueNode( mt ) ) ;
}
else if( t == "cos" )
{
if( mt.peek() != "(" )
{
std::cerr << "built-in function " << t << " must be followed by parentheses." << std::endl ;
return new NodePlus( new NodeConstantValue( 0. ), ParseExpressionNode( mt ) ) ;
}
return new NodeCosine( ParseValueNode( mt ) ) ;
}
else if( t == "log" )
{
if( mt.peek() != "(" )
{
std::cerr << "built-in function " << t << " must be followed by parentheses." << std::endl ;
return new NodePlus( new NodeConstantValue( 0. ), ParseExpressionNode( mt ) ) ;
}
return new NodeLog( ParseValueNode( mt ) ) ;
}
else if( t == "ln" )
{
if( mt.peek() != "(" )
{
std::cerr << "built-in function " << t << " must be followed by parentheses." << std::endl ;
return new NodePlus( new NodeConstantValue( 0. ), ParseExpressionNode( mt ) ) ;
}
return new NodeLN( ParseValueNode( mt ) ) ;
}
else if( t == "exp" )
{
if( mt.peek() != "(" )
{
std::cerr << "built-in function " << t << " must be followed by parentheses." << std::endl ;
return new NodePlus( new NodeConstantValue( 0. ), ParseExpressionNode( mt ) ) ;
}
return new NodeExp( ParseValueNode( mt ) ) ;
}
else if( t == "sqrt" )
{
if( mt.peek() != "(" )
{
std::cerr << "built-in function " << t << " must be followed by parentheses." << std::endl ;
return new NodePlus( new NodeConstantValue( 0. ), ParseExpressionNode( mt ) ) ;
}
return new NodeSqrt( ParseValueNode( mt ) ) ;
}
else if( t == "PI" )
{
return new NodeConstantValue( M_PI ) ;
}
else
{
return new NodeVariableValue( t ) ;
}
}
Node* MakeOperationNode( const std::string& op, Node* lhs, Node* rhs )
{
if( op == "+" )
{
return new NodePlus( lhs, rhs ) ;
}
else if( op == "-" )
{
return new NodeMinus( lhs, rhs ) ;
}
else if( op == "*" )
{
return new NodeTimes( lhs, rhs ) ;
}
else if( op == "/" )
{
return new NodeDividedBy( lhs, rhs ) ;
}
else if( op == "%" )
{
return new NodeModulus( lhs, rhs ) ;
}
else if( op == "**" )
{
return new NodePow( lhs, rhs ) ;
}
else if( op == "^" )
{
return new NodePow( lhs, rhs ) ;
}
// error: unknown
else
{
std::cerr << "unknown operation: " << op << std::endl ;
delete lhs ;
delete rhs ;
return new NodeConstantValue( 0. ) ;
}
}
Node* ParseExpressionNode_RightAssociative( MiniTokenizer& mt )
{
Node* lhs = ParseValueNode( mt ) ;
// short circuit if we're a single value
if( mt.peek() == ")" ) return lhs ;
std::string op = mt.eat() ;
// error: prematurely expression end
if( op.size() == 0 )
{
std::cerr << "expression cut short" << std::endl ;
delete lhs ;
return new NodeConstantValue( 0. ) ;
}
Node* rhs = ParseExpressionNode( mt ) ;
return MakeOperationNode( op, lhs, rhs );
}
Node* ParseExpressionNode_LeftAssociative( MiniTokenizer& mt )
{
Node* lhs = ParseValueNode( mt ) ;
// short circuit when we reach the right parenthesis
while( mt.peek() != ")" )
{
std::string op = mt.eat() ;
// error: prematurely expression end
if( op.size() == 0 )
{
std::cerr << "expression cut short" << std::endl ;
delete lhs ;
return new NodeConstantValue( 0. ) ;
}
Node* rhs = ParseValueNode( mt ) ;
lhs = MakeOperationNode( op, lhs, rhs );
}
return lhs ;
}
Node* ParseExpressionNode( MiniTokenizer& mt )
{
// Most grammars are left associative (e.g. natural arithmetic, C).
return ParseExpressionNode_LeftAssociative( mt ) ;
}
} // ~unnamed namespace
MiniParser::MiniParser( const std::string& expression )
: mParseTree( NULL )
{
mParseTree = MiniParserNode::FromString( expression ) ;
}
MiniParser::~MiniParser()
{
delete mParseTree ;
}
real
MiniParser::eval( const IDMap& ids )
const
{
if( !mParseTree )
{
std::cerr << "No parse tree!" << std::endl ;
return 0. ;
}
if( ids.count( "PI" ) )
{
std::cerr << "Warning: PI is a built-in constant; the value passed in the IDMap will be ignored." << std::endl ;
}
return mParseTree->eval( ids ) ;
}