forked from AliceO2Group/AliceO2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExpressions.cxx
More file actions
1351 lines (1255 loc) · 38.1 KB
/
Expressions.cxx
File metadata and controls
1351 lines (1255 loc) · 38.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2019-2020 CERN and copyright holders of ALICE O2.
// See https://alice-o2.web.cern.ch/copyright for details of the copyright holders.
// All rights not expressly granted are reserved.
//
// This software is distributed under the terms of the GNU General Public
// License v3 (GPL Version 3), copied verbatim in the file "COPYING".
//
// In applying this license CERN does not waive the privileges and immunities
// granted to it by virtue of its status as an Intergovernmental Organization
// or submit itself to any jurisdiction.
#include "Framework/ExpressionHelpers.h"
#include "Framework/RuntimeError.h"
#include "Framework/VariantHelpers.h"
#include "arrow/table.h"
#include "gandiva/tree_expr_builder.h"
#include <algorithm>
#include <iostream>
#include <set>
#include <stack>
#include <unordered_map>
#include "CommonConstants/MathConstants.h"
using namespace o2::framework;
namespace o2::framework::expressions
{
void unknownParameterUsed(const char* name)
{
runtime_error_f("Unknown parameter used in expression: %s", name);
}
/// a map between BasicOp and tokens in string expressions
constexpr std::array<std::string_view, BasicOp::Conditional + 1> mapping{
"&&",
"||",
"+",
"-",
"/",
"*",
"&",
"|",
"^",
"<",
"<=",
">",
">=",
"==",
"!=",
"natan2",
"npow",
"nsqrt",
"nexp",
"nlog",
"nlog10",
"nsin",
"ncos",
"ntan",
"nasin",
"nacos",
"natan",
"nabs",
"nround",
"nbitwise_not",
"ifnode"};
constexpr std::array<std::string_view, 8> cfgtypes{
"uint16_t", // 0
"int16_t", // 1
"uint32_t", // 2
"int32_t", // 3
"uint64_t", // 4
"int64_t", // 5
"float", // 6
"double" // 7
};
/// math constants to recognize in string expressions
constexpr std::array<std::string_view, 9> mathConstants{
"Almost0",
"Epsilon",
"Almost1",
"VeryBig",
"PI",
"TwoPI",
"PIHalf",
"PIThird",
"PIQuarter"};
/// values of math constants to substiture
constexpr std::array<float, 9> mathConstantsValues{
o2::constants::math::Almost0,
o2::constants::math::Epsilon,
o2::constants::math::Almost1,
o2::constants::math::VeryBig,
o2::constants::math::PI,
o2::constants::math::TwoPI,
o2::constants::math::PIHalf,
o2::constants::math::PIThird,
o2::constants::math::PIQuarter};
/// a map between BasicOp and gandiva node definitions
/// note that logical 'and' and 'or' are created separately
constexpr std::array<const char*, BasicOp::Conditional + 1> basicOperationsMap = {
"and",
"or",
"add",
"subtract",
"divide",
"multiply",
"bitwise_and",
"bitwise_or",
"bitwise_xor",
"less_than",
"less_than_or_equal_to",
"greater_than",
"greater_than_or_equal_to",
"equal",
"not_equal",
"atan2f",
"powerf",
"sqrtf",
"expf",
"logf",
"log10f",
"sinf",
"cosf",
"tanf",
"asinf",
"acosf",
"atanf",
"absf",
"round",
"bitwise_not",
"if"};
size_t Filter::designateSubtrees(Node* node, size_t index)
{
std::stack<NodeRecord> path;
auto local_index = index;
path.emplace(node, 0);
while (!path.empty()) {
auto top = path.top();
top.node_ptr->index = local_index;
path.pop();
if (top.node_ptr->condition != nullptr) {
// start new subtrees
index = designateSubtrees(top.node_ptr->left.get(), local_index + 1);
index = designateSubtrees(top.node_ptr->condition.get(), index + 1);
index = designateSubtrees(top.node_ptr->right.get(), index + 1);
} else {
// continue current subtree
if (top.node_ptr->left != nullptr) {
path.emplace(top.node_ptr->left.get(), 0);
}
if (top.node_ptr->right != nullptr) {
path.emplace(top.node_ptr->right.get(), 0);
}
}
}
return index;
}
void Filter::parse()
{
node = std::make_unique<Node>(Parser::parse(input));
(void)designateSubtrees(node.get());
}
template <typename T>
constexpr inline auto makeDatum(T const&)
{
return DatumSpec{};
}
template <is_literal_like T>
constexpr inline auto makeDatum(T const& node)
{
return DatumSpec{node.value, node.type};
}
template <is_binding T>
constexpr inline auto makeDatum(T const& node)
{
return DatumSpec{node.name, node.hash, node.type};
}
template <typename T>
constexpr inline auto makeOp(T const&, size_t const&)
{
return ColumnOperationSpec{};
}
template <is_operation T>
constexpr inline auto makeOp(T const& node, size_t const& index)
{
return ColumnOperationSpec{node.op, index};
}
template <is_conditional T>
constexpr inline auto makeOp(T const&, size_t const& index)
{
return ColumnOperationSpec{BasicOp::Conditional, index};
}
std::shared_ptr<arrow::DataType> concreteArrowType(atype::type type)
{
switch (type) {
case atype::UINT8:
return arrow::uint8();
case atype::INT8:
return arrow::int8();
case atype::INT16:
return arrow::int16();
case atype::UINT16:
return arrow::uint16();
case atype::INT32:
return arrow::int32();
case atype::UINT32:
return arrow::uint32();
case atype::INT64:
return arrow::int64();
case atype::UINT64:
return arrow::uint64();
case atype::FLOAT:
return arrow::float32();
case atype::DOUBLE:
return arrow::float64();
case atype::BOOL:
return arrow::boolean();
default:
return nullptr;
}
}
std::string upcastTo(atype::type f)
{
switch (f) {
case atype::INT32:
return "castINT";
case atype::INT64:
return "castBIGINT";
case atype::FLOAT:
return "castFLOAT4";
case atype::DOUBLE:
return "castFLOAT8";
default:
throw runtime_error_f("Do not know how to cast to %s", stringType(f));
}
}
std::ostream& operator<<(std::ostream& os, DatumSpec const& spec)
{
std::visit(
overloaded{
[&os](LiteralNode::var_t&& arg) {
std::visit(
[&os](auto&& arg) { os << arg; },
arg);
},
[&os](size_t&& arg) { os << arg; },
[&os](std::string&& arg) { os << arg; },
[](auto&&) {}},
spec.datum);
return os;
}
void updatePlaceholders(Filter& filter, InitContext& context)
{
if (filter.node == nullptr && !filter.input.empty()) {
filter.parse();
}
expressions::walk(filter.node.get(), [&](Node* node) {
if (node->self.index() == 3) {
std::get_if<3>(&node->self)->reset(context);
}
});
}
const char* stringType(atype::type t)
{
switch (t) {
case atype::BOOL:
return "bool";
case atype::DOUBLE:
return "double";
case atype::FLOAT:
return "float";
case atype::INT8:
return "int8";
case atype::INT16:
return "int16";
case atype::INT32:
return "int32";
case atype::INT64:
return "int64";
case atype::UINT8:
return "uint8";
case atype::UINT16:
return "uint16";
case atype::UINT32:
return "uint32";
case atype::UINT64:
return "uint64";
default:
return "unsupported";
}
O2_BUILTIN_UNREACHABLE();
}
Operations createOperations(Filter const& expression)
{
Operations OperationSpecs;
std::stack<NodeRecord> path;
auto isLeaf = [](Node const* const node) {
return ((node->left == nullptr) && (node->right == nullptr));
};
auto processLeaf = [](Node const* const node) {
return std::visit(
[](auto const& n) { return makeDatum(n); },
node->self);
};
size_t index = 0;
// insert the top node into stack
path.emplace(expression.node.get(), index++);
// while the stack is not empty
while (!path.empty()) {
auto top = path.top();
// create operation spec, pop the node and add its children
auto operationSpec =
std::visit(
[&](auto const& n) { return makeOp(n, top.node_ptr->index); },
top.node_ptr->self);
operationSpec.result = DatumSpec{top.index, operationSpec.type};
path.pop();
auto* left = top.node_ptr->left.get();
bool leftLeaf = isLeaf(left);
size_t li = 0;
if (leftLeaf) {
operationSpec.left = processLeaf(left);
} else {
li = index;
operationSpec.left = DatumSpec{index++, atype::NA};
}
decltype(left) right = nullptr;
if (top.node_ptr->right != nullptr) {
right = top.node_ptr->right.get();
}
bool rightLeaf = true;
if (right != nullptr) {
rightLeaf = isLeaf(right);
}
size_t ri = 0;
auto isUnary = false;
if (top.node_ptr->right == nullptr) {
operationSpec.right = DatumSpec{};
isUnary = true;
} else {
if (rightLeaf) {
operationSpec.right = processLeaf(right);
} else {
ri = index;
operationSpec.right = DatumSpec{index++, atype::NA};
}
}
decltype(left) condition = nullptr;
if (top.node_ptr->condition != nullptr) {
condition = top.node_ptr->condition.get();
}
bool condleaf = condition != nullptr ? isLeaf(condition) : true;
size_t ci = 0;
if (condition != nullptr) {
if (condleaf) {
operationSpec.condition = processLeaf(condition);
} else {
ci = index;
operationSpec.condition = DatumSpec{index++, atype::BOOL};
}
} else {
operationSpec.condition = DatumSpec{};
}
OperationSpecs.push_back(std::move(operationSpec));
if (!leftLeaf) {
path.emplace(left, li);
}
if (!isUnary && !rightLeaf) {
path.emplace(right, ri);
}
if (!condleaf) {
path.emplace(condition, ci);
}
}
// at this stage the operations vector is created, but the field types are
// only set for the logical operations and leaf nodes
std::vector<atype::type> resultTypes;
resultTypes.resize(OperationSpecs.size());
auto inferResultType = [&resultTypes](BasicOp op, DatumSpec& left, DatumSpec& right) {
// if the left datum is monostate (error)
if (left.datum.index() == 0) {
throw runtime_error("Malformed operation spec: empty left datum");
}
// check if the datums are references
if (left.datum.index() == 1) {
left.type = resultTypes[std::get<size_t>(left.datum)];
}
if (right.datum.index() == 1) {
right.type = resultTypes[std::get<size_t>(right.datum)];
}
auto t1 = left.type;
auto t2 = right.type;
// if the right datum is monostate (unary op)
if (right.datum.index() == 0) {
if (t1 == atype::DOUBLE) {
return atype::DOUBLE;
}
return atype::FLOAT;
}
if (t1 == t2) {
return t1;
}
auto isIntType = [](auto t) {
return (t == atype::UINT8) || (t == atype::INT8) || (t == atype::UINT16) || (t == atype::INT16) || (t == atype::UINT32) || (t == atype::INT32) || (t == atype::UINT64) || (t == atype::INT64);
};
auto isBitwiseOp = [](auto o) {
return ((o == BasicOp::BitwiseAnd) || (o == BasicOp::BitwiseNot) || (o == BasicOp::BitwiseOr) || (o == BasicOp::BitwiseXor));
};
if (isIntType(t1)) {
if (t2 == atype::FLOAT && !isBitwiseOp(op)) {
return atype::FLOAT;
}
if (t2 == atype::DOUBLE && !isBitwiseOp(op)) {
return atype::DOUBLE;
}
if (isIntType(t2)) {
if (t1 > t2) {
return t1;
}
return t2;
}
}
if (t1 == atype::FLOAT) {
if (isIntType(t2) && !isBitwiseOp(op)) {
return atype::FLOAT;
}
if (t2 == atype::DOUBLE) {
return atype::DOUBLE;
}
}
if (t1 == atype::DOUBLE) {
return atype::DOUBLE;
}
if (isIntType(t1) && isBitwiseOp(op)) {
return t1;
}
if (isIntType(t2) && isBitwiseOp(op)) {
return t2;
}
throw runtime_error_f("Invalid combination of argument types %s and %s", stringType(t1), stringType(t2));
};
for (auto it = OperationSpecs.rbegin(); it != OperationSpecs.rend(); ++it) {
auto type = inferResultType(it->op, it->left, it->right);
if (it->type == atype::NA) {
it->type = type;
}
it->result.type = it->type;
resultTypes[std::get<size_t>(it->result.datum)] = it->type;
}
return OperationSpecs;
}
gandiva::ConditionPtr makeCondition(gandiva::NodePtr node)
{
return gandiva::TreeExprBuilder::MakeCondition(std::move(node));
}
gandiva::ExpressionPtr makeExpression(gandiva::NodePtr node, gandiva::FieldPtr result)
{
return gandiva::TreeExprBuilder::MakeExpression(std::move(node), std::move(result));
}
std::shared_ptr<gandiva::Filter>
createFilter(gandiva::SchemaPtr const& Schema, Operations const& opSpecs)
{
std::shared_ptr<gandiva::Filter> filter;
auto s = gandiva::Filter::Make(Schema,
makeCondition(createExpressionTree(opSpecs, Schema)),
&filter);
if (!s.ok()) {
throw runtime_error_f("Failed to create filter: %s", s.ToString().c_str());
}
return filter;
}
std::shared_ptr<gandiva::Filter>
createFilter(gandiva::SchemaPtr const& Schema, gandiva::ConditionPtr condition)
{
std::shared_ptr<gandiva::Filter> filter;
auto s = gandiva::Filter::Make(Schema,
condition,
&filter);
if (!s.ok()) {
throw runtime_error_f("Failed to create filter: %s", s.ToString().c_str());
}
return filter;
}
std::shared_ptr<gandiva::Projector>
createProjector(gandiva::SchemaPtr const& Schema, Operations const& opSpecs, gandiva::FieldPtr result)
{
std::shared_ptr<gandiva::Projector> projector;
auto s = gandiva::Projector::Make(Schema,
{makeExpression(createExpressionTree(opSpecs, Schema), std::move(result))},
&projector);
if (!s.ok()) {
throw runtime_error_f("Failed to create projector: %s", s.ToString().c_str());
}
return projector;
}
std::shared_ptr<gandiva::Projector>
createProjector(gandiva::SchemaPtr const& Schema, Projector&& p, gandiva::FieldPtr result)
{
return createProjector(Schema, createOperations(p), std::move(result));
}
std::shared_ptr<gandiva::Projector> createProjectorHelper(size_t nColumns, expressions::Projector* projectors,
std::shared_ptr<arrow::Schema> schema,
std::vector<std::shared_ptr<arrow::Field>> const& fields)
{
std::vector<gandiva::ExpressionPtr> expressions;
for (size_t ci = 0; ci < nColumns; ++ci) {
expressions.push_back(
makeExpression(
framework::expressions::createExpressionTree(
framework::expressions::createOperations(projectors[ci]),
schema),
fields[ci]));
}
std::shared_ptr<gandiva::Projector> projector;
auto s = gandiva::Projector::Make(
schema,
expressions,
&projector);
if (s.ok()) {
return projector;
}
throw o2::framework::runtime_error_f("Failed to create projector: %s", s.ToString().c_str());
}
gandiva::Selection createSelection(std::shared_ptr<arrow::Table> const& table, std::shared_ptr<gandiva::Filter> const& gfilter)
{
gandiva::Selection selection;
auto s = gandiva::SelectionVector::MakeInt64(table->num_rows(),
arrow::default_memory_pool(),
&selection);
if (!s.ok()) {
throw runtime_error_f("Cannot allocate selection vector %s", s.ToString().c_str());
}
if (table->num_rows() == 0) {
return selection;
}
arrow::TableBatchReader reader(*table);
std::shared_ptr<arrow::RecordBatch> batch;
while (true) {
s = reader.ReadNext(&batch);
if (!s.ok()) {
throw runtime_error_f("Cannot read batches from table %s", s.ToString().c_str());
}
if (batch == nullptr) {
break;
}
s = gfilter->Evaluate(*batch, selection);
if (!s.ok()) {
throw runtime_error_f("Cannot apply filter %s", s.ToString().c_str());
}
}
return selection;
}
gandiva::Selection createSelection(std::shared_ptr<arrow::Table> const& table,
Filter const& expression)
{
return createSelection(table, createFilter(table->schema(), createOperations(std::move(expression))));
}
auto createProjection(std::shared_ptr<arrow::Table> const& table, std::shared_ptr<gandiva::Projector> const& gprojector)
{
arrow::TableBatchReader reader(*table);
std::shared_ptr<arrow::RecordBatch> batch;
std::shared_ptr<arrow::ArrayVector> v;
while (true) {
auto s = reader.ReadNext(&batch);
if (!s.ok()) {
throw runtime_error_f("Cannot read batches from table %s", s.ToString().c_str());
}
if (batch == nullptr) {
break;
}
s = gprojector->Evaluate(*batch, arrow::default_memory_pool(), v.get());
if (!s.ok()) {
throw runtime_error_f("Cannot apply projector %s", s.ToString().c_str());
}
}
return v;
}
gandiva::NodePtr createExpressionTree(Operations const& opSpecs,
gandiva::SchemaPtr const& Schema)
{
std::vector<gandiva::NodePtr> opNodes;
opNodes.resize(opSpecs.size());
std::fill(opNodes.begin(), opNodes.end(), nullptr);
std::unordered_map<std::string, gandiva::NodePtr> fieldNodes;
std::unordered_map<size_t, gandiva::NodePtr> subtrees;
auto datumNode = [Schema, &opNodes, &fieldNodes](DatumSpec const& spec) {
if (spec.datum.index() == 0) {
return gandiva::NodePtr(nullptr);
}
if (spec.datum.index() == 1) {
return opNodes[std::get<size_t>(spec.datum)];
}
if (spec.datum.index() == 2) {
auto content = std::get<LiteralNode::var_t>(spec.datum);
switch (content.index()) {
case 0: // int
return gandiva::TreeExprBuilder::MakeLiteral(static_cast<int32_t>(std::get<int>(content)));
case 1: // bool
return gandiva::TreeExprBuilder::MakeLiteral(std::get<bool>(content));
case 2: // float
return gandiva::TreeExprBuilder::MakeLiteral(std::get<float>(content));
case 3: // double
return gandiva::TreeExprBuilder::MakeLiteral(std::get<double>(content));
case 4: // uint8
return gandiva::TreeExprBuilder::MakeLiteral(std::get<uint8_t>(content));
case 5: // int64
return gandiva::TreeExprBuilder::MakeLiteral(std::get<int64_t>(content));
case 6: // int16
return gandiva::TreeExprBuilder::MakeLiteral(std::get<int16_t>(content));
case 7: // uint16
return gandiva::TreeExprBuilder::MakeLiteral(std::get<uint16_t>(content));
case 8: // int8
return gandiva::TreeExprBuilder::MakeLiteral(std::get<int8_t>(content));
case 9: // uint32
return gandiva::TreeExprBuilder::MakeLiteral(std::get<uint32_t>(content));
case 10: // uint64
return gandiva::TreeExprBuilder::MakeLiteral(std::get<uint64_t>(content));
default:
throw runtime_error("Malformed LiteralNode");
}
}
if (spec.datum.index() == 3) {
auto name = std::get<std::string>(spec.datum);
auto lookup = fieldNodes.find(name);
if (lookup != fieldNodes.end()) {
return lookup->second;
}
auto field = Schema->GetFieldByName(name);
if (field == nullptr) {
throw runtime_error_f("Cannot find field \"%s\"", name.c_str());
}
auto node = gandiva::TreeExprBuilder::MakeField(field);
fieldNodes.insert({name, node});
return node;
}
throw runtime_error("Malformed DatumSpec");
};
auto insertUpcastNode = [](gandiva::NodePtr node, atype::type t0, atype::type t) {
if (t != t0) {
auto upcast = gandiva::TreeExprBuilder::MakeFunction(upcastTo(t0), {node}, concreteArrowType(t0));
node = upcast;
}
return node;
};
auto insertEqualizeUpcastNode = [](gandiva::NodePtr& node1, gandiva::NodePtr& node2, atype::type t1, atype::type t2) {
if (t2 > t1) {
auto upcast = gandiva::TreeExprBuilder::MakeFunction(upcastTo(t2), {node1}, concreteArrowType(t2));
node1 = upcast;
} else if (t1 > t2) {
auto upcast = gandiva::TreeExprBuilder::MakeFunction(upcastTo(t1), {node2}, concreteArrowType(t1));
node2 = upcast;
}
};
auto isBitwiseOp = [](auto o) {
return ((o == BasicOp::BitwiseAnd) || (o == BasicOp::BitwiseNot) || (o == BasicOp::BitwiseOr) || (o == BasicOp::BitwiseXor));
};
gandiva::NodePtr tree = nullptr;
for (auto it = opSpecs.rbegin(); it != opSpecs.rend(); ++it) {
auto leftNode = datumNode(it->left);
auto rightNode = datumNode(it->right);
auto condNode = datumNode(it->condition);
gandiva::NodePtr temp_node;
switch (it->op) {
case BasicOp::LogicalOr:
temp_node = gandiva::TreeExprBuilder::MakeOr({leftNode, rightNode});
break;
case BasicOp::LogicalAnd:
temp_node = gandiva::TreeExprBuilder::MakeAnd({leftNode, rightNode});
break;
case BasicOp::Conditional:
temp_node = gandiva::TreeExprBuilder::MakeIf(condNode, leftNode, rightNode, concreteArrowType(it->type));
break;
default:
if (it->op < BasicOp::Sqrt) {
if (it->type != atype::BOOL && !isBitwiseOp(it->op)) {
leftNode = insertUpcastNode(leftNode, it->type, it->left.type);
rightNode = insertUpcastNode(rightNode, it->type, it->right.type);
} else if (it->op == BasicOp::Equal || it->op == BasicOp::NotEqual) {
insertEqualizeUpcastNode(leftNode, rightNode, it->left.type, it->right.type);
}
temp_node = gandiva::TreeExprBuilder::MakeFunction(basicOperationsMap[it->op], {leftNode, rightNode}, concreteArrowType(it->type));
} else {
if (!isBitwiseOp(it->op)) {
leftNode = insertUpcastNode(leftNode, it->type, it->left.type);
}
temp_node = gandiva::TreeExprBuilder::MakeFunction(basicOperationsMap[it->op], {leftNode}, concreteArrowType(it->type));
}
break;
}
if (it->index == 0) {
tree = temp_node;
} else {
auto subtree = subtrees.find(it->index);
if (subtree == subtrees.end()) {
subtrees.insert({it->index, temp_node});
} else {
subtree->second = temp_node;
}
}
opNodes[std::get<size_t>(it->result.datum)] = temp_node;
}
return tree;
}
bool isTableCompatible(std::set<uint32_t> const& hashes, Operations const& specs)
{
std::set<uint32_t> opHashes;
for (auto const& spec : specs) {
if (spec.left.datum.index() == 3) {
opHashes.insert(spec.left.hash);
}
if (spec.right.datum.index() == 3) {
opHashes.insert(spec.right.hash);
}
}
return std::includes(hashes.begin(), hashes.end(),
opHashes.begin(), opHashes.end());
}
void updateExpressionInfos(expressions::Filter const& filter, std::vector<ExpressionInfo>& eInfos)
{
if (eInfos.empty()) {
throw runtime_error("Empty expression info vector.");
}
Operations ops = createOperations(filter);
for (auto& info : eInfos) {
if (isTableCompatible(info.hashes, ops)) {
auto tree = createExpressionTree(ops, info.schema);
/// If the tree is already set, add a new tree to it with logical 'and'
if (info.tree != nullptr) {
info.tree = gandiva::TreeExprBuilder::MakeAnd({info.tree, tree});
} else {
info.tree = tree;
}
}
}
}
void updateFilterInfo(ExpressionInfo& info, std::shared_ptr<arrow::Table>& table)
{
if (info.tree != nullptr && info.filter == nullptr) {
info.filter = framework::expressions::createFilter(table->schema(), framework::expressions::makeCondition(info.tree));
}
if (info.tree != nullptr && info.filter != nullptr && info.resetSelection == true) {
info.selection = framework::expressions::createSelection(table, info.filter);
info.resetSelection = false;
}
}
/// String parsing
Tokenizer::Tokenizer(std::string const& input)
: source{input},
IdentifierStr{""},
StrValue{""},
IntegerValue{0},
FloatValue{0.f}
{
LastChar = ' ';
if (!source.empty()) {
source.erase(std::remove_if(source.begin(), source.end(), ::isspace), source.end()); // strip whitespaces
source.erase(std::remove(source.begin(), source.end(), '\"'), source.end()); // strip quotes
}
current = source.begin();
}
void Tokenizer::reset(std::string const& input)
{
LastChar = ' ';
IdentifierStr = "";
StrValue = "";
IntegerValue = 0;
FloatValue = 0.f;
source = input;
if (!source.empty()) {
source.erase(std::remove_if(source.begin(), source.end(), ::isspace), source.end()); // strip whitespaces
source.erase(std::remove(source.begin(), source.end(), '\"'), source.end()); // strip quotes
}
current = source.begin();
currentToken = Token::Unexpected;
}
int Tokenizer::nextToken()
{
// skip initial space
if (isspace(LastChar)) {
pop();
}
// logical or bitwise OR
if (LastChar == '|') {
BinaryOpStr = LastChar;
if (peek() == '|') {
pop();
BinaryOpStr += LastChar;
pop();
TokenStr = BinaryOpStr;
currentToken = Token::BinaryOp;
return currentToken;
} else {
pop();
TokenStr = BinaryOpStr;
currentToken = Token::BinaryOp;
return currentToken;
}
}
// logical or bitwise AND
if (LastChar == '&') {
BinaryOpStr = LastChar;
if (peek() == '&') {
pop();
BinaryOpStr += LastChar;
pop();
TokenStr = BinaryOpStr;
currentToken = Token::BinaryOp;
return currentToken;
} else {
pop();
TokenStr = BinaryOpStr;
currentToken = Token::BinaryOp;
return currentToken;
}
}
// less than or less or equal than
if (LastChar == '<') {
BinaryOpStr = LastChar;
if (peek() == '=') {
pop();
BinaryOpStr += LastChar;
pop();
TokenStr = BinaryOpStr;
currentToken = Token::BinaryOp;
return currentToken;
} else {
pop();
TokenStr = BinaryOpStr;
currentToken = Token::BinaryOp;
return currentToken;
}
}
// greater than or greater or equal than
if (LastChar == '>') {
BinaryOpStr = LastChar;
if (peek() == '=') {
pop();
BinaryOpStr += LastChar;
pop();
TokenStr = BinaryOpStr;
currentToken = Token::BinaryOp;
return currentToken;
} else {
pop();
TokenStr = BinaryOpStr;
currentToken = Token::BinaryOp;
return currentToken;
}
}
// equal or error
if (LastChar == '=') {
BinaryOpStr = LastChar;
if (peek() == '=') {
pop();
BinaryOpStr += LastChar;
pop();
TokenStr = BinaryOpStr;
currentToken = Token::BinaryOp;
return currentToken;
} else {
pop();
TokenStr = BinaryOpStr;
currentToken = Token::Unexpected;
return currentToken;
}
}
// not equal or error
if (LastChar == '!') {
BinaryOpStr = LastChar;
if (peek() == '=') {
pop();
BinaryOpStr += LastChar;
pop();
TokenStr = BinaryOpStr;
currentToken = Token::BinaryOp;
return currentToken;
} else {
pop();
TokenStr = BinaryOpStr;
currentToken = Token::BinaryOp;
return currentToken;
}
}
// unambiguous single-character binary operations: addition, multiplication, subtraction, division, bitwise XOR
if (LastChar == '+' || LastChar == '*' || (LastChar == '-' && (currentToken != Token::BinaryOp && currentToken != '(' && currentToken != Token::Unexpected)) || LastChar == '/' || LastChar == '^') {
BinaryOpStr = LastChar;
pop();
TokenStr = BinaryOpStr;
currentToken = Token::BinaryOp;
return currentToken;
}
// identifier: column, function, constant
if (isalpha(LastChar)) {
// identifier
IdentifierStr = LastChar;
pop();
while (isalnum(LastChar) || (LastChar == '_') || (LastChar == ':')) {
IdentifierStr += LastChar;
pop();
}
TokenStr = IdentifierStr;
currentToken = Token::Identifier;
return currentToken;
}
// number: integer, unsigned integer or float
if (isdigit(LastChar) || LastChar == '.' || (LastChar == '-' && isdigit(peek()))) {
// number
StrValue = "";
bool isFloat = false;
bool isUnsigned = false;
do {
StrValue += LastChar;
pop();
} while (isdigit(LastChar) || LastChar == '.');
if (LastChar == 'f') {
isFloat = true;
pop();
}
if (LastChar == 'u') {
isUnsigned = true;
pop();
}
if (std::find(StrValue.begin(), StrValue.end(), '.') == StrValue.end() && !isFloat) {
if (!isUnsigned) {
IntegerValue = atoi(StrValue.c_str());
} else {
IntegerValue = static_cast<unsigned int>(atoi(StrValue.c_str()));