Website Summary Files Commits Branches @commit @diff @stats
path: root / JSImpl / src / ASTInterpreter.cpp
blob: baf38ae60b92b3282b262017e21a1d29a7b1e4d5 (plain) (blame)
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
#include "ASTInterpreter.h"
#include "Expression.h"
#include <iostream>
#include <math.h>

#undef NOT_IMPLEMENTED
#define NOT_IMPLEMENTED (void)e; assert(0 && "not-implemented")

namespace
{
    template <typename T>
    ASTInterpreter::ValuePtr MakeValue(T&& v)
    {
        return IPLMakeSharePtr<ASTInterpreter::Value>(v);
    }

    template <typename T>
    ASTInterpreter::ValuePtr MakeValue(const T& v)
    {
        return IPLMakeSharePtr<ASTInterpreter::Value>(v);
    }

    struct ValueToBool
    {
        bool operator()(double d) const
        {
            return d != 0.0;
        }
        bool operator()(const IPLString& s) const
        {
            return !s.empty();
        }
    };

    struct UnsupportedOpReport
    {
        template <typename V>
        ASTInterpreter::ValuePtr operator()(V) const
        {
            throw std::runtime_error("unsupported operation");
        }

        template <typename L, typename R>
        ASTInterpreter::ValuePtr operator()(L, R) const
        {
            throw std::runtime_error("unsupported operation");
        }
    };

    struct ValueAdd : UnsupportedOpReport
    {
        using UnsupportedOpReport::operator();

        ASTInterpreter::ValuePtr operator()(double l, double r) const
        {
            return MakeValue(l + r);
        }

        ASTInterpreter::ValuePtr operator()(const IPLString& l, const IPLString& r) const
        {
            return MakeValue(l + r);
        }
    };

    struct ValueMinus : UnsupportedOpReport
    {
        using UnsupportedOpReport::operator();

        ASTInterpreter::ValuePtr operator()(double l, double r) const
        {
            return MakeValue(l - r);
        }
    };

    struct ValueProduct : UnsupportedOpReport
    {
        using UnsupportedOpReport::operator();

        ASTInterpreter::ValuePtr operator()(double l, double r) const
        {
            return MakeValue(l * r);
        }
    };

    struct ValueDivide : UnsupportedOpReport
    {
        using UnsupportedOpReport::operator();

        ASTInterpreter::ValuePtr operator()(double l, double r) const
        {
            return MakeValue(l / r);
        }
    };

    struct ValueLess : UnsupportedOpReport
    {
        using UnsupportedOpReport::operator();

        template <typename V>
        ASTInterpreter::ValuePtr operator()(const V& l, const V& r) const
        {
            return MakeValue(l < r);
        }
    };
    struct ValueLessEqual : UnsupportedOpReport
    {
        using UnsupportedOpReport::operator();

        template <typename V>
        ASTInterpreter::ValuePtr operator()(V l, V r) const
        {
            return MakeValue(l <= r);
        }
    };

    struct ValueGreater : UnsupportedOpReport
    {
        using UnsupportedOpReport::operator();

        template <typename V>
        ASTInterpreter::ValuePtr operator()(V l, V r) const
        {
            return MakeValue(l > r);
        }
    };

    struct ValueGreaterEqual : UnsupportedOpReport
    {
        using UnsupportedOpReport::operator();

        template <typename V>
        ASTInterpreter::ValuePtr operator()(V l, V r) const
        {
            return MakeValue(l >= r);
        }
    };

    struct ValueEqualEqual : UnsupportedOpReport
    {
        using UnsupportedOpReport::operator();

        ASTInterpreter::ValuePtr operator()(double left, double right) const
        {
            return MakeValue(fabs(left - right) <= 0.0001);
        }

        ASTInterpreter::ValuePtr operator()(const IPLString& left, const IPLString& right) const
        {
            return MakeValue(left == right);
        }
    };

    struct ValueBangEqual : UnsupportedOpReport
    {
        using UnsupportedOpReport::operator();

        ASTInterpreter::ValuePtr operator()(double left, double right) const
        {
            return MakeValue(fabs(left - right) > 0.0001);
        }
        ASTInterpreter::ValuePtr operator()(const IPLString& left, const IPLString& right) const
        {
            return MakeValue(left != right);
        }
    };

    struct ValueUnaryMinus : UnsupportedOpReport
    {
        using UnsupportedOpReport::operator();

        ASTInterpreter::ValuePtr operator()(double v) const
        {
            return MakeValue(-v);
        }
    };

    struct ValueIncrement
    {
        void operator()(double& v) const
        {
            v += 1;
        }

        template <typename V>
        void operator()(V&) const
        {
            throw std::runtime_error("unsupported operation");
        }
    };

    struct ValueDecrement
    {
        void operator()(double& v) const
        {
            v -= 1;
        }

        template <typename V>
        void operator()(V&) const
        {
            throw std::runtime_error("unsupported operation");
        }
    };

    struct ValuePrint
    {
        ValuePrint(const char* name, ASTInterpreter::Printer* printer)
            : Name(name)
            , Printer(printer)
        {}

        void operator()(double value) const
        {
            Printer->PrintVariable(Name, value);
        }

        void operator()(const IPLString& value) const
        {
            Printer->PrintVariable(Name, value);
        }

        const char* Name;
        ASTInterpreter::Printer* Printer;
    };
}

struct LValueExtractor : public ExpressionVisitor
{
public:
    LValueExtractor(ASTInterpreter* interpreter)
        : m_Interpreter(interpreter)
        , m_LValue(nullptr)
    {}
    ~LValueExtractor() {}

    ASTInterpreter::ValuePtr Run(Expression* program)
    {
        m_LValue = nullptr;
        program->Accept(*this);
        return m_LValue;
    }

    virtual void Visit(IdentifierExpression* e) override { m_LValue = m_Interpreter->ModifyVariable(e->GetName()); }
    virtual void Visit(Call* e) override { e->GetObjectOrCall()->Accept(*this); }

    ASTInterpreter* m_Interpreter;
    ASTInterpreter::ValuePtr m_LValue;
};


struct VariableScope
{
    VariableScope(ASTInterpreter* interpreter)
        : m_Interpreter(interpreter)
    {
        m_Interpreter->EnterScope();
    }

    ~VariableScope() {
        m_Interpreter->LeaveScope();
    }

    VariableScope(VariableScope&) = delete;
    VariableScope(VariableScope&&) = delete;
    VariableScope& operator=(VariableScope&) = delete;
    VariableScope& operator=(VariableScope&&) = delete;

    ASTInterpreter* m_Interpreter;
};

struct StackScope
{
    StackScope(ASTInterpreter* interpreter)
        : m_Interpreter(interpreter)
                , m_StackSize(m_Interpreter->m_Evaluation.size())
    {
    }

    ~StackScope() {
        m_Interpreter->m_Evaluation.resize(m_StackSize);
    }

    StackScope(StackScope&) = delete;
    StackScope(StackScope&&) = delete;
    StackScope& operator=(StackScope&) = delete;
    StackScope& operator=(StackScope&&) = delete;

    ASTInterpreter* m_Interpreter;
        size_t m_StackSize;
};

ASTInterpreter::ASTInterpreter()
{
    // Allow globals
    EnterScope();
}

ASTInterpreter::~ASTInterpreter()
{}

ASTInterpreter::ValueStack ASTInterpreter::Run(Expression* program)
{
    program->Accept(*this);
    ValueStack result;
    m_Evaluation.swap(result);
    return result;
}

void ASTInterpreter::RunExpression(const ExpressionPtr& e)
{
    if (e) {
        e->Accept(*this);
    }
}

bool ASTInterpreter::EvalToBool(const ExpressionPtr& e)
{
    e->Accept(*this);
    auto result = m_Evaluation.back();
    m_Evaluation.pop_back();
    return std::visit(ValueToBool(), *result);
}

void ASTInterpreter::EnterScope()
{
    m_Scopes.push(Scope{});
}

void ASTInterpreter::LeaveScope()
{
    const auto& scope = m_Scopes.top();
    for (auto& var : scope) {
        auto values = m_Variables.find(var);
        values->second.pop_back();
        if (values->second.empty()) {
            m_Variables.erase(values);
        }
    }
    m_Scopes.pop();
}

ASTInterpreter::ValuePtr& ASTInterpreter::ModifyVariable(const IPLString& name)
{
    auto values = m_Variables.find(name);
    if (values != m_Variables.end()) {
        return values->second.back();
    }
    else {
        assert(0 && "not-defined");
    }
    static ValuePtr undefined;
    return undefined;
}

bool ASTInterpreter::HasVariable(const IPLString& name)
{
    return m_Variables.find(name) != m_Variables.end();
}

void ASTInterpreter::Visit(LiteralNull* e) {
   NOT_IMPLEMENTED; 
}

void ASTInterpreter::Visit(LiteralUndefined* e) {
   NOT_IMPLEMENTED; 
}
void ASTInterpreter::Visit(LiteralString* e) {
    m_Evaluation.push_back(MakeValue(e->GetValue()));
}

void ASTInterpreter::Visit(LiteralObject* e)
{
   NOT_IMPLEMENTED;
}

void ASTInterpreter::Visit(LiteralNumber* e) {
    m_Evaluation.push_back(MakeValue(e->GetValue()));
}
void ASTInterpreter::Visit(LiteralBoolean* e) {
    m_Evaluation.push_back(MakeValue(e->GetValue()));
}

void ASTInterpreter::Visit(BinaryExpression* e) {
    e->GetLeft()->Accept(*this);
    e->GetRight()->Accept(*this);
    auto right = *m_Evaluation.back();
    m_Evaluation.pop_back();

    auto left = *m_Evaluation.back();
    m_Evaluation.pop_back();

    switch (e->GetOperator()) {
        case TokenType::Plus:
            m_Evaluation.push_back(std::visit(ValueAdd(), left, right));
            break;
        case TokenType::Minus:
            m_Evaluation.push_back(std::visit(ValueMinus(), left, right));
            break;
        case TokenType::Star:
            m_Evaluation.push_back(std::visit(ValueProduct(), left, right));
            break;
        case TokenType::Division:
            m_Evaluation.push_back(std::visit(ValueDivide(), left, right));
            break;
        case TokenType::Less:
            m_Evaluation.push_back(std::visit(ValueLess(), left, right));
            break;
        case TokenType::LessEqual:
            m_Evaluation.push_back(std::visit(ValueLessEqual(), left, right));
            break;
        case TokenType::Greater:
            m_Evaluation.push_back(std::visit(ValueGreater(), left, right));
            break;
        case TokenType::GreaterEqual:
            m_Evaluation.push_back(std::visit(ValueGreaterEqual(), left, right));
            break;
        case TokenType::Comma:
            m_Evaluation.push_back(MakeValue(std::move(right)));
            break;
        case TokenType::EqualEqual:
            m_Evaluation.push_back(std::visit(ValueEqualEqual(), left, right));
            break;
        case TokenType::BangEqual:
            m_Evaluation.push_back(std::visit(ValueBangEqual(), left, right));
            break;
        case TokenType::Equal:
        {
            LValueExtractor extractor(this);
            auto lvalue = extractor.Run(e->GetLeft().get());
            *lvalue = right;
        }
        break;
        default:
            NOT_IMPLEMENTED;
    }
}

void ASTInterpreter::Visit(UnaryExpression* e) {
    switch (e->GetOperator())
    {
        case TokenType::Minus:
        {
            e->GetExpr()->Accept(*this);
            auto v = m_Evaluation.back();
            m_Evaluation.pop_back();
            m_Evaluation.push_back(std::visit(ValueUnaryMinus(), *v));
            break;
        }
        case TokenType::Plus:
        {
            e->GetExpr()->Accept(*this);
            break;
        }
        case TokenType::PlusPlus: // FALLTHROUGH
        case TokenType::MinusMinus:
        {
            LValueExtractor extractor(this);
            auto lvalue = extractor.Run(e->GetExpr().get());
            if (e->GetSuffix())
            {
                m_Evaluation.push_back(MakeValue(*lvalue));
            }
            if (e->GetOperator() == TokenType::PlusPlus)
            {
                std::visit(ValueIncrement(), *lvalue);
            }
            else
            {
                std::visit(ValueDecrement(), *lvalue);
            }
            if (!e->GetSuffix())
            {
                m_Evaluation.push_back(MakeValue(*lvalue));
            }
            break;
        }
        default:
        {
            NOT_IMPLEMENTED;
        }
    }

}

void ASTInterpreter::Visit(IdentifierExpression* e) {
    m_Evaluation.push_back(ModifyVariable(e->GetName()));
}

void ASTInterpreter::Visit(ListExpression* e) {
    for (const auto& stmt: e->GetValues()) {
        stmt->Accept(*this);
    }
}

void ASTInterpreter::Visit(VariableDefinitionExpression* e) {
    e->GetValue()->Accept(*this);
    auto& name = e->GetName();
    m_Variables[name].push_back(m_Evaluation.back());
    m_Scopes.top().push_back(name);
    m_Evaluation.pop_back();
}

void ASTInterpreter::Visit(BlockStatement* e) {
    for (const auto& stmt: e->GetValues()) {
        stmt->Accept(*this);
    }
}

void ASTInterpreter::Visit(LabeledStatement* e) {
    RunExpression(e->GetStatement());
}

void ASTInterpreter::Visit(IfStatement* e) {
    VariableScope scope(this);
    if (EvalToBool(e->GetCondition())) {
        VariableScope ifScope(this);
        RunExpression(e->GetIfStatement());
    } else {
        VariableScope elseScope(this);
        RunExpression(e->GetElseStatement());
    }
}

void ASTInterpreter::Visit(SwitchStatement* e) { NOT_IMPLEMENTED;}
void ASTInterpreter::Visit(CaseStatement *e) { NOT_IMPLEMENTED;}

void ASTInterpreter::Visit(WhileStatement* e) {
    VariableScope scope(this);
    if (e->GetDoWhile()) {
        VariableScope bodyScope(this);
        RunExpression(e->GetBody());
    }
    while (EvalToBool(e->GetCondition())) {
        VariableScope bodyScope(this);
        RunExpression(e->GetBody());
    }
}

void ASTInterpreter::Visit(ForStatement* e) {
    VariableScope scope(this);

    {
        StackScope stackScope(this);
        RunExpression(e->GetInitialization());
    }
    while (EvalToBool(e->GetCondition()))
    {
        {
            VariableScope bodyScope(this);
            RunExpression(e->GetBody());
        }
        {
            StackScope stackScope(this);
            RunExpression(e->GetIteration());
        }
    }
}

void ASTInterpreter::Visit(FunctionDeclaration* e) { NOT_IMPLEMENTED;}
void ASTInterpreter::Visit(TopStatements* e) {
    for (const auto& stmt: e->GetValues()) {
        stmt->Accept(*this);
    }
}

void ASTInterpreter::Visit(EmptyExpression* e) {
    NOT_IMPLEMENTED;
}

void ASTInterpreter::Visit(Call* e)
{
    e->GetObjectOrCall()->Accept(*this);
    if (e->GetMember())
    {
        e->GetMember()->Accept(*this);
    }
}

void ASTInterpreter::Print(Printer& p)
{
    for (auto& it : m_Variables)
    {
        auto& value = ModifyVariable(it.first);
        std::visit(ValuePrint(it.first.c_str(), &p), *value);
    }
}