-
Notifications
You must be signed in to change notification settings - Fork 2
/
script_parser.cpp
executable file
·1019 lines (924 loc) · 31.5 KB
/
script_parser.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
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
/*
* Copyright (C) 2000, 2013 Thierry Crozat
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact: criezy01@gmail.com
*/
#include "script_parser.h"
#include "math_utils.h"
#include <ctype.h>
/*! \fn ScriptParser::ScriptParser()
*
* Create a ScriptParser object.
*/
ScriptParser::ScriptParser() :
args_double_(NULL)
{
}
ScriptParser::~ScriptParser() {
clear();
}
void ScriptParser::clear() {
for (List<ScriptParserExpression*>::iterator it = expressions_.begin() ; it != expressions_.end() ; ++it)
delete (*it);
expressions_.clear();
delete [] args_double_;
args_double_ = NULL;
args_names_.clear();
errors_.clear();
}
/*! \fn bool ScriptParser::parse(const String &script, const StringList &variable_names)
*
* Parse the given script.
* Parsing has to be done before calling evaluate(). If a parsing
* error occurs this function return false. You can get the errors
* with nbErrors() and getError(int).
*/
bool ScriptParser::parse(
const String &script,
const StringList &variable_names
) {
clear();
args_names_ = variable_names;
if (!args_names_.isEmpty()) {
args_double_ = new double[args_names_.size()];
memset(args_double_, 0, args_names_.size() * sizeof(double));
}
breakBlock(script, expressions_, variable_names, false, errors_, args_double_);
if (!errors_.isEmpty()) {
for (List<ScriptParserExpression*>::iterator it = expressions_.begin() ; it != expressions_.end() ; ++it)
delete (*it);
expressions_.clear();
delete [] args_double_;
args_double_ = NULL;
return false;
}
return true;
}
/*! \fn StringList ScriptParser::getVariablesList(const String &script)
*
* Get the list of variables from the script. This will
* also report parsing errors, so in most cases you will
* want to check that nbErrors() return 0 after calling
* this function.
*/
StringList ScriptParser::getVariablesList(const String &script) {
// We parse the script with the breakBlock() function and auto_add_variables
// variable set to true. This is not correct because the created EquationParser
// will use different list of variables, but at least it can be used to list all
// the variables.
clear();
List<ScriptParserExpression*> expressions;
breakBlock(script, expressions, StringList(), true, errors_);
StringList variables;
for (int i = 0 ; i < expressions.size() ; ++i) {
StringList vars = expressions[i]->variablesName();
delete expressions[i];
for (int j = 0 ; j < vars.size() ; ++j) {
if (!variables.contains(vars[j]))
variables.append(vars[j]);
}
}
return variables;
}
/*! \fn void ScriptParser::evaluate(double *var)
*
* Evaluate the last script parsed with the given variable values
* or the variable values set in the VariablesValue() array if
* no value array is given.
*/
void ScriptParser::evaluate(double *var) {
if (var != NULL && args_double_ != NULL)
memcpy(args_double_, var, args_names_.size() * sizeof(double));
for (List<ScriptParserExpression*>::iterator it = expressions_.begin() ; it != expressions_.end() ; ++it)
(*it)->evaluate();
if (var != NULL && args_double_ != NULL)
memcpy(var, args_double_, args_names_.size() * sizeof(double));
}
/*! \fn double *ScriptParser::VariablesValue()
*
* Return the array of double precision floating point number
* that is used during the evaluate() call.
*/
double *ScriptParser::VariablesValue() {
return args_double_;
}
/*! \fn const StringList &ScriptParser::variablesName() const
*
* Return the list of variables used in the last script parsed.
*/
const StringList &ScriptParser::variablesName() const {
return args_names_;
}
/*! \fn int ScriptParser::nbErrors() const
*
* Get the number of script parsing errors.
*/
int ScriptParser::nbErrors() const {
return errors_.size();
}
/*! \fn String ScriptParser::getError(int index) const
*
* Get the script parsing errors.
*/
String ScriptParser::getError(int index) const {
if (index < 0 || index >= errors_.size())
return String();
return errors_[index];
}
/*! \fn String ScriptParser::getLastError() const
*
* Return the last script parsing error or an empty String
* if there is no parsing errors.
*/
String ScriptParser::getLastError() const {
return getError(nbErrors() - 1);
}
/*! \fn void ScriptParser::breakBlock(const String &script_block, List<ScriptParserExpression*> &expressions, const StringList &variable_names, bool auto_add_variables, StringList &errors, double* variable_array = NULL)
*
* Parse the given script block and fill the given ScriptParserExpression
* list with expressions found in the script. If error are found during the
* parsing they will be appended to the errors list.
*
* If \p auto_add_variables is false, you can pass the value array for the
* variables. The \p variable_array should therefore be allocated to hold as
* many value as elements in the \p variable_names list. The values will
* also be stored in the same order as the list.
*/
void ScriptParser::breakBlock(
const String &script_block, List<ScriptParserExpression*> &expressions,
const StringList &variable_names, bool auto_add_variables,
StringList &errors,
double* variable_array
) {
String script;
bool is_original_script = false;
if (!script_block.startsWith("!!")) {
is_original_script = true;
// Inject line numbers (used for parsing error messages
StrReadStream stream(script_block);
String s;
int line = 1;
while (!stream.atEnd()) {
if (line > 1)
s += '\n';
s += String::format("!!%d\n", line) + stream.readLine();
++line;
}
// remove C style comments
// remove C++ and Shell (one line) style comments
// add new line after ;
// add new line after and before } and {
// simplify new lines
// simplify any space and new line between else and if
// This way each line only contains one expression.
// This also means that if { ... } else { ... } construct will look like
// if
// {
// ....
// }
// else if
// {
// ...
// }
// else
// {
// ....
// }
// whatever the original way if was formatted
int i = 0, length = s.length();
while (i < length) {
char c = s[i];
if (i+1 < length && c == '/' && s[i+1] == '*') {
// C style comment
i += 4;
while (i < length && (s[i-2] != '*' || s[i-1] != '/')) {
// keep line numbers
if (s[i-2] == '!' && s[i-1] == '!') {
int j = i;
while (j < length && s[j] != '\n') {
if (!isdigit(s[j]))
j = length;
}
if (j < length) {
script += s.mid(i-2, j);
i = j+1;
}
}
// skip character
++i;
}
} else if (i+1 < length && c == '/' && s[i+1] == '/') {
// C++ style comment
i += 2;
while (i < length && s[i] != '\n')
++i;
} else if (c == '#') {
// Shell style comment
++i;
while (i < length && s[i] != '\n')
++i;
} else {
if (c == '{' || c == '}')
script += '\n';
script += c;
if (c == '{' || c == '}' || c == ';')
script += '\n';
++i;
if (script.endsWith("\nelse") && s.isSpace(i)) {
// check if this is followed by a if, and make sure to only keep a single
// space between the two.
int j = i + 1;
while (j < length) {
if (s.isSpace(j))
++j;
else if (
j + 2 < length && s[j-1] == '\n' && s[j] == '!' && s[j+1] == '!' &&
s[j+2] >= 48 && s[j+2] <= 57
) {
// This is a line number inserted above. Skip it.
j = j + 3;
while (j < length && s[j] >= 48 && s[j] <= 57)
++j;
if (j == length || s[j] != '\n')
break;
++j;
} else if (
j + 2 < length && s[j] == 'i' && s[j+1] == 'f' &&
(s.isSpace(j+2) || s[j+2] == '(')
) {
script += " if";
i = j + 2;
break;
} else
break;
}
}
}
}
} else
script = script_block;
// Simplify new lines and spaces
script.simplify('\n');
script.replaceChar('\t', ' ');
script.simplify(' ');
// Parsing state
// 0: normal
// 1: leaving 'if' block (=>check if we have a 'else' or 'else if' block starting)
// 2: leaving 'else if' block (=>check if we have a 'else' or 'else if' block starting)
// 3: leaving 'else' block
int state = 0;
String if_condition, else_if_condition, if_block, else_block, expression;
bool conditional_else_block = false;
// Use a StrReadStream to read the script line by line
int line_number = 1;
StrReadStream stream(script);
while (!stream.atEnd()) {
String line = stream.readLine().trimmed();
// Check there is something on the line
if (line.isEmpty())
continue;
if (line.startsWith("!!")) {
line_number = line.right(2).toInt();
continue;
}
// Check if we are leaving a block
if (line == "}") {
errors << String::format("Script parsing error line %d: unexpected '}'.",line_number);
return;
}
// If we have left a 'if', 'else if' block check if we have something more
// and complete the conditional expression if needed.
if (state == 1 || state == 2) {
if (line.startsWith("else if") && (line.length() == 7 || line.isSpace(7) || line[7] == '(')) {
// Look for start of condition
line = line.right(7).trimmed();
while (line.isEmpty() && !stream.atEnd()) {
line = stream.readLine().trimmed();
if (line.startsWith("!!")) {
line_number = line.right(2).toInt();
line.clear();
}
}
if (line[0] != '(') {
errors << String::format("Script parsing error line %d: '(' expected after 'else if'.", line_number);
return;
}
// Read condition
line = line.right(1);
if (!readCondition(else_if_condition, stream, line, line_number, errors))
return;
// Add condition
if (else_block.isEmpty())
else_block += String::format("!!%d\nif (", line_number) + else_if_condition + ")\n{\n";
else {
else_block += "else if (" + else_if_condition + ")\n{\n";
}
else_if_condition.clear();
// Read block
if (!readBlock(else_block, stream, line, line_number, errors))
return;
// Add a '}' to match the added 'if (...) {' at the beginning of the else block
else_block += "\n}\n";
state = 2;
continue;
} else if (line.startsWith("else") && (line.length() == 4 || line.isSpace(4))) {
line = line.right(4).trimmed();
// Read block
if (conditional_else_block)
else_block += " else\n{\n";
if (!readBlock(else_block, stream, line, line_number, errors))
return;
if (conditional_else_block)
else_block += "\n}\n";
state = 3;
continue;
} else
state = 3;
}
// If we are at the end of a conditional expression, create it and
// start normal reading
if (state == 3) {
ScriptParserExpression *exp = 0;
if (else_block.isEmpty())
exp = new ScriptParserConditionalExpression(if_condition, if_block, variable_names, auto_add_variables, variable_array);
else
exp = new ScriptParserConditionalExpression(if_condition, if_block, else_block, variable_names, auto_add_variables, variable_array);
expressions.append(exp);
for (int e = 0 ; e < exp->nbErrors() ; ++e)
errors.append(exp->getError(e));
if_condition.clear();
if_block.clear();
else_block.clear();
conditional_else_block = false;
state = 0;
}
// Normal reading
if (state == 0) {
// Checking if we start a if statement
if (line.startsWith("if") && (line.length() == 2 || line.isSpace(2) || line[2] == '(')) {
if (!expression.isEmpty()) {
errors << String::format("Script parsing error line %d: missing ';' before 'if'.", line_number);
return;
}
line = line.right(2).trimmed();
while (line.isEmpty() && !stream.atEnd()) {
line = stream.readLine().trimmed();
if (line.startsWith("!!")) {
line_number = line.right(2).toInt();
line.clear();
}
}
if (line[0] != '(') {
errors << String::format("Script parsing error line %d: '(' expected after 'if'.", line_number);
return;
}
line = line.right(1);
if (!readCondition(if_condition, stream, line, line_number, errors))
return;
// Read block
if (!readBlock(if_block, stream, line, line_number, errors))
return;
state = 1;
continue;
}
// Checking if we start a while statement
else if (line.startsWith("while") && (line.length() == 5 || line.isSpace(5) || line[5] == '(')) {
if (!expression.isEmpty()) {
errors << String::format("Script parsing error line %d: missing ';' before 'while'.", line_number);
return;
}
line = line.right(5).trimmed();
while (line.isEmpty() && !stream.atEnd()) {
line = stream.readLine().trimmed();
if (line.startsWith("!!")) {
line_number = line.right(2).toInt();
line.clear();
}
}
if (line[0] != '(') {
errors << String::format("Script parsing error line %d: '(' expected after 'while'.", line_number);
return;
}
// Read condition
line = line.right(1);
String while_condition;
if (!readCondition(while_condition, stream, line, line_number, errors))
return;
// Read block
String while_block;
if (!readBlock(while_block, stream, line, line_number, errors))
return;
// Create while parser object
ScriptParserExpression *exp = new ScriptParserWhileExpression(while_condition, while_block, variable_names, auto_add_variables, variable_array);
expressions.append(exp);
for (int e = 0 ; e < exp->nbErrors() ; ++e)
errors.append(exp->getError(e));
state = 0;
continue;
}
// Check we do not have a else
else if (line.startsWith("else") && (line.length() == 4 || line[4] == ' ')) {
errors << String::format("Script parsing error line %d: unexpected 'else' (not preceded by 'if' or 'else if' statement).", line_number);
return;
}
// Otherwise read until we reach a ';' (which should be at the end of a line)
else if (!line.isEmpty() && line[line.length() - 1] == ';') {
expression += line.left(-2);
if (!expression.isEmpty()) {
ScriptParserExpression *exp = new ScriptParserEquationExpression(expression, variable_names, auto_add_variables, variable_array);
expressions.append(exp);
if (exp->nbErrors() > 0) {
errors << String::format("Script parsing error line %d:invalid expression '%s'.", line_number, expression.c_str());
for (int e = 0 ; e < exp->nbErrors() ; ++e)
errors.append(exp->getError(e));
}
expression.clear();
}
} else {
expression += line;
}
}
}
if (state == 1 || state == 2 || state == 3) {
ScriptParserExpression *exp = 0;
if (else_block.isEmpty())
exp = new ScriptParserConditionalExpression(if_condition, if_block, variable_names, auto_add_variables, variable_array);
else
exp = new ScriptParserConditionalExpression(if_condition, if_block, else_block, variable_names, auto_add_variables, variable_array);
expressions.append(exp);
for (int e = 0 ; e < exp->nbErrors() ; ++e)
errors.append(exp->getError(e));
}
else if (state != 0 || !expression.isEmpty()) {
if (is_original_script)
errors << String("Script parsing error: unexpected end of script.");
else
// this function was called with a if or else block
errors << String::format("Script parsing error line %d: missing ';' before '}'.", line_number);
}
}
/*! \fn bool ScriptParser::readCondition(String &condition, StrReadStream &script, String &line, int &line_number, StringList &errors)
*
* Internal function used to read a condition from the stream.
*/
bool ScriptParser::readCondition(
String &condition, StrReadStream &stream,
String &line, int &line_number,
StringList &errors
) {
int condition_level = 1;
do {
while (!line.isEmpty() && condition_level > 0) {
int close_parenthesis_index = line.findChar(')');
if (close_parenthesis_index == -1) {
condition += line;
condition_level += line.countChar('(');
line.clear();
} else {
String left = line.left(close_parenthesis_index);
condition += left;
condition_level += left.countChar('(') - 1;
line = line.right(close_parenthesis_index + 1).trimmed();
}
}
if (condition_level == 0)
break;
// read next line
line = stream.readLine().trimmed();
// Check there is something on the line
if (line.startsWith("!!")) {
line_number = line.right(2).toInt();
line.clear();
}
} while (!stream.atEnd());
if (condition_level != 0) {
errors << String("Script parsing error: unexpected end of script (unbalanced parenthesis).");
return false;
}
// remove last parenthesis
condition = condition.left(-2).trimmed();
// check the condition is not empty
if (condition.isEmpty()) {
errors << String::format("Script parsing error line %d: empty conditional expression.", line_number);
return false;
}
return true;
}
/*! \fn bool ScriptParser::readBlock(String &block, StrReadStream &stream, String &line, int &line_number, StringList &errors)
*
* Internal function used to read a block of expressions from the stream.
*/
bool ScriptParser::readBlock(
String &block, StrReadStream &stream,
String &line, int &line_number,
StringList &errors
) {
// Look for start of block
while (line.isEmpty() && !stream.atEnd()) {
line = stream.readLine().trimmed();
if (line.startsWith("!!")) {
line_number = line.right(2 ).toInt();
line.clear();
}
}
if (line != "{") {
// single line statement (except it may have more than one level)
block += line + "\n";
if (line.endsWith(";"))
return true;
while (!stream.atEnd()) {
line = stream.readLine().trimmed();
// Check there is something on the line
if (line.isEmpty())
continue;
block += line + "\n";
if (line.startsWith("!!"))
line_number = line.right(2).toInt();
if (line == "{") {
// Forbid this. This can get confusing if we allow nested blocks in a single-line block.
// The script may not behave as the user expect.
errors << String::format("Script parsing error line %d: nested blocks inside a single line conditional is forbidden.", line_number);
return false;
}
if (line.endsWith(";"))
return true;
}
errors << String::format("Script parsing error line %d: unexpected end of script (unbalanced '{' and '}' or missing ';')", line_number);
return false;
}
int block_level = 1;
while (!stream.atEnd()) {
line = stream.readLine().trimmed();
// Check there is something on the line
if (line.isEmpty())
continue;
if (line.startsWith("!!"))
line_number = line.right(2).toInt();
// Check if we are leaving a block
if (line == "}") {
--block_level;
if (block_level == 0)
return true;
} else if (line == "{")
++block_level;
block += line + "\n";
}
errors << String::format("Script parsing error: unexpected end of script (unbalanced '{' and '}').");
return false;
}
/*! \fn ScriptParserExpression::ScriptParserExpression()
*
* Cnstructor for the ScriptParserExpression class.
*/
ScriptParserExpression::ScriptParserExpression() {
}
ScriptParserExpression::~ScriptParserExpression() {
}
/*! \fn int ScriptParserExpression::nbErrors() const
*
* Return the number of errors of this ScriptParserExpression.
*/
int ScriptParserExpression::nbErrors() const {
return 0;
}
/*! \fn String ScriptParserExpression::getError(int) const
*
* Return the error at the given index or an empty
* String if the index is out of bound.s
*/
String ScriptParserExpression::getError(int) const {
return String();
}
/***********************************************************************************
* ScriptParserConditionalExpression
***********************************************************************************/
/*! \fn ScriptParserConditionalExpression::ScriptParserConditionalExpression(const String &condition, const String &if_block, const String &else_block, const StringList &variable_names, bool auto_add_variables, double* variable_array = NULL)
*
* Create a ScriptParserConditionalExpression from the given condition
* expression and the expressions blocks in the if and else block.
*/
ScriptParserConditionalExpression::ScriptParserConditionalExpression(
const String &condition,
const String &if_block,
const String &else_block,
const StringList &variable_names,
bool auto_add_variables,
double* variable_array
) :
ScriptParserExpression(), condition_(NULL)
{
if (!condition.isEmpty()) {
// Create condition
String equation = "if(" + condition + ", 1., 0.)";
condition_ = new EquationParser();
condition_->parse(equation, variable_names, auto_add_variables, variable_array);
for (int e = 0 ; e < condition_->nbErrors() ; ++e)
errors_.append(condition_->getError(e));
// Parse if block
ScriptParser::breakBlock(if_block, if_expressions_, variable_names, auto_add_variables, errors_, variable_array);
// Parse else block
ScriptParser::breakBlock(else_block, else_expressions_, variable_names, auto_add_variables, errors_, variable_array);
}
}
/*! \fn ScriptParserConditionalExpression::ScriptParserConditionalExpression(const String &condition, const String &if_block, const StringList &variable_names, bool auto_add_variables, double* variable_array = NULL)
*
* Create a ScriptParserConditionalExpression from the given condition
* expression and the expressions block in the if block.
*/
ScriptParserConditionalExpression::ScriptParserConditionalExpression(
const String &condition,
const String &if_block,
const StringList &variable_names,
bool auto_add_variables,
double* variable_array
) :
ScriptParserExpression(), condition_(NULL)
{
if (!condition.isEmpty()) {
// Create condition
String equation = "if(" + condition + ", 1., 0.)";
condition_ = new EquationParser();
condition_->parse(equation, variable_names, auto_add_variables, variable_array);
for (int e = 0 ; e < condition_->nbErrors() ; ++e)
errors_.append(condition_->getError(e));
// Parse if block
ScriptParser::breakBlock(if_block, if_expressions_, variable_names, auto_add_variables, errors_, variable_array);
}
}
ScriptParserConditionalExpression::~ScriptParserConditionalExpression() {
delete condition_;
for (List<ScriptParserExpression*>::iterator it = if_expressions_.begin() ; it != if_expressions_.end() ; ++it)
delete (*it);
for (List<ScriptParserExpression*>::iterator it = else_expressions_.begin() ; it != else_expressions_.end() ; ++it)
delete (*it);
}
/*! \fn int ScriptParserConditionalExpression::nbErrors() const
*
* Return the number of errors.
*/
int ScriptParserConditionalExpression::nbErrors() const {
return errors_.size();
}
/*! \fn String ScriptParserConditionalExpression::getError(int index) const
*
* Return the error at the given index.
*/
String ScriptParserConditionalExpression::getError(int index) const {
if (index < 0 || index >= errors_.size())
return String();
return errors_[index];
}
/*! \fn void ScriptParserConditionalExpression::evaluate()
*
* Evaluate the condition and depending on the rsult evaluate the expressions
* in the if block or in the else block.
*/
void ScriptParserConditionalExpression::evaluate() {
if (condition_ == NULL)
return;
if (!MathUtils::isEqual(condition_->evaluate(), 0.)) {
for (List<ScriptParserExpression*>::iterator it = if_expressions_.begin() ; it != if_expressions_.end() ; ++it)
(*it)->evaluate();
} else {
for (List<ScriptParserExpression*>::iterator it = else_expressions_.begin() ; it != else_expressions_.end() ; ++it)
(*it)->evaluate();
}
}
/*! \fn StringList ScriptParserConditionalExpression::variablesName() const
*
* Returns the list of variables used in this expression.
*/
StringList ScriptParserConditionalExpression::variablesName() const {
StringList vars;
if (condition_ != NULL)
vars = condition_->variablesName();
for (int i = 0 ; i < if_expressions_.size() ; ++i) {
StringList list = if_expressions_[i]->variablesName();
for (int j = 0 ; j < list.size() ; ++j) {
if (!vars.contains(list[j]))
vars.append(list[j]);
}
}
for (int i = 0 ; i < else_expressions_.size() ; ++i) {
StringList list = else_expressions_[i]->variablesName();
for (int j = 0 ; j < list.size() ; ++j) {
if (!vars.contains(list[j]))
vars.append(list[j]);
}
}
return vars;
}
/***********************************************************************************
* ScriptParserWhileExpression
***********************************************************************************/
/*! \fn ScriptParserWhileExpression::ScriptParserWhileExpression(const String &condition, const String &block, const StringList &variable_names, bool auto_add_variables, double* variable_array = NULL)
*
* Create a ScriptParserWhileExpression from the given condition
* expression and the expressions block in the loop block.
*/
ScriptParserWhileExpression::ScriptParserWhileExpression(
const String &condition,
const String &block,
const StringList &variable_names,
bool auto_add_variables,
double* variable_array
) :
ScriptParserExpression(), condition_(NULL)
{
if (!condition.isEmpty()) {
// Create condition
String equation = "if(" + condition + ", 1., 0.)";
condition_ = new EquationParser();
condition_->parse(equation, variable_names, auto_add_variables, variable_array);
for (int e = 0 ; e < condition_->nbErrors() ; ++e)
errors_.append(condition_->getError(e));
// Parse if block
ScriptParser::breakBlock(block, expressions_, variable_names, auto_add_variables, errors_, variable_array);
}
}
ScriptParserWhileExpression::~ScriptParserWhileExpression() {
delete condition_;
for (List<ScriptParserExpression*>::iterator it = expressions_.begin() ; it != expressions_.end() ; ++it)
delete (*it);
}
/*! \fn int ScriptParserWhileExpression::nbErrors() const
*
* Return the number of errors.
*/
int ScriptParserWhileExpression::nbErrors() const {
return errors_.size();
}
/*! \fn String ScriptParserWhileExpression::getError(int) const
*
* Return the error at the given index.
*/
String ScriptParserWhileExpression::getError(int index) const {
if (index < 0 || index >= errors_.size())
return String();
return errors_[index];
}
/*! \fn void ScriptParserWhileExpression::evaluate()
*
* Evaluate the condition and while it is true execute the expressions
* in the while loop.
*/
void ScriptParserWhileExpression::evaluate() {
if (condition_ == NULL)
return;
while (!MathUtils::isEqual(condition_->evaluate(), 0.)) {
for (List<ScriptParserExpression*>::iterator it = expressions_.begin() ; it != expressions_.end() ; ++it)
(*it)->evaluate();
}
}
/*! \fn StringList ScriptParserWhileExpression::variablesName() const
*
* Returns the list of variables used in this expression.
*/
StringList ScriptParserWhileExpression::variablesName() const {
StringList vars;
if (condition_ != NULL)
vars = condition_->variablesName();
for (int i = 0 ; i < expressions_.size() ; ++i) {
StringList list = expressions_[i]->variablesName();
for (int j = 0 ; j < list.size() ; ++j) {
if (!vars.contains(list[j]))
vars.append(list[j]);
}
}
return vars;
}
/***********************************************************************************
* ScriptParserEquationExpression
***********************************************************************************/
/*! \fn ScriptParserEquationExpression::ScriptParserEquationExpression(const String &equation, const StringList &variable_names, bool auto_add_variables, double* variable_array = NULL)
*
* Build a ScriptParserEquationExpression for the given equation
* using the given parameters.
*/
ScriptParserEquationExpression::ScriptParserEquationExpression(
const String &equation,
const StringList &variable_names,
bool auto_add_variables,
double* variable_array
) :
ScriptParserExpression(), equation_(NULL)
{
if (!equation.isEmpty()) {
equation_ = new EquationParser();
equation_->parse(equation, variable_names, auto_add_variables, variable_array);
}
}
ScriptParserEquationExpression::~ScriptParserEquationExpression() {
delete equation_;
}
/*! \fn int ScriptParserEquationExpression::nbErrors() const
*
* Return the number of errors when parsing this equation.
*/
int ScriptParserEquationExpression::nbErrors() const {
if (equation_ == NULL)
return 0;
return equation_->nbErrors();
}
/*! \fn String ScriptParserEquationExpression::getError(int) const
*
* get the equation parsing errors.
*/
String ScriptParserEquationExpression::getError(int index) const {
if (equation_ == NULL)
return String();
return equation_->getError(index);
}
/*! \fn void ScriptParserEquationExpression::evaluate()
*
* Evaluate the result of this equation.
*/
void ScriptParserEquationExpression::evaluate() {
if (equation_ != NULL)
equation_->evaluate();
}
/*! \fn StringList ScriptParserEquationExpression::variablesName() const
*
* Returns the list of variables used in this expression.
*/
StringList ScriptParserEquationExpression::variablesName() const {
StringList vars;
if (equation_ != NULL)
vars = equation_->variablesName();
return vars;
}
/***********************************************************************************
* Debug code
***********************************************************************************/
#ifdef PARSER_TREE_DEBUG
EquationParser::ParserTreeNode ScriptParser::getParserTreeDescription() const {
EquationParser::ParserTreeNode root;
root.description_ = "Script";
for (int i = 0 ; i < expressions_.size() ; ++i)
root.children_ << expressions_[i]->getParserTreeDescription();
return root;
}
EquationParser::ParserTreeNode ScriptParserConditionalExpression::getParserTreeDescription() const {
EquationParser::ParserTreeNode if_node;
if_node.description_ = "If";
EquationParser::ParserTreeNode cond_node;
cond_node.description_ = "Condition";
if (condition_ != NULL) {
EquationParser::ParserTreeNode if_cond_node = condition_->getParserTreeDescription();
// What we get above has three children for Condition/Then/Else.
// We only keep the Condition children part (the Then Else are constant 0 or 1).
if (!if_cond_node.children_.isEmpty())
cond_node.children_ << if_cond_node.children_.first().children_.first();
}
if_node.children_ << cond_node;
EquationParser::ParserTreeNode then_node;
then_node.description_ = "Then";
for (int i = 0 ; i < if_expressions_.size() ; ++i)
then_node.children_ << if_expressions_[i]->getParserTreeDescription();
if_node.children_ << then_node;
if (!else_expressions_.isEmpty()) {
EquationParser::ParserTreeNode else_node;
else_node.description_ = "Else";
for (int i = 0 ; i < else_expressions_.size() ; ++i)
else_node.children_ << else_expressions_[i]->getParserTreeDescription();
if_node.children_ << else_node;
}
return if_node;
}
EquationParser::ParserTreeNode ScriptParserWhileExpression::getParserTreeDescription() const {
EquationParser::ParserTreeNode while_node;
while_node.description_ = "While loop";
EquationParser::ParserTreeNode cond_node;
cond_node.description_ = "Condition";
if (condition_ != NULL)
cond_node.children_ << condition_->getParserTreeDescription();
while_node.children_ << cond_node;