/
operatorexpression.cpp
509 lines (438 loc) · 14 KB
/
operatorexpression.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
/*
* The Doomsday Engine Project -- libcore
*
* Copyright © 2004-2017 Jaakko Keränen <jaakko.keranen@iki.fi>
*
* @par License
* LGPL: http://www.gnu.org/licenses/lgpl.html
*
* <small>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at your
* option) any later version. This program is distributed in the hope that it
* will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
* General Public License for more details. You should have received a copy of
* the GNU Lesser General Public License along with this program; if not, see:
* http://www.gnu.org/licenses</small>
*/
#include "de/OperatorExpression"
#include "de/Evaluator"
#include "de/Value"
#include "de/NumberValue"
#include "de/TextValue"
#include "de/ArrayValue"
#include "de/RefValue"
#include "de/RecordValue"
#include "de/NoneValue"
#include "de/Writer"
#include "de/Reader"
#include "de/math.h"
namespace de {
/// Used for popping a result and checking if it's True.
static OperatorExpression isResultTrue(RESULT_TRUE, nullptr);
OperatorExpression::OperatorExpression() : _op(NONE), _leftOperand(nullptr), _rightOperand(nullptr)
{}
OperatorExpression::OperatorExpression(Operator op, Expression *operand)
: _op(op), _leftOperand(nullptr), _rightOperand(operand)
{
if (!isUnary(op))
{
throw NonUnaryError("OperatorExpression::OperatorExpression",
"Unary " + operatorToText(op) + " not defined");
}
}
OperatorExpression::OperatorExpression(Operator op, Expression *leftOperand, Expression *rightOperand)
: _op(op), _leftOperand(leftOperand), _rightOperand(rightOperand)
{
if (!isBinary(op))
{
throw NonBinaryError("OperatorExpression::OperatorExpression",
"Binary " + operatorToText(op) + " not defined");
}
}
OperatorExpression::~OperatorExpression()
{
delete _leftOperand;
delete _rightOperand;
}
void OperatorExpression::push(Evaluator &evaluator, Value *scope) const
{
Expression::push(evaluator);
if (_op == MEMBER)
{
// The MEMBER operator works a bit differently. Just push the left side
// now. We'll push the other side when we've found out what is the
// scope defined by the result of the left side.
_leftOperand->push(evaluator, scope);
}
else if (_op == AND || _op == OR)
{
// Early termination: AND/OR only push the left operand, and skip evaluation
// of the right operand if False/True is encountered.
_leftOperand->push(evaluator, scope);
}
else if (_op == RESULT_TRUE)
{
// This is not a normal operator: it pops a result and checks if it is True.
// We have no operands to push.
}
else
{
_rightOperand->push(evaluator);
if (_leftOperand)
{
_leftOperand->push(evaluator, scope);
}
}
}
Value *OperatorExpression::newBooleanValue(bool isTrue)
{
return new NumberValue(isTrue? NumberValue::True : NumberValue::False,
NumberValue::Boolean);
}
void OperatorExpression::verifyAssignable(Value *value)
{
DE_ASSERT(value != nullptr);
if (!dynamic_cast<RefValue *>(value))
{
throw NotAssignableError("OperatorExpression::verifyAssignable",
"Cannot assign to: " + value->asText());
}
}
Value *OperatorExpression::evaluate(Evaluator &evaluator) const
{
//qDebug() << "OperatorExpression:" << operatorToText(_op);
// Get the operands.
Value *rightValue = (_op == MEMBER || _op == AND || _op == OR? nullptr : evaluator.popResult());
Value *leftScopePtr = nullptr;
Value *leftValue = (_leftOperand? evaluator.popResult(&leftScopePtr) : nullptr);
Value *result = (leftValue? leftValue : rightValue);
std::unique_ptr<Value> leftScope(leftScopePtr); // will be deleted if not needed
DE_ASSERT(_op == MEMBER || _op == AND || _op == OR ||
(!isUnary(_op) && leftValue && rightValue) ||
( isUnary(_op) && rightValue));
try
{
switch (_op)
{
case PLUS:
if (leftValue)
{
leftValue->sum(*rightValue);
}
else
{
// Unary plus is a no-op.
}
break;
case PLUS_ASSIGN:
verifyAssignable(leftValue);
leftValue->sum(*rightValue);
break;
case MINUS:
if (leftValue)
{
leftValue->subtract(*rightValue);
}
else
{
// Negation.
rightValue->negate();
}
break;
case MINUS_ASSIGN:
verifyAssignable(leftValue);
leftValue->subtract(*rightValue);
break;
case DIVIDE:
leftValue->divide(*rightValue);
break;
case DIVIDE_ASSIGN:
verifyAssignable(leftValue);
leftValue->divide(*rightValue);
break;
case MULTIPLY:
leftValue->multiply(*rightValue);
break;
case MULTIPLY_ASSIGN:
verifyAssignable(leftValue);
leftValue->multiply(*rightValue);
break;
case MODULO:
leftValue->modulo(*rightValue);
break;
case MODULO_ASSIGN:
verifyAssignable(leftValue);
leftValue->modulo(*rightValue);
break;
case NOT:
result = newBooleanValue(rightValue->isFalse());
break;
case RESULT_TRUE:
result = newBooleanValue(rightValue->isTrue());
break;
case AND:
if (!leftValue->isTrue())
{
// Early termination.
result = newBooleanValue(false);
}
else
{
isResultTrue.push(evaluator);
_rightOperand->push(evaluator);
result = nullptr;
}
break;
case OR:
if (leftValue->isTrue())
{
// Early termination.
result = newBooleanValue(true);
}
else
{
isResultTrue.push(evaluator);
_rightOperand->push(evaluator);
result = nullptr;
}
break;
case EQUAL:
result = newBooleanValue(!leftValue->compare(*rightValue));
break;
case NOT_EQUAL:
result = newBooleanValue(leftValue->compare(*rightValue) != 0);
break;
case LESS:
result = newBooleanValue(leftValue->compare(*rightValue) < 0);
break;
case GREATER:
result = newBooleanValue(leftValue->compare(*rightValue) > 0);
break;
case LEQUAL:
result = newBooleanValue(leftValue->compare(*rightValue) <= 0);
break;
case GEQUAL:
result = newBooleanValue(leftValue->compare(*rightValue) >= 0);
break;
case IN:
result = newBooleanValue(rightValue->contains(*leftValue));
break;
case CALL:
leftValue->call(evaluator.process(), *rightValue, leftScope.release());
// Result comes from whatever is being called.
result = nullptr;
break;
case INDEX:
{
/*
LOG_DEV_TRACE_DEBUGONLY("INDEX: types %s [ %s ] byref:%b",
DE_TYPE_NAME(*leftValue) << DE_TYPE_NAME(*rightValue)
<< flags().testFlag(ByReference));
*/
// As a special case, records can be indexed also by reference.
RecordValue *recValue = dynamic_cast<RecordValue *>(leftValue);
if (flags().testFlag(ByReference) && recValue)
{
result = new RefValue(&recValue->dereference()[rightValue->asText()]);
}
else
{
// Index by value.
result = leftValue->duplicateElement(*rightValue);
}
break;
}
case SLICE:
result = performSlice(*leftValue, *rightValue);
break;
case MEMBER:
{
Record *scope = (leftValue? leftValue->memberScope() : nullptr);
if (!scope)
{
throw ScopeError("OperatorExpression::evaluate",
"Left side of " + operatorToText(_op) + " does not have members [" +
DE_TYPE_NAME(*leftValue) + "]");
}
// Now that we know what the scope is, push the rest of the expression
// for evaluation (in this specific scope).
_rightOperand->push(evaluator, leftValue);
// Cleanup.
//delete leftValue;
DE_ASSERT(rightValue == nullptr);
// The MEMBER operator does not evaluate to any result.
// Whatever is on the right side will be the result.
return nullptr;
}
default:
throw Error("OperatorExpression::evaluate",
"Operator " + operatorToText(_op) + " not implemented");
}
}
catch (Error const &)
{
delete rightValue;
delete leftValue;
throw;
}
// Delete the unnecessary values.
if (result != rightValue) delete rightValue;
if (result != leftValue) delete leftValue;
return result;
}
// Flags for serialization:
static duint8 const HAS_LEFT_OPERAND = 0x80;
static duint8 const OPERATOR_MASK = 0x7f;
void OperatorExpression::operator >> (Writer &to) const
{
to << SerialId(OPERATOR);
Expression::operator >> (to);
duint8 header = _op;
if (_leftOperand)
{
header |= HAS_LEFT_OPERAND;
}
to << header << *_rightOperand;
if (_leftOperand)
{
to << *_leftOperand;
}
}
void OperatorExpression::operator << (Reader &from)
{
SerialId id;
from >> id;
if (id != OPERATOR)
{
/// @throw DeserializationError The identifier that species the type of the
/// serialized expression was invalid.
throw DeserializationError("OperatorExpression::operator <<", "Invalid ID");
}
Expression::operator << (from);
duint8 header;
from >> header;
_op = Operator(header & OPERATOR_MASK);
delete _leftOperand;
delete _rightOperand;
_leftOperand = nullptr;
_rightOperand = nullptr;
_rightOperand = Expression::constructFrom(from);
if (header & HAS_LEFT_OPERAND)
{
_leftOperand = Expression::constructFrom(from);
}
}
namespace internal {
struct SliceTarget {
SliceTarget(Value *v) : value(v) {}
virtual ~SliceTarget() {
delete value;
}
Value *take() {
Value *v = value;
value = nullptr;
return v;
}
virtual void append(Value const &src, dint index) = 0;
Value *value;
};
struct ArraySliceTarget : public SliceTarget {
ArraySliceTarget() : SliceTarget(new ArrayValue) {}
ArrayValue &array() { return *static_cast<ArrayValue *>(value); }
void append(Value const &src, dint index) {
array().add(src.duplicateElement(NumberValue(index)));
}
};
struct TextSliceTarget : public SliceTarget {
TextSliceTarget() : SliceTarget(new TextValue) {}
TextValue &text() { return *static_cast<TextValue *>(value); }
void append(Value const &src, dint index) {
text().sum(TextValue(src.asText().mid(CharPos(index), 1))); ///@todo Performance??
}
};
}
Value *OperatorExpression::performSlice(Value &leftValue, Value &rightValue) const
{
using internal::SliceTarget;
using internal::TextSliceTarget;
using internal::ArraySliceTarget;
DE_ASSERT(rightValue.size() >= 2);
ArrayValue const *args = dynamic_cast<ArrayValue *>(&rightValue);
DE_ASSERT(args != nullptr); // Parser makes sure.
// The resulting slice of leftValue's elements.
std::unique_ptr<SliceTarget> slice;
if (dynamic_cast<TextValue *>(&leftValue))
{
slice.reset(new TextSliceTarget);
}
else
{
slice.reset(new ArraySliceTarget);
}
// Determine the stepping of the slice.
dint step = 1;
if (args->size() >= 3)
{
step = dint(args->elements()[2]->asNumber());
if (!step)
{
throw SliceError("OperatorExpression::evaluate",
operatorToText(_op) + " cannot use zero as step");
}
}
dint leftSize = dint(leftValue.size());
dint begin = 0;
dint end = leftSize;
bool unspecifiedStart = false;
bool unspecifiedEnd = false;
// Check the start index of the slice.
Value const *startValue = args->elements()[0];
if (dynamic_cast<NoneValue const *>(startValue))
{
unspecifiedStart = true;
}
else
{
begin = dint(startValue->asNumber());
}
// Check the end index of the slice.
Value const *endValue = args->elements()[1];
if (dynamic_cast<NoneValue const *>(endValue))
{
unspecifiedEnd = true;
}
else
{
end = dint(endValue->asNumber());
}
// Convert them to positive indices.
if (begin < 0)
{
begin += leftSize;
}
if (end < 0)
{
end += leftSize;
}
if ((end > begin && step < 0) || (begin > end && step > 0))
{
// The step goes to the wrong direction.
begin = end = 0;
}
// Full reverse range?
if (unspecifiedStart && unspecifiedEnd && step < 0)
{
begin = leftSize - 1;
end = -1;
}
begin = clamp(0, begin, leftSize - 1);
end = clamp(-1, end, leftSize);
for (dint i = begin; (end >= begin && i < end) || (begin > end && i > end); i += step)
{
slice->append(leftValue, i);
}
return slice->take();
}
} // namespace de