/
GuiExpression.cpp
743 lines (626 loc) · 16.9 KB
/
GuiExpression.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
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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
#include "GuiExpression.h"
#include <list>
#include <stack>
#include "itextstream.h"
#include "string/trim.h"
#include "string/convert.h"
#include "string/predicate.h"
namespace gui
{
// An expression referring to a GUI state variable
GuiStateVariableExpression::GuiStateVariableExpression(const std::string& variableName) :
_variableName(variableName)
{}
float GuiStateVariableExpression::getFloatValue()
{
return 0.0f; // TODO
}
std::string GuiStateVariableExpression::getStringValue()
{
return ""; // TODO
}
namespace detail
{
// Abstract base class for an expression taking two sub-expression as arguments
// Additions, Multiplications, Divisions, Modulo, comparisons, etc.
class BinaryExpression :
public GuiExpression
{
public:
// The operator precedence, smaller values mean higher priority
enum Precedence
{
LOGICAL_NOT = 0, // !
MULTIPLICATION = 0, // *
DIVISION = 0, // /
MODULO = 0, // %
ADDITION = 1, // +
SUBTRACTION = 1, // -
RELATIONAL_COMPARISON = 2, // > >= < <=
EQUALITY_COMPARISON = 3, // == !=
LOGICAL_AND = 4, // &&
LOGICAL_OR = 5, // ||
};
protected:
GuiExpressionPtr _a;
GuiExpressionPtr _b;
Precedence _precedence;
public:
BinaryExpression(Precedence precedence,
const GuiExpressionPtr& a = GuiExpressionPtr(),
const GuiExpressionPtr& b = GuiExpressionPtr()) :
GuiExpression(),
_a(a),
_b(b),
_precedence(precedence)
{}
Precedence getPrecedence() const
{
return _precedence;
}
void setA(const GuiExpressionPtr& a)
{
_a = a;
}
void setB(const GuiExpressionPtr& b)
{
_b = b;
}
virtual std::string getStringValue() override
{
return string::to_string(getFloatValue());
}
};
typedef std::shared_ptr<BinaryExpression> BinaryExpressionPtr;
// An expression adding the value of two expressions
class AddExpression :
public BinaryExpression
{
public:
AddExpression(const GuiExpressionPtr& a = GuiExpressionPtr(),
const GuiExpressionPtr& b = GuiExpressionPtr()) :
BinaryExpression(ADDITION, a, b)
{}
virtual float getFloatValue() override
{
return _a->getFloatValue() + _b->getFloatValue();
}
};
// An expression subtracting the value of two expressions
class SubtractExpression :
public BinaryExpression
{
public:
SubtractExpression(const GuiExpressionPtr& a = GuiExpressionPtr(),
const GuiExpressionPtr& b = GuiExpressionPtr()) :
BinaryExpression(SUBTRACTION, a, b)
{}
virtual float getFloatValue() override
{
return _a->getFloatValue() - _b->getFloatValue();
}
};
// An expression multiplying the value of two expressions
class MultiplyExpression :
public BinaryExpression
{
public:
MultiplyExpression(const GuiExpressionPtr& a = GuiExpressionPtr(),
const GuiExpressionPtr& b = GuiExpressionPtr()) :
BinaryExpression(MULTIPLICATION, a, b)
{}
virtual float getFloatValue() override
{
return _a->getFloatValue() * _b->getFloatValue();
}
};
// An expression dividing the value of two expressions
class DivideExpression :
public BinaryExpression
{
public:
DivideExpression(const GuiExpressionPtr& a = GuiExpressionPtr(),
const GuiExpressionPtr& b = GuiExpressionPtr()) :
BinaryExpression(DIVISION, a, b)
{}
virtual float getFloatValue() override
{
return _a->getFloatValue() / _b->getFloatValue();
}
};
// An expression returning modulo of A % B
class ModuloExpression :
public BinaryExpression
{
public:
ModuloExpression(const GuiExpressionPtr& a = GuiExpressionPtr(),
const GuiExpressionPtr& b = GuiExpressionPtr()) :
BinaryExpression(MODULO, a, b)
{}
virtual float getFloatValue() override
{
return fmod(_a->getFloatValue(), _b->getFloatValue());
}
};
// An expression returning 1 if A < B, otherwise 0
class LesserThanExpression :
public BinaryExpression
{
public:
LesserThanExpression(const GuiExpressionPtr& a = GuiExpressionPtr(),
const GuiExpressionPtr& b = GuiExpressionPtr()) :
BinaryExpression(RELATIONAL_COMPARISON, a, b)
{}
virtual float getFloatValue() override
{
return _a->getFloatValue() < _b->getFloatValue() ? 1.0f : 0;
}
};
// An expression returning 1 if A <= B, otherwise 0
class LesserThanOrEqualExpression :
public BinaryExpression
{
public:
LesserThanOrEqualExpression(const GuiExpressionPtr& a = GuiExpressionPtr(),
const GuiExpressionPtr& b = GuiExpressionPtr()) :
BinaryExpression(RELATIONAL_COMPARISON, a, b)
{}
virtual float getFloatValue() override
{
return _a->getFloatValue() <= _b->getFloatValue() ? 1.0f : 0;
}
};
// An expression returning 1 if A > B, otherwise 0
class GreaterThanExpression :
public BinaryExpression
{
public:
GreaterThanExpression(const GuiExpressionPtr& a = GuiExpressionPtr(),
const GuiExpressionPtr& b = GuiExpressionPtr()) :
BinaryExpression(RELATIONAL_COMPARISON, a, b)
{}
virtual float getFloatValue() override
{
return _a->getFloatValue() > _b->getFloatValue() ? 1.0f : 0;
}
};
// An expression returning 1 if A >= B, otherwise 0
class GreaterThanOrEqualExpression :
public BinaryExpression
{
public:
GreaterThanOrEqualExpression(const GuiExpressionPtr& a = GuiExpressionPtr(),
const GuiExpressionPtr& b = GuiExpressionPtr()) :
BinaryExpression(RELATIONAL_COMPARISON, a, b)
{}
virtual float getFloatValue() override
{
return _a->getFloatValue() >= _b->getFloatValue() ? 1.0f : 0;
}
};
// An expression returning 1 if A == B, otherwise 0
class EqualityExpression :
public BinaryExpression
{
public:
EqualityExpression(const GuiExpressionPtr& a = GuiExpressionPtr(),
const GuiExpressionPtr& b = GuiExpressionPtr()) :
BinaryExpression(EQUALITY_COMPARISON, a, b)
{}
virtual float getFloatValue() override
{
return _a->getFloatValue() == _b->getFloatValue() ? 1.0f : 0;
}
};
// An expression returning 1 if A != B, otherwise 0
class InequalityExpression :
public BinaryExpression
{
public:
InequalityExpression(const GuiExpressionPtr& a = GuiExpressionPtr(),
const GuiExpressionPtr& b = GuiExpressionPtr()) :
BinaryExpression(EQUALITY_COMPARISON, a, b)
{}
virtual float getFloatValue() override
{
return _a->getFloatValue() != _b->getFloatValue() ? 1.0f : 0;
}
};
// An expression returning the opposite of the contained expression
class LogicalNotExpression :
public BinaryExpression
{
private:
GuiExpressionPtr _contained;
public:
LogicalNotExpression(const GuiExpressionPtr& contained = GuiExpressionPtr()) :
BinaryExpression(LOGICAL_NOT, contained)
{}
virtual float getFloatValue() override
{
return _a->getFloatValue() != 0.0f ? 1.0f : 0.0f;
}
virtual std::string getStringValue() override
{
return ""; // not implemented for string values
}
};
// An expression returning 1 if both A and B are true (non-zero), otherwise 0
class LogicalAndExpression :
public BinaryExpression
{
public:
LogicalAndExpression(const GuiExpressionPtr& a = GuiExpressionPtr(),
const GuiExpressionPtr& b = GuiExpressionPtr()) :
BinaryExpression(LOGICAL_AND, a, b)
{}
virtual float getFloatValue() override
{
return (_a->getFloatValue() != 0 && _b->getFloatValue() != 0) ? 1.0f : 0;
}
};
// An expression returning 1 if either A or B are true (non-zero), otherwise 0
class LogicalOrExpression :
public BinaryExpression
{
public:
LogicalOrExpression(const GuiExpressionPtr& a = GuiExpressionPtr(),
const GuiExpressionPtr& b = GuiExpressionPtr()) :
BinaryExpression(LOGICAL_OR, a, b)
{}
virtual float getFloatValue() override
{
return (_a->getFloatValue() != 0 || _b->getFloatValue() != 0) ? 1.0f : 0;
}
};
// Fixme: Maybe merge this with ShaderExpressionTokeniser
class GuiExpressionTokeniser :
public parser::DefTokeniser
{
private:
parser::DefTokeniser& _tokeniser;
// buffer containing tokens pulled from the wrapped tokeniser
std::list<std::string> _buffer;
const char* _delims;
public:
GuiExpressionTokeniser(parser::DefTokeniser& tokeniser) :
_tokeniser(tokeniser),
_delims("+-%*/=!<>&|")
{}
bool hasMoreTokens() const override
{
return !_buffer.empty() || _tokeniser.hasMoreTokens();
}
std::string nextToken() override
{
if (_buffer.empty())
{
// Pull a new token from the underlying stream and split it up
fillBuffer(_tokeniser.nextToken());
}
std::string result = _buffer.front();
_buffer.pop_front();
return result;
}
std::string peek() const override
{
if (!_buffer.empty())
{
// We have items in the buffer, return that one
return _buffer.front();
}
// No items in the buffer, take a peek in the underlying stream
std::string rawToken = _tokeniser.peek();
if (rawToken.empty())
{
return rawToken; // don't tokenise empty strings, just return it as it is
}
// Split up the token by using a sub-tokeniser, keeping all delimiters
parser::BasicDefTokeniser<std::string> subtokeniser(rawToken, "", _delims);
// Return the first of these tokens, then exit
return subtokeniser.nextToken();
}
private:
void fillBuffer(const std::string& token)
{
if (token.empty())
{
// It's possible to retrieve an empty token if the DefTokeniser encounters an empty string ""
// This is valid, so push the empty token
_buffer.push_back(token);
return;
}
// Use a separate tokeniser and keep all delimiters
parser::BasicDefTokeniser<std::string> subtokeniser(token, "", _delims);
while (subtokeniser.hasMoreTokens())
{
_buffer.push_back(subtokeniser.nextToken());
}
}
};
class GuiExpressionParser
{
private:
GuiExpressionTokeniser& _tokeniser;
typedef std::stack<GuiExpressionPtr> OperandStack;
typedef std::stack<BinaryExpressionPtr> OperatorStack;
public:
GuiExpressionParser(GuiExpressionTokeniser& tokeniser) :
_tokeniser(tokeniser)
{}
GuiExpressionPtr getExpression()
{
// The local variable and operator stack
OperandStack operands;
OperatorStack operators;
enum {
SearchingForOperand,
SearchingForOperator,
} searchState;
searchState = SearchingForOperand;
while (_tokeniser.hasMoreTokens())
{
if (searchState == SearchingForOperand)
{
// Don't actually pull the token from the tokeniser, we might want to
// return the tokeniser to the caller if the token is not part of the expression
// The token will be exhausted from the stream once it is recognised as keyword
std::string token = _tokeniser.peek();
// The parsed operand
GuiExpressionPtr term;
if (token == "(")
{
_tokeniser.nextToken(); // valid token, exhaust
// New scope, treat this as new expression
term = getExpression();
}
else if (token == ")")
{
_tokeniser.nextToken(); // valid token, exhaust
// End of scope reached, break the loop and roll up the expression
break;
}
else if (string::starts_with(token, "gui::"))
{
// This is a GUI state variable
_tokeniser.nextToken();
term = std::make_shared<GuiStateVariableExpression>(token.substr(5));
}
// If this is a + or -, take it as a sign operator
else if (token == "+")
{
// A leading +, just ignore it
_tokeniser.nextToken();
continue;
}
else if (token == "-")
{
// A leading -, interpret it as -1 *
operands.push(std::make_shared<ConstantExpression<float>>(-1.0f));
operators.push(std::make_shared<MultiplyExpression>());
// Discard the - token
_tokeniser.nextToken();
continue;
}
else
{
// This might either be a float or a string constant
term = std::make_shared<ConstantExpression<std::string>>(_tokeniser.nextToken());
}
if (!term)
{
break; // We've run out of terms
}
// The token has already been pulled from the tokeniser
operands.push(term);
// Look for an operator next
searchState = SearchingForOperator;
continue;
}
else if (searchState == SearchingForOperator)
{
// Get an operator
BinaryExpressionPtr op = getOperator();
if (op)
{
// Check precedence if we have previous operators
while (!operators.empty())
{
if (operators.top()->getPrecedence() <= op->getPrecedence())
{
finaliseOperator(operands, operators);
}
else
{
break;
}
}
// Push this one on the operator stack
operators.push(op);
searchState = SearchingForOperand; // back to operand search mode
continue;
}
// We might also hit a closing parenthesis after an operand
if (_tokeniser.peek() == ")")
{
// Exhaust and break the loop
_tokeniser.nextToken();
}
// Not an operator, break the loop
break;
}
}
// Roll up the operations
while (!operators.empty())
{
finaliseOperator(operands, operators);
}
if (operands.empty())
{
throw parser::ParseException("Missing expression");
}
GuiExpressionPtr rv = operands.top();
operands.pop();
assert(operands.empty()); // there should be nothing left on the stack
return rv;
}
private:
void finaliseOperator(OperandStack& operands, OperatorStack& operators)
{
const BinaryExpressionPtr& op = operators.top();
// Set operand B first, we're dealing with a LIFO stack
// Do not push a second operand in the case of a logical NOT
if (!std::dynamic_pointer_cast<LogicalNotExpression>(op))
{
// Need two operands for an operator
if (operands.size() < 2)
{
throw parser::ParseException("Too few operands for operator.");
}
op->setB(operands.top());
operands.pop();
}
else
{
// Need at least one operand for a NOT operator
if (operands.size() < 1)
{
throw parser::ParseException("Too few operands for ! operator.");
}
}
op->setA(operands.top());
operands.pop();
// Push the result back on the stack, as operand
operands.push(op);
// Remove the operator, after we've copied it to the operand stack
operators.pop();
}
// Try to get a valid expression from the token. If the token was found to be valid
// The token is actually pulled from the tokeniser using nextToken()
GuiExpressionPtr getTerm(const std::string& token)
{
std::string tokenCleaned = string::trim_copy(token, "\"");
_tokeniser.nextToken(); // valid token, exhaust
return std::make_shared<ConstantExpression<std::string>>(tokenCleaned);
}
// Helper routines
BinaryExpressionPtr getOperator()
{
if (!_tokeniser.hasMoreTokens())
{
return BinaryExpressionPtr();
}
std::string token = _tokeniser.peek();
if (token == "+")
{
_tokeniser.nextToken();
return std::make_shared<AddExpression>();
}
else if (token == "-")
{
_tokeniser.nextToken();
return std::make_shared<SubtractExpression>();
}
else if (token == "*")
{
_tokeniser.nextToken();
return std::make_shared<MultiplyExpression>();
}
else if (token == "/")
{
_tokeniser.nextToken();
return std::make_shared<DivideExpression>();
}
else if (token == "%")
{
_tokeniser.nextToken();
return std::make_shared<ModuloExpression>();
}
else if (token == "<")
{
_tokeniser.nextToken();
if (_tokeniser.peek() == "=")
{
_tokeniser.nextToken();
return std::make_shared<LesserThanOrEqualExpression>();
}
return std::make_shared<LesserThanExpression>();
}
else if (token == ">")
{
_tokeniser.nextToken();
if (_tokeniser.peek() == "=")
{
_tokeniser.nextToken();
return std::make_shared<GreaterThanOrEqualExpression>();
}
return std::make_shared<GreaterThanExpression>();
}
else if (token == "=")
{
_tokeniser.nextToken();
if (_tokeniser.peek() == "=")
{
_tokeniser.nextToken();
return std::make_shared<EqualityExpression>();
}
rError() << "Assignment operator '=' found in expression, did you mean '=='?" << std::endl;
}
else if (token == "!")
{
_tokeniser.nextToken();
if (_tokeniser.peek() == "=")
{
_tokeniser.nextToken();
return std::make_shared<InequalityExpression>();
}
return std::make_shared<LogicalNotExpression>();
}
else if (token == "&")
{
_tokeniser.nextToken();
if (_tokeniser.peek() == "&")
{
_tokeniser.nextToken();
return std::make_shared<LogicalAndExpression>();
}
rError() << "Bit-wise operator '&' found in expression, did you mean '&&'?" << std::endl;
}
else if (token == "|")
{
_tokeniser.nextToken();
if (_tokeniser.peek() == "|")
{
_tokeniser.nextToken();
return std::make_shared<LogicalOrExpression>();
}
rError() << "Bit-wise operator '|' found in expression, did you mean '||'?" << std::endl;
}
return BinaryExpressionPtr();
}
};
}
GuiExpression::GuiExpression()
{}
GuiExpressionPtr GuiExpression::createFromString(const std::string& exprStr)
{
parser::BasicDefTokeniser<std::string> tokeniser(exprStr, parser::WHITESPACE, "{}(),");
return createFromTokens(tokeniser);
}
GuiExpressionPtr GuiExpression::createFromTokens(parser::DefTokeniser& tokeniser)
{
// Create an adapter which takes care of splitting the tokens into finer grains
// The incoming DefTokeniser is not splitting up expressions like "3*4" without any whitespace in them
detail::GuiExpressionTokeniser adapter(tokeniser);
try
{
detail::GuiExpressionParser parser(adapter);
return parser.getExpression();
}
catch (parser::ParseException& ex)
{
rWarning() << "[GuiExpressionParser] " << ex.what() << std::endl;
return GuiExpressionPtr();
}
}
}