-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathinterpreter.cpp
More file actions
2172 lines (1973 loc) · 68.9 KB
/
Copy pathinterpreter.cpp
File metadata and controls
2172 lines (1973 loc) · 68.9 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
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
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Interpreter Project
// Copyright (C) 2020 by Contributors <https://github.com/Tyill/interpreter>
//
// This code is licensed under the MIT License.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#include "../include/interpreter.h"
#include <sstream>
#include <iomanip>
#include <algorithm>
#include <cctype>
#include <memory>
#include <optional>
#include <set>
#include <string_view>
#include <type_traits>
#include <utility>
// --- ir::detail (declarations) ---
namespace ir {
namespace detail {
constexpr size_t kNoIndex = static_cast<size_t>(-1);
bool isDigits(std::string_view s);
std::optional<int64_t> parseInteger(std::string_view s);
std::optional<Interpreter::Value> parseNumber(std::string_view s);
bool isIdentContinue(unsigned char c);
bool matchKeywordAt(std::string_view script, size_t cpos, std::string_view kw);
Interpreter::Value parseLiteralText(std::string_view s);
Interpreter::Value parseQuotedLiteral(std::string s);
Interpreter::Value valueOfValueExpr(const Interpreter::Value& result,
const std::vector<Interpreter::Value>& params);
const std::string& paramKey(const std::vector<Interpreter::Value>& params);
size_t paramIndex(const std::vector<Interpreter::Value>& params);
bool isBreakValue(const Interpreter::Value& v);
bool isContinueValue(const Interpreter::Value& v);
} // namespace detail
} // namespace ir
class Interpreter::Impl {
public:
Impl() = default;
bool addFunction(const std::string& name, Interpreter::UserFunction ufunc);
bool addOperator(const std::string& name, Interpreter::UserOperator uopr, uint32_t priority);
bool addAttribute(const std::string& name);
Interpreter::CmdResult cmd(std::string script);
bool parseScript(std::string script, Interpreter::Error& outErr);
Interpreter::Value evalScript();
std::pair<Interpreter::Value, Interpreter::Error> runScript();
std::map<std::string, Interpreter::Value> allVariables() const;
Interpreter::Value variable(const std::string& vname) const;
Interpreter::Value runFunction(const std::string& fname, const std::vector<Interpreter::Value>& args);
bool setVariable(const std::string& vname, const Interpreter::Value& value);
bool setMacro(const std::string& mname, const std::string& script);
bool gotoOnLabel(const std::string& lname);
void exitFromScript();
std::vector<Interpreter::Entity> allEntities() const;
Interpreter::Entity currentEntity() const;
Interpreter::Entity getEntityByIndex(size_t beginIndex) const;
std::vector<std::string> getAttributeByIndex(size_t beginIndex) const;
bool gotoOnEntity(size_t iBegin);
Interpreter::UserFunction getUserFunction(const std::string& fname);
Interpreter::UserOperator getUserOperator(const std::string& oname);
private:
enum class Keyword {
INSTRUCTION,
EXPRESSION,
OPERATOR,
WHILE,
IF,
ELSE,
ELSE_IF,
BREAK,
CONTINUE,
FUNCTION,
ARGUMENT,
MACRO,
VARIABLE,
VALUE,
GOTO,
};
struct Expression {
Keyword keyw;
size_t iConditionEnd;
size_t iBodyEnd;
size_t iOperator;
std::vector<Interpreter::Value> params;
Interpreter::Value result{std::string{}};
};
struct Operator {
size_t inx, priority, iLOpr, iROpr;
};
std::map<std::string, Interpreter::UserFunction> m_ufunc;
std::map<std::string, std::pair<Interpreter::UserOperator, uint32_t>> m_uoper;
std::map<std::string, Interpreter::Value> m_var;
std::map<std::string, std::string> m_macro;
std::map<std::string, size_t> m_label;
std::set<std::string> m_attribute;
std::map<size_t, std::vector<std::string>> m_exprAttribute;
std::map<size_t, std::vector<Operator>> m_soper;
std::map<std::string, Impl> m_internFunc;
std::vector<Expression> m_expr;
Interpreter::Error m_parseErr;
std::string m_prevScript;
size_t m_gotoIndex = ir::detail::kNoIndex;
size_t m_currentIndex = 0;
bool m_exit = false;
Interpreter::Value calcOperation(Keyword mainKeyword, size_t iExpr);
Interpreter::Value calcFunction(size_t iExpr);
Interpreter::Value calcCondition(size_t iExpr);
Interpreter::Value calcExpression(size_t iBegin, size_t iEnd);
void calcOperatorPriority(size_t iBegin, size_t iEnd, std::vector<Operator>& oprs);
bool parseInstructionScript(std::string& script, size_t gpos);
bool parseExpressionScript(std::string& script, size_t gpos);
bool parseArgumentScript(std::string& script, size_t gpos);
bool parseExprPrimary(std::string& script, size_t& cpos, size_t& iExpr, size_t gpos, bool& breakLoop);
bool parseExprUnary(std::string& script, size_t& cpos, size_t& iExpr, size_t gpos);
bool parseExprOperator(std::string& script, size_t& cpos, size_t& iExpr, size_t gpos);
bool skipOneSpareSymbol(const std::string& script, size_t& cpos);
bool parseControlBody(std::string& script, size_t& cpos, size_t gpos,
const char* emptyBodyMsg, const char* invalidBodyMsg);
bool parseInstrExprOrOpCall(std::string& script, size_t& cpos, size_t gpos, size_t& iExpr);
bool parseInstrControlFlow(std::string& script, size_t& cpos, size_t gpos, size_t& iExpr, size_t& iIF);
bool parseInstrElse(std::string& script, size_t& cpos, size_t gpos, size_t& iExpr, size_t iIF);
bool parseInstrMacro(std::string& script, size_t& cpos, size_t gpos);
bool expandAllMacros(std::string& script);
bool parseInstrGotoLabel(std::string& script, size_t& cpos, size_t gpos, size_t& iExpr);
bool parseInstrFunctionDecl(std::string& script, size_t& cpos, size_t gpos);
bool parseInstrStatementExpr(std::string& script, size_t& cpos, size_t gpos, size_t& iExpr);
void emplaceSyntheticNegatePrefix(size_t& iExpr);
void mergeInternFuncs(Impl& callee) const;
void bindCallerScope(Impl& callee, const std::vector<Interpreter::Value>& args,
std::set<std::string>& outScopeVars) const;
void writeBackScope(Impl& callee, const std::set<std::string>& scopeVars);
bool parseMacroArgs(const std::string& args, std::string& macro);
void emplaceExpr(size_t& iExpr, Keyword keyw,
std::vector<Interpreter::Value> params = {},
Interpreter::Value result = std::string{});
void emplaceExprAt(size_t iExpr, Keyword keyw,
std::vector<Interpreter::Value> params = {},
Interpreter::Value result = std::string{});
enum class ParseInitOutcome { NotHandled, Handled, BreakLoop };
ParseInitOutcome parseNamedInitBody(Keyword entityKw, bool bindVariable,
std::string& script, size_t& cpos, size_t& iExpr,
size_t posmem, const std::string& oprName);
Interpreter::Entity makeEntity(size_t index, const Expression& exp) const;
Impl makeChildImplForParse() const;
bool failParse(size_t cpos, size_t gpos, const char* what);
static bool failCheck(std::string& err, const char* what);
void cleaningScript(std::string& script) const;
bool checkScript(const std::string& script, std::string& err) const;
bool startWith(std::string_view str, size_t pos, std::string_view begin) const;
bool isFindKeySymbol(const std::string& script, size_t cpos, size_t maxpos) const;
Interpreter::Value evalOperand(size_t iExpr);
Interpreter::Value variableByKey(const std::string& key) const;
Keyword keywordByName(std::string_view oprName) const;
Interpreter::EntityType keywordToEntityType(Keyword keyw) const;
std::string getNextParam(const std::string& script, size_t& cpos, char symb) const;
std::string getOperatorAtFirst(const std::string& script, size_t& cpos) const;
std::string getFunctionAtFirst(const std::string& script, size_t& cpos) const;
std::string peekFunctionCall(const std::string& script, size_t cpos) const;
std::string getMacroAtFirst(const std::string& script, size_t& cpos) const;
std::string getAttributeAtFirst(const std::string& script, size_t& cpos) const;
std::string getNextOperator(const std::string& script, size_t& cpos) const;
std::string getIntroScript(const std::string& script, size_t& cpos, char symbBegin, char symbEnd) const;
bool isUnaryMinusAt(const std::string& script, size_t cpos) const;
bool isUnaryMinusContext(const std::string& script, size_t cpos) const;
};
void Interpreter::Impl::emplaceExpr(size_t& iExpr, Keyword keyw,
std::vector<Interpreter::Value> params, Interpreter::Value result) {
m_expr.emplace_back(Expression{keyw, iExpr, iExpr, ir::detail::kNoIndex,
std::move(params), std::move(result)});
++iExpr;
}
void Interpreter::Impl::emplaceExprAt(size_t iExpr, Keyword keyw,
std::vector<Interpreter::Value> params, Interpreter::Value result) {
m_expr.emplace_back(Expression{keyw, iExpr, iExpr, ir::detail::kNoIndex,
std::move(params), std::move(result)});
}
// --- eval ---
Interpreter::CmdResult Interpreter::Impl::cmd(std::string script) {
Interpreter::Error err;
if (!parseScript(std::move(script), err)) {
return {Interpreter::Value{std::string{}}, std::move(err)};
}
auto run = runScript();
return {std::move(run.first), std::move(run.second)};
}
bool Interpreter::Impl::parseScript(std::string script, Interpreter::Error& outErr) {
outErr = {};
m_parseErr = {};
cleaningScript(script);
if (script.empty()) {
outErr.kind = Interpreter::Error::Kind::Parse;
outErr.message = "Error: empty script";
return false;
}
if (script.back() != ';') {
script += ';';
}
if (!expandAllMacros(script)) {
m_prevScript.clear();
if (!m_parseErr.message.empty()) {
outErr = m_parseErr;
}
else {
outErr.kind = Interpreter::Error::Kind::Parse;
outErr.message = "Error: macro expansion failed";
}
return false;
}
if (m_prevScript != script) {
m_expr.clear();
m_label.clear();
m_soper.clear();
m_parseErr = {};
std::string checkErr;
if (!checkScript(script, checkErr) || !parseInstructionScript(script, 0)) {
if (!m_parseErr.message.empty()) {
outErr = m_parseErr;
}
else {
outErr.kind = Interpreter::Error::Kind::Parse;
outErr.message = checkErr;
}
return false;
}
m_prevScript = std::move(script);
}
return true;
}
std::pair<Interpreter::Value, Interpreter::Error> Interpreter::Impl::runScript() {
return {evalScript(), {}};
}
Interpreter::Value Interpreter::Impl::evalScript() {
for (auto& ex : m_expr)
ex.iOperator = ir::detail::kNoIndex;
Interpreter::Value result;
m_exit = false;
for (size_t i = 0; i < m_expr.size();) {
result = calcOperation(m_expr[i].keyw, i);
i = std::max(m_expr[i].iConditionEnd, m_expr[i].iBodyEnd);
if (m_gotoIndex != ir::detail::kNoIndex) {
for (size_t j = m_gotoIndex; j < i; ++j)
m_expr[j].iOperator = ir::detail::kNoIndex;
i = m_gotoIndex;
m_gotoIndex = ir::detail::kNoIndex;
}
if (m_exit) break;
}
return result;
}
void Interpreter::Impl::cleaningScript(std::string& script) const {
std::string out;
out.reserve(script.size());
bool inString = false;
for (size_t i = 0; i < script.size();) {
if (!inString && i + 1 < script.size() && script[i] == '/' && script[i + 1] == '/') {
i += 2;
while (i < script.size() && script[i] != '\n') {
++i;
}
continue;
}
if (script[i] == '"') {
if (inString && i > 0 && script[i - 1] == '\\') {
out += script[i++];
continue;
}
inString = !inString;
out += script[i++];
continue;
}
if (inString) {
out += script[i++];
continue;
}
const char c = script[i];
if (c == ' ' || c == '\n' || c == '\t' || c == '\v' || c == '\f' || c == '\r') {
++i;
continue;
}
out += c;
++i;
}
script = std::move(out);
}
bool Interpreter::Impl::failCheck(std::string& err, const char* what) { // NOLINT(readability-make-member-function-const)
if (err.empty()) {
err = std::string("Error check script: ") + what;
}
return false;
}
bool Interpreter::Impl::checkScript(const std::string& script, std::string& err) const {
if (std::count(script.begin(), script.end(), '{') != std::count(script.begin(), script.end(), '}')) {
return failCheck(err, "{ } mismatch");
}
if (std::count(script.begin(), script.end(), '(') != std::count(script.begin(), script.end(), ')')) {
return failCheck(err, "( ) mismatch");
}
if (std::count(script.begin(), script.end(), '"') % 2 != 0) {
return failCheck(err, "unclosed string");
}
return true;
}
bool Interpreter::Impl::addFunction(const std::string& name, Interpreter::UserFunction ufunc) {
if (name.empty() || (keywordByName(name) != Keyword::INSTRUCTION) || isFindKeySymbol(name, 0, name.size())) return false;
m_ufunc[name] = std::move(ufunc);
return true;
}
bool Interpreter::Impl::addOperator(const std::string& name, Interpreter::UserOperator uopr, uint32_t priority) {
if (name.empty() || (keywordByName(name) != Keyword::INSTRUCTION) || isFindKeySymbol(name, 0, name.size())) return false;
m_uoper[name] = {std::move(uopr), priority};
return true;
}
bool Interpreter::Impl::addAttribute(const std::string& name) {
m_attribute.insert(name);
return true;
}
std::map<std::string, Interpreter::Value> Interpreter::Impl::allVariables() const {
return m_var;
}
Interpreter::Value Interpreter::Impl::variable(const std::string& vname) const {
auto it = m_var.find(vname);
return it != m_var.end() ? it->second : Interpreter::Value{std::string{}};
}
bool Interpreter::Impl::setVariable(const std::string& vname, const Interpreter::Value& value) {
m_var[vname] = value;
return true;
}
Interpreter::Value Interpreter::Impl::runFunction(const std::string& fname, const std::vector<Interpreter::Value>& args) {
return m_ufunc.count(fname) ? m_ufunc[fname](args) : Interpreter::Value{std::string{}};
}
bool Interpreter::Impl::setMacro(const std::string& mname, const std::string& script) {
if (mname.empty()) {
return false;
}
const std::string key = (mname.front() == '#') ? mname : "#" + mname;
m_macro[key] = script;
return true;
}
bool Interpreter::Impl::gotoOnLabel(const std::string& lname) {
const auto it = m_label.find(lname);
if (it == m_label.end()) {
return false;
}
m_gotoIndex = it->second;
return true;
}
void Interpreter::Impl::exitFromScript() {
m_exit = true;
}
Interpreter::Entity Interpreter::Impl::makeEntity(size_t index, const Expression& exp) const {
Interpreter::Entity entity{
index, exp.iConditionEnd, exp.iBodyEnd,
keywordToEntityType(exp.keyw), ir::detail::paramKey(exp.params), exp.result
};
if (exp.keyw == Keyword::ELSE || exp.keyw == Keyword::ELSE_IF) {
entity.linkIndex = ir::detail::paramIndex(exp.params);
}
return entity;
}
std::vector<Interpreter::Entity> Interpreter::Impl::allEntities() const {
std::vector<Interpreter::Entity> res;
res.reserve(m_expr.size());
for (size_t i = 0; i < m_expr.size(); ++i) {
res.push_back(makeEntity(i, m_expr[i]));
}
return res;
}
Interpreter::Entity Interpreter::Impl::currentEntity() const {
if (m_currentIndex >= m_expr.size()) {
return Interpreter::Entity{0};
}
return makeEntity(m_currentIndex, m_expr[m_currentIndex]);
}
Interpreter::Entity Interpreter::Impl::getEntityByIndex(size_t beginIndex) const {
if (beginIndex >= m_expr.size()) {
return Interpreter::Entity{0};
}
return makeEntity(beginIndex, m_expr[beginIndex]);
}
std::vector<std::string> Interpreter::Impl::getAttributeByIndex(size_t index) const {
const auto it = m_exprAttribute.find(index);
return it != m_exprAttribute.end() ? it->second : std::vector<std::string>{};
}
bool Interpreter::Impl::gotoOnEntity(size_t beginIndex) {
if (beginIndex < m_expr.size()) {
m_gotoIndex = beginIndex;
return true;
}
return false;
}
Interpreter::UserFunction Interpreter::Impl::getUserFunction(const std::string& fname) {
return m_ufunc.count(fname) ? m_ufunc[fname] : nullptr;
}
Interpreter::UserOperator Interpreter::Impl::getUserOperator(const std::string& oname) {
return m_uoper.count(oname) ? m_uoper[oname].first : nullptr;
}
Interpreter::Value Interpreter::Impl::calcOperation(Keyword mainKeyword, size_t iExpr) {
Interpreter::Value g_result;
switch (mainKeyword) {
case Keyword::VARIABLE:
g_result = variableByKey(ir::detail::paramKey(m_expr[iExpr].params));
break;
case Keyword::VALUE:
g_result = ir::detail::valueOfValueExpr(m_expr[iExpr].result, m_expr[iExpr].params);
break;
case Keyword::EXPRESSION:
g_result = m_expr[iExpr].result = calcExpression(iExpr + 1, m_expr[iExpr].iBodyEnd);
break;
case Keyword::FUNCTION:
g_result = m_expr[iExpr].result = calcFunction(iExpr);
break;
case Keyword::WHILE:
case Keyword::IF:
case Keyword::ELSE:
case Keyword::ELSE_IF:
g_result = calcCondition(iExpr);
break;
case Keyword::GOTO: {
const std::string& gotoLabel = ir::detail::paramKey(m_expr[iExpr].params);
auto it = m_label.find(gotoLabel);
if (it != m_label.end()) {
m_gotoIndex = it->second;
}
}
break;
default:
break;
}
return g_result;
}
Interpreter::Value Interpreter::Impl::calcFunction(size_t iExpr) {
Interpreter::Value g_result;
size_t iBegin = iExpr + 1;
size_t iEnd = m_expr[iExpr].iConditionEnd;
std::vector<Interpreter::Value> args;
for (size_t i = iBegin; i < iEnd;) {
if ((i + 1 == m_expr[i].iBodyEnd - 1) && ((m_expr[i + 1].keyw == Keyword::VARIABLE) || (m_expr[i + 1].keyw == Keyword::VALUE))) {
if (m_expr[i + 1].keyw == Keyword::VARIABLE)
m_expr[i].result = variableByKey(ir::detail::paramKey(m_expr[i + 1].params));
else
m_expr[i].result = ir::detail::valueOfValueExpr(m_expr[i + 1].result, m_expr[i + 1].params);
}
else {
m_expr[i].result = calcExpression(i + 1, m_expr[i].iBodyEnd);
}
args.emplace_back(m_expr[i].result);
i = m_expr[i].iBodyEnd;
}
m_currentIndex = iExpr;
const std::string& fname = ir::detail::paramKey(m_expr[iExpr].params);
if (m_internFunc.count(fname)) {
auto& impl = m_internFunc[fname];
mergeInternFuncs(impl);
std::set<std::string> scopeVars;
bindCallerScope(impl, args, scopeVars);
g_result = impl.evalScript();
writeBackScope(impl, scopeVars);
}
else {
g_result = m_ufunc[fname](args);
}
return g_result;
}
Interpreter::Value Interpreter::Impl::calcCondition(size_t iExpr) {
Interpreter::Value g_result;
size_t iBegin = iExpr + 1;
size_t iCondEnd = m_expr[iExpr].iConditionEnd;
size_t iBodyEnd = m_expr[iExpr].iBodyEnd;
if ((m_expr[iExpr].keyw == Keyword::ELSE) || (m_expr[iExpr].keyw == Keyword::ELSE_IF)) {
const size_t iIF = ir::detail::paramIndex(m_expr[iExpr].params);
if (iIF == ir::detail::kNoIndex) {
return g_result;
}
if (Interpreter::valueIsTruthy(m_expr[iIF].result)) {
return g_result;
}
}
Interpreter::Value condn;
if (iBegin < iCondEnd) {
condn = m_expr[iExpr].result = calcExpression(iBegin, iCondEnd);
}
if ((m_expr[iExpr].keyw == Keyword::ELSE) || Interpreter::valueIsTruthy(condn)) {
bool isContinue = false,
isBreak = false;
for (size_t i = iCondEnd; i < iBodyEnd;) {
switch (m_expr[i].keyw) {
case Keyword::EXPRESSION: {
m_expr[i].result = calcExpression(i + 1, m_expr[i].iBodyEnd);
i = m_expr[i].iBodyEnd;
}
break;
case Keyword::WHILE:
case Keyword::IF:
case Keyword::ELSE:
case Keyword::ELSE_IF: {
Interpreter::Value res = calcCondition(i);
if (m_expr[i].keyw != Keyword::WHILE) {
isBreak = ir::detail::isBreakValue(res);
isContinue = ir::detail::isContinueValue(res);
g_result = res;
}
i = m_expr[i].iBodyEnd;
}
break;
case Keyword::BREAK: {
isBreak = true;
if (m_expr[iExpr].keyw != Keyword::WHILE) {
g_result = Interpreter::ControlFlow::Break;
}
}
break;
case Keyword::CONTINUE: {
isContinue = true;
if (m_expr[iExpr].keyw != Keyword::WHILE) {
g_result = Interpreter::ControlFlow::Continue;
}
}
break;
case Keyword::GOTO: {
const std::string& gotoLabel = ir::detail::paramKey(m_expr[i].params);
auto it = m_label.find(gotoLabel);
if (it != m_label.end()) {
m_gotoIndex = it->second;
}
}
break;
default:
break;
}
if (isBreak || m_exit) break;
if (m_gotoIndex != ir::detail::kNoIndex) {
if ((iCondEnd <= m_gotoIndex) && (m_gotoIndex < iBodyEnd)) {
for (size_t j = m_gotoIndex; j < i; ++j)
m_expr[j].iOperator = ir::detail::kNoIndex;
i = m_gotoIndex;
m_gotoIndex = ir::detail::kNoIndex;
}
else break;
}
if (isContinue) i = iBodyEnd;
if ((m_expr[iExpr].keyw == Keyword::WHILE) && (i >= iBodyEnd)) {
isContinue = false;
for (size_t j = iBegin; j < iCondEnd; ++j)
m_expr[j].iOperator = ir::detail::kNoIndex;
condn = m_expr[iExpr].result = calcExpression(iBegin, iCondEnd);
if (Interpreter::valueIsTruthy(condn)) {
for (size_t j = iCondEnd; j < iBodyEnd; ++j)
m_expr[j].iOperator = ir::detail::kNoIndex;
i = iCondEnd;
}
}
}
}
return g_result;
}
Interpreter::Value Interpreter::Impl::calcExpression(size_t iBegin, size_t iEnd) {
if (iBegin + 1 == iEnd) {
return evalOperand(iBegin);
}
if (m_soper.find(iBegin) == m_soper.end()) {
m_soper.insert({ iBegin, std::vector<Operator>() });
}
std::vector<Operator>& oprs = m_soper[iBegin];
if (oprs.empty()) {
calcOperatorPriority(iBegin, iEnd, oprs);
}
if (oprs.empty()) {
return calcOperation(m_expr[iBegin].keyw, iBegin);
}
Interpreter::Value g_result;
for (auto& op : oprs) {
size_t iOp = op.inx;
Expression* pLeftOperd = nullptr,
* pRightOperd = nullptr;
Interpreter::Value lValue, rValue;
if (op.iLOpr != ir::detail::kNoIndex) {
pLeftOperd = &m_expr[op.iLOpr];
lValue = evalOperand(op.iLOpr);
}
if (op.iROpr != ir::detail::kNoIndex) {
pRightOperd = &m_expr[op.iROpr];
rValue = evalOperand(op.iROpr);
}
m_currentIndex = iOp;
g_result = m_expr[iOp].result = m_uoper[ir::detail::paramKey(m_expr[iOp].params)].first(lValue, rValue);
if (pLeftOperd && (pLeftOperd->keyw == Keyword::VARIABLE) && (pLeftOperd->iOperator == ir::detail::kNoIndex)) {
pLeftOperd->result = m_var[ir::detail::paramKey(pLeftOperd->params)] = lValue;
}
if (pRightOperd && (pRightOperd->keyw == Keyword::VARIABLE) && (pRightOperd->iOperator == ir::detail::kNoIndex)) {
pRightOperd->result = m_var[ir::detail::paramKey(pRightOperd->params)] = rValue;
}
if (pLeftOperd) {
if (pLeftOperd->iOperator != ir::detail::kNoIndex) {
size_t iLOp = pLeftOperd->iOperator;
for (size_t i = iBegin; i < iEnd; ++i) {
if (m_expr[i].iOperator == iLOp)
m_expr[i].iOperator = iOp;
}
}
else pLeftOperd->iOperator = iOp;
}
if (pRightOperd) {
if (pRightOperd->iOperator != ir::detail::kNoIndex) {
size_t iROp = pRightOperd->iOperator;
for (size_t i = iBegin; i < iEnd; ++i) {
if (m_expr[i].iOperator == iROp)
m_expr[i].iOperator = iOp;
}
}
else pRightOperd->iOperator = iOp;
}
}
return g_result;
}
void Interpreter::Impl::calcOperatorPriority(size_t iBegin, size_t iEnd, std::vector<Operator>& oprs) {
size_t iLOpr = ir::detail::kNoIndex;
for (size_t i = iBegin; i < iEnd;) {
if (m_expr[i].keyw == Keyword::FUNCTION) {
iLOpr = i;
i = m_expr[i].iConditionEnd;
continue;
}
if (m_expr[i].keyw == Keyword::EXPRESSION) {
iLOpr = i;
i = m_expr[i].iBodyEnd;
continue;
}
if (m_expr[i].keyw == Keyword::OPERATOR) {
uint32_t priority = m_uoper[ir::detail::paramKey(m_expr[i].params)].second;
size_t iROpr = (i < iEnd - 1) ? i + 1 : ir::detail::kNoIndex;
oprs.emplace_back<Operator>({ i, priority, iLOpr, iROpr }); // inx, priority
}
iLOpr = i;
++i;
}
const auto osz = oprs.size();
if (osz > 1) {
if (osz == 2) {
if (oprs[0].priority > oprs[1].priority) std::swap(oprs[0], oprs[1]);
}
else if (osz == 3) {
if (oprs[0].priority < oprs[1].priority) {
if (oprs[2].priority < oprs[0].priority) std::swap(oprs[0], oprs[2]);
}
else {
if (oprs[1].priority < oprs[2].priority) std::swap(oprs[0], oprs[1]);
else std::swap(oprs[0], oprs[2]);
}
if (oprs[2].priority < oprs[1].priority) std::swap(oprs[1], oprs[2]);
}
else{
std::sort(oprs.begin(), oprs.end(), [](const Operator& l, const Operator& r) {
return l.priority < r.priority;
});
}
}
}
// --- parse ---
bool Interpreter::Impl::failParse(size_t cpos, size_t gpos, const char* what) {
if (m_parseErr.message.empty()) {
m_parseErr.kind = Interpreter::Error::Kind::Parse;
m_parseErr.position = cpos + gpos;
m_parseErr.message = "Error script pos " + std::to_string(m_parseErr.position) + ": " + what;
}
return false;
}
bool Interpreter::Impl::skipOneSpareSymbol(const std::string& script, size_t& cpos) {
if (cpos >= script.size()) {
return false;
}
const char c = script[cpos];
if (c == ';' || c == ',' || c == ']' || c == '[') {
++cpos;
return true;
}
return false;
}
bool Interpreter::Impl::parseControlBody(std::string& script, size_t& cpos, size_t gpos,
const char* emptyBodyMsg, const char* invalidBodyMsg) {
if (script[cpos] == '{') {
std::string body = getIntroScript(script, cpos, '{', '}');
if (body.empty() || !parseInstructionScript(body, gpos + cpos - body.size() - 2)) {
return failParse(cpos, gpos, emptyBodyMsg);
}
}
else {
std::string body = getNextParam(script, cpos, ';') + ';';
if ((body.size() != 1) && !parseInstructionScript(body, gpos + cpos - body.size())) {
return failParse(cpos, gpos, invalidBodyMsg);
}
}
return true;
}
bool Interpreter::Impl::parseInstrExprOrOpCall(std::string& script, size_t& cpos, size_t gpos,
size_t& iExpr) {
size_t cposFunc = cpos;
size_t cposOpr = cpos;
if (getFunctionAtFirst(script, cposFunc).empty() && getOperatorAtFirst(script, cposOpr).empty()) {
return false;
}
emplaceExprAt(iExpr, Keyword::EXPRESSION);
std::string expr = getNextParam(script, cpos, ';');
if (expr.empty() || !parseExpressionScript(expr, gpos + cpos - expr.size() - 1)) {
return failParse(cpos, gpos, "empty expression");
}
iExpr = m_expr[iExpr].iBodyEnd = m_expr.size();
return true;
}
bool Interpreter::Impl::parseInstrControlFlow(std::string& script, size_t& cpos, size_t gpos,
size_t& iExpr, size_t& iIF) {
if (!startWith(script, cpos, "while") && !startWith(script, cpos, "if")
&& !startWith(script, cpos, "elseif")) {
if (!startWith(script, cpos, "break") && !startWith(script, cpos, "continue")) {
return false;
}
const std::string kname = getNextParam(script, cpos, ';');
if (kname.empty()) {
return failParse(cpos, gpos, "expected break or continue");
}
emplaceExpr(iExpr, keywordByName(kname));
return true;
}
const std::string kname = getNextParam(script, cpos, '(');
if (kname.empty()) {
return failParse(cpos, gpos, "expected keyword");
}
const Keyword keyw = keywordByName(kname);
emplaceExprAt(iExpr, keyw);
if (keyw == Keyword::IF) {
iIF = iExpr;
}
else if (keyw == Keyword::ELSE_IF) {
m_expr[iExpr].params = { static_cast<int64_t>(iIF) };
iIF = iExpr;
}
--cpos;
std::string condition = getIntroScript(script, cpos, '(', ')');
if (condition.empty() || !parseExpressionScript(condition, gpos + cpos - condition.size() - 2)) {
return failParse(cpos, gpos, "empty condition");
}
m_expr[iExpr].iConditionEnd = m_expr.size();
if (!parseControlBody(script, cpos, gpos, "empty body", "invalid instruction body")) {
return true;
}
iExpr = m_expr[iExpr].iBodyEnd = m_expr.size();
if ((cpos < script.size()) && (script[cpos] == ';')) {
++cpos;
}
return true;
}
bool Interpreter::Impl::parseInstrElse(std::string& script, size_t& cpos, size_t gpos,
size_t& iExpr, size_t iIF) {
if (!startWith(script, cpos, "else")) {
return false;
}
cpos += 4;
emplaceExprAt(iExpr, Keyword::ELSE);
m_expr[iExpr].params = { static_cast<int64_t>(iIF) };
if (!parseControlBody(script, cpos, gpos, "empty else body", "invalid else body")) {
return true;
}
m_expr[iExpr].iConditionEnd = iExpr + 1;
iExpr = m_expr[iExpr].iBodyEnd = m_expr.size();
if ((cpos < script.size()) && (script[cpos] == ';')) {
++cpos;
}
return true;
}
bool Interpreter::Impl::expandAllMacros(std::string& script) {
size_t cpos = 0;
while (cpos < script.size()) {
if (skipOneSpareSymbol(script, cpos)) {
continue;
}
if (!startWith(script, cpos, "#macro")) {
++cpos;
continue;
}
const size_t declStart = cpos;
cpos += 6;
const std::string mname = getNextParam(script, cpos, '{');
--cpos;
const std::string mvalue = getIntroScript(script, cpos, '{', '}');
if (mname.empty() || mvalue.empty()) {
return failParse(cpos, 0, "empty macro declaration");
}
m_macro["#" + mname] = mvalue;
size_t declEnd = cpos;
if ((declEnd < script.size()) && (script[declEnd] == ';')) {
++declEnd;
}
script.erase(declStart, declEnd - declStart);
cpos = declStart;
}
cpos = 0;
while (cpos < script.size()) {
if (skipOneSpareSymbol(script, cpos)) {
continue;
}
if (script[cpos] != '#') {
++cpos;
continue;
}
size_t cposMName = cpos;
const std::string mname = getMacroAtFirst(script, cposMName);
if (mname.empty() || (m_macro.find(mname) == m_macro.end())) {
return failParse(cpos, 0, "unknown macro");
}
size_t cposArg = cposMName;
const std::string args = getIntroScript(script, cposArg, '(', ')');
std::string macro = m_macro[mname];
if (!args.empty() && !parseMacroArgs(args, macro)) {
return failParse(cpos, 0, "invalid macro arguments");
}
cleaningScript(macro);
if (cposArg == cposMName) {
script.replace(cpos, mname.size(), macro);
}
else {
script.replace(cpos, (mname + "(" + args + ")").size(), macro);
}
}
return true;
}
bool Interpreter::Impl::parseInstrMacro(std::string& script, size_t& cpos, size_t gpos) {
if (startWith(script, cpos, "#macro")) {
cpos += 6;
const std::string mname = getNextParam(script, cpos, '{');
--cpos;
const std::string mvalue = getIntroScript(script, cpos, '{', '}');
if (mname.empty() || mvalue.empty()) {
return failParse(cpos, gpos, "empty macro declaration");
}
m_macro["#" + mname] = mvalue;
if ((cpos < script.size()) && (script[cpos] == ';')) {
++cpos;
}
return true;
}
if (cpos >= script.size() || script[cpos] != '#') {
return false;
}
size_t cposMName = cpos;
const std::string mname = getMacroAtFirst(script, cposMName);
if (mname.empty() || (m_macro.find(mname) == m_macro.end())) {
return failParse(cpos, gpos, "unknown macro");
}
size_t cposArg = cposMName;
const std::string args = getIntroScript(script, cposArg, '(', ')');
std::string macro = m_macro[mname];
if (!args.empty() && !parseMacroArgs(args, macro)) {
return failParse(cpos, gpos, "invalid macro arguments");
}
cleaningScript(macro);
if (cposArg == cposMName) {
script.replace(cpos, mname.size(), macro);
}
else {
script.replace(cpos, (mname + "(" + args + ")").size(), macro);
}
return true;
}
bool Interpreter::Impl::parseInstrGotoLabel(std::string& script, size_t& cpos, size_t gpos,
size_t& iExpr) {
if (startWith(script, cpos, "goto")) {
cpos += 4;
const std::string lname = getNextParam(script, cpos, ';');
if (lname.empty()) {
return failParse(cpos, gpos, "empty goto label");
}
if (m_label.find(lname) == m_label.end()) {
m_label.insert({ lname, ir::detail::kNoIndex });
}
emplaceExpr(iExpr, Keyword::GOTO, Interpreter::makeParam(lname));
return true;
}
if (!startWith(script, cpos, "l_")) {
return false;
}
const std::string lname = getNextParam(script, cpos, ':');
if (lname.empty()) {
return failParse(cpos, gpos, "empty label name");
}