-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsalaprogram.cpp
More file actions
1661 lines (1587 loc) · 66.4 KB
/
Copy pathsalaprogram.cpp
File metadata and controls
1661 lines (1587 loc) · 66.4 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
// SPDX-FileCopyrightText: 2011-2012 Tasos Varoudis
//
// SPDX-License-Identifier: GPL-3.0-or-later
// salaprogram.cpp - a component of sala - spatial network analysis
// platform SalaScripting language
/////////////////////////////////////////////////////////////////////////
// SalaScripting language
// A "Pythonesque" language, which is pre-interpretted, and thus generally
// should run fairly fast
// The class implementation is very much hardcoded for built-in classes,
// so user defined classes will be difficult to implement
// (but would you really want classes in an inbuilt scripting language?! -- I
// guess some people would)
// User defined functions are not included yet, but should be fairly easy using
// a global function stack alongside the global variable stack
#include "salaprogram.hpp"
#include "connector.hpp"
#include "latticemap.hpp"
#include "ngraph.hpp"
#include "shapemap.hpp"
#include <cmath>
#include <cstring>
#include <time.h>
///////////////////////////////////////////////////////////////////////////////////////////////
// Assign and list access rather incongruently in math ops, but never mind:
namespace {
bool g_sala_loaded = false;
std::vector<SalaFuncLabel> g_sala_math_ops;
std::vector<SalaFuncLabel> g_sala_comp_ops;
std::vector<SalaFuncLabel> g_sala_logical_ops;
std::vector<SalaFuncLabel> g_sala_global_funcs;
std::vector<SalaMemberFuncLabel> g_sala_member_funcs;
void loadSalaProgram() {
// math ops
g_sala_math_ops.push_back(SalaFuncLabel(SalaObj::S_ADD, "+", "add"));
g_sala_math_ops.push_back(SalaFuncLabel(SalaObj::S_SUBTRACT, "-", "subtract"));
g_sala_math_ops.push_back(SalaFuncLabel(SalaObj::S_MINUS, "-", "negative"));
g_sala_math_ops.push_back(SalaFuncLabel(SalaObj::S_PLUS, "+", "positive"));
g_sala_math_ops.push_back(SalaFuncLabel(SalaObj::S_MULTIPLY, "*", "multiply"));
g_sala_math_ops.push_back(SalaFuncLabel(SalaObj::S_DIVIDE, "/", "divide"));
g_sala_math_ops.push_back(SalaFuncLabel(SalaObj::S_MODULO, "%", "modulo"));
g_sala_math_ops.push_back(SalaFuncLabel(SalaObj::S_POWER, "^", "power"));
g_sala_math_ops.push_back(SalaFuncLabel(SalaObj::S_ASSIGN, "=", "assignment"));
g_sala_math_ops.push_back(SalaFuncLabel(SalaObj::S_LIST_ACCESS, "[]",
"list access")); // list access included even though
// not parsed directly like this
// comp ops
g_sala_comp_ops.push_back(SalaFuncLabel(SalaObj::S_GT, ">", "greater than"));
g_sala_comp_ops.push_back(SalaFuncLabel(SalaObj::S_LT, "<", "less than"));
g_sala_comp_ops.push_back(SalaFuncLabel(SalaObj::S_GEQ, ">=", "greater than or equal to"));
g_sala_comp_ops.push_back(SalaFuncLabel(SalaObj::S_LEQ, "<=", "less than or equal to"));
g_sala_comp_ops.push_back(SalaFuncLabel(SalaObj::S_NEQ, "!=", "not equal to"));
g_sala_comp_ops.push_back(SalaFuncLabel(SalaObj::S_EQ, "==", "equal to"));
g_sala_comp_ops.push_back(SalaFuncLabel(SalaObj::S_IS, "is", "is the same object as"));
// logical ops
g_sala_logical_ops.push_back(SalaFuncLabel(SalaObj::S_NOT, "not", "logical not"));
g_sala_logical_ops.push_back(SalaFuncLabel(SalaObj::S_NOT, "!", "logical not"));
g_sala_logical_ops.push_back(SalaFuncLabel(SalaObj::S_AND, "and", "logical and"));
g_sala_logical_ops.push_back(SalaFuncLabel(SalaObj::S_AND, "&&", "logical and"));
g_sala_logical_ops.push_back(SalaFuncLabel(SalaObj::S_OR, "or", "logical or"));
g_sala_logical_ops.push_back(SalaFuncLabel(SalaObj::S_OR, "||", "logical or"));
// global functions
g_sala_global_funcs.push_back(SalaFuncLabel(SalaObj::S_SQRT, "sqrt", "square root"));
g_sala_global_funcs.push_back(SalaFuncLabel(SalaObj::S_LOG, "log", "log base 10"));
g_sala_global_funcs.push_back(SalaFuncLabel(SalaObj::S_LN, "ln", "natural logarithm"));
g_sala_global_funcs.push_back(
SalaFuncLabel(SalaObj::S_RAND, "random", "random number (0.0 to 1.0)"));
g_sala_global_funcs.push_back(SalaFuncLabel(SalaObj::S_SIN, "sin", "sine"));
g_sala_global_funcs.push_back(SalaFuncLabel(SalaObj::S_COS, "cos", "cosine"));
g_sala_global_funcs.push_back(SalaFuncLabel(SalaObj::S_TAN, "tan", "tangent"));
g_sala_global_funcs.push_back(SalaFuncLabel(SalaObj::S_ASIN, "asin", "inverse sine"));
g_sala_global_funcs.push_back(SalaFuncLabel(SalaObj::S_ACOS, "acos", "inverse cosine"));
g_sala_global_funcs.push_back(SalaFuncLabel(SalaObj::S_ATAN, "atan", "inverse tangent"));
g_sala_global_funcs.push_back(
SalaFuncLabel(SalaObj::S_LEN, "len", "array or string length"));
g_sala_global_funcs.push_back(SalaFuncLabel(SalaObj::S_RANGE, "range", "set of integers"));
// member functions
g_sala_member_funcs.push_back(
SalaMemberFuncLabel(SalaObj::S_LIST, SalaObj::S_FAPPEND, "append", "append item"));
g_sala_member_funcs.push_back(
SalaMemberFuncLabel(SalaObj::S_LIST, SalaObj::S_FEXTEND, "extend", "extend by list"));
g_sala_member_funcs.push_back(
SalaMemberFuncLabel(SalaObj::S_LIST, SalaObj::S_FPOP, "pop", "pop (last) item"));
g_sala_member_funcs.push_back(
SalaMemberFuncLabel(SalaObj::S_LIST, SalaObj::S_FCLEAR, "clear", "clear contents"));
g_sala_member_funcs.push_back(SalaMemberFuncLabel(SalaObj::S_GRAPHOBJ, SalaObj::S_FVALUE,
"value", "get attribute value"));
g_sala_member_funcs.push_back(SalaMemberFuncLabel(SalaObj::S_GRAPHOBJ, SalaObj::S_FSETVALUE,
"setvalue", "set attribute value"));
g_sala_member_funcs.push_back(
SalaMemberFuncLabel(SalaObj::S_GRAPHOBJ, SalaObj::S_FMARK, "mark", "get node mark"));
g_sala_member_funcs.push_back(SalaMemberFuncLabel(SalaObj::S_GRAPHOBJ, SalaObj::S_FSETMARK,
"setmark", "set node mark"));
g_sala_member_funcs.push_back(SalaMemberFuncLabel(SalaObj::S_GRAPHOBJ,
SalaObj::S_FCONNECTIONS, "connections",
"get list of connections"));
g_sala_loaded = true;
}
} // namespace
///////////////////////////////////////////////////////////////////////////////////////////////
SalaProgram::SalaProgram(SalaObj context)
: m_rootCommand(), m_varStack(), m_errorStack(), m_col(), m_marked(false), _padding0(0),
m_thisobj(), m_marks() {
if (!g_sala_loaded) {
loadSalaProgram();
}
// col is used when run in update mode, it does not form part of the program:
m_col = -1;
m_thisobj = context;
}
SalaProgram::~SalaProgram() {}
// use istrstream to make an istream from a string:
// istrstream file(char *);
bool SalaProgram::parse(std::istream &program) {
m_varStack.clear();
m_errorStack.clear();
// this ensures wipe of any pre-existing variables in the global context:
m_rootCommand = SalaCommand(this, nullptr, -1, SalaCommand::SC_ROOT);
int line = 0;
SalaCommand *parent = &m_rootCommand;
while (!program.eof()) {
// the problem with a language being "Pythonesque" is that the "end" of
// any control is implicit through the amount of indentation
// Thus, the parser eats the white space, only handing of control
// to a function when it is ready to parse, and knows its parent
int indent = 0;
bool endloop = false;
while (!endloop) {
std::istream::traits_type::int_type c = program.peek();
if (c == std::istream::traits_type::eof()) {
read(program); // actually shift onto the eof character
break;
}
auto ch = std::istream::traits_type::to_char_type(c);
switch (ch) {
case ' ':
indent++;
break;
case 13:
break; // ignore
case '\n':
line++;
indent = 0;
break;
case '#':
// hit comment, read to end of line:
while (std::istream::traits_type::not_eof(c) && ch != '\n') {
read(program);
c = program.peek();
ch = std::istream::traits_type::to_char_type(c);
}
line++;
break;
case '\\':
// hit line continuation, ignore everything after it:
while (std::istream::traits_type::not_eof(c) && ch != '\n') {
read(program);
c = program.peek();
ch = std::istream::traits_type::to_char_type(c);
}
line++;
break;
default:
endloop = true;
break;
}
if (!endloop) {
read(program);
}
}
// okay, we now know indent level, and we are ready to parse:
if (!program.eof()) {
while (indent <= parent->m_indent) {
parent = parent->m_parent;
}
parent->m_children.push_back(SalaCommand(this, parent, indent));
// TODO (PK): Coverity here suggests that .back() creates a use-after-free
// issue because the above push_back invalidates m_children. Since this is a
// neglacted piece of code, we'll disable the warning until a closer look is
// taken on all of salapgrogam.hpp/.cpp
/* coverity[use_after_free] */
SalaCommand &thiscommand = parent->m_children.back();
try {
line = thiscommand.parse(program, line);
} catch (SalaError e) {
if (e.lineno == -1)
e.lineno = line;
m_errorStack.push_back(std::move(e));
return false;
}
// sort out commands capable of having children:
if (thiscommand.m_command == SalaCommand::SC_FOR ||
thiscommand.m_command == SalaCommand::SC_IF ||
thiscommand.m_command == SalaCommand::SC_WHILE) {
parent = &thiscommand;
} else if (thiscommand.m_command == SalaCommand::SC_ELSE) {
if (parent->m_children.size() < 2) {
m_errorStack.push_back(SalaError(
"'Else' must be preceded by an 'if','for' or 'while'", thiscommand.m_line));
return false;
}
int command = parent->m_children[parent->m_children.size() - 2].m_command;
if (command != SalaCommand::SC_IF && command != SalaCommand::SC_ELIF &&
command != SalaCommand::SC_FOR && command != SalaCommand::SC_WHILE) {
m_errorStack.push_back(SalaError(
"'Else' must be preceded by an 'if','for' or 'while'", thiscommand.m_line));
return false;
}
parent = &thiscommand;
} else if (thiscommand.m_command == SalaCommand::SC_ELIF) {
if (parent->m_children.size() < 2) {
m_errorStack.push_back(SalaError("'Elif' must be preceded by an 'if' condition",
thiscommand.m_line));
return false;
}
int command = parent->m_children[parent->m_children.size() - 2].m_command;
if (command != SalaCommand::SC_IF && command != SalaCommand::SC_ELIF) {
m_errorStack.push_back(SalaError("'Elif' must be preceded by an 'if' condition",
thiscommand.m_line));
return false;
}
parent = &thiscommand;
}
}
}
// do a quick check that all 'for', 'if' and 'elif' have children:
// TO DO!
return true;
}
SalaObj SalaProgram::evaluate() {
for (size_t i = 0; i < m_varStack.size(); i++) {
// uninitialise all variables:
m_varStack[i].uninit();
}
m_marked = false;
// run the program
SalaObj obj;
bool ret = false, ifhandled = false;
m_rootCommand.evaluate(obj, ret, ifhandled);
// clear marks if they've been used:
if (m_marked) {
m_marks.clear();
m_marked = false;
}
return obj;
}
// this function is called by sala to run a script to update a column
// the operation is on a single node / row of the database combination
bool SalaProgram::runupdate(int col, const std::set<int> &selset) {
AttributeTable *table = m_thisobj.getTable();
//
// note: reference, will change object directly, which is important for
// commands running the program
int &row = m_thisobj.m_data.graph.node;
m_col = col;
if (selset.size()) {
for (auto &sel : selset) {
row = sel;
try {
SalaObj val = evaluate();
float v = static_cast<float>(val.toDouble()); // note, toDouble will type check and
// throw if there's a problem
if (!std::isfinite(v)) {
v = -1.0f;
}
table->getRow(AttributeKey(sel)).setValue(static_cast<size_t>(m_col), v);
} catch (SalaError e) {
// error
m_errorStack.push_back(e);
return false;
}
}
} else {
for (auto iter = table->begin(); iter != table->end(); iter++) {
row = iter->getKey().value;
try {
SalaObj val = evaluate();
float v = static_cast<float>(val.toDouble()); // note, toDouble will type check and
// throw if there's a problem
if (!std::isfinite(v)) {
v = -1.0f;
}
iter->getRow().setValue(static_cast<size_t>(m_col), v);
} catch (SalaError e) {
// error
m_errorStack.push_back(e);
return false;
}
}
}
return true;
}
// this function is called by sala to run a script to select values
// the operation is on a single node / row of the database combination
bool SalaProgram::runselect(std::vector<int> &selsetout, const std::set<int> &selsetin) {
AttributeTable *table = m_thisobj.getTable();
if (selsetin.size()) {
for (auto &key : selsetin) {
try {
SalaObj val = evaluate();
bool v = val.toBool(); // note, toBool will type check and throw if
// there's a problem
if (v) {
selsetout.push_back(key);
}
} catch (SalaError e) {
// error
m_errorStack.push_back(e);
return false;
}
}
} else {
for (auto iter = table->begin(); iter != table->end(); iter++) {
int key = iter->getKey().value;
try {
SalaObj val = evaluate();
bool v = val.toBool(); // note, toBool will type check and throw if
// there's a problem
if (v) {
selsetout.push_back(key);
}
} catch (SalaError e) {
// error
m_errorStack.push_back(e);
return false;
}
}
}
return true;
}
std::string SalaProgram::getLastErrorMessage() const {
const SalaError &error = m_errorStack.back();
if (error.lineno == -1) {
return error.message;
} else {
return error.message + " on line " + dXstring::formatString(error.lineno + 1, "%d");
}
}
////////////////////////////////////////////////////////////////////////////
SalaCommand::SalaCommand(SalaProgram *program, SalaCommand *parent, int indent, Command command)
: m_program(program), m_parent(parent), m_children(), m_varNames(), m_command(command),
m_indent(indent), m_evalStack(), m_funcStack(), m_forIter(), _padding0(0), m_line(0),
m_lastString() {}
int SalaCommand::parse(std::istream &program, int line) {
m_funcStack.clear();
m_evalStack.clear();
m_varNames.clear();
m_command = SC_NONE;
// useful to know which line the command starts on for debugging purposes
m_line = line;
int last = SP_FUNCTION;
bool endloop = false;
bool overridecache = false;
SalaBuffer buffer;
char cache = ' ';
//
while (!endloop && !program.eof()) {
char alpha = read(program);
switch (alpha) {
// string constant
case '\"':
case '\'': // variants: either delimit with single or double quotes
if (!buffer.empty()) {
decode(buffer);
buffer.clear();
}
{
char delim = alpha;
std::istream::traits_type::int_type b = program.peek();
char beta = std::istream::traits_type::to_char_type(b);
while (std::istream::traits_type::not_eof(b) && beta != '\n' &&
(beta != delim || alpha == '\\')) {
alpha = read(program);
b = program.peek();
beta = std::istream::traits_type::to_char_type(b);
buffer.add(alpha);
}
if (b == std::istream::traits_type::eof() || beta == '\n') {
throw SalaError("No closing quote", m_line);
} else {
read(program); // take off closing quote and discard
}
// add even if the string constant is empty:
m_evalStack.push_back(std::string(buffer));
buffer.clear();
last = SP_DATA;
}
break;
// operator stack
case '+':
case '-':
if (!buffer.empty()) {
last = decode(buffer);
if (last & SP_NUMBER && cache == 'e') {
// check for 9.999e+99...
// decode will handle later:
buffer.add(alpha);
break;
}
// otherwise handled, clear the buffer:
buffer.clear();
}
if (last == SP_FUNCTION || last == SP_COMMAND) {
pushFunc(alpha == '+' ? SalaObj(SalaObj::S_PLUS) : SalaObj(SalaObj::S_MINUS));
} else {
pushFunc(alpha == '+' ? SalaObj(SalaObj::S_ADD) : SalaObj(SalaObj::S_SUBTRACT));
}
last = SP_FUNCTION;
break;
case '=':
if (!buffer.empty()) {
// n.b., this will catch '>=', '<=', '==' and '!='
if (strchr("><=!", cache) != nullptr) {
buffer.add(alpha);
last = decode(buffer);
buffer.clear();
overridecache = true;
// handled next step (see default clause below)
break;
} else {
last = decode(buffer);
buffer.clear();
}
}
buffer.add(alpha); // <- '=' decoded later
break;
case '!':
case '<':
case '>':
if (!buffer.empty()) {
last = decode(buffer);
buffer.clear();
}
// note: this looks a little odd, simply adding to the buffer, but these
// are handled by the default function next step if still hanging on the
// buffer
buffer.add(alpha);
break;
case '/':
case '*':
case '%':
case '^':
if (!buffer.empty()) {
decode(buffer);
buffer.clear();
}
last = decode(std::string(1, alpha));
break;
case '(':
// note: the opening bracket forms a function
if (!buffer.empty()) {
last = decode(buffer);
buffer.clear();
}
if (last == SP_DATA) {
// whatever that just went onto the eval stack, the user thought it was
// a function... alert them:
throw SalaError(m_lastString + " is not a known function name", m_line);
// (in the future, we may well want to transfer an object hashed
// function name to the func stack instead)
} else if (last == SP_NUMBER) {
throw SalaError("Cannot treat a number as if it were a function", m_line);
}
// check for pair of open / close brackets: () or ( ) -- this is a null
// value
{
std::istream::traits_type::int_type b = program.peek();
char beta = std::istream::traits_type::to_char_type(b);
while (std::istream::traits_type::not_eof(b) && beta == ' ') {
alpha = read(program);
b = program.peek();
beta = std::istream::traits_type::to_char_type(b);
}
if (beta == ')') {
alpha = read(program);
m_evalStack.push_back(SalaObj());
last = SP_DATA;
} else {
pushFunc(SalaObj::S_OPEN_BRACKET);
last = SP_FUNCTION;
}
}
break;
case ')':
// note: the closing bracket forms a data packet:
if (!buffer.empty()) {
decode(buffer);
buffer.clear();
}
pushFunc(SalaObj::S_CLOSE_BRACKET);
last = SP_DATA;
break;
case '[':
if (!buffer.empty()) {
last = decode(buffer);
buffer.clear();
}
// check for pair of open / close brackets: [] or [ ] -- this is a null
// value or empty list depending on context
{
std::istream::traits_type::int_type b = program.peek();
char beta = std::istream::traits_type::to_char_type(b);
while (std::istream::traits_type::not_eof(b) && beta == ' ') {
alpha = read(program);
b = program.peek();
beta = std::istream::traits_type::to_char_type(b);
}
if (beta == ']') {
alpha = read(program);
if (last == SP_DATA) {
throw SalaError("Accessor operator ('[]') requires a parameter", m_line);
} else {
// put an empty list on the stack
m_evalStack.push_back(SalaObj(SalaObj::S_CONST_LIST, 0));
}
last = SP_DATA;
} else {
if (last == SP_DATA) {
// list accessor function
pushFunc(SalaObj::S_LIST_ACCESS);
pushFunc(SalaObj::S_OPEN_SQR_BRACKET_ACCESS);
} else {
// making an list...
pushFunc(SalaObj::S_OPEN_SQR_BRACKET_LIST);
}
last = SP_FUNCTION;
}
}
break;
case ']':
// note: the closing bracket forms a data packet:
if (!buffer.empty()) {
decode(buffer);
buffer.clear();
}
pushFunc(SalaObj::S_CLOSE_SQR_BRACKET);
last = SP_DATA;
break;
case ',':
if (!buffer.empty()) {
decode(buffer);
buffer.clear();
}
pushFunc(SalaObj::S_COMMA);
last = SP_FUNCTION;
break;
case ':':
if (!buffer.empty()) {
last = decode(buffer);
buffer.clear();
}
// end of command (def, if, else, elif and for)
if (m_command == SC_FOR || m_command == SC_WHILE || m_command == SC_IF ||
m_command == SC_ELIF || m_command == SC_ELSE) {
bool commentfound = false;
alpha = read(program);
while (!program.eof() && alpha != '\n') {
// continue to end of line, only comments allowed though!
if (!commentfound) {
if (alpha == '#') {
commentfound = true;
} else if (alpha != ' ' &&
alpha != 13) { // 13 ignored, as it appears \n is 10 in
// this stream... (so 13,10 can be found)
throw SalaError("'For', 'if', 'else', etc cannot have execution part "
"on same line; insert a new line after ':'",
m_line);
}
}
alpha = read(program);
}
line++;
endloop = true;
} else {
throw SalaError("Unexpected colon ':' in expression", m_line);
}
break;
// end of line:
case '\\':
// hit line continuation, read to end of line:
if (!buffer.empty()) {
last = decode(buffer);
buffer.clear();
}
while (!program.eof() && program.get() != '\n')
;
// note, end loop is not set, this is a continuation character
line++; // line is incremented, although it this command will still start
// on the original line
break;
case '#':
// loop through until hit \n or end
if (!buffer.empty()) {
last = decode(buffer);
buffer.clear();
}
while (!program.eof() && program.get() != '\n')
;
line++; // should have hit a line end (or if it's end of file, it doesn't
// matter)
endloop = true;
break;
case '\n':
// force end of command parse:
if (!buffer.empty()) {
last = decode(buffer);
buffer.clear();
}
line++; // hit a line end
endloop = true;
break;
case ' ':
// white space: read word
if (!buffer.empty()) {
last = decode(buffer);
buffer.clear();
}
break;
case '.':
// currently handled inelegantly through decode for either number (1.002)
// or member access (blah.x())
buffer.add('.');
break;
case '\t':
throw SalaError("Tab character found: please use only spaces to indent lines", m_line);
default:
if (strchr("<>=!", cache)) {
// >, <, = and ! are held as next step operators
last = decode(buffer);
buffer.clear();
}
if (!program.eof() &&
alpha != 13) { // 13 ignored, as it appears \n is 10 in this stream...
if (!isalphanum_(alpha) && alpha != '&' &&
alpha != '|') { // include & and | for and and or
throw SalaError("Unrecognised symbol ('" + std::string(1, alpha) + "')",
m_line);
}
buffer.add(alpha);
}
break;
}
if (overridecache) {
cache = ' ';
overridecache = false;
} else {
cache = alpha;
}
if (last == SP_COMMAND) {
if (m_command == SC_FOR) {
// check the name of the for variable:
alpha = read(program);
while (alpha == ' ') {
alpha = read(program);
}
if (!isalpha_(alpha)) {
throw SalaError("'For' command expecting variable name", m_line);
}
while (isalphanum_(alpha)) {
buffer.add(alpha);
alpha = read(program);
}
if (alpha != ' ') {
throw SalaError("Command expecting syntax 'for xyz in'...", m_line);
}
// add the for iterator variable:
m_program->m_varStack.push_back(SalaObj());
int x = static_cast<int>(m_program->m_varStack.size() - 1);
m_varNames.insert(std::make_pair(buffer, x));
m_forIter = SalaObj(SalaObj::S_VAR, x);
// now check for 'in'
while (alpha == ' ') {
alpha = read(program);
}
if (alpha != 'i' || program.get() != 'n') {
throw SalaError("Command expecting syntax 'for xyz in'...", m_line);
}
}
last = SP_FUNCTION;
}
}
if (!buffer.empty()) {
decode(buffer);
buffer.clear();
}
// push remaining functions onto eval stack:
while (m_funcStack.size()) {
if (m_funcStack.back().m_type & SalaObj::S_BRACKET) {
throw SalaError("Unmatched brackets", m_line);
}
m_evalStack.push_back(m_funcStack.back());
m_funcStack.pop_back();
}
if (m_evalStack.size() == 0 && m_command != SC_ELSE) { // note, else is by definition empty
throw SalaError("Partial or missing command", m_line);
}
return line;
}
int SalaCommand::decode(std::string string) // string copied as makelower applied
{
// ideally, some form of hashing the string should be performed so that
// functions can be found quicker than a long list of "else ifs"
int retvar = SP_NONE;
dXstring::toLower(string);
if (m_command == SC_NONE) {
if (string == "return") {
m_command = SC_RETURN;
retvar = SP_COMMAND;
} else if (string == "for") {
m_command = SC_FOR; // n.b. will still need a variable name and "in": for x in ...
retvar = SP_COMMAND;
} else if (string == "while") {
m_command = SC_WHILE;
retvar = SP_COMMAND;
} else if (string == "if") {
m_command = SC_IF;
retvar = SP_COMMAND;
} else if (string == "elif") {
m_command = SC_ELIF;
retvar = SP_COMMAND;
} else if (string == "else") {
m_command = SC_ELSE;
retvar = SP_COMMAND;
}
}
if (retvar == SP_COMMAND) {
//
m_lastString = std::move(string); // make a copy for debugging purposes
return retvar;
}
// numeric constant
if (isdigit(string[0]) || (string.length() > 1 && string[0] == '.' && isdigit(string[1]))) {
if (string[string.length() - 1] == 'e') {
// handle later... at the moment we have hit + or - in 9.999e+99
// or 9.999e-99
m_lastString = std::move(string); // make a copy for debugging purposes
return SP_NUMBER;
}
if (string.find_first_of('.') != std::string::npos ||
string.find_first_of('e') != std::string::npos) {
m_evalStack.push_back(atof(string.c_str()));
} else {
m_evalStack.push_back(atoi(string.c_str()));
}
retvar = SP_NUMBER;
}
// this is a different 'e' to the 'e' above -> natural logarithm
else if (string == "e") {
m_evalStack.push_back(2.7182818284590452353602874713527);
retvar = SP_NUMBER;
} else if (string == "pi") {
m_evalStack.push_back(3.1415926535897932384626433832795);
retvar = SP_NUMBER;
}
// boolean constants
else if (string == "true") {
m_evalStack.push_back(bool(true));
retvar = SP_NUMBER;
} else if (string == "false") {
m_evalStack.push_back(bool(false));
retvar = SP_NUMBER;
}
// this
else if (string == "this") {
m_evalStack.push_back(SalaObj(SalaObj::S_THIS));
retvar = SP_DATA;
} else if (string == "none") {
m_evalStack.push_back(SalaObj());
retvar = SP_DATA;
} else {
// everything else should be in one of the operator / func lists:
size_t i;
if (retvar == SP_NONE) {
// note, math ops include assignment
for (i = 0; i < g_sala_math_ops.size(); i++) {
if (string == g_sala_math_ops[i].name) {
pushFunc(g_sala_math_ops[i].func);
retvar = SP_FUNCTION;
break;
}
}
}
if (retvar == SP_NONE) {
for (i = 0; i < g_sala_comp_ops.size(); i++) {
if (string == g_sala_comp_ops[i].name) {
pushFunc(g_sala_comp_ops[i].func);
retvar = SP_FUNCTION;
break;
}
}
}
if (retvar == SP_NONE) {
for (i = 0; i < g_sala_logical_ops.size(); i++) {
if (string == g_sala_logical_ops[i].name) {
pushFunc(g_sala_logical_ops[i].func);
retvar = SP_FUNCTION;
break;
}
}
}
if (retvar == SP_NONE) {
for (i = 0; i < g_sala_global_funcs.size(); i++) {
if (string == g_sala_global_funcs[i].name) {
pushFunc(g_sala_global_funcs[i].func);
retvar = SP_FUNCTION;
}
}
}
}
if (retvar == SP_NONE) {
size_t ndot = string.find_first_of(".");
if (ndot != std::string::npos) {
if (ndot > 0) {
decode(string.substr(0, ndot));
}
if (decode_member(string.substr(ndot + 1), false) == SP_NONE) {
throw SalaError(
"There is no known member function called " + string.substr(ndot + 1), m_line);
}
retvar = SP_FUNCTION;
} else {
// see if it's a member function of 'this':
retvar = decode_member(string, true);
if (retvar == SP_NONE) {
// see if it exists in the variable stack (walk up scope)
SalaCommand *parent = m_parent;
auto n = parent->m_varNames.end();
int x = -1;
while (parent != nullptr) {
n = parent->m_varNames.find(string);
if (n != parent->m_varNames.end()) {
x = n->second;
parent = nullptr;
} else {
parent = parent->m_parent;
}
}
if (x != -1) {
m_evalStack.push_back(SalaObj(SalaObj::S_VAR, x));
retvar = SP_DATA;
} else {
m_program->m_varStack.push_back(SalaObj());
x = static_cast<int>(m_program->m_varStack.size() - 1);
// note: attach simply to your m_parent, not parent variable, which
// has walked up the stack
m_parent->m_varNames.insert(std::make_pair(string, x));
m_evalStack.push_back(SalaObj(SalaObj::S_VAR, x));
retvar = SP_DATA;
}
}
}
}
if (retvar == SP_NONE) {
// should never reach this point
throw SalaError("There is no known function or variable called " + string, m_line);
}
if (m_command == SC_NONE) {
m_command = SC_EXPR;
}
m_lastString = std::move(string); // make a copy for debugging purposes
return retvar;
}
// note, thisobj not usually known (type S_NALL),
// but, depending where SalaScript is called from, it may be:
// a graph node / table row (for "select by query" and "edit connections")
// a map (not yet implemented, but intended for scripting agents)
int SalaCommand::decode_member(const std::string &string, bool applyToThis) {
int retvar = SP_NONE;
// note, all hardcoded for built in classes:
// string classes:
for (size_t i = 0; i < g_sala_member_funcs.size(); i++) {
// note '&' in the type -- essentially allows for inheritance between
// objects (tuple is type of list, etc)
if (!applyToThis || (m_program->m_thisobj.m_type & g_sala_member_funcs[i].type) != 0) {
if (string == g_sala_member_funcs[i].name) {
pushFunc(g_sala_member_funcs[i].func);
retvar = SP_FUNCTION;
break;
}
}
}
if (retvar == SP_FUNCTION && applyToThis) {
m_evalStack.push_back(SalaObj(SalaObj::S_THIS));
}
return retvar;
}
void SalaCommand::pushFunc(const SalaObj &func) {
// note comma is part of the "Bracket" class of things:
if (func.m_type & SalaObj::S_BRACKET) {
if (func.m_type == SalaObj::S_CLOSE_BRACKET) {
while (m_funcStack.size() && m_funcStack.back().m_type != SalaObj::S_OPEN_BRACKET) {
m_evalStack.push_back(m_funcStack.back());
m_funcStack.pop_back();
}
if (m_funcStack.size()) {
// don't necessarily pop it... if it's a group marker, we want to hang
// onto it:
if (m_funcStack.back().m_data.count > 1) {
m_funcStack.back().m_type = SalaObj::S_CONST_TUPLE;
m_evalStack.push_back(m_funcStack.back());
}
m_funcStack.pop_back(); // remove opening bracket
}
} else if (func.m_type == SalaObj::S_CLOSE_SQR_BRACKET) {
while (m_funcStack.size() &&
(m_funcStack.back().m_type & SalaObj::S_OPEN_SQR_BRACKET) == 0) {
m_evalStack.push_back(m_funcStack.back());
m_funcStack.pop_back();
}
if (m_funcStack.size()) {
// don't pop it, always make a list from a make list command, even if
// it's only one item long:
if (m_funcStack.back().m_type == SalaObj::S_OPEN_SQR_BRACKET_LIST ||
m_funcStack.back().m_data.count > 1) {
m_funcStack.back().m_type = SalaObj::S_CONST_LIST;
m_evalStack.push_back(m_funcStack.back());
}
m_funcStack.pop_back();
}
} else if (func.m_type == SalaObj::S_COMMA) {
// go and increment your associated group / list
while (m_funcStack.size() && m_funcStack.back().m_type != SalaObj::S_OPEN_BRACKET &&
(m_funcStack.back().m_type & SalaObj::S_OPEN_SQR_BRACKET) == 0) {
m_evalStack.push_back(m_funcStack.back());
m_funcStack.pop_back();
}
if (m_funcStack.size()) {
m_funcStack.back().m_data.count++;
}
} else {
m_funcStack.push_back(func);
}
} else if (!m_funcStack.size() ||
func.precedence() > m_funcStack.back().precedence()) { // original: >
m_funcStack.push_back(func);