-
-
Notifications
You must be signed in to change notification settings - Fork 991
/
formula.cpp
1285 lines (1140 loc) · 35.6 KB
/
formula.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) 2007 by David White <dave.net>
Part of the Silver Tree Project
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 or later.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY.
See the COPYING file for more details.
*/
#include "global.hpp"
#include <boost/lexical_cast.hpp>
#include <iostream>
#include <set>
#include <sstream>
#include "formula_callable.hpp"
#include "formula_function.hpp"
#include "map_utils.hpp"
#include <boost/foreach.hpp>
namespace game_logic
{
void formula_callable::set_value(const std::string& key, const variant& /*value*/)
{
std::cerr << "ERROR: cannot set key '" << key << "' on object" << std::endl;
}
map_formula_callable::map_formula_callable(const formula_callable* fallback) :
formula_callable(false),
values_(),
fallback_(fallback)
{}
map_formula_callable& map_formula_callable::add(const std::string& key,
const variant& value)
{
values_[key] = value;
return *this;
}
variant map_formula_callable::get_value(const std::string& key) const
{
return map_get_value_default(values_, key,
fallback_ ? fallback_->query_value(key) : variant());
}
void map_formula_callable::get_inputs(std::vector<formula_input>* inputs) const
{
if(fallback_) {
fallback_->get_inputs(inputs);
}
for(std::map<std::string,variant>::const_iterator i = values_.begin(); i != values_.end(); ++i) {
inputs->push_back(formula_input(i->first, FORMULA_READ_WRITE));
}
}
void map_formula_callable::set_value(const std::string& key, const variant& value)
{
values_[key] = value;
}
namespace {
class function_list_expression : public formula_expression {
public:
explicit function_list_expression(function_symbol_table *symbols)
: symbols_(symbols)
{}
virtual std::string str() const
{
return "{function_list_expression()}";
}
private:
variant execute(const formula_callable& /*variables*/, formula_debugger * /*fdb*/) const {
std::vector<variant> res;
std::vector<std::string> function_names = builtin_function_names();
std::vector<std::string> more_function_names = symbols_->get_function_names();
function_names.insert(function_names.end(), more_function_names.begin(), more_function_names.end());
for(size_t i = 0; i < function_names.size(); i++) {
res.push_back(variant(function_names[i]));
}
return variant(&res);
}
function_symbol_table* symbols_;
};
class list_expression : public formula_expression {
public:
explicit list_expression(const std::vector<expression_ptr>& items)
: items_(items)
{}
private:
variant execute(const formula_callable& variables, formula_debugger *fdb) const {
std::vector<variant> res;
res.reserve(items_.size());
for(std::vector<expression_ptr>::const_iterator i = items_.begin(); i != items_.end(); ++i) {
res.push_back((*i)->evaluate(variables,fdb));
}
return variant(&res);
}
std::vector<expression_ptr> items_;
std::string str() const
{
std::stringstream s;
s << '[';
bool first_item = true;
BOOST_FOREACH(expression_ptr a , items_) {
if (!first_item) {
s << ',';
} else {
first_item = false;
}
s << a->str();
}
s << ']';
return s.str();
}
};
class map_expression : public formula_expression {
public:
explicit map_expression(const std::vector<expression_ptr>& items)
: items_(items)
{}
virtual std::string str() const
{
std::stringstream s;
s << " [";
for(std::vector<expression_ptr>::const_iterator i = items_.begin(); ( i != items_.end() ) && ( i+1 != items_.end() ) ; i+=2) {
s << (*i)->str();
s << " -> ";
s << (*(i+1))->str();
}
s << " ]";
return s.str();
}
private:
variant execute(const formula_callable& variables, formula_debugger *fdb) const {
std::map<variant,variant> res;
for(std::vector<expression_ptr>::const_iterator i = items_.begin(); ( i != items_.end() ) && ( i+1 != items_.end() ) ; i+=2) {
variant key = (*i)->evaluate(variables,fdb);
variant value = (*(i+1))->evaluate(variables,fdb);
res[ key ] = value;
}
return variant(&res);
}
std::vector<expression_ptr> items_;
};
class unary_operator_expression : public formula_expression {
public:
unary_operator_expression(const std::string& op, expression_ptr arg) :
op_(),op_str_(op),
operand_(arg)
{
if(op == "not") {
op_ = NOT;
} else if(op == "-") {
op_ = SUB;
} else {
throw formula_error("Illegal unary operator: '" + op + "'" , "", "", 0);
}
}
virtual std::string str() const {
std::stringstream s;
s << op_str_ << '('<< operand_->str() << ')';
return s.str();
}
private:
variant execute(const formula_callable& variables, formula_debugger *fdb) const {
const variant res = operand_->evaluate(variables,fdb);
switch(op_) {
case NOT:
return res.as_bool() ? variant(0) : variant(1);
case SUB:
default:
return -res;
}
}
enum OP { NOT, SUB };
OP op_;
std::string op_str_;
expression_ptr operand_;
};
class list_callable : public formula_callable {
variant list_;
public:
explicit list_callable(const variant& list) : list_(list)
{}
void get_inputs(std::vector<formula_input>* inputs) const {
inputs->push_back(formula_input("size", FORMULA_READ_WRITE));
inputs->push_back(formula_input("empty", FORMULA_READ_WRITE));
inputs->push_back(formula_input("first", FORMULA_READ_WRITE));
inputs->push_back(formula_input("last", FORMULA_READ_WRITE));
}
variant get_value(const std::string& key) const {
if(key == "size") {
return variant(list_.num_elements());
} else if(key == "empty") {
return variant(list_.num_elements() == 0);
} else if(key == "first") {
if(list_.num_elements() > 0) {
return list_[0];
} else {
return variant();
}
} else if(key == "last") {
if(list_.num_elements() > 0) {
return list_[list_.num_elements()-1];
} else {
return variant();
}
} else {
return variant();
}
}
};
class dot_callable : public formula_callable {
public:
dot_callable(const formula_callable &global,
const formula_callable& local)
: global_(global), local_(local) { }
private:
const formula_callable& global_, &local_;
void get_inputs(std::vector<formula_input>* inputs) const {
return local_.get_inputs(inputs);
}
variant get_value(const std::string& key) const {
variant v = local_.query_value(key);
if ( v == variant() )
return global_.query_value(key);
else
return v;
}
};
class dot_expression : public formula_expression {
public:
dot_expression(expression_ptr left, expression_ptr right)
: left_(left), right_(right)
{}
std::string str() const
{
std::stringstream s;
s << left_->str() << "." << right_->str();
return s.str();
}
private:
variant execute(const formula_callable& variables, formula_debugger *fdb) const {
const variant left = left_->evaluate(variables,add_debug_info(fdb,0,"left."));
if(!left.is_callable()) {
if(left.is_list()) {
list_callable list_call(left);
dot_callable callable(variables, list_call);
return right_->evaluate(callable,fdb);
}
return left;
}
dot_callable callable(variables, *left.as_callable());
return right_->evaluate(callable,add_debug_info(fdb,1,".right"));
}
expression_ptr left_, right_;
};
class square_bracket_expression : public formula_expression {
public:
square_bracket_expression(expression_ptr left, expression_ptr key)
: left_(left), key_(key)
{}
std::string str() const
{
std::stringstream s;
s << left_->str() << '[' << key_->str() << ']';
return s.str();
}
private:
variant execute(const formula_callable& variables, formula_debugger *fdb) const {
const variant left = left_->evaluate(variables,fdb);
const variant key = key_->evaluate(variables,fdb);
if(left.is_list() || left.is_map()) {
return left[ key ];
} else {
return variant();
}
}
expression_ptr left_, key_;
};
class operator_expression : public formula_expression {
public:
operator_expression(const std::string& op, expression_ptr left,
expression_ptr right)
: op_(OP(op[0])), op_str_(op), left_(left), right_(right)
{
if(op == ">=") {
op_ = GTE;
} else if(op == "<=") {
op_ = LTE;
} else if(op == "!=") {
op_ = NEQ;
} else if(op == "and") {
op_ = AND;
} else if(op == "or") {
op_ = OR;
} else if(op == ".+") {
op_ = ADDL;
} else if(op == ".-") {
op_ = SUBL;
} else if(op == ".*") {
op_ = MULL;
} else if(op == "./") {
op_ = DIVL;
} else if(op == "..") {
op_ = CAT;
}
}
std::string str() const
{
std::stringstream s;
s << left_->str() << op_str_ << right_->str();
return s.str();
}
private:
variant execute(const formula_callable& variables, formula_debugger *fdb) const {
const variant left = left_->evaluate(variables,add_debug_info(fdb,0,"left_OP"));
const variant right = right_->evaluate(variables,add_debug_info(fdb,1,"OP_right"));
switch(op_) {
case AND:
return left.as_bool() == false ? left : right;
case OR:
return left.as_bool() ? left : right;
case ADD:
return left + right;
case SUB:
return left - right;
case MUL:
return left * right;
case DIV:
return left / right;
case POW:
return left ^ right;
case ADDL:
return left.list_elements_add(right);
case SUBL:
return left.list_elements_sub(right);
case MULL:
return left.list_elements_mul(right);
case DIVL:
return left.list_elements_div(right);
case CAT:
return left.concatenate(right);
case EQ:
return left == right ? variant(1) : variant(0);
case NEQ:
return left != right ? variant(1) : variant(0);
case LTE:
return left <= right ? variant(1) : variant(0);
case GTE:
return left >= right ? variant(1) : variant(0);
case LT:
return left < right ? variant(1) : variant(0);
case GT:
return left > right ? variant(1) : variant(0);
case MOD:
return left % right;
case RAN:
return left.build_range(right);
case DICE:
return variant(dice_roll(left.as_int(), right.as_int()));
default:
std::cerr << "ERROR: Unimplemented operator!" << std::endl;
return variant();
}
}
static int dice_roll(int num_rolls, int faces) {
int res = 0;
while(faces > 0 && num_rolls-- > 0) {
// TODO: should we use the synced rng here ?
res += (rand()%faces)+1;
}
return res;
}
enum OP { AND, OR, NEQ, LTE, GTE, CAT, GT='>', LT='<', EQ='=', RAN='~',
ADD='+', SUB='-', MUL='*', DIV='/', ADDL, SUBL, MULL, DIVL, DICE='d', POW='^', MOD='%' };
OP op_;
std::string op_str_;
expression_ptr left_, right_;
};
typedef std::map<std::string,expression_ptr> expr_table;
typedef boost::shared_ptr<expr_table> expr_table_ptr;
typedef std::map<std::string, variant> exp_table_evaluated;
class where_variables: public formula_callable {
public:
where_variables(const formula_callable &base,
expr_table_ptr table )
: formula_callable(false)
, base_(base)
, table_(table)
, evaluated_table_()
{
}
private:
const formula_callable& base_;
expr_table_ptr table_;
mutable exp_table_evaluated evaluated_table_;
void get_inputs(std::vector<formula_input>* inputs) const {
for(expr_table::const_iterator i = table_->begin(); i != table_->end(); ++i) {
inputs->push_back(formula_input(i->first, FORMULA_READ_ONLY));
}
}
variant get_value(const std::string& key) const {
expr_table::iterator i = table_->find(key);
if(i != table_->end()) {
exp_table_evaluated::const_iterator ev = evaluated_table_.find(key);
if( ev != evaluated_table_.end())
return ev->second;
variant v = i->second->evaluate(base_);
evaluated_table_[key] = v;
return v;
}
return base_.query_value(key);
}
};
class where_expression: public formula_expression {
public:
explicit where_expression(expression_ptr body,
expr_table_ptr clauses)
: body_(body), clauses_(clauses)
{}
std::string str() const
{
std::stringstream s;
s << "{where:(";
s << body_->str();
BOOST_FOREACH(const expr_table::value_type &a, *clauses_) {
s << ", [" << a.first << "] -> ["<< a.second->str()<<"]";
}
s << ")}";
return s.str();
}
private:
expression_ptr body_;
expr_table_ptr clauses_;
variant execute(const formula_callable& variables,formula_debugger *fdb) const {
where_variables wrapped_variables(variables, clauses_);
return body_->evaluate(wrapped_variables,fdb);
}
};
class identifier_expression : public formula_expression {
public:
explicit identifier_expression(const std::string& id) : id_(id)
{}
std::string str() const
{
return id_;
}
private:
variant execute(const formula_callable& variables, formula_debugger * /*fdb*/) const {
return variables.query_value(id_);
}
std::string id_;
};
class null_expression : public formula_expression {
public:
explicit null_expression() {}
std::string str() const {
return "";
}
private:
variant execute(const formula_callable& /*variables*/, formula_debugger * /*fdb*/) const {
return variant();
}
};
class integer_expression : public formula_expression {
public:
explicit integer_expression(int i) : i_(i)
{}
std::string str() const
{
std::stringstream s;
s << i_;
return s.str();
}
private:
variant execute(const formula_callable& /*variables*/, formula_debugger * /*fdb*/) const {
return variant(i_);
}
int i_;
};
class decimal_expression : public formula_expression {
public:
explicit decimal_expression(int i, int f) : i_(i), f_(f)
{}
std::string str() const
{
std::stringstream s;
s << i_ << '.' << f_;
return s.str();
}
private:
variant execute(const formula_callable& /*variables*/, formula_debugger * /*fdb*/) const {
return variant(i_ * 1000 + f_, variant::DECIMAL_VARIANT );
}
int i_, f_;
};
class string_expression : public formula_expression {
public:
explicit string_expression(std::string str) :
str_(),
subs_()
{
std::string::iterator i;
while((i = std::find(str.begin(), str.end(), '[')) != str.end()) {
std::string::iterator j = std::find(i, str.end(), ']');
if(j == str.end()) {
break;
}
const std::string formula_str(i+1, j);
const int pos = i - str.begin();
str.erase(i, j+1);
substitution sub;
sub.pos = pos;
sub.calculation.reset(new formula(formula_str));
subs_.push_back(sub);
}
std::reverse(subs_.begin(), subs_.end());
str_ = variant(str);
}
std::string str() const
{
return str_.as_string();
}
private:
variant execute(const formula_callable& variables, formula_debugger *fdb) const {
if(subs_.empty()) {
return str_;
} else {
std::string res = str_.as_string();
for(size_t i=0; i < subs_.size(); ++i) {
const substitution& sub = subs_[i];
const std::string str = sub.calculation->evaluate(variables,fdb).string_cast();
res.insert(sub.pos, str);
}
return variant(res);
}
}
struct substitution {
substitution() :
pos(0),
calculation()
{
}
int pos;
const_formula_ptr calculation;
};
variant str_;
std::vector<substitution> subs_;
};
using namespace formula_tokenizer;
int operator_precedence(const token& t)
{
static std::map<std::string,int> precedence_map;
if(precedence_map.empty()) {
int n = 0;
precedence_map["not"] = ++n;
precedence_map["where"] = ++n;
precedence_map["or"] = ++n;
precedence_map["and"] = ++n;
precedence_map["="] = ++n;
precedence_map["!="] = n;
precedence_map["<"] = n;
precedence_map[">"] = n;
precedence_map["<="] = n;
precedence_map[">="] = n;
precedence_map["~"] = ++n;
precedence_map["+"] = ++n;
precedence_map["-"] = n;
precedence_map[".."] = n;
precedence_map["*"] = ++n;
precedence_map["/"] = n;
precedence_map["%"] = ++n;
precedence_map["^"] = ++n;
precedence_map["d"] = ++n;
precedence_map["."] = ++n;
}
assert(precedence_map.count(std::string(t.begin,t.end)));
return precedence_map[std::string(t.begin,t.end)];
}
expression_ptr parse_expression(const token* i1, const token* i2, function_symbol_table* symbols);
//function used when creating error reports, parses all tokens passed to parse_expression, thus there are no EOL or whitespaces
std::string tokens_to_string(const token* i1, const token* i2)
{
std::ostringstream expr;
while(i1 != i2) {
expr << std::string(i1->begin,i1->end) << " ";
++i1;
}
return expr.str();
}
void parse_function_args(const token* &i1, const token* i2,
std::vector<std::string>* res)
{
const token* begin = i1, *end = i2; //these are used for error reporting
if(i1->type == TOKEN_LPARENS) {
++i1;
} else {
throw formula_error("Invalid function definition", tokens_to_string(begin,end-1), *i1->filename, i1->line_number);
}
while((i1-> type != TOKEN_RPARENS) && (i1 != i2)) {
if(i1->type == TOKEN_IDENTIFIER) {
if(std::string((i1+1)->begin, (i1+1)->end) == "*") {
res->push_back(std::string(i1->begin, i1->end) + std::string("*"));
++i1;
} else {
res->push_back(std::string(i1->begin, i1->end));
}
} else if (i1->type == TOKEN_COMMA) {
//do nothing
} else {
throw formula_error("Invalid function definition", tokens_to_string(begin,end-1), *i1->filename, i1->line_number);
}
++i1;
}
if(i1->type != TOKEN_RPARENS) {
throw formula_error("Invalid function definition", tokens_to_string(begin,end-1), *i1->filename, i1->line_number);
}
++i1;
}
void parse_args(const token* i1, const token* i2,
std::vector<expression_ptr>* res,
function_symbol_table* symbols)
{
int parens = 0;
const token* beg = i1;
while(i1 != i2) {
if(i1->type == TOKEN_LPARENS || i1->type == TOKEN_LSQUARE ) {
++parens;
} else if(i1->type == TOKEN_RPARENS || i1->type == TOKEN_RSQUARE ) {
--parens;
} else if(i1->type == TOKEN_COMMA && !parens) {
res->push_back(parse_expression(beg,i1, symbols));
beg = i1+1;
}
++i1;
}
if(beg != i1) {
res->push_back(parse_expression(beg,i1, symbols));
}
}
void parse_set_args(const token* i1, const token* i2,
std::vector<expression_ptr>* res,
function_symbol_table* symbols)
{
int parens = 0;
bool check_pointer = false;
const token* beg = i1;
const token* begin = i1, *end = i2; //these are used for error reporting
while(i1 != i2) {
if(i1->type == TOKEN_LPARENS || i1->type == TOKEN_LSQUARE) {
++parens;
} else if(i1->type == TOKEN_RPARENS || i1->type == TOKEN_RSQUARE) {
--parens;
} else if( i1->type == TOKEN_POINTER && !parens ) {
if (!check_pointer) {
check_pointer = true;
res->push_back(parse_expression(beg,i1, symbols));
beg = i1+1;
} else {
throw formula_error("Too many '->' operators found", tokens_to_string(begin,end-1), *i1->filename, i1->line_number);
}
} else if( i1->type == TOKEN_COMMA && !parens ) {
if (check_pointer)
check_pointer = false;
else {
throw formula_error("Expected comma, but '->' found", tokens_to_string(begin,end-1), *i1->filename, i1->line_number);
}
res->push_back(parse_expression(beg,i1, symbols));
beg = i1+1;
}
++i1;
}
if(beg != i1) {
res->push_back(parse_expression(beg,i1, symbols));
}
}
void parse_where_clauses(const token* i1, const token * i2,
expr_table_ptr res, function_symbol_table* symbols) {
int parens = 0;
const token *original_i1_cached = i1;
const token *beg = i1;
const token* begin = i1, *end = i2; //these are used for error reporting
std::string var_name;
while(i1 != i2) {
if(i1->type == TOKEN_LPARENS) {
++parens;
} else if(i1->type == TOKEN_RPARENS) {
--parens;
} else if(!parens) {
if(i1->type == TOKEN_COMMA) {
if(var_name.empty()) {
throw formula_error("There is 'where <expression>' but 'where name=<expression>' was needed", tokens_to_string(begin,end-1), *i1->filename, i1->line_number);
}
(*res)[var_name] = parse_expression(beg,i1, symbols);
beg = i1+1;
var_name = "";
} else if(i1->type == TOKEN_OPERATOR) {
std::string op_name(i1->begin, i1->end);
if(op_name == "=") {
if(beg->type != TOKEN_IDENTIFIER) {
if(i1 == original_i1_cached) {
throw formula_error("There is 'where <expression' but 'where name=<expression>' was needed", tokens_to_string(begin,end-1), *i1->filename, i1->line_number);
} else {
throw formula_error("There is 'where <expression>=<expression>' but 'where name=<expression>' was needed", tokens_to_string(begin,end-1), *i1->filename, i1->line_number);
}
} else if(beg+1 != i1) {
throw formula_error("There is 'where name <expression>=<expression>' but 'where name=<expression>' was needed", tokens_to_string(begin,end-1), *i1->filename, i1->line_number);
} else if(!var_name.empty()) {
throw formula_error("There is 'where name=name=<expression>' but 'where name=<expression>' was needed", tokens_to_string(begin,end-1), *i1->filename, i1->line_number);
}
var_name.insert(var_name.end(), beg->begin, beg->end);
beg = i1+1;
}
}
}
++i1;
}
if(beg != i1) {
if(var_name.empty()) {
throw formula_error("There is 'where <expression>' but 'where name=<expression>' was needed", tokens_to_string(begin,end-1), *i1->filename, i1->line_number);
}
(*res)[var_name] = parse_expression(beg,i1, symbols);
}
}
expression_ptr parse_expression(const token* i1, const token* i2, function_symbol_table* symbols)
{
if(i1 == i2) {
throw formula_error("Empty expression", "", *i1->filename, i1->line_number);
}
const token* begin = i1, *end = i2; //these are used for error reporting
if(i1->type == TOKEN_KEYWORD &&
(i1+1)->type == TOKEN_IDENTIFIER) {
if(std::string(i1->begin, i1->end) == "def") {
++i1;
const std::string formula_name = std::string(i1->begin, i1->end);
std::vector<std::string> args;
parse_function_args(++i1, i2, &args);
const token* beg = i1;
while((i1 != i2) && (i1->type != TOKEN_SEMICOLON)) {
++i1;
}
const std::string precond = "";
if(symbols == NULL) {
throw formula_error("Function symbol table required but not present", "",*i1->filename, i1->line_number);
}
symbols->add_formula_function(formula_name,
const_formula_ptr(new formula(beg, i1, symbols)),
formula::create_optional_formula(precond, symbols),
args);
if((i1 == i2) || (i1 == (i2-1))) {
return expression_ptr(new function_list_expression(symbols));
}
else {
return parse_expression((i1+1), i2, symbols);
}
}
}
int parens = 0;
const token* op = NULL;
bool operator_group = false;
for(const token* i = i1; i != i2; ++i) {
if(i->type == TOKEN_LPARENS || i->type == TOKEN_LSQUARE) {
++parens;
} else if(i->type == TOKEN_RPARENS || i->type == TOKEN_RSQUARE) {
--parens;
} else if(parens == 0 && i->type == TOKEN_OPERATOR) {
if( ( !operator_group ) && (op == NULL || operator_precedence(*op) >=
operator_precedence(*i)) ) {
op = i;
}
operator_group = true;
} else {
operator_group = false;
}
}
if(op == NULL) {
if(i1->type == TOKEN_LPARENS && (i2-1)->type == TOKEN_RPARENS) {
return parse_expression(i1+1,i2-1,symbols);
} else if( (i2-1)->type == TOKEN_RSQUARE) { //check if there is [ ] : either a list/map definition, or a operator
const token* tok = i2-2;
int square_parens = 0;
bool is_map = false;
while ( (tok->type != TOKEN_LSQUARE || square_parens) && tok != i1) {
if (tok->type == TOKEN_RSQUARE) {
square_parens++;
} else if(tok->type == TOKEN_LSQUARE) {
square_parens--;
} else if( (tok->type == TOKEN_POINTER) && !square_parens ) {
is_map = true;
}
--tok;
}
if (tok->type == TOKEN_LSQUARE) {
if (tok == i1) {
//create a list or a map
std::vector<expression_ptr> args;
if ( is_map ) {
parse_set_args(i1+1, i2-1, &args, symbols);
return expression_ptr(new map_expression(args));
} else {
parse_args(i1+1,i2-1,&args,symbols);
return expression_ptr(new list_expression(args));
}
} else {
//execute operator [ ]
try{
return expression_ptr(new square_bracket_expression(
parse_expression(i1,tok,symbols),
parse_expression(tok+1,i2-1,symbols)));
}
catch (formula_error& e){
throw formula_error( e.type, tokens_to_string(i1, i2-1), *i1->filename, i1->line_number );
}
}
}
} else if(i2 - i1 == 1) {
if(i1->type == TOKEN_KEYWORD) {
if(std::string(i1->begin,i1->end) == "functions") {
return expression_ptr(new function_list_expression(symbols));
}
} else if(i1->type == TOKEN_IDENTIFIER) {
return expression_ptr(new identifier_expression(
std::string(i1->begin,i1->end)));
} else if(i1->type == TOKEN_INTEGER) {
int n = atoi(std::string(i1->begin,i1->end).c_str());
return expression_ptr(new integer_expression(n));
} else if(i1->type == TOKEN_DECIMAL) {
iterator dot = i1->begin;
while( *dot != '.' )
++dot;
int n = atoi(std::string(i1->begin,dot).c_str());
iterator end = i1->end;
if( end - dot > 4)
end = dot + 4;
++dot;
int f = 0;
int multiplicator = 100;
while( dot != end) {
f += (*dot - 48)*multiplicator;
multiplicator /= 10;
++dot;
}
return expression_ptr(new decimal_expression(n, f));
} else if(i1->type == TOKEN_STRING_LITERAL) {
return expression_ptr(new string_expression(std::string(i1->begin+1,i1->end-1)));
}
} else if(i1->type == TOKEN_IDENTIFIER &&
(i1+1)->type == TOKEN_LPARENS &&
(i2-1)->type == TOKEN_RPARENS) {
const token* begin = i1, *end = i2; //these are used for error reporting
int nleft = 0, nright = 0;
for(const token* i = i1; i != i2; ++i) {
if(i->type == TOKEN_LPARENS) {
++nleft;
} else if(i->type == TOKEN_RPARENS) {
++nright;
}
}
if(nleft == nright) {
std::vector<expression_ptr> args;
parse_args(i1+2,i2-1,&args,symbols);
try{
return create_function(std::string(i1->begin,i1->end),args,symbols);
}
catch(formula_error& e) {
throw formula_error(e.type, tokens_to_string(begin,end), *i1->filename, i1->line_number);
}
}
}
throw formula_error("Could not parse expression", tokens_to_string(i1, i2), *i1->filename, i1->line_number);
}
if (op + 1 == end) {
throw formula_error("Expected another token", tokens_to_string(begin,end-1), *op->filename, op->line_number);
}
if(op == i1) {
try{
return expression_ptr(new unary_operator_expression(
std::string(op->begin,op->end),
parse_expression(op+1,i2,symbols)));
}
catch(formula_error& e) {
throw formula_error( e.type, tokens_to_string(begin,end-1), *op->filename, op->line_number);
}
}
const std::string op_name(op->begin,op->end);
if(op_name == ".") {
return expression_ptr(new dot_expression(
parse_expression(i1,op,symbols),
parse_expression(op+1,i2,symbols)));
}
if(op_name == "where") {
expr_table_ptr table(new expr_table());