Repository navigation
Expand file tree
/
Copy pathoperators.hpp
More file actions
729 lines (666 loc) · 17.9 KB
/
Copy pathoperators.hpp
File metadata and controls
729 lines (666 loc) · 17.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
/* Copyright (C) 2022-2025 Davide Faconti - All Rights Reserved
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#pragma once
#include "behaviortree_cpp/scripting/any_types.hpp"
#include "behaviortree_cpp/scripting/script_parser.hpp"
#include <charconv>
#include <cmath>
#include <memory>
#include <string>
#include <vector>
// Naive implementation of an AST with simple evaluation function.
namespace BT::Ast
{
using SimpleString = SafeAny::SimpleString;
using expr_ptr = std::shared_ptr<struct ExprBase>;
// extended string to number that consider enums and booleans
inline double StringToDouble(const Any& value, const Environment& env)
{
const auto str = value.cast<std::string>();
if(str == "true")
{
return 1.0;
}
if(str == "false")
{
return 0.0;
}
if(env.enums)
{
auto it = env.enums->find(str);
if(it != env.enums->end())
{
return it->second;
}
}
return value.cast<double>();
}
// Replace a string holding a whole number (e.g. "42" or "1.5") with that number.
// Unlike StringToDouble, it rejects numeric prefixes, booleans and enums.
inline void NumericStringToNumber(Any& value)
{
const auto str = value.cast<std::string>();
const char* end = str.data() + str.size();
int64_t int_val = 0;
const auto [ptr, ec] = std::from_chars(str.data(), end, int_val);
double dbl_val = 0;
if(ec == std::errc() && ptr == end)
{
value = Any(int_val);
}
else if(parseDouble(str, dbl_val, /*require_full_consumption=*/true))
{
value = Any(dbl_val);
}
}
struct ExprBase
{
using Ptr = std::shared_ptr<ExprBase>;
virtual ~ExprBase() = default;
virtual Any evaluate(Environment& env) const = 0;
};
inline std::string ErrorNotInit(const char* side, const char* op_str)
{
return StrCat("The ", side, " operand of the operator [", op_str,
"] is not initialized");
}
struct ExprLiteral : ExprBase
{
Any value;
ExprLiteral(Any v) : value(v)
{}
Any evaluate(Environment&) const override
{
return value;
}
};
struct ExprName : ExprBase
{
std::string name;
explicit ExprName(std::string n) : name(std::move(n))
{}
Any evaluate(Environment& env) const override
{
//search first in the enums table
if(env.enums)
{
auto enum_ptr = env.enums->find(name);
if(enum_ptr != env.enums->end())
{
return Any(double(enum_ptr->second));
}
}
// search now in the variables table
auto any_ref = env.vars->getAnyLocked(name);
if(!any_ref)
{
throw RuntimeError(StrCat("Variable not found: ", name));
}
return *any_ref.get();
}
};
struct ExprUnaryArithmetic : ExprBase
{
enum op_t
{
negate,
complement,
logical_not
} op;
expr_ptr rhs;
explicit ExprUnaryArithmetic(op_t op, expr_ptr e) : op(op), rhs(std::move(e))
{}
Any evaluate(Environment& env) const override
{
auto rhs_v = rhs->evaluate(env);
if(rhs_v.isNumber())
{
const double rv = rhs_v.cast<double>();
switch(op)
{
case negate:
return Any(-rv);
case complement:
// Use the checked conversion, like the binary bitwise operators do.
// A plain static_cast is undefined for NaN and for values at or
// beyond the int64_t range: the hand-written comparison used here
// before let NaN (every comparison is false) and 2^63 (not greater
// than double(INT64_MAX), which rounds up to 2^63) through, and
// silently truncated fractional values.
try
{
return Any(static_cast<double>(~rhs_v.cast<int64_t>()));
}
catch(const std::exception&)
{
throw RuntimeError("Number out of range for bitwise operation");
}
case logical_not:
return Any(static_cast<double>(!static_cast<bool>(rv)));
}
}
else if(rhs_v.isString())
{
if(op == logical_not)
{
const auto str = rhs_v.cast<std::string>();
if(str == "true" || str == "True" || str == "TRUE" || str == "1")
{
return Any(0.0);
}
if(str == "false" || str == "False" || str == "FALSE" || str == "0")
{
return Any(1.0);
}
}
throw RuntimeError("Invalid operator for std::string");
}
throw RuntimeError("ExprUnaryArithmetic: undefined");
}
};
struct ExprBinaryArithmetic : ExprBase
{
enum op_t
{
plus,
minus,
times,
div,
concat,
bit_and,
bit_or,
bit_xor,
logic_and,
logic_or
} op;
const char* opStr() const
{
switch(op)
{
case plus:
return "+";
case minus:
return "-";
case times:
return "*";
case div:
return "/";
case concat:
return "..";
case bit_and:
return "&";
case bit_or:
return "|";
case bit_xor:
return "^";
case logic_and:
return "&&";
case logic_or:
return "||";
}
return "";
}
expr_ptr lhs, rhs;
explicit ExprBinaryArithmetic(expr_ptr lhs, op_t op, expr_ptr rhs)
: op(op), lhs(std::move(lhs)), rhs(std::move(rhs))
{}
Any evaluate(Environment& env) const override
{
auto lhs_v = lhs->evaluate(env);
auto rhs_v = rhs->evaluate(env);
if(lhs_v.empty())
{
throw RuntimeError(ErrorNotInit("left", opStr()));
}
if(rhs_v.empty())
{
throw RuntimeError(ErrorNotInit("right", opStr()));
}
// A numeric string mixed with a number is used as that number, e.g. the
// literal SubTree port int_val="42" in "int_val + 1"
if(op == plus || op == minus || op == times || op == div)
{
if(lhs_v.isString() && rhs_v.isNumber())
{
NumericStringToNumber(lhs_v);
}
else if(lhs_v.isNumber() && rhs_v.isString())
{
NumericStringToNumber(rhs_v);
}
}
if(rhs_v.isNumber() && lhs_v.isNumber())
{
auto lv = lhs_v.cast<double>();
auto rv = rhs_v.cast<double>();
switch(op)
{
case plus:
return Any(lv + rv);
case minus:
return Any(lv - rv);
case times:
return Any(lv * rv);
case div:
return Any(lv / rv);
default: {
}
}
if(op == bit_and || op == bit_or || op == bit_xor)
{
try
{
int64_t li = lhs_v.cast<int64_t>();
int64_t ri = rhs_v.cast<int64_t>();
switch(op)
{
case bit_and:
return Any(static_cast<double>(li & ri));
case bit_or:
return Any(static_cast<double>(li | ri));
case bit_xor:
return Any(static_cast<double>(li ^ ri));
default: {
}
}
}
catch(...)
{
throw RuntimeError("Binary operators are not allowed if "
"one of the operands is not an integer");
}
}
if(op == logic_or || op == logic_and)
{
try
{
auto lb = lhs_v.cast<bool>();
auto rb = rhs_v.cast<bool>();
switch(op)
{
case logic_or:
return Any(static_cast<double>(lb || rb));
case logic_and:
return Any(static_cast<double>(lb && rb));
default: {
}
}
}
catch(...)
{
throw RuntimeError("Logic operators are not allowed if "
"one of the operands is not castable to bool");
}
}
}
else if(rhs_v.isString() && lhs_v.isString() && op == plus)
{
return Any(lhs_v.cast<std::string>() + rhs_v.cast<std::string>());
}
else if(op == concat && ((rhs_v.isString() && lhs_v.isString()) ||
(rhs_v.isString() && lhs_v.isNumber()) ||
(rhs_v.isNumber() && lhs_v.isString())))
{
return Any(lhs_v.cast<std::string>() + rhs_v.cast<std::string>());
}
else
{
throw RuntimeError("Operation not permitted");
}
return {}; // unreachable
}
};
template <typename T>
bool IsSame(const T& lv, const T& rv)
{
if constexpr(std::is_same_v<double, T>)
{
constexpr double EPS = static_cast<double>(std::numeric_limits<float>::epsilon());
return std::abs(lv - rv) <= EPS;
}
else
{
return (lv == rv);
}
}
struct ExprComparison : ExprBase
{
enum op_t
{
equal,
not_equal,
less,
greater,
less_equal,
greater_equal
};
const char* opStr(op_t op) const
{
switch(op)
{
case equal:
return "==";
case not_equal:
return "!=";
case less:
return "<";
case greater:
return ">";
case less_equal:
return "<=";
case greater_equal:
return ">=";
}
return "";
}
std::vector<op_t> ops;
std::vector<expr_ptr> operands;
Any evaluate(Environment& env) const override
{
auto SwitchImpl = [&](const auto& lv, const auto& rv, op_t op) {
switch(op)
{
case equal:
if(!IsSame(lv, rv))
return false;
break;
case not_equal:
if(IsSame(lv, rv))
return false;
break;
case less:
if(lv >= rv)
return false;
break;
case greater:
if(lv <= rv)
return false;
break;
case less_equal:
if(lv > rv)
return false;
break;
case greater_equal:
if(lv < rv)
return false;
break;
}
return true;
};
auto lhs_v = operands[0]->evaluate(env);
for(auto i = 0u; i != ops.size(); ++i)
{
auto rhs_v = operands[i + 1]->evaluate(env);
if(lhs_v.empty())
{
throw RuntimeError(ErrorNotInit("left", opStr(ops[i])));
}
if(rhs_v.empty())
{
throw RuntimeError(ErrorNotInit("right", opStr(ops[i])));
}
const Any False(0.0);
if(lhs_v.isNumber() && rhs_v.isNumber())
{
auto lv = lhs_v.cast<double>();
auto rv = rhs_v.cast<double>();
if(!SwitchImpl(lv, rv, ops[i]))
{
return False;
}
}
else if(lhs_v.isString() && rhs_v.isString())
{
auto lv = lhs_v.cast<SimpleString>();
auto rv = rhs_v.cast<SimpleString>();
if(!SwitchImpl(lv, rv, ops[i]))
{
return False;
}
}
else if(lhs_v.isString() && rhs_v.isNumber())
{
auto lv = StringToDouble(lhs_v, env);
auto rv = rhs_v.cast<double>();
if(!SwitchImpl(lv, rv, ops[i]))
{
return False;
}
}
else if(lhs_v.isNumber() && rhs_v.isString())
{
auto lv = lhs_v.cast<double>();
auto rv = StringToDouble(rhs_v, env);
if(!SwitchImpl(lv, rv, ops[i]))
{
return False;
}
}
else
{
throw RuntimeError(StrCat("Can't mix different types in Comparison. "
"Left operand [",
BT::demangle(lhs_v.type()), "] right operand [",
BT::demangle(rhs_v.type()), "]"));
}
lhs_v = rhs_v;
}
return Any(1.0);
}
};
struct ExprIf : ExprBase
{
expr_ptr condition, then, else_;
explicit ExprIf(expr_ptr condition, expr_ptr then, expr_ptr else_)
: condition(std::move(condition)), then(std::move(then)), else_(std::move(else_))
{}
Any evaluate(Environment& env) const override
{
const auto& v = condition->evaluate(env);
bool valid = (v.isType<SimpleString>() && v.cast<SimpleString>().size() > 0) ||
(v.cast<double>() != 0.0);
if(valid)
{
return then->evaluate(env);
}
else
{
return else_->evaluate(env);
}
}
};
struct ExprAssignment : ExprBase
{
enum op_t
{
assign_create,
assign_existing,
assign_plus,
assign_minus,
assign_times,
assign_div
} op;
const char* opStr() const
{
switch(op)
{
case assign_create:
return ":=";
case assign_existing:
return "=";
case assign_plus:
return "+=";
case assign_minus:
return "-=";
case assign_times:
return "*=";
case assign_div:
return "/=";
}
return "";
}
expr_ptr lhs, rhs;
explicit ExprAssignment(expr_ptr _lhs, op_t op, expr_ptr _rhs)
: op(op), lhs(std::move(_lhs)), rhs(std::move(_rhs))
{}
Any evaluate(Environment& env) const override
{
auto varname = dynamic_cast<ExprName*>(lhs.get());
if(!varname)
{
throw RuntimeError("Assignment left operand not a blackboard entry");
}
const auto& key = varname->name;
auto entry = env.vars->getEntry(key);
if(!entry)
{
// variable doesn't exist, create it if using operator assign_create
if(op == assign_create)
{
env.vars->createEntry(key, PortInfo());
entry = env.vars->getEntry(key);
if(!entry)
{
throw LogicError("Bug: report");
}
}
else
{
// fail otherwise
auto msg = StrCat("The blackboard entry [", key,
"] doesn't exist, yet.\n"
"If you want to create a new one, "
"use the operator "
"[:=] instead of [=]");
throw RuntimeError(msg);
}
}
auto value = rhs->evaluate(env);
std::scoped_lock lock(entry->entry_mutex);
auto* dst_ptr = &entry->value;
auto errorPrefix = [dst_ptr, &key]() {
return StrCat("Error assigning a value to entry [", key, "] with type [",
BT::demangle(dst_ptr->type()), "]. ");
};
if(value.empty())
{
throw RuntimeError(ErrorNotInit("right", opStr()));
}
if(op == assign_create || op == assign_existing)
{
// the very fist assignment can come from any type.
// In the future, type check will be done by Any::copyInto
if(dst_ptr->empty() && entry->info.type() == typeid(AnyTypeAllowed))
{
*dst_ptr = value;
}
else if(value.isString() && !dst_ptr->isString())
{
// special case: string to other type.
// Check if we can use the StringConverter
auto const str = value.cast<std::string>();
const auto* entry_info = env.vars->entryInfo(key);
if(auto converter = entry_info->converter())
{
*dst_ptr = converter(str);
}
else if(dst_ptr->isNumber())
{
auto num_value = StringToDouble(value, env);
*dst_ptr = Any(num_value);
}
else
{
auto msg = StrCat(errorPrefix(),
"\nThe right operand is a string, "
"can't convert to ",
demangle(dst_ptr->type()));
throw RuntimeError(msg);
}
}
else
{
try
{
value.copyInto(*dst_ptr);
}
catch(std::exception&)
{
auto msg = StrCat(errorPrefix(), "\nThe right operand has type [",
BT::demangle(value.type()), "] and can't be converted to [",
BT::demangle(dst_ptr->type()), "]");
throw RuntimeError(msg);
}
}
entry->sequence_id++;
entry->stamp = std::chrono::steady_clock::now().time_since_epoch();
return *dst_ptr;
}
if(dst_ptr->empty())
{
throw RuntimeError(ErrorNotInit("left", opStr()));
}
// temporary use
Any temp_variable = *dst_ptr;
if(value.isNumber())
{
if(!temp_variable.isNumber())
{
throw RuntimeError("This Assignment operator can't be used "
"with a non-numeric type");
}
auto lv = temp_variable.cast<double>();
auto rv = value.cast<double>();
switch(op)
{
case assign_plus:
temp_variable = Any(lv + rv);
break;
case assign_minus:
temp_variable = Any(lv - rv);
break;
case assign_times:
temp_variable = Any(lv * rv);
break;
case assign_div:
temp_variable = Any(lv / rv);
break;
default: {
}
}
}
else if(value.isString())
{
if(op == assign_plus)
{
auto lv = temp_variable.cast<std::string>();
auto rv = value.cast<std::string>();
temp_variable = Any(lv + rv);
}
else
{
throw RuntimeError("Operator not supported for strings");
}
}
temp_variable.copyInto(*dst_ptr);
entry->sequence_id++;
entry->stamp = std::chrono::steady_clock::now().time_since_epoch();
return *dst_ptr;
}
};
} // namespace BT::Ast
namespace BT::Scripting
{
/// Parse a script string into a list of AST expression nodes.
/// Throws std::runtime_error on parse failure.
std::vector<Ast::expr_ptr> parseStatements(const std::string& script);
} // namespace BT::Scripting