forked from apache/arrow
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexpression.cc
More file actions
1487 lines (1202 loc) · 48.6 KB
/
Copy pathexpression.cc
File metadata and controls
1487 lines (1202 loc) · 48.6 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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "arrow/compute/exec/expression.h"
#include <algorithm>
#include <optional>
#include <unordered_map>
#include <unordered_set>
#include "arrow/chunked_array.h"
#include "arrow/compute/api_vector.h"
#include "arrow/compute/exec/expression_internal.h"
#include "arrow/compute/exec/util.h"
#include "arrow/compute/exec_internal.h"
#include "arrow/compute/function_internal.h"
#include "arrow/io/memory.h"
#include "arrow/ipc/reader.h"
#include "arrow/ipc/writer.h"
#include "arrow/util/hash_util.h"
#include "arrow/util/key_value_metadata.h"
#include "arrow/util/logging.h"
#include "arrow/util/string.h"
#include "arrow/util/value_parsing.h"
#include "arrow/util/vector.h"
namespace arrow {
using internal::checked_cast;
using internal::checked_pointer_cast;
using internal::EndsWith;
using internal::ToChars;
namespace compute {
void Expression::Call::ComputeHash() {
hash = std::hash<std::string>{}(function_name);
for (const auto& arg : arguments) {
arrow::internal::hash_combine(hash, arg.hash());
}
}
Expression::Expression(Call call) {
call.ComputeHash();
impl_ = std::make_shared<Impl>(std::move(call));
}
Expression::Expression(Datum literal)
: impl_(std::make_shared<Impl>(std::move(literal))) {}
Expression::Expression(Parameter parameter)
: impl_(std::make_shared<Impl>(std::move(parameter))) {}
Expression literal(Datum lit) { return Expression(std::move(lit)); }
Expression field_ref(FieldRef ref) {
return Expression(Expression::Parameter{std::move(ref), TypeHolder{}, {-1}});
}
Expression call(std::string function, std::vector<Expression> arguments,
std::shared_ptr<compute::FunctionOptions> options) {
Expression::Call call;
call.function_name = std::move(function);
call.arguments = std::move(arguments);
call.options = std::move(options);
return Expression(std::move(call));
}
const Datum* Expression::literal() const {
if (impl_ == nullptr) return nullptr;
return std::get_if<Datum>(impl_.get());
}
const Expression::Parameter* Expression::parameter() const {
if (impl_ == nullptr) return nullptr;
return std::get_if<Parameter>(impl_.get());
}
const FieldRef* Expression::field_ref() const {
if (auto parameter = this->parameter()) {
return ¶meter->ref;
}
return nullptr;
}
const Expression::Call* Expression::call() const {
if (impl_ == nullptr) return nullptr;
return std::get_if<Call>(impl_.get());
}
const DataType* Expression::type() const {
if (impl_ == nullptr) return nullptr;
if (const Datum* lit = literal()) {
return lit->type().get();
}
if (const Parameter* parameter = this->parameter()) {
return parameter->type.type;
}
return CallNotNull(*this)->type.type;
}
namespace {
std::string PrintDatum(const Datum& datum) {
if (datum.is_scalar()) {
if (!datum.scalar()->is_valid) return "null[" + datum.type()->ToString() + "]";
switch (datum.type()->id()) {
case Type::STRING:
case Type::LARGE_STRING:
return '"' +
Escape(std::string_view(*datum.scalar_as<BaseBinaryScalar>().value)) + '"';
case Type::BINARY:
case Type::FIXED_SIZE_BINARY:
case Type::LARGE_BINARY:
return '"' + datum.scalar_as<BaseBinaryScalar>().value->ToHexString() + '"';
default:
break;
}
return datum.scalar()->ToString();
} else if (datum.is_array()) {
return "Array[" + datum.type()->ToString() + "]";
}
return datum.ToString();
}
} // namespace
std::string Expression::ToString() const {
if (auto lit = literal()) {
return PrintDatum(*lit);
}
if (auto ref = field_ref()) {
if (auto name = ref->name()) {
return *name;
}
if (auto path = ref->field_path()) {
return path->ToString();
}
return ref->ToString();
}
auto call = CallNotNull(*this);
auto binary = [&](std::string op) {
return "(" + call->arguments[0].ToString() + " " + op + " " +
call->arguments[1].ToString() + ")";
};
if (auto cmp = Comparison::Get(call->function_name)) {
return binary(Comparison::GetOp(*cmp));
}
constexpr std::string_view kleene = "_kleene";
if (EndsWith(call->function_name, kleene)) {
auto op = call->function_name.substr(0, call->function_name.size() - kleene.size());
return binary(std::move(op));
}
if (auto options = GetMakeStructOptions(*call)) {
std::string out = "{";
auto argument = call->arguments.begin();
for (const auto& field_name : options->field_names) {
out += field_name + "=" + argument++->ToString() + ", ";
}
out.resize(out.size() - 1);
out.back() = '}';
return out;
}
std::string out = call->function_name + "(";
for (const auto& arg : call->arguments) {
out += arg.ToString() + ", ";
}
if (call->options) {
out += call->options->ToString();
} else if (call->arguments.size()) {
out.resize(out.size() - 2);
}
out += ')';
return out;
}
void PrintTo(const Expression& expr, std::ostream* os) {
*os << expr.ToString();
if (expr.IsBound()) {
*os << "[bound]";
}
}
bool Expression::Equals(const Expression& other) const {
if (Identical(*this, other)) return true;
if (impl_->index() != other.impl_->index()) {
return false;
}
if (auto lit = literal()) {
return lit->Equals(*other.literal());
}
if (auto ref = field_ref()) {
return ref->Equals(*other.field_ref());
}
auto call = CallNotNull(*this);
auto other_call = CallNotNull(other);
if (call->function_name != other_call->function_name ||
call->kernel != other_call->kernel) {
return false;
}
for (size_t i = 0; i < call->arguments.size(); ++i) {
if (!call->arguments[i].Equals(other_call->arguments[i])) {
return false;
}
}
if (call->options == other_call->options) return true;
if (call->options && other_call->options) {
return call->options->Equals(other_call->options);
}
return false;
}
bool Identical(const Expression& l, const Expression& r) { return l.impl_ == r.impl_; }
size_t Expression::hash() const {
if (auto lit = literal()) {
if (lit->is_scalar()) {
return lit->scalar()->hash();
}
return 0;
}
if (auto ref = field_ref()) {
return ref->hash();
}
return CallNotNull(*this)->hash;
}
bool Expression::IsBound() const {
if (type() == nullptr) return false;
if (const Call* call = this->call()) {
if (call->kernel == nullptr) return false;
for (const Expression& arg : call->arguments) {
if (!arg.IsBound()) return false;
}
}
return true;
}
bool Expression::IsScalarExpression() const {
if (auto lit = literal()) {
return lit->is_scalar();
}
if (field_ref()) return true;
auto call = CallNotNull(*this);
for (const Expression& arg : call->arguments) {
if (!arg.IsScalarExpression()) return false;
}
if (call->function) {
return call->function->kind() == compute::Function::SCALAR;
}
// this expression is not bound; make a best guess based on
// the default function registry
if (auto function = compute::GetFunctionRegistry()
->GetFunction(call->function_name)
.ValueOr(nullptr)) {
return function->kind() == compute::Function::SCALAR;
}
// unknown function or other error; conservatively return false
return false;
}
bool Expression::IsNullLiteral() const {
if (auto lit = literal()) {
if (lit->null_count() == lit->length()) {
return true;
}
}
return false;
}
namespace {
std::optional<compute::NullHandling::type> GetNullHandling(const Expression::Call& call) {
DCHECK_NE(call.function, nullptr);
if (call.function->kind() == compute::Function::SCALAR) {
return static_cast<const compute::ScalarKernel*>(call.kernel)->null_handling;
}
return std::nullopt;
}
} // namespace
bool Expression::IsSatisfiable() const {
if (type() == nullptr) return true;
if (type()->id() != Type::BOOL) return true;
if (auto lit = literal()) {
if (lit->null_count() == lit->length()) {
return false;
}
if (lit->is_scalar()) {
return lit->scalar_as<BooleanScalar>().value;
}
return true;
}
if (field_ref()) return true;
auto call = CallNotNull(*this);
// invert(true_unless_null(x)) is always false or null by definition
// true_unless_null arises in simplification of inequalities below
if (call->function_name == "invert") {
if (auto nested_call = call->arguments[0].call()) {
if (nested_call->function_name == "true_unless_null") return false;
}
}
if (call->function_name == "and_kleene" || call->function_name == "and") {
for (const Expression& arg : call->arguments) {
if (!arg.IsSatisfiable()) return false;
}
}
return true;
}
namespace {
// Produce a bound Expression from unbound Call and bound arguments.
Result<Expression> BindNonRecursive(Expression::Call call, bool insert_implicit_casts,
compute::ExecContext* exec_context) {
DCHECK(std::all_of(call.arguments.begin(), call.arguments.end(),
[](const Expression& argument) { return argument.IsBound(); }));
std::vector<TypeHolder> types = GetTypes(call.arguments);
ARROW_ASSIGN_OR_RAISE(call.function, GetFunction(call, exec_context));
if (!insert_implicit_casts) {
ARROW_ASSIGN_OR_RAISE(call.kernel, call.function->DispatchExact(types));
} else {
ARROW_ASSIGN_OR_RAISE(call.kernel, call.function->DispatchBest(&types));
for (size_t i = 0; i < types.size(); ++i) {
if (types[i] == call.arguments[i].type()) continue;
if (const Datum* lit = call.arguments[i].literal()) {
ARROW_ASSIGN_OR_RAISE(Datum new_lit,
compute::Cast(*lit, types[i].GetSharedPtr()));
call.arguments[i] = literal(std::move(new_lit));
continue;
}
// construct an implicit cast Expression with which to replace this argument
Expression::Call implicit_cast;
implicit_cast.function_name = "cast";
implicit_cast.arguments = {std::move(call.arguments[i])};
// TODO(wesm): Use TypeHolder in options
implicit_cast.options = std::make_shared<compute::CastOptions>(
compute::CastOptions::Safe(types[i].GetSharedPtr()));
ARROW_ASSIGN_OR_RAISE(
call.arguments[i],
BindNonRecursive(std::move(implicit_cast),
/*insert_implicit_casts=*/false, exec_context));
}
}
compute::KernelContext kernel_context(exec_context, call.kernel);
if (call.kernel->init) {
const FunctionOptions* options =
call.options ? call.options.get() : call.function->default_options();
ARROW_ASSIGN_OR_RAISE(
call.kernel_state,
call.kernel->init(&kernel_context, {call.kernel, types, options}));
kernel_context.SetState(call.kernel_state.get());
}
ARROW_ASSIGN_OR_RAISE(
call.type, call.kernel->signature->out_type().Resolve(&kernel_context, types));
return Expression(std::move(call));
}
template <typename TypeOrSchema>
Result<Expression> BindImpl(Expression expr, const TypeOrSchema& in,
compute::ExecContext* exec_context) {
if (exec_context == nullptr) {
compute::ExecContext exec_context;
return BindImpl(std::move(expr), in, &exec_context);
}
if (expr.literal()) return expr;
if (const FieldRef* ref = expr.field_ref()) {
ARROW_ASSIGN_OR_RAISE(FieldPath path, ref->FindOne(in));
Expression::Parameter param = *expr.parameter();
param.indices.resize(path.indices().size());
std::copy(path.indices().begin(), path.indices().end(), param.indices.begin());
ARROW_ASSIGN_OR_RAISE(auto field, path.Get(in));
param.type = field->type();
return Expression{std::move(param)};
}
auto call = *CallNotNull(expr);
for (auto& argument : call.arguments) {
ARROW_ASSIGN_OR_RAISE(argument, BindImpl(std::move(argument), in, exec_context));
}
return BindNonRecursive(std::move(call),
/*insert_implicit_casts=*/true, exec_context);
}
} // namespace
Result<Expression> Expression::Bind(const TypeHolder& in,
compute::ExecContext* exec_context) const {
return BindImpl(*this, *in.type, exec_context);
}
Result<Expression> Expression::Bind(const Schema& in_schema,
compute::ExecContext* exec_context) const {
return BindImpl(*this, in_schema, exec_context);
}
Result<ExecBatch> MakeExecBatch(const Schema& full_schema, const Datum& partial,
Expression guarantee) {
ExecBatch out;
if (partial.kind() == Datum::RECORD_BATCH) {
const auto& partial_batch = *partial.record_batch();
out.guarantee = std::move(guarantee);
out.length = partial_batch.num_rows();
ARROW_ASSIGN_OR_RAISE(auto known_field_values,
ExtractKnownFieldValues(out.guarantee));
for (const auto& field : full_schema.fields()) {
auto field_ref = FieldRef(field->name());
// If we know what the value must be from the guarantee, prefer to use that value
// than the data from the record batch (if it exists at all -- probably it doesn't),
// because this way it will be a scalar.
auto known_field_value = known_field_values.map.find(field_ref);
if (known_field_value != known_field_values.map.end()) {
out.values.emplace_back(known_field_value->second);
continue;
}
ARROW_ASSIGN_OR_RAISE(auto column, field_ref.GetOneOrNone(partial_batch));
if (column) {
if (!column->type()->Equals(field->type())) {
// Referenced field was present but didn't have the expected type.
// This *should* be handled by readers, and will just be an error in the future.
ARROW_ASSIGN_OR_RAISE(
auto converted,
compute::Cast(column, field->type(), compute::CastOptions::Safe()));
column = converted.make_array();
}
out.values.emplace_back(std::move(column));
} else {
out.values.emplace_back(MakeNullScalar(field->type()));
}
}
return out;
}
// wasteful but useful for testing:
if (partial.type()->id() == Type::STRUCT) {
if (partial.is_array()) {
ARROW_ASSIGN_OR_RAISE(auto partial_batch,
RecordBatch::FromStructArray(partial.make_array()));
return MakeExecBatch(full_schema, partial_batch, std::move(guarantee));
}
if (partial.is_scalar()) {
ARROW_ASSIGN_OR_RAISE(auto partial_array,
MakeArrayFromScalar(*partial.scalar(), 1));
ARROW_ASSIGN_OR_RAISE(
auto out, MakeExecBatch(full_schema, partial_array, std::move(guarantee)));
for (Datum& value : out.values) {
if (value.is_scalar()) continue;
ARROW_ASSIGN_OR_RAISE(value, value.make_array()->GetScalar(0));
}
return out;
}
}
return Status::NotImplemented("MakeExecBatch from ", PrintDatum(partial));
}
Result<Datum> ExecuteScalarExpression(const Expression& expr, const Schema& full_schema,
const Datum& partial_input,
compute::ExecContext* exec_context) {
ARROW_ASSIGN_OR_RAISE(auto input, MakeExecBatch(full_schema, partial_input));
return ExecuteScalarExpression(expr, input, exec_context);
}
Result<Datum> ExecuteScalarExpression(const Expression& expr, const ExecBatch& input,
compute::ExecContext* exec_context) {
if (exec_context == nullptr) {
compute::ExecContext exec_context;
return ExecuteScalarExpression(expr, input, &exec_context);
}
if (!expr.IsBound()) {
return Status::Invalid("Cannot Execute unbound expression.");
}
if (!expr.IsScalarExpression()) {
return Status::Invalid(
"ExecuteScalarExpression cannot Execute non-scalar expression ", expr.ToString());
}
if (auto lit = expr.literal()) return *lit;
if (auto param = expr.parameter()) {
if (param->type.id() == Type::NA) {
return MakeNullScalar(null());
}
Datum field = input[param->indices[0]];
if (param->indices.size() > 1) {
std::vector<int> indices(param->indices.begin() + 1, param->indices.end());
compute::StructFieldOptions options(std::move(indices));
ARROW_ASSIGN_OR_RAISE(
field, compute::CallFunction("struct_field", {std::move(field)}, &options));
}
if (!field.type()->Equals(*param->type.type)) {
return Status::Invalid("Referenced field ", expr.ToString(), " was ",
field.type()->ToString(), " but should have been ",
param->type.ToString());
}
return field;
}
auto call = CallNotNull(expr);
std::vector<Datum> arguments(call->arguments.size());
bool all_scalar = true;
for (size_t i = 0; i < arguments.size(); ++i) {
ARROW_ASSIGN_OR_RAISE(
arguments[i], ExecuteScalarExpression(call->arguments[i], input, exec_context));
if (arguments[i].is_array()) {
all_scalar = false;
}
}
auto executor = compute::detail::KernelExecutor::MakeScalar();
compute::KernelContext kernel_context(exec_context, call->kernel);
kernel_context.SetState(call->kernel_state.get());
const Kernel* kernel = call->kernel;
std::vector<TypeHolder> types = GetTypes(arguments);
auto options = call->options.get();
RETURN_NOT_OK(executor->Init(&kernel_context, {kernel, types, options}));
compute::detail::DatumAccumulator listener;
RETURN_NOT_OK(executor->Execute(
ExecBatch(std::move(arguments), all_scalar ? 1 : input.length), &listener));
const auto out = executor->WrapResults(arguments, listener.values());
#ifndef NDEBUG
DCHECK_OK(executor->CheckResultType(out, call->function_name.c_str()));
#endif
return out;
}
namespace {
std::array<std::pair<const Expression&, const Expression&>, 2>
ArgumentsAndFlippedArguments(const Expression::Call& call) {
DCHECK_EQ(call.arguments.size(), 2);
return {std::pair<const Expression&, const Expression&>{call.arguments[0],
call.arguments[1]},
std::pair<const Expression&, const Expression&>{call.arguments[1],
call.arguments[0]}};
}
} // namespace
std::vector<FieldRef> FieldsInExpression(const Expression& expr) {
if (expr.literal()) return {};
if (auto ref = expr.field_ref()) {
return {*ref};
}
std::vector<FieldRef> fields;
for (const Expression& arg : CallNotNull(expr)->arguments) {
auto argument_fields = FieldsInExpression(arg);
std::move(argument_fields.begin(), argument_fields.end(), std::back_inserter(fields));
}
return fields;
}
bool ExpressionHasFieldRefs(const Expression& expr) {
if (expr.literal()) return false;
if (expr.field_ref()) return true;
for (const Expression& arg : CallNotNull(expr)->arguments) {
if (ExpressionHasFieldRefs(arg)) return true;
}
return false;
}
Result<Expression> FoldConstants(Expression expr) {
if (!expr.IsBound()) {
return Status::Invalid("Cannot fold constants in unbound expression.");
}
return ModifyExpression(
std::move(expr), [](Expression expr) { return expr; },
[](Expression expr, ...) -> Result<Expression> {
auto call = CallNotNull(expr);
if (std::all_of(call->arguments.begin(), call->arguments.end(),
[](const Expression& argument) { return argument.literal(); })) {
// all arguments are literal; we can evaluate this subexpression *now*
static const ExecBatch ignored_input = ExecBatch({}, 1);
ARROW_ASSIGN_OR_RAISE(Datum constant,
ExecuteScalarExpression(expr, ignored_input));
return literal(std::move(constant));
}
// XXX the following should probably be in a registry of passes instead
// of inline
if (GetNullHandling(*call) == compute::NullHandling::INTERSECTION) {
// kernels which always produce intersected validity can be resolved
// to null *now* if any of their inputs is a null literal
if (!call->type.type) {
return Status::Invalid("Cannot fold constants for unbound expression ",
expr.ToString());
}
for (const Expression& argument : call->arguments) {
if (argument.IsNullLiteral()) {
if (argument.type()->Equals(*call->type.type)) {
return argument;
} else {
return literal(MakeNullScalar(call->type.GetSharedPtr()));
}
}
}
}
if (call->function_name == "and_kleene") {
for (auto args : ArgumentsAndFlippedArguments(*call)) {
// true and x == x
if (args.first == literal(true)) return args.second;
// false and x == false
if (args.first == literal(false)) return args.first;
// x and x == x
if (args.first == args.second) return args.first;
}
return expr;
}
if (call->function_name == "or_kleene") {
for (auto args : ArgumentsAndFlippedArguments(*call)) {
// false or x == x
if (args.first == literal(false)) return args.second;
// true or x == true
if (args.first == literal(true)) return args.first;
// x or x == x
if (args.first == args.second) return args.first;
}
return expr;
}
return expr;
});
}
namespace {
std::vector<Expression> GuaranteeConjunctionMembers(
const Expression& guaranteed_true_predicate) {
auto guarantee = guaranteed_true_predicate.call();
if (!guarantee || guarantee->function_name != "and_kleene") {
return {guaranteed_true_predicate};
}
return FlattenedAssociativeChain(guaranteed_true_predicate).fringe;
}
/// \brief Extract an equality from an expression.
///
/// Recognizes expressions of the form:
/// equal(a, 2)
/// is_null(a)
std::optional<std::pair<FieldRef, Datum>> ExtractOneFieldValue(
const Expression& guarantee) {
auto call = guarantee.call();
if (!call) return std::nullopt;
// search for an equality conditions between a field and a literal
if (call->function_name == "equal") {
auto ref = call->arguments[0].field_ref();
if (!ref) return std::nullopt;
auto lit = call->arguments[1].literal();
if (!lit) return std::nullopt;
return std::make_pair(*ref, *lit);
}
// ... or a known null field
if (call->function_name == "is_null") {
auto ref = call->arguments[0].field_ref();
if (!ref) return std::nullopt;
return std::make_pair(*ref, Datum(std::make_shared<NullScalar>()));
}
return std::nullopt;
}
// Conjunction members which are represented in known_values are erased from
// conjunction_members
Status ExtractKnownFieldValues(std::vector<Expression>* conjunction_members,
KnownFieldValues* known_values) {
// filter out consumed conjunction members, leaving only unconsumed
*conjunction_members = arrow::internal::FilterVector(
std::move(*conjunction_members),
[known_values](const Expression& guarantee) -> bool {
if (auto known_value = ExtractOneFieldValue(guarantee)) {
known_values->map.insert(std::move(*known_value));
return false;
}
return true;
});
return Status::OK();
}
} // namespace
Result<KnownFieldValues> ExtractKnownFieldValues(
const Expression& guaranteed_true_predicate) {
KnownFieldValues known_values;
auto conjunction_members = GuaranteeConjunctionMembers(guaranteed_true_predicate);
RETURN_NOT_OK(ExtractKnownFieldValues(&conjunction_members, &known_values));
return known_values;
}
Result<Expression> ReplaceFieldsWithKnownValues(const KnownFieldValues& known_values,
Expression expr) {
if (!expr.IsBound()) {
return Status::Invalid(
"ReplaceFieldsWithKnownValues called on an unbound Expression");
}
return ModifyExpression(
std::move(expr),
[&known_values](Expression expr) -> Result<Expression> {
if (auto ref = expr.field_ref()) {
auto it = known_values.map.find(*ref);
if (it != known_values.map.end()) {
Datum lit = it->second;
if (lit.type()->Equals(*expr.type())) return literal(std::move(lit));
// type mismatch, try casting the known value to the correct type
if (expr.type()->id() == Type::DICTIONARY &&
lit.type()->id() != Type::DICTIONARY) {
// the known value must be dictionary encoded
const auto& dict_type = checked_cast<const DictionaryType&>(*expr.type());
if (!lit.type()->Equals(dict_type.value_type())) {
ARROW_ASSIGN_OR_RAISE(lit, compute::Cast(lit, dict_type.value_type()));
}
if (lit.is_scalar()) {
ARROW_ASSIGN_OR_RAISE(auto dictionary,
MakeArrayFromScalar(*lit.scalar(), 1));
lit = Datum{DictionaryScalar::Make(MakeScalar<int32_t>(0),
std::move(dictionary))};
}
}
ARROW_ASSIGN_OR_RAISE(lit, compute::Cast(lit, expr.type()->GetSharedPtr()));
return literal(std::move(lit));
}
}
return expr;
},
[](Expression expr, ...) { return expr; });
}
namespace {
bool IsBinaryAssociativeCommutative(const Expression::Call& call) {
static std::unordered_set<std::string> binary_associative_commutative{
"and", "or", "and_kleene", "or_kleene", "xor",
"multiply", "add", "multiply_checked", "add_checked"};
auto it = binary_associative_commutative.find(call.function_name);
return it != binary_associative_commutative.end();
}
Result<Expression> HandleInconsistentTypes(Expression::Call call,
compute::ExecContext* exec_context) {
// ARROW-18334: due to reordering of arguments, the call may have
// inconsistent argument types. For example, the call's kernel may
// correspond to `timestamp + duration` but the arguments happen to
// be `duration, timestamp`. The addition itself is still commutative,
// but the mismatch in declared argument types is potentially problematic
// if we ever start using the Expression::Call::kernel field more than
// we do currently. Check and rebind if necessary.
//
// The more correct fix for this problem is to ensure that all kernels of
// functions which are commutative be commutative as well, which would
// obviate rebinding like this. In the context of ARROW-18334, this
// would require rewriting KernelSignature so that a single kernel can
// handle both `timestamp + duration` and `duration + timestamp`.
if (call.kernel->signature->MatchesInputs(GetTypes(call.arguments))) {
return Expression(std::move(call));
}
return BindNonRecursive(std::move(call), /*insert_implicit_casts=*/false, exec_context);
}
} // namespace
Result<Expression> Canonicalize(Expression expr, compute::ExecContext* exec_context) {
if (!expr.IsBound()) {
return Status::Invalid("Cannot canonicalize an unbound expression.");
}
if (exec_context == nullptr) {
compute::ExecContext exec_context;
return Canonicalize(std::move(expr), &exec_context);
}
// If potentially reconstructing more deeply than a call's immediate arguments
// (for example, when reorganizing an associative chain), add expressions to this set to
// avoid unnecessary work
struct {
std::unordered_set<Expression, Expression::Hash> set_;
bool operator()(const Expression& expr) const {
return set_.find(expr) != set_.end();
}
void Add(std::vector<Expression> exprs) {
std::move(exprs.begin(), exprs.end(), std::inserter(set_, set_.end()));
}
} AlreadyCanonicalized;
return ModifyExpression(
std::move(expr),
[&AlreadyCanonicalized, exec_context](Expression expr) -> Result<Expression> {
auto call = expr.call();
if (!call) return expr;
if (AlreadyCanonicalized(expr)) return expr;
if (IsBinaryAssociativeCommutative(*call)) {
struct {
int Priority(const Expression& operand) const {
// order literals first, starting with nulls
if (operand.IsNullLiteral()) return 0;
if (operand.literal()) return 1;
return 2;
}
bool operator()(const Expression& l, const Expression& r) const {
return Priority(l) < Priority(r);
}
} CanonicalOrdering;
FlattenedAssociativeChain chain(expr);
if (chain.was_left_folded &&
std::is_sorted(chain.fringe.begin(), chain.fringe.end(),
CanonicalOrdering)) {
// fast path for expressions which happen to have arrived in an
// already-canonical form
AlreadyCanonicalized.Add(std::move(chain.exprs));
return expr;
}
std::stable_sort(chain.fringe.begin(), chain.fringe.end(), CanonicalOrdering);
// fold the chain back up
Expression folded = std::move(chain.fringe.front());
for (auto it = chain.fringe.begin() + 1; it != chain.fringe.end(); ++it) {
auto canonicalized_call = *call;
canonicalized_call.arguments = {std::move(folded), std::move(*it)};
ARROW_ASSIGN_OR_RAISE(
folded,
HandleInconsistentTypes(std::move(canonicalized_call), exec_context));
AlreadyCanonicalized.Add({expr});
}
return folded;
}
if (auto cmp = Comparison::Get(call->function_name)) {
if (call->arguments[0].literal() && !call->arguments[1].literal()) {
// ensure that literals are on comparisons' RHS
auto flipped_call = *call;
std::swap(flipped_call.arguments[0], flipped_call.arguments[1]);
flipped_call.function_name =
Comparison::GetName(Comparison::GetFlipped(*cmp));
return BindNonRecursive(flipped_call,
/*insert_implicit_casts=*/false, exec_context);
}
}
return expr;
},
[](Expression expr, ...) { return expr; });
}
namespace {
// An inequality comparison which a target Expression is known to satisfy. If nullable,
// the target may evaluate to null in addition to values satisfying the comparison.
struct Inequality {
// The inequality type
Comparison::type cmp;
// The LHS of the inequality
const FieldRef& target;
// The RHS of the inequality
const Datum& bound;
// Whether target can be null
bool nullable;
// Extract an Inequality if possible, derived from "less",
// "greater", "less_equal", and "greater_equal" expressions,
// possibly disjuncted with an "is_null" Expression.
// cmp(a, 2)
// cmp(a, 2) or is_null(a)
static std::optional<Inequality> ExtractOne(const Expression& guarantee) {
auto call = guarantee.call();
if (!call) return std::nullopt;
if (call->function_name == "or_kleene") {
// expect the LHS to be a usable field inequality
auto out = ExtractOneFromComparison(call->arguments[0]);
if (!out) return std::nullopt;
// expect the RHS to be an is_null expression
auto call_rhs = call->arguments[1].call();
if (!call_rhs) return std::nullopt;
if (call_rhs->function_name != "is_null") return std::nullopt;