-
Notifications
You must be signed in to change notification settings - Fork 81
/
formula_function.cpp
6501 lines (5458 loc) · 199 KB
/
formula_function.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) 2003-2013 by David White <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#include <glm/gtx/intersect.hpp>
#include <boost/format.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/uuid/sha1.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/exception/diagnostic_information.hpp>
#include <boost/exception_ptr.hpp>
#include <iomanip>
#include <iostream>
#include <iomanip>
#include <stack>
#include <cmath>
#if defined(_MSC_VER)
#include <boost/math/special_functions/round.hpp>
#define bmround boost::math::round
#else
#define bmround round
#endif
#ifndef __APPLE__
#include <malloc.h>
#endif
#include "geometry.hpp"
#ifdef USE_SVG
#include "cairo.hpp"
#endif
#include "array_callable.hpp"
#include "asserts.hpp"
#include "base64.hpp"
#include "code_editor_dialog.hpp"
#include "compress.hpp"
#include "custom_object.hpp"
#include "dialog.hpp"
#include "debug_console.hpp"
#include "draw_primitive.hpp"
#include "formatter.hpp"
#include "formula.hpp"
#include "formula_callable.hpp"
#include "formula_callable_definition.hpp"
#include "formula_callable_utils.hpp"
#include "formula_function.hpp"
#include "formula_function_registry.hpp"
#include "formula_internal.hpp"
#include "formula_object.hpp"
#include "formula_profiler.hpp"
#include "formula_vm.hpp"
#include "hex.hpp"
#include "hex_helper.hpp"
#include "level_runner.hpp"
#include "lua_iface.hpp"
#include "md5.hpp"
#include "module.hpp"
#include "random.hpp"
#include "rectangle_rotator.hpp"
#include "string_utils.hpp"
#include "unit_test.hpp"
#include "variant_callable.hpp"
#include "controls.hpp"
#include "pathfinding.hpp"
#include "preferences.hpp"
#include "random.hpp"
#include "level.hpp"
#include "json_parser.hpp"
#include "utf8_to_codepoint.hpp"
#include "uuid.hpp"
#include "variant_utils.hpp"
#include "voxel_model.hpp"
#include "widget_factory.hpp"
#include "Texture.hpp"
#include "Cursor.hpp"
#include <boost/regex.hpp>
#if defined(_MSC_VER) && _MSC_VER < 1800
#include <boost/math/special_functions/asinh.hpp>
#include <boost/math/special_functions/acosh.hpp>
#include <boost/math/special_functions/atanh.hpp>
using boost::math::asinh;
using boost::math::acosh;
using boost::math::atanh;
#endif
using namespace formula_vm;
PREF_BOOL(log_instrumentation, false, "Make instrument() FFL calls log to the console as well as the F7 profiler");
PREF_BOOL(dump_to_console, true, "Send dump() to the console");
PREF_STRING(log_console_filter, "", "");
PREF_STRING(auto_update_status, "", "");
PREF_INT(fake_time_adjust, 0, "Adjusts the time known to the game by the specified number of seconds.");
extern variant g_auto_update_info;
std::map<std::string, variant> g_user_info_registry;
namespace
{
//these global variables make the EVAL_ARG/NUM_ARGS macros work
//for functions not yet converted to the new syntax. Remove eventually.
const variant* passed_args = nullptr;
int num_passed_args = -1;
const std::string FunctionModule = "core";
const float radians_to_degrees = 57.29577951308232087f;
const std::string& EmptyStr() {
static std::string* empty_str = new std::string;
return *empty_str;
}
using namespace game_logic;
std::string read_identifier_expression(const FormulaExpression& expr) {
variant literal;
expr.isLiteral(literal);
if(literal.is_string()) {
return literal.as_string();
} else {
std::string result;
if(expr.isIdentifier(&result)) {
return result;
}
ASSERT_LOG(false, "Expected identifier, found " << expr.str() << expr.debugPinpointLocation());
return "";
}
}
}
namespace game_logic
{
ExpressionPtr createVMExpression(const formula_vm::VirtualMachine vm, variant_type_ptr t, const FormulaExpression& o);
FormulaExpression::FormulaExpression(const char* name) : FormulaCallable(GARBAGE_COLLECTOR_EXCLUDE), name_(name ? name : "unknown"), begin_str_(EmptyStr().begin()), end_str_(EmptyStr().end()), ntimes_called_(0)
{
}
FormulaExpression::~FormulaExpression()
{
}
std::vector<ConstExpressionPtr> FormulaExpression::queryChildren() const {
std::vector<ConstExpressionPtr> result = getChildren();
result.erase(std::remove(result.begin(), result.end(), ConstExpressionPtr()), result.end());
return result;
}
std::vector<ConstExpressionPtr> FormulaExpression::queryChildrenRecursive() const {
std::vector<ConstExpressionPtr> result;
result.push_back(ConstExpressionPtr(this));
for(ConstExpressionPtr child : queryChildren()) {
if(child.get() != this) {
std::vector<ConstExpressionPtr> items = child->queryChildrenRecursive();
result.insert(result.end(), items.begin(), items.end());
}
}
return result;
}
void FormulaExpression::emitVM(formula_vm::VirtualMachine& vm) const
{
for(auto p : queryChildrenRecursive()) {
LOG_ERROR(" Sub-expr: " << p->name() << ": ((" << p->str() << ")) -> can_vm = " << (p->canCreateVM() ? "yes" : "no") << "\n");
}
ASSERT_LOG(false, "Trying to emit VM from non-VMable expression: " << name() << " :: " << str());
}
void FormulaExpression::copyDebugInfoFrom(const FormulaExpression& o)
{
setDebugInfo(o.parent_formula_, o.begin_str_, o.end_str_);
}
void FormulaExpression::setDebugInfo(const variant& parent_formula,
std::string::const_iterator begin_str,
std::string::const_iterator end_str)
{
parent_formula_ = parent_formula;
begin_str_ = begin_str;
end_str_ = end_str;
}
void FormulaExpression::setVMDebugInfo(formula_vm::VirtualMachine& vm) const
{
if(!hasDebugInfo()) {
return;
}
const std::string& s = parent_formula_.as_string();
vm.setDebugInfo(parent_formula_, begin_str_ - s.begin(), end_str_ - s.begin());
}
void FormulaExpression::setDebugInfo(const FormulaExpression& o)
{
setDebugInfo(o.parent_formula_, o.begin_str_, o.end_str_);
}
bool FormulaExpression::hasDebugInfo() const
{
return parent_formula_.is_string() && parent_formula_.get_debug_info();
}
ConstFormulaCallableDefinitionPtr FormulaExpression::getTypeDefinition() const
{
variant_type_ptr type = queryVariantType();
if(type) {
return ConstFormulaCallableDefinitionPtr(type->getDefinition());
}
return nullptr;
}
std::string pinpoint_location(variant v, std::string::const_iterator begin)
{
return pinpoint_location(v, begin, begin);
}
std::string pinpoint_location(variant v, std::string::const_iterator begin,
std::string::const_iterator end,
PinpointedLoc* pos_info)
{
std::string str(begin, end);
if(!v.is_string() || !v.get_debug_info()) {
return "Unknown location (" + str + ")\n";
}
int line_num = v.get_debug_info()->line;
int begin_line_base = v.get_debug_info()->column;
std::string::const_iterator begin_line = v.as_string().begin();
while(std::find(begin_line, begin, '\n') != begin) {
begin_line_base = 0;
begin_line = std::find(begin_line, begin, '\n')+1;
++line_num;
}
//this is the real start of the line. begin_line will advance
//to the first non-whitespace character.
std::string::const_iterator real_start_of_line = begin_line;
while(begin_line != begin && util::c_isspace(*begin_line)) {
++begin_line;
}
std::string::const_iterator end_line = std::find(begin_line, v.as_string().end(), '\n');
std::string line(begin_line, end_line);
auto pos = begin - begin_line;
if(pos_info) {
const int col = static_cast<int>((begin - real_start_of_line) + begin_line_base);
pos_info->begin_line = line_num;
pos_info->begin_col = col+1;
int end_line = line_num;
int end_col = col+1;
for(auto itor = begin; itor != end; ++itor) {
if(*itor == '\n') {
end_col = 1;
end_line++;
} else {
end_col++;
}
}
pos_info->end_line = end_line;
pos_info->end_col = end_col;
}
if(pos > 40) {
line.erase(line.begin(), line.begin() + pos - 40);
pos = 40;
std::fill(line.begin(), line.begin() + 3, '.');
}
if(line.size() > 78) {
line.resize(78);
std::fill(line.end() - 3, line.end(), '.');
}
std::ostringstream s;
s << "At " << *v.get_debug_info()->filename << " " << line_num << ":\n";
s << line << "\n";
for(int n = 0; n != pos; ++n) {
s << " ";
}
s << "^";
if(end > begin && static_cast<unsigned>(pos + (end - begin)) < line.size()) {
for(int n = 0; n < (end - begin)-1; ++n) {
s << "-";
}
s << "^";
}
s << "\n";
return s.str();
}
std::string FormulaExpression::debugPinpointLocation(PinpointedLoc* loc) const
{
if(!hasDebugInfo()) {
return "Unknown Location (" + str() + ")\n";
}
return pinpoint_location(parent_formula_, begin_str_, end_str_, loc);
}
std::pair<int,int> FormulaExpression::debugLocInFile() const
{
if(!hasDebugInfo()) {
return std::pair<int,int>(-1,-1);
}
return std::pair<int,int>(static_cast<int>(begin_str_ - parent_formula_.as_string().begin()),
static_cast<int>(end_str_ - parent_formula_.as_string().begin()));
}
variant FormulaExpression::executeMember(const FormulaCallable& variables, std::string& id, variant* variant_id) const
{
Formula::failIfStaticContext();
ASSERT_LOG(false, "Trying to set illegal value: " << str() << "\n" << debugPinpointLocation());
return variant();
}
void FormulaExpression::optimizeChildToVM(ExpressionPtr& expr)
{
if(expr) {
bool can_vm = expr->canCreateVM();
auto opt = expr->optimizeToVM();
if(opt.get() != nullptr) {
ASSERT_LOG(can_vm == opt->canCreateVM(), "Expression says it cannot be made into a VM but it can: " << expr->str());
expr = opt;
}
if(can_vm && expr->isVM() == false) {
ASSERT_LOG(false, "Expressions says it can be made into a VM but it cannot: " << expr->name() << " :: " << expr->str());
}
}
}
namespace
{
variant split_variant_if_str(const variant& s)
{
if(!s.is_string()) {
return s;
}
std::vector<std::string> v = util::split(s.as_string(), "");
std::vector<variant> res;
res.reserve(v.size());
for(const std::string& str : v) {
res.push_back(variant(str));
}
return variant(&res);
}
std::set<class ffl_cache*>& get_all_ffl_caches()
{
static std::set<class ffl_cache*>* caches = new std::set<class ffl_cache*>;
return *caches;
}
class ffl_cache : public FormulaCallable
{
public:
struct Entry {
Entry() : use_weak(false) {}
variant key;
variant obj;
ffl::weak_ptr<FormulaCallable> weak;
bool use_weak;
};
void setName(const std::string& name) { name_ = name; }
const std::string& getName() const { return name_; }
explicit ffl_cache(int max_entries) : max_entries_(max_entries)
{
get_all_ffl_caches().insert(this);
}
~ffl_cache()
{
get_all_ffl_caches().erase(this);
}
const variant* get(const variant& key) const {
std::map<variant, std::list<Entry>::iterator>::iterator i = cache_.find(key);
if(i != cache_.end()) {
if(i->second->use_weak && i->second->weak.get() == nullptr) {
lru_.erase(i->second);
cache_.erase(i);
return nullptr;
} else if(i->second->use_weak) {
auto weak = i->second->weak.get();
i->second->use_weak = false;
i->second->obj = variant(weak.get());
i->second->weak.reset();
}
lru_.splice(lru_.begin(), lru_, i->second);
const Entry& entry = *i->second;
return &entry.obj;
} else {
return nullptr;
}
}
void store(const variant& key, const variant& value) const {
lru_.push_front(Entry());
lru_.front().obj = value;
lru_.front().key = key;
bool succeeded = cache_.insert(std::pair<variant,std::list<Entry>::iterator>(key, lru_.begin())).second;
ASSERT_LOG(succeeded, "Inserted into cache when there is already a valid entry: " << key.write_json());
if(cache_.size() > max_entries_) {
int num_delete = std::max(1, max_entries_/5);
int looked = 0;
while(num_delete > 0 && looked < static_cast<int>(cache_.size()) && !lru_.empty()) {
auto end = lru_.end();
--end;
Entry& entry = *end;
if(entry.use_weak) {
if(entry.weak.get() == nullptr) {
cache_.erase(entry.key);
lru_.erase(end);
--num_delete;
} else {
lru_.splice(lru_.begin(), lru_, end);
}
} else if( false && entry.obj.refcount() > 1) {
lru_.splice(lru_.begin(), lru_, end);
} else {
cache_.erase(entry.key);
lru_.erase(end);
--num_delete;
}
++looked;
}
if(cache_.size() > max_entries_) {
for(Entry& entry : lru_) {
if(entry.use_weak == false && entry.obj.is_callable()) {
entry.weak.reset(entry.obj.mutable_callable());
entry.obj = variant();
entry.use_weak = true;
}
}
LOG_ERROR("Failed to delete all objects from cache. " << cache_.size() << "/" << max_entries_ << " remain");
}
}
}
void clear() {
lru_.clear();
cache_.clear();
}
void surrenderReferences(GarbageCollector* collector) override {
for(std::pair<const variant, std::list<Entry>::iterator>& p : cache_) {
collector->surrenderVariant(&p.first);
collector->surrenderVariant(&p.second->key);
collector->surrenderVariant(&p.second->obj);
}
}
std::string debugObjectName() const override {
std::ostringstream s;
s << "ffl_cache(" << name_ << ", " << lru_.size() << "/" << max_entries_ << ")";
return s.str();
}
private:
DECLARE_CALLABLE(ffl_cache);
mutable std::list<Entry> lru_;
mutable std::map<variant, std::list<Entry>::iterator> cache_;
std::string name_;
int max_entries_;
};
BEGIN_DEFINE_CALLABLE_NOBASE(ffl_cache)
DEFINE_FIELD(name, "string")
return variant(obj.name_);
DEFINE_FIELD(enumerate, "[any]")
std::vector<variant> result;
for(auto item : obj.lru_) {
result.push_back(item.obj);
}
return variant(&result);
DEFINE_FIELD(keys, "[any]")
std::vector<variant> result;
for(auto item : obj.lru_) {
result.push_back(item.key);
}
return variant(&result);
DEFINE_FIELD(num_entries, "int")
return variant(obj.cache_.size());
DEFINE_FIELD(max_entries, "int")
return variant(obj.max_entries_);
DEFINE_FIELD(all, "[builtin ffl_cache]")
std::vector<variant> v;
for(auto item : get_all_ffl_caches()) {
v.push_back(variant(item));
}
return variant(&v);
BEGIN_DEFINE_FN(get, "(any) ->any")
variant key = FN_ARG(0);
const variant* result = obj.get(key);
if(result != nullptr) {
return *result;
}
return variant();
END_DEFINE_FN
BEGIN_DEFINE_FN(contains, "(any) ->bool")
variant key = FN_ARG(0);
const variant* result = obj.get(key);
return variant::from_bool(result != nullptr);
END_DEFINE_FN
BEGIN_DEFINE_FN(store, "(any, any) ->commands")
variant key = FN_ARG(0);
variant value = FN_ARG(1);
ffl::IntrusivePtr<ffl_cache> ptr(const_cast<ffl_cache*>(&obj));
return variant(new game_logic::FnCommandCallable("cache_store", [=]() {
if(ptr->get(key) == nullptr) {
ptr->store(key, value);
}
}));
END_DEFINE_FN
BEGIN_DEFINE_FN(clear, "() ->commands")
ffl::IntrusivePtr<ffl_cache> ptr(const_cast<ffl_cache*>(&obj));
return variant(new game_logic::FnCommandCallable("cache_clear", [=]() {
ptr->clear();
}));
END_DEFINE_FN
END_DEFINE_CALLABLE(ffl_cache)
class Geometry : public game_logic::FormulaCallable {
public:
Geometry() {}
private:
DECLARE_CALLABLE(Geometry);
};
BEGIN_DEFINE_CALLABLE_NOBASE(Geometry)
BEGIN_DEFINE_FN(line_segment_intersection, "(decimal,decimal,decimal,decimal,decimal,decimal,decimal,decimal)->[decimal,decimal]|null")
const decimal a_x1 = FN_ARG(0).as_decimal();
const decimal a_y1 = FN_ARG(1).as_decimal();
const decimal a_x2 = FN_ARG(2).as_decimal();
const decimal a_y2 = FN_ARG(3).as_decimal();
const decimal b_x1 = FN_ARG(4).as_decimal();
const decimal b_y1 = FN_ARG(5).as_decimal();
const decimal b_x2 = FN_ARG(6).as_decimal();
const decimal b_y2 = FN_ARG(7).as_decimal();
decimal d = (a_x1-a_x2)*(b_y1-b_y2) - (a_y1-a_y2)*(b_x1-b_x2);
if(d == decimal::from_int(0)) {
return variant();
}
decimal xi = ((b_x1-b_x2)*(a_x1*a_y2-a_y1*a_x2)-(a_x1-a_x2)*(b_x1*b_y2-b_y1*b_x2))/d;
decimal yi = ((b_y1-b_y2)*(a_x1*a_y2-a_y1*a_x2)-(a_y1-a_y2)*(b_x1*b_y2-b_y1*b_x2))/d;
if(xi < std::min(a_x1,a_x2) || xi > std::max(a_x1,a_x2)) {
return variant();
}
if(xi < std::min(b_x1,b_x2) || xi > std::max(b_x1,b_x2)) {
return variant();
}
std::vector<variant> v;
v.push_back(variant(xi));
v.push_back(variant(yi));
return variant(&v);
END_DEFINE_FN
END_DEFINE_CALLABLE(Geometry)
FUNCTION_DEF(geometry_api, 0, 1, "geometry_api()")
static Geometry* geo = new Geometry;
static variant holder(geo);
return holder;
FUNCTION_ARGS_DEF
RETURN_TYPE("builtin geometry")
END_FUNCTION_DEF(geometry_api)
#ifdef USE_SVG
FUNCTION_DEF(canvas, 0, 0, "canvas() -> canvas object")
static variant result(new graphics::cairo_callable());
return result;
FUNCTION_ARGS_DEF
RETURN_TYPE("builtin cairo_callable")
END_FUNCTION_DEF(canvas)
#endif
class DateTime : public game_logic::FormulaCallable {
public:
DateTime(time_t unix, const tm* tm) : unix_(unix), tm_(*tm)
{}
private:
DECLARE_CALLABLE(DateTime);
time_t unix_;
tm tm_;
};
BEGIN_DEFINE_CALLABLE_NOBASE(DateTime)
DEFINE_FIELD(unix, "int")
return variant(static_cast<int>(obj.unix_));
DEFINE_FIELD(second, "int")
return variant(obj.tm_.tm_sec);
DEFINE_FIELD(minute, "int")
return variant(obj.tm_.tm_min);
DEFINE_FIELD(hour, "int")
return variant(obj.tm_.tm_hour);
DEFINE_FIELD(day, "int")
return variant(obj.tm_.tm_mday);
DEFINE_FIELD(yday, "int")
return variant(obj.tm_.tm_yday);
DEFINE_FIELD(month, "int")
return variant(obj.tm_.tm_mon + 1);
DEFINE_FIELD(year, "int")
return variant(obj.tm_.tm_year + 1900);
DEFINE_FIELD(is_dst, "bool")
return variant::from_bool(obj.tm_.tm_isdst != 0);
DEFINE_FIELD(weekday, "string")
std::string weekday;
switch(obj.tm_.tm_wday) {
case 0: weekday = "Sunday"; break;
case 1: weekday = "Monday"; break;
case 2: weekday = "Tuesday"; break;
case 3: weekday = "Wednesday"; break;
case 4: weekday = "Thursday"; break;
case 5: weekday = "Friday"; break;
case 6: weekday = "Saturday"; break;
};
return variant(weekday);
END_DEFINE_CALLABLE(DateTime)
FUNCTION_DEF(time, 0, 1, "time(int unix_time) -> date_time: returns the current real time")
Formula::failIfStaticContext();
time_t t;
if(NUM_ARGS == 0) {
t = time(nullptr) + g_fake_time_adjust;
} else {
t = EVAL_ARG(0).as_int();
}
tm* ltime = localtime(&t);
if(ltime == nullptr) {
t = time(nullptr) + g_fake_time_adjust;
ltime = localtime(&t);
ASSERT_LOG(ltime != nullptr, "Could not get time()");
}
return variant(new DateTime(t, ltime));
FUNCTION_ARGS_DEF
ARG_TYPE("int");
RETURN_TYPE("builtin date_time")
END_FUNCTION_DEF(time)
FUNCTION_DEF(get_debug_info, 1, 1, "get_debug_info(value)")
variant value = EVAL_ARG(0);
const variant::debug_info* info = value.get_debug_info();
if(info == nullptr) {
return variant();
}
variant_builder b;
if(info->filename) {
b.add("filename", variant(*info->filename));
}
b.add("line", info->line);
b.add("col", info->column);
b.add("end_line", info->end_line);
b.add("end_col", info->end_column);
return b.build();
FUNCTION_ARGS_DEF
ARG_TYPE("any");
RETURN_TYPE("null|{filename: string|null, line: int, col: int, end_line: int, end_col: int}")
END_FUNCTION_DEF(get_debug_info)
FUNCTION_DEF(set_user_info, 2, 2, "set_user_info(string, any): sets some user info used in stats collection")
std::string key = EVAL_ARG(0).as_string();
variant value = EVAL_ARG(1);
return variant(new FnCommandCallable("set_user_info", [=]() { g_user_info_registry[key] = value; }));
RETURN_TYPE("commands")
END_FUNCTION_DEF(set_user_info)
FUNCTION_DEF(current_level, 0, 0, "current_level(): return the current level the game is in")
Formula::failIfStaticContext();
return variant(&Level::current());
RETURN_TYPE("builtin level")
END_FUNCTION_DEF(current_level)
FUNCTION_DEF(cancel, 0, 0, "cancel(): cancel the current command pipeline")
return variant(new FnCommandCallable("cancel", [=]() { deferCurrentCommandSequence(); }));
RETURN_TYPE("commands")
END_FUNCTION_DEF(cancel)
FUNCTION_DEF(overload, 1, -1, "overload(fn...): makes an overload of functions")
std::vector<variant> functions;
for(int n = 0; n != NUM_ARGS; ++n) {
functions.push_back(EVAL_ARG(n));
ASSERT_LOG(functions.back().is_function(), "CALL TO overload() WITH NON-FUNCTION VALUE " << functions.back().write_json());
}
return variant::create_function_overload(functions);
FUNCTION_TYPE_DEF
int min_args = -1;
std::vector<std::vector<variant_type_ptr> > arg_types;
std::vector<variant_type_ptr> return_types;
std::vector<variant_type_ptr> function_types;
for(int n = 0; n != NUM_ARGS; ++n) {
variant_type_ptr t = args()[n]->queryVariantType();
function_types.push_back(t);
std::vector<variant_type_ptr> a;
variant_type_ptr return_type;
int nargs = -1;
if(t->is_function(&a, &return_type, &nargs) == false) {
ASSERT_LOG(false, "CALL to overload() with non-function type: " << args()[n]->debugPinpointLocation());
}
return_types.push_back(return_type);
if(min_args == -1 || nargs < min_args) {
min_args = nargs;
}
for(unsigned m = 0; m != a.size(); ++m) {
if(arg_types.size() <= m) {
arg_types.resize(m+1);
}
arg_types[m].push_back(a[m]);
}
}
if(min_args < 0) {
min_args = 0;
}
variant_type_ptr return_union = variant_type::get_union(return_types);
std::vector<variant_type_ptr> arg_union;
for(int n = 0; n != arg_types.size(); ++n) {
arg_union.push_back(variant_type::get_union(arg_types[n]));
}
return variant_type::get_function_overload_type(variant_type::get_function_type(arg_union, return_union, min_args), function_types);
END_FUNCTION_DEF(overload)
FUNCTION_DEF(addr, 1, 1, "addr(obj): Provides the address of the given object as a string. Useful for distinguishing objects")
variant v = EVAL_ARG(0);
FormulaCallable* addr = nullptr;
if(!v.is_null()) {
addr = v.convert_to<FormulaCallable>();
}
char buf[128];
sprintf(buf, "%p", addr);
return variant(std::string(buf));
FUNCTION_ARGS_DEF
ARG_TYPE("object|null");
RETURN_TYPE("string");
END_FUNCTION_DEF(addr)
FUNCTION_DEF(get_call_stack, 0, 0, "get_call_stack()")
return variant(get_call_stack());
FUNCTION_ARGS_DEF
RETURN_TYPE("string");
END_FUNCTION_DEF(get_call_stack)
FUNCTION_DEF(get_full_call_stack, 0, 0, "get_full_call_stack()")
return variant(get_full_call_stack());
FUNCTION_ARGS_DEF
RETURN_TYPE("string");
END_FUNCTION_DEF(get_full_call_stack)
FUNCTION_DEF(create_cache, 0, 1, "create_cache(max_entries=4096): makes an FFL cache object")
Formula::failIfStaticContext();
std::string name = "";
int max_entries = 4096;
if(NUM_ARGS >= 1) {
variant arg = EVAL_ARG(0);
if(arg.is_int()) {
max_entries = arg.as_int();
} else {
const std::map<variant,variant>& m = arg.as_map();
max_entries = arg[variant("size")].as_int(max_entries);
name = arg[variant("name")].as_string_default("");
}
}
auto cache = new ffl_cache(max_entries);
cache->setName(name);
return variant(cache);
FUNCTION_ARGS_DEF
ARG_TYPE("int|{size: int|null, name: string|null}");
RETURN_TYPE("object");
END_FUNCTION_DEF(create_cache)
FUNCTION_DEF(global_cache, 0, 2, "create_cache(max_entries=4096): makes an FFL cache object")
std::string name = "global";
int max_entries = 4096;
for(int n = 0; n < NUM_ARGS; ++n) {
variant arg = EVAL_ARG(n);
if(arg.is_int()) {
max_entries = arg.as_int();
} else if(arg.is_string()) {
name = arg.as_string();
}
}
auto cache = new ffl_cache(max_entries);
cache->setName(name);
return variant(cache);
FUNCTION_ARGS_DEF
ARG_TYPE("int|string");
ARG_TYPE("int");
RETURN_TYPE("object");
END_FUNCTION_DEF(global_cache)
FUNCTION_DEF_CTOR(query_cache, 3, 3, "query_cache(ffl_cache, key, expr): ")
FUNCTION_DEF_MEMBERS
bool optimizeArgNumToVM(int narg) const override {
return narg != 2;
}
FUNCTION_DEF_IMPL
const variant key = EVAL_ARG(1);
variant cache_variant = EVAL_ARG(0);
const ffl_cache* cache = cache_variant.try_convert<ffl_cache>();
ASSERT_LOG(cache != nullptr, "ILLEGAL CACHE ARGUMENT TO query_cache");
const variant* result = cache->get(key);
if(result != nullptr) {
return *result;
}
const variant value = args()[2]->evaluate(variables);
cache->store(key, value);
return value;
FUNCTION_DYNAMIC_ARGUMENTS
FUNCTION_TYPE_DEF
return args()[2]->queryVariantType();
END_FUNCTION_DEF(query_cache)
FUNCTION_DEF(game_preferences, 0, 0, "game_preferences() ->builtin game_preferences")
Formula::failIfStaticContext();
return preferences::ffl_interface();
FUNCTION_ARGS_DEF
RETURN_TYPE("builtin game_preferences");
END_FUNCTION_DEF(game_preferences)
FUNCTION_DEF(md5, 1, 1, "md5(string) ->string")
return variant(md5::sum(EVAL_ARG(0).as_string()));
FUNCTION_ARGS_DEF
ARG_TYPE("string");
RETURN_TYPE("string");
END_FUNCTION_DEF(md5)
FUNCTION_DEF(if, 2, -1, "if(a,b,c)")
const int nargs = static_cast<int>(NUM_ARGS);
for(int n = 0; n < nargs-1; n += 2) {
const bool result = EVAL_ARG(n).as_bool();
if(result) {
return EVAL_ARG(n+1);
}
}
if((nargs % 2) == 0) {
return variant();
}
return EVAL_ARG(nargs-1);
FUNCTION_DYNAMIC_ARGUMENTS
FUNCTION_OPTIMIZE
variant v;
if(NUM_ARGS <= 3 && args()[0]->canReduceToVariant(v)) {
if(v.as_bool()) {
return args()[1];
} else {
if(NUM_ARGS == 3) {
return args()[2];
} else {
return ExpressionPtr(new VariantExpression(variant()));
}
}
}
return ExpressionPtr();
CAN_VM
return canChildrenVM();
FUNCTION_VM
for(ExpressionPtr& a : args_mutable()) {
optimizeChildToVM(a);
}
for(auto a : args()) {
if(a->canCreateVM() == false) {
return ExpressionPtr();
}
}
std::vector<int> jump_to_end_sources;
for(int n = 0; n+1 < static_cast<int>(NUM_ARGS); n += 2) {
args()[n]->emitVM(vm);
const int jump_source = vm.addJumpSource(OP_JMP_UNLESS);
vm.addInstruction(OP_POP);
args()[n+1]->emitVM(vm);
jump_to_end_sources.push_back(vm.addJumpSource(OP_JMP));
vm.jumpToEnd(jump_source);
vm.addInstruction(OP_POP);
}
if(NUM_ARGS%2 == 1) {
args().back()->emitVM(vm);
} else {
vm.addInstruction(OP_PUSH_NULL);
}
for(int j : jump_to_end_sources) {
vm.jumpToEnd(j);
}
return createVMExpression(vm, queryVariantType(), *this);
FUNCTION_TYPE_DEF
std::vector<variant_type_ptr> types;
types.push_back(args()[1]->queryVariantType());
const int nargs = static_cast<int>(NUM_ARGS);
for(int n = 1; n < nargs; n += 2) {
types.push_back(args()[n]->queryVariantType());
}