• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

llnl-asr / dftracer-utils / 45735107228

26 Nov 2026 01:20AM UTC coverage: 77.696% (+0.4%) from 77.313%
45735107228

push

github

rayandrew
fix: convert natively at the edge and read chunked nested columns safely

to_pandas, from_pandas, table files, loc, reindex, where, unnest and the
dask viewer called pyarrow kernels to convert columns, so they failed
without pyarrow and copied text twice. They now use native codes, masks
and buffers, and pyarrow appears only when a user asks for Arrow.
Readers of list offsets and struct children now go through flat pieces
of a column, so a chunked, selected or dictionary nested column no
longer crashes explode, the CLI printer or child access.

164371 of 253360 branches covered (64.88%)

Branch coverage included in aggregate %.

1455 of 1580 new or added lines in 20 files covered. (92.09%)

795 existing lines in 33 files now uncovered.

190713 of 203655 relevant lines covered (93.65%)

4484549.26 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

79.04
/src/dftracer/utils/dataframe/expr.cpp
1
// SPDX-License-Identifier: MIT
2
#include <dftracer/utils/common/calendar.h>
3
#include <dftracer/utils/common/error.h>
4
#include <dftracer/utils/dataframe/batch_ops.h>          // concat_columns
5
#include <dftracer/utils/dataframe/expr.h>
6
#include <dftracer/utils/dataframe/internal/cell_ops.h>  // cell_to_string
7
#include <dftracer/utils/dataframe/internal/column_data.h>
8
#include <dftracer/utils/dataframe/internal/expr_handle.h>
9
#include <dftracer/utils/dataframe/internal/expr_windows.h>
10
#include <dftracer/utils/dataframe/internal/fingerprint.h>
11
#include <dftracer/utils/dataframe/internal/scalar.h>     // scalar_as
12
#include <dftracer/utils/dataframe/kernels/string_ops.h>  // str_pattern
13
#include <dftracer/utils/dataframe/parallel.h>
14
#include <dftracer/utils/dataframe/udf_registry.h>
15
#include <dftracer/utils/dstd/fatal.h>
16
#include <dftracer/utils/dstd/fmt.h>
17
#include <dftracer/utils/dstd/map.h>
18
#include <dftracer/utils/dstd/memory.h>
19
#include <dftracer/utils/dstd/optional.h>
20
#include <dftracer/utils/dstd/span.h>
21
#include <dftracer/utils/dstd/string.h>
22
#include <dftracer/utils/dstd/to_chars.h>
23
#include <dftracer/utils/dstd/tuple.h>
24
#include <dftracer/utils/dstd/vector.h>
25
#include <dftracer/utils/duql/pattern_engine.h>
26
#include <dftracer/utils/duql/substr_simd.h>
27
#include <dftracer/utils/json/json_escape.h>
28

29
#include <algorithm>
30
#include <array>
31
#include <atomic>
32
#include <bit>
33
#include <charconv>
34
#include <cmath>
35
#include <cstdint>
36
#include <limits>
37
#include <mutex>
38
#include <optional>
39
#include <random>
40
#include <span>
41
#include <string>
42
#include <tuple>
43
#include <type_traits>
44

45
using namespace dftracer::utils;
46

47
namespace dftracer::utils::dataframe {
48

49
enum class ExprKind {
50
    LitI64,
51
    LitF64,
52
    Col,
53
    Binary,
54
    Prim,
55
    Unary,
56
    Clip,
57
    Fillna,
58
    Cmp,
59
    Logical,
60
    Not,
61
    Cast,
62
    StrPred,
63
    StrMap,
64
    StrLen,
65
    StrFind,
66
    StrReplace,
67
    StrSlice,
68
    IsIn,
69
    Select,
70
    IsNull,
71
    LitStr,
72
    LitBool,
73
    LitNull,
74
    Arith,
75
    Neg,
76
    CmpExpr,
77
    Coalesce,
78
    Extreme,
79
    Concat,
80
    Round,
81
    Log,
82
    Pow,
83
    StrSubstr,
84
    StrPattern,
85
    StrExtract,
86
    StrRegexReplace,
87
    Convert,
88
    ListLen,
89
    ListGet,
90
    ListSum,
91
    ListContains,
92
    StrFn,
93
    StrPredCol,
94
    StrReplaceCol,
95
    StrSubstrCol,
96
    RoundCol,
97
    StrExtractCol,
98
    DatePart,
99
    FormatTime,
100
    Udf
101
};
102

103
struct ExprNode {
49,170 ✔
104
    ExprKind kind;
105
    std::int32_t i = 0;     // col index / prim / unary / cmp op / logical op /
49,170 ✔
106
                            // cast type / binary op / str op / chars / all
107
    dftu_scalar scalar{};   // literal value / cmp rhs / clip lo / slice start
49,170 ✔
108
    dftu_scalar scalar2{};  // clip hi / slice len
49,170 ✔
109
    // Owns the text of a STR-tagged `scalar`, which borrows it, or a string
110
    // op's pattern / needle / from. The node is built once and never copied
111
    // (it lives behind shared_ptr<const>), and eval_many holds the roots for
112
    // the whole evaluation, so the borrow is valid for as long as the
113
    // compiled program can read it.
114
    dstd::String text;
115
    dstd::String text2;  // str_replace `to`
116
    dftracer::utils::dstd::SharedPtr<const duql::CompiledPattern>
117
        pattern;         // text: identity
118
    dftracer::utils::dstd::SharedPtr<const duql::Substitution>
119
        subst;           // regex replace
120
    Series values;       // is_in set
121
    dftracer::utils::dstd::SharedPtr<const ExprNode>
122
        a;               // first child (select: cond)
123
    dftracer::utils::dstd::SharedPtr<const ExprNode>
124
        b;               // second child (select: then)
125
    dftracer::utils::dstd::SharedPtr<const ExprNode> c;  // select: otherwise
126
    // Udf: the call's operands, and the registered UDF (named by `text`).
127
    dstd::Vector<dstd::SharedPtr<const ExprNode>> args;
128
    dstd::SharedPtr<const UdfRecord> udf;
129
};
130

131
namespace {
132

133
Expr make(ExprKind k, std::int32_t i, dftu_scalar s,
91,431 ✔
134
          dftracer::utils::dstd::SharedPtr<const ExprNode> a,
135
          dftracer::utils::dstd::SharedPtr<const ExprNode> b) {
136
    auto n = dstd::make_shared<ExprNode>();
91,431 ✔
137
    n->kind = k;
91,430 ✔
138
    n->i = i;
91,430 ✔
139
    n->scalar = s;
91,430 ✔
140
    n->a = std::move(a);
91,430 ✔
141
    n->b = std::move(b);
91,429 ✔
142
    return Expr{std::move(n)};
91,427 !
143
}
91,427 ✔
144

145
}  // namespace
146

147
Expr expr_col(std::int32_t index) {
54,274 ✔
148
    return make(ExprKind::Col, index, {}, nullptr, nullptr);
54,274 !
149
}
27,145 ✔
150
std::int32_t expr_col_index(const Expr& e) {
121,394 ✔
151
    const auto& n = e.node();
121,394 !
152
    return n && n->kind == ExprKind::Col ? n->i : -1;
121,394 !
153
}
60,711 ✔
154

155
namespace {
156

157
void fingerprint_node(detail::Fingerprint& fp, const ExprNode* n) {
3,456 ✔
158
    if (!n) {
3,456 ✔
159
        fp.pod(std::int32_t{-1});
2,422 ✔
160
        return;
2,422 ✔
161
    }
162
    fp.pod(static_cast<std::int32_t>(n->kind));
1,034 ✔
163
    fp.pod(n->i);
1,034 ✔
164
    fp.scalar(n->scalar);
1,034 ✔
165
    fp.scalar(n->scalar2);
1,034 ✔
166
    fp.str(n->text);
1,034 ✔
167
    fp.str(n->text2);
1,034 ✔
168
    const dftu_series* vals = n->values.handle();
1,034 ✔
169
    fp.pod(vals && vals->data.block() ? vals->data.data() : nullptr);
1,034 ✔
170
    fp.pod(vals ? n->values.length() : std::int64_t{0});
1,034 ✔
171
    fingerprint_node(fp, n->a.get());
1,034 ✔
172
    fingerprint_node(fp, n->b.get());
1,034 ✔
173
    fingerprint_node(fp, n->c.get());
1,034 ✔
174
    for (const auto& arg : n->args) fingerprint_node(fp, arg.get());
1,034 !
175
}
2,245 ✔
176

177
}  // namespace
178

179
std::uint64_t expr_fingerprint(const Expr& e) {
354 ✔
180
    detail::Fingerprint fp;
354 ✔
181
    fingerprint_node(fp, e.node().get());
354 ✔
182
    return fp.value();
531 ✔
183
}
177 ✔
184

185
bool expr_as_col_cmp(const Expr& e, std::int32_t* col, CmpOp* op, Scalar* rhs) {
1,338 ✔
186
    const auto& n = e.node();
1,338 ✔
187
    if (!n || n->kind != ExprKind::Cmp || !n->a || n->a->kind != ExprKind::Col)
1,338 !
188
        return false;
164 ✔
189
    *col = n->a->i;
1,010 ✔
190
    *op = static_cast<CmpOp>(n->i);
1,010 ✔
191
    *rhs = n->scalar;
1,010 ✔
192
    return true;
1,010 ✔
193
}
669 ✔
194

195
bool expr_as_col_binary(const Expr& e, BinaryOp* op, std::int32_t* a,
16 ✔
196
                        std::int32_t* b) {
197
    const auto& n = e.node();
16 !
198
    if (!n || n->kind != ExprKind::Binary || !n->a || !n->b ||
16 !
199
        n->a->kind != ExprKind::Col || n->b->kind != ExprKind::Col)
24 !
200
        return false;
4 ✔
201
    *op = static_cast<BinaryOp>(n->i);
8 ✔
202
    *a = n->a->i;
8 ✔
203
    *b = n->b->i;
8 ✔
204
    return true;
8 ✔
205
}
8 ✔
206

207
bool expr_as_logical(const Expr& e, LogicalOp* op, Expr* a, Expr* b) {
1,076 ✔
208
    const auto& n = e.node();
1,076 ✔
209
    if (!n || n->kind != ExprKind::Logical || !n->a || !n->b) return false;
1,076 !
210
    *op = static_cast<LogicalOp>(n->i);
112 !
211
    *a = Expr{n->a};
168 !
212
    *b = Expr{n->b};
168 !
213
    return true;
112 ✔
214
}
538 ✔
215

216
bool expr_as_not(const Expr& e, Expr* a) {
394 ✔
217
    const auto& n = e.node();
394 ✔
218
    if (!n || n->kind != ExprKind::Not || !n->a) return false;
394 ✔
219
    *a = Expr{n->a};
75 !
220
    return true;
50 ✔
221
}
197 ✔
222

223
namespace {
224
bool node_references(const dftracer::utils::dstd::SharedPtr<const ExprNode>& n,
6,218 ✔
225
                     std::int32_t index) {
226
    if (!n) return false;
6,218 ✔
227
    if (n->kind == ExprKind::Col) return n->i == index;
4,098 ✔
228
    for (const auto& arg : n->args)
1,748 !
UNCOV
229
        if (node_references(arg, index)) return true;
×
230
    return node_references(n->a, index) || node_references(n->b, index) ||
2,276 !
231
           node_references(n->c, index);
1,056 ✔
232
}
3,109 ✔
233
}  // namespace
234

235
bool expr_references(const Expr& e, std::int32_t index) {
2,352 ✔
236
    return node_references(e.node(), index);
2,352 ✔
237
}
238

239
namespace {
240
std::int32_t node_max_col(
1,334 ✔
241
    const dftracer::utils::dstd::SharedPtr<const ExprNode>& n) {
242
    if (!n) return -1;
1,334 ✔
243
    if (n->kind == ExprKind::Col) return n->i;
696 ✔
244
    std::int32_t out =
477 ✔
245
        std::max({node_max_col(n->a), node_max_col(n->b), node_max_col(n->c)});
318 ✔
246
    for (const auto& arg : n->args) out = std::max(out, node_max_col(arg));
318 !
247
    return out;
318 ✔
248
}
667 ✔
249
}  // namespace
250

251
std::int32_t expr_max_col(const Expr& e) { return node_max_col(e.node()); }
380 ✔
252

253
namespace {
254
// Series is move-only, so a node copy shares the values set explicitly.
255
dftracer::utils::dstd::SharedPtr<ExprNode> clone(const ExprNode& n) {
5,068 ✔
256
    auto c = dstd::make_shared<ExprNode>();
5,068 ✔
257
    c->kind = n.kind;
5,068 ✔
258
    c->i = n.i;
5,068 ✔
259
    c->scalar = n.scalar;
5,068 ✔
260
    c->scalar2 = n.scalar2;
5,068 ✔
261
    c->text = n.text;
5,068 ✔
262
    c->text2 = n.text2;
5,068 ✔
263
    c->pattern = n.pattern;
5,068 ✔
264
    c->subst = n.subst;
5,068 ✔
265
    if (n.scalar.kind == DFTU_SCALAR_TAG_STR) {
5,068 ✔
266
        c->scalar.value.s = c->text.data();
2 ✔
267
        c->scalar.len = static_cast<std::uint32_t>(c->text.size());
2 ✔
268
    }
1 ✔
269
    if (n.values.valid()) c->values = n.values.share();
5,068 !
270
    c->a = n.a;
5,068 ✔
271
    c->b = n.b;
5,068 ✔
272
    c->c = n.c;
5,068 ✔
273
    c->args = n.args;
5,068 ✔
274
    c->udf = n.udf;
5,068 ✔
275
    return c;
5,068 ✔
276
}
2,534 !
277

278
dftracer::utils::dstd::SharedPtr<const ExprNode> node_remap(
2,276 ✔
279
    const dftracer::utils::dstd::SharedPtr<const ExprNode>& n,
280
    dstd::Span<const std::int32_t> old_to_new) {
281
    if (!n) return nullptr;
2,276 ✔
282
    if (n->kind == ExprKind::Col) {
1,252 ✔
283
        const bool in_range =
1,113 !
284
            n->i >= 0 && static_cast<std::size_t>(n->i) < old_to_new.size();
742 !
285
        auto c = clone(*n);
742 ✔
286
        c->i = in_range ? old_to_new[static_cast<std::size_t>(n->i)] : n->i;
742 !
287
        return c;
742 !
288
    }
742 ✔
289
    auto a = node_remap(n->a, old_to_new);
510 ✔
290
    auto b = node_remap(n->b, old_to_new);
510 ✔
291
    auto c3 = node_remap(n->c, old_to_new);
510 ✔
292
    dstd::Vector<dstd::SharedPtr<const ExprNode>> args;
510 ✔
293
    bool same_args = true;
510 ✔
294
    for (const auto& arg : n->args) {
510 !
295
        args.push_back(node_remap(arg, old_to_new));
×
UNCOV
296
        same_args = same_args && args.back() == arg;
×
297
    }
298
    if (a == n->a && b == n->b && c3 == n->c && same_args)
510 !
299
        return n;  // unchanged: share
178 !
300
    auto c = clone(*n);
332 ✔
301
    c->a = std::move(a);
332 ✔
302
    c->b = std::move(b);
332 ✔
303
    c->c = std::move(c3);
332 ✔
304
    c->args = std::move(args);
332 ✔
305
    return c;
332 !
306
}
1,393 !
307
dftracer::utils::dstd::SharedPtr<const ExprNode> node_rebind(
22,054 ✔
308
    const dftracer::utils::dstd::SharedPtr<const ExprNode>& n,
309
    dstd::Span<const Expr> by) {
310
    if (!n) return nullptr;
22,054 ✔
311
    if (n->kind == ExprKind::Col) {
9,592 ✔
312
        const bool in_range =
5,319 !
313
            n->i >= 0 && static_cast<std::size_t>(n->i) < by.size();
5,319 !
314
        return in_range && by[static_cast<std::size_t>(n->i)].valid()
3,546 !
315
                   ? by[static_cast<std::size_t>(n->i)].node()
3,546 ✔
316
                   : n;
1,773 ✔
317
    }
1,773 ✔
318
    auto a = node_rebind(n->a, by);
6,046 ✔
319
    auto b = node_rebind(n->b, by);
6,046 ✔
320
    auto c3 = node_rebind(n->c, by);
6,046 ✔
321
    dstd::Vector<dstd::SharedPtr<const ExprNode>> args;
6,046 ✔
322
    bool same_args = true;
6,046 ✔
323
    for (const auto& arg : n->args) {
6,202 ✔
324
        args.push_back(node_rebind(arg, by));
156 !
325
        same_args = same_args && args.back() == arg;
215 !
326
    }
78 ✔
327
    if (a == n->a && b == n->b && c3 == n->c && same_args) return n;
6,046 !
328
    auto c = clone(*n);
3,994 ✔
329
    c->a = std::move(a);
3,994 ✔
330
    c->b = std::move(b);
3,994 ✔
331
    c->c = std::move(c3);
3,994 ✔
332
    c->args = std::move(args);
3,994 ✔
333
    return c;
3,994 !
334
}
14,050 !
335

336
void canonical_scalar(dstd::String& out, const dftu_scalar& v) {
2,028 ✔
337
    out += dstd::to_string(v.kind);
2,028 ✔
338
    out += ':';
2,028 ✔
339
    if (v.kind == DFTU_SCALAR_TAG_STR) {
2,028 ✔
340
        const dftracer::utils::dstd::StringView s =
96 ✔
341
            v.value.s ? dftracer::utils::dstd::StringView(v.value.s, v.len)
96 !
342
                      : dftracer::utils::dstd::StringView();
48 ✔
343
        out += dstd::to_string(s.size());
96 ✔
344
        out += ':';
96 ✔
345
        out += s;
96 ✔
346
    } else {
48 ✔
347
        out += dstd::to_string(v.value.u);
1,932 ✔
348
    }
349
}
2,028 ✔
350

351
void canonical_text(dstd::String& out, dftracer::utils::dstd::StringView s) {
2,064 ✔
352
    out += dstd::to_string(s.size());
2,064 ✔
353
    out += ':';
2,064 ✔
354
    out += s;
2,064 ✔
355
}
2,064 ✔
356

357
void canonical_node(dstd::String& out, const ExprNode* n) {
3,478 ✔
358
    if (!n) {
3,478 ✔
359
        out += '_';
2,464 ✔
360
        return;
2,464 ✔
361
    }
362
    out += '(';
1,014 ✔
363
    out += dstd::to_string(static_cast<int>(n->kind));
1,014 ✔
364
    out += ',';
1,014 ✔
365
    out += dstd::to_string(n->i);
1,014 ✔
366
    out += ',';
1,014 ✔
367
    canonical_scalar(out, n->scalar);
1,014 ✔
368
    out += ',';
1,014 ✔
369
    canonical_scalar(out, n->scalar2);
1,014 ✔
370
    out += ',';
1,014 ✔
371
    canonical_text(out, n->text);
1,014 ✔
372
    out += ',';
1,014 ✔
373
    canonical_text(out, n->text2);
1,014 ✔
374
    out += ',';
1,014 ✔
375
    if (n->values.valid()) {
1,014 ✔
376
        out += dstd::to_string(static_cast<int>(n->values.type()));
12 ✔
377
        for (std::int64_t r = 0; r < n->values.length(); ++r) {
48 ✔
378
            out += ',';
36 ✔
379
            canonical_text(out, cell_to_string(n->values, r));
36 ✔
380
        }
18 ✔
381
    }
6 ✔
382
    out += ',';
1,014 ✔
383
    canonical_node(out, n->a.get());
1,014 ✔
384
    out += ',';
1,014 ✔
385
    canonical_node(out, n->b.get());
1,014 ✔
386
    out += ',';
1,014 ✔
387
    canonical_node(out, n->c.get());
1,014 ✔
388
    for (const auto& arg : n->args) {
1,014 !
389
        out += ',';
×
UNCOV
390
        canonical_node(out, arg.get());
×
391
    }
392
    out += ')';
1,014 ✔
393
}
2,246 ✔
394

395
}  // namespace
396

397
Expr expr_remap_cols(const Expr& e, dstd::Span<const std::int32_t> old_to_new) {
746 ✔
398
    return Expr{node_remap(e.node(), old_to_new)};
746 !
399
}
373 ✔
400

401
Expr expr_rebind_cols(const Expr& e, dstd::Span<const Expr> by_index) {
3,760 ✔
402
    return Expr{node_rebind(e.node(), by_index)};
3,760 !
403
}
1,880 ✔
404

405
dstd::String expr_canonical(const Expr& e) {
436 ✔
406
    dstd::String out;
436 ✔
407
    canonical_node(out, e.node().get());
436 ✔
408
    return out;
436 ✔
409
}
218 !
410
Expr expr_lit(std::int64_t value) {
7,838 ✔
411
    dftu_scalar s{};
7,838 ✔
412
    s.kind = DFTU_SCALAR_TAG_I64;
7,838 ✔
413
    s.value.i = value;
7,838 ✔
414
    return make(ExprKind::LitI64, 0, s, nullptr, nullptr);
7,838 !
415
}
3,919 ✔
416
Expr expr_lit(double value) {
1,078 ✔
417
    dftu_scalar s{};
1,078 ✔
418
    s.kind = DFTU_SCALAR_TAG_F64;
1,078 ✔
419
    s.value.d = value;
1,078 ✔
420
    return make(ExprKind::LitF64, 0, s, nullptr, nullptr);
1,078 !
421
}
539 ✔
422
Expr expr_binary(BinaryOp op, const Expr& a, const Expr& b) {
10,722 ✔
423
    return make(ExprKind::Binary, static_cast<std::int32_t>(op), {}, a.node(),
16,083 !
424
                b.node());
21,444 !
425
}
5,361 ✔
426
Expr expr_prim(PrimOp prim, const Expr& a) {
48 ✔
427
    return make(ExprKind::Prim, static_cast<std::int32_t>(prim), {}, a.node(),
72 !
428
                nullptr);
72 !
429
}
24 ✔
430
Expr expr_unary(UnaryOp op, const Expr& a) {
472 ✔
431
    return make(ExprKind::Unary, static_cast<std::int32_t>(op), {}, a.node(),
708 !
432
                nullptr);
708 !
433
}
236 ✔
434
Expr expr_clip(const Expr& a, Scalar lo, Scalar hi) {
84 ✔
435
    auto n = dstd::make_shared<ExprNode>();
84 ✔
436
    n->kind = ExprKind::Clip;
84 ✔
437
    n->scalar = lo;
84 ✔
438
    n->scalar2 = hi;
84 ✔
439
    n->a = a.node();
84 ✔
440
    return Expr{std::move(n)};
84 !
441
}
84 ✔
442
Expr expr_fillna(const Expr& a, Scalar fill, bool nan) {
62 ✔
443
    Expr e = make(ExprKind::Fillna, nan ? 1 : 0, fill, a.node(), nullptr);
102 !
444
    const dftu_scalar raw = fill;
62 ✔
445
    if (raw.kind == DFTU_SCALAR_TAG_STR) {
62 ✔
446
        auto* n = const_cast<ExprNode*>(e.node().get());
14 !
447
        n->text.assign(raw.value.s != nullptr ? raw.value.s : "", raw.len);
21 !
448
        n->scalar.value.s = n->text.data();
14 ✔
449
        n->scalar.len = static_cast<std::uint32_t>(n->text.size());
14 ✔
450
    }
7 ✔
451
    return e;
62 ✔
452
}
31 !
453
Expr expr_cmp(CmpOp cmp, const Expr& a, Scalar rhs) {
3,414 ✔
454
    Expr e = make(ExprKind::Cmp, static_cast<std::int32_t>(cmp), rhs, a.node(),
5,121 !
455
                  nullptr);
5,121 !
456
    // A STR rhs only borrows its text, and the caller's buffer may die before
457
    // the Expr is evaluated. Take a copy the node owns and repoint at it.
458
    const dftu_scalar raw = rhs;
3,414 ✔
459
    if (raw.kind == DFTU_SCALAR_TAG_STR) {
3,414 ✔
460
        auto* n = const_cast<ExprNode*>(e.node().get());
178 !
461
        n->text.assign(raw.value.s != nullptr ? raw.value.s : "", raw.len);
267 !
462
        n->scalar.value.s = n->text.data();
178 ✔
463
        n->scalar.len = static_cast<std::uint32_t>(n->text.size());
178 ✔
464
    }
89 ✔
465
    return e;
3,414 ✔
466
}
1,707 !
467
Expr expr_logical(LogicalOp op, const Expr& a, const Expr& b) {
484 ✔
468
    return make(ExprKind::Logical, static_cast<std::int32_t>(op), {}, a.node(),
726 !
469
                b.node());
968 !
470
}
242 ✔
471
Expr expr_not(const Expr& a) {
206 ✔
472
    return make(ExprKind::Not, 0, {}, a.node(), nullptr);
309 !
473
}
103 ✔
474
Expr expr_cast(TypeId type, const Expr& a) {
2,560 ✔
475
    return make(ExprKind::Cast, static_cast<std::int32_t>(type), {}, a.node(),
3,840 !
476
                nullptr);
3,840 !
477
}
1,280 ✔
478
Expr expr_str_pred(StrPredOp op, const Expr& a,
314 ✔
479
                   dftracer::utils::dstd::StringView pattern) {
480
    Expr e = make(ExprKind::StrPred, static_cast<std::int32_t>(op), {},
471 !
481
                  a.node(), nullptr);
471 !
482
    const_cast<ExprNode*>(e.node().get())->text.assign(pattern);
314 ✔
483
    return e;
314 ✔
484
}
157 !
485
Expr expr_str_map(StrMapOp op, const Expr& a) {
410 ✔
486
    return make(ExprKind::StrMap, static_cast<std::int32_t>(op), {}, a.node(),
615 !
487
                nullptr);
615 !
488
}
205 ✔
489
Expr expr_lower(const Expr& a) { return expr_str_map(StrMapOp::Lower, a); }
270 ✔
490
Expr expr_str_size(const Expr& a, bool chars) {
60 ✔
491
    return make(ExprKind::StrLen, chars ? 1 : 0, {}, a.node(), nullptr);
97 !
492
}
30 ✔
493
Expr expr_str_find(const Expr& a, dftracer::utils::dstd::StringView needle) {
44 ✔
494
    Expr e = make(ExprKind::StrFind, 0, {}, a.node(), nullptr);
66 !
495
    const_cast<ExprNode*>(e.node().get())->text.assign(needle);
44 ✔
496
    return e;
44 ✔
497
}
22 !
498
Expr expr_str_replace(const Expr& a, dftracer::utils::dstd::StringView from,
30 ✔
499
                      dftracer::utils::dstd::StringView to, bool all) {
500
    Expr e = make(ExprKind::StrReplace, all ? 1 : 0, {}, a.node(), nullptr);
49 !
501
    auto* n = const_cast<ExprNode*>(e.node().get());
30 ✔
502
    n->text.assign(from);
30 ✔
503
    n->text2.assign(to);
30 ✔
504
    return e;
30 ✔
505
}
15 !
506
namespace {
507
dstd::Result<Expr> make_time_node(ExprKind k, std::int32_t part, const Expr& a,
1,026 ✔
508
                                  std::int64_t ns_per_unit,
509
                                  dftracer::utils::dstd::StringView fmt) {
510
    if (ns_per_unit <= 0)
1,026 ✔
511
        return common::make_error(common::ErrorCode::InvalidArgument,
8 ✔
512
                                  "expr: time unit must be positive");
4 ✔
513
    auto n = dstd::make_shared<ExprNode>();
1,022 ✔
514
    n->kind = k;
1,022 ✔
515
    n->i = part;
1,022 ✔
516
    n->scalar.kind = DFTU_SCALAR_TAG_I64;
1,022 ✔
517
    n->scalar.value.i = ns_per_unit;
1,022 ✔
518
    n->text.assign(fmt);
1,022 ✔
519
    n->a = a.node();
1,022 ✔
520
    return Expr{std::move(n)};
1,022 !
521
}
1,026 ✔
522
}  // namespace
523
dstd::Result<Expr> expr_date_part(const Expr& a, std::int32_t part,
886 ✔
524
                                  std::int64_t ns_per_unit) {
525
    if (!common::is_date_part_code(part))
886 ✔
526
        return common::make_error(common::ErrorCode::InvalidArgument,
8 ✔
527
                                  "expr: unknown date part");
4 ✔
528
    return make_time_node(ExprKind::DatePart, part, a, ns_per_unit, {});
882 ✔
529
}
443 ✔
530
dstd::Result<Expr> expr_format_time(const Expr& a,
148 ✔
531
                                    dftracer::utils::dstd::StringView fmt,
532
                                    std::int64_t ns_per_unit) {
533
    const dftracer::utils::dstd::StringView bad =
148 ✔
534
        common::invalid_time_format(fmt);
148 ✔
535
    if (!bad.empty())
148 ✔
536
        return common::make_error<"expr: invalid time format directive '{}'">(
6 ✔
537
            common::ErrorCode::InvalidArgument, bad);
2 ✔
538
    return make_time_node(ExprKind::FormatTime, 0, a, ns_per_unit, fmt);
144 ✔
539
}
74 ✔
540
Expr expr_str_slice(const Expr& a, std::int64_t start, std::int64_t len) {
12 ✔
541
    auto n = dstd::make_shared<ExprNode>();
12 ✔
542
    n->kind = ExprKind::StrSlice;
12 ✔
543
    n->scalar.kind = DFTU_SCALAR_TAG_I64;
12 ✔
544
    n->scalar.value.i = start;
12 ✔
545
    n->scalar2.kind = DFTU_SCALAR_TAG_I64;
12 ✔
546
    n->scalar2.value.i = len;
12 ✔
547
    n->a = a.node();
12 ✔
548
    return Expr{std::move(n)};
12 !
549
}
12 ✔
550
Expr expr_str_fn(StrFn fn, const Expr& a, const Expr* b,
560 ✔
551
                 dftracer::utils::dstd::StringView text,
552
                 dftracer::utils::dstd::StringView text2, std::int64_t i0,
553
                 std::int64_t i1) {
554
    auto n = dstd::make_shared<ExprNode>();
560 ✔
555
    n->kind = ExprKind::StrFn;
560 ✔
556
    n->i = static_cast<std::int32_t>(fn);
560 ✔
557
    n->scalar.kind = DFTU_SCALAR_TAG_I64;
560 ✔
558
    n->scalar.value.i = i0;
560 ✔
559
    n->scalar2.kind = DFTU_SCALAR_TAG_I64;
560 ✔
560
    n->scalar2.value.i = i1;
560 ✔
561
    n->text.assign(text);
560 ✔
562
    n->text2.assign(text2);
560 ✔
563
    n->a = a.node();
560 ✔
564
    if (b != nullptr) n->b = b->node();
560 ✔
565
    return Expr{std::move(n)};
560 !
566
}
560 ✔
567
Expr expr_is_in(const Expr& a, Series values) {
834 ✔
568
    Expr e = make(ExprKind::IsIn, 0, {}, a.node(), nullptr);
1,251 !
569
    const_cast<ExprNode*>(e.node().get())->values = std::move(values);
834 ✔
570
    return e;
834 ✔
571
}
417 !
572
Expr expr_is_null(const Expr& a, bool null) {
1,922 ✔
573
    return make(ExprKind::IsNull, null ? 1 : 0, {}, a.node(), nullptr);
3,767 !
574
}
961 ✔
575
Expr expr_is_na(const Expr& a, bool na) {
166 ✔
576
    return make(ExprKind::IsNull, na ? 2 : 3, {}, a.node(), nullptr);
279 !
577
}
83 ✔
578
Expr expr_select(const Expr& cond, const Expr& a, const Expr& b) {
824 ✔
579
    Expr e = make(ExprKind::Select, 0, {}, cond.node(), a.node());
1,648 !
580
    const_cast<ExprNode*>(e.node().get())->c = b.node();
824 ✔
581
    return e;
824 ✔
582
}
412 !
583

584
Expr expr_lit_str(dftracer::utils::dstd::StringView value) {
692 ✔
585
    Expr e = make(ExprKind::LitStr, 0, {}, nullptr, nullptr);
692 !
586
    const_cast<ExprNode*>(e.node().get())->text.assign(value);
692 ✔
587
    return e;
692 ✔
588
}
346 !
589
Expr expr_lit_bool(bool value) {
316 ✔
590
    return make(ExprKind::LitBool, value ? 1 : 0, {}, nullptr, nullptr);
354 !
591
}
158 ✔
592
Expr expr_lit_null(TypeId type) {
624 ✔
593
    return make(ExprKind::LitNull, static_cast<std::int32_t>(type), {}, nullptr,
936 ✔
594
                nullptr);
624 !
595
}
312 ✔
596
Expr expr_arith(ArithOp op, const Expr& a, const Expr& b) {
1,816 ✔
597
    return make(ExprKind::Arith, static_cast<std::int32_t>(op), {}, a.node(),
2,724 !
598
                b.node());
3,632 !
599
}
908 ✔
600
Expr expr_neg(const Expr& a) {
30 ✔
601
    return make(ExprKind::Neg, 0, {}, a.node(), nullptr);
45 !
602
}
15 ✔
603
Expr expr_cmp_expr(CmpOp cmp, const Expr& a, const Expr& b) {
850 ✔
604
    return make(ExprKind::CmpExpr, static_cast<std::int32_t>(cmp), {}, a.node(),
1,275 !
605
                b.node());
1,700 !
606
}
425 ✔
607

608
namespace {
609
// An n-ary node as a right fold of binary nodes; every n-ary form here is
610
// associative.
611
Expr fold_args(ExprKind k, std::int32_t i, dstd::Span<const Expr> args,
284 ✔
612
               dstd::StringView who) {
613
    if (args.empty())
284 ✔
UNCOV
614
        dstd::fatal("expr: an n-ary expression needs at least one operand",
×
615
                    who);
616
    Expr out = args.back();
284 !
617
    for (auto it = args.rbegin() + 1; it != args.rend(); ++it)
676 ✔
618
        out = make(k, i, {}, it->node(), out.node());
784 !
619
    return out;
284 ✔
620
}
142 !
621
}  // namespace
622

623
Expr udf_call_expr(dstd::SharedPtr<const UdfRecord> udf,
142 ✔
624
                   dstd::Span<const Expr> args) {
625
    auto n = dstd::make_shared<ExprNode>();
142 ✔
626
    n->kind = ExprKind::Udf;
142 ✔
627
    n->text = dstd::String(udf->name());
142 ✔
628
    n->udf = std::move(udf);
142 ✔
629
    for (const Expr& arg : args) {
322 ✔
630
        if (!arg.valid()) dstd::fatal("expr: a udf call has a null operand");
180 ✔
631
        n->args.push_back(arg.node());
180 ✔
632
    }
90 ✔
633
    return Expr{std::move(n)};
142 !
634
}
142 ✔
635

UNCOV
636
dstd::Result<Expr> expr_udf(dstd::StringView name,
×
637
                            dstd::Span<const Expr> args) {
638
    auto udf = find_udf(name);
×
639
    if (!udf)
×
UNCOV
640
        return common::make_error<"no udf named '{}'">(
×
641
            common::ErrorCode::NotFound, name);
642
    return udf_call_expr(std::move(udf), args);
×
UNCOV
643
}
×
644

645
Expr expr_coalesce(dstd::Span<const Expr> args) {
152 ✔
646
    return fold_args(ExprKind::Coalesce, 0, args, "coalesce");
152 ✔
647
}
76 ✔
648
Expr expr_extreme(dstd::Span<const Expr> args, bool least) {
26 ✔
649
    return fold_args(ExprKind::Extreme, least ? 1 : 0, args,
39 ✔
650
                     least ? "least" : "greatest");
38 ✔
651
}
13 ✔
652
Expr expr_concat(dstd::Span<const Expr> args) {
106 ✔
653
    if (args.size() == 1)
106 !
654
        return make(ExprKind::Concat, 0, {}, args.front().node(),
×
UNCOV
655
                    expr_lit_str("").node());
×
656
    return fold_args(ExprKind::Concat, 0, args, "concat");
106 ✔
657
}
53 ✔
658
Expr expr_round(const Expr& a, std::int64_t digits) {
26 ✔
659
    dftu_scalar s{};
26 ✔
660
    s.kind = DFTU_SCALAR_TAG_I64;
26 ✔
661
    s.value.i = digits;
26 ✔
662
    return make(ExprKind::Round, 0, s, a.node(), nullptr);
39 !
663
}
13 ✔
664
Expr expr_log(const Expr& a) {
4 ✔
665
    return make(ExprKind::Log, 0, {}, a.node(), nullptr);
6 !
666
}
2 ✔
667
Expr expr_pow(const Expr& a, const Expr& b) {
6 ✔
668
    return make(ExprKind::Pow, 0, {}, a.node(), b.node());
12 !
669
}
3 ✔
670
dstd::Result<Expr> expr_str_pred_col(StrPredOp op, const Expr& a,
88 ✔
671
                                     const Expr& needle) {
672
    if (op != StrPredOp::Contains && op != StrPredOp::StartsWith &&
88 ✔
673
        op != StrPredOp::EndsWith)
8 ✔
674
        return common::make_error(
4 ✔
675
            common::ErrorCode::InvalidArgument,
676
            "expr: a column needle takes contains, starts_with or ends_with");
2 ✔
677
    return make(ExprKind::StrPredCol, static_cast<std::int32_t>(op), {},
215 !
678
                a.node(), needle.node());
86 !
679
}
44 ✔
680
Expr expr_str_replace_col(const Expr& a, const Expr& from, const Expr& to) {
32 ✔
681
    Expr e = make(ExprKind::StrReplaceCol, 0, {}, a.node(), from.node());
64 !
682
    const_cast<ExprNode*>(e.node().get())->c = to.node();
32 ✔
683
    return e;
32 ✔
684
}
16 !
685
Expr expr_str_substr_col(const Expr& a, const Expr& start, const Expr* len) {
28 ✔
686
    Expr e = make(ExprKind::StrSubstrCol, 0, {}, a.node(), start.node());
56 !
687
    if (len != nullptr) const_cast<ExprNode*>(e.node().get())->c = len->node();
28 ✔
688
    return e;
28 ✔
689
}
14 !
690
Expr expr_round_col(const Expr& a, const Expr& digits) {
28 ✔
691
    return make(ExprKind::RoundCol, 0, {}, a.node(), digits.node());
56 !
692
}
14 ✔
693
Expr expr_str_substr(const Expr& a, std::int64_t start, std::int64_t len) {
16 ✔
694
    auto n = dstd::make_shared<ExprNode>();
16 ✔
695
    n->kind = ExprKind::StrSubstr;
16 ✔
696
    n->scalar.kind = DFTU_SCALAR_TAG_I64;
16 ✔
697
    n->scalar.value.i = start;
16 ✔
698
    n->scalar2.kind = DFTU_SCALAR_TAG_I64;
16 ✔
699
    n->scalar2.value.i = len;
16 ✔
700
    n->a = a.node();
16 ✔
701
    return Expr{std::move(n)};
16 !
702
}
16 ✔
703
namespace {
704
// A compiled pattern has no source text to persist, so each pattern node
705
// gets an identity no other node in any process shares: a persisted plan
706
// that holds one never matches another, where a shared text could match a
707
// different pattern.
708
dstd::String pattern_identity() {
86 ✔
709
    static const dstd::String seed = [] {
57 !
710
        std::random_device rd;
14 ✔
711
        return dstd::fmt<"{}.{}.{}">(rd(), rd(), rd());
14 ✔
712
    }();
50 !
713
    static std::atomic<std::uint64_t> next{0};
43 ✔
714
    return dstd::fmt<"pattern:{}:{}">(seed, next++);
86 ✔
715
}
716

717
Expr pattern_node(
86 ✔
718
    ExprKind k, const Expr& a,
719
    dftracer::utils::dstd::SharedPtr<const duql::CompiledPattern> p,
720
    std::int64_t group) {
721
    dftu_scalar s{};
86 ✔
722
    s.kind = DFTU_SCALAR_TAG_I64;
86 ✔
723
    s.value.i = group;
86 ✔
724
    Expr e = make(k, 0, s, a.node(), nullptr);
129 !
725
    auto* n = const_cast<ExprNode*>(e.node().get());
86 ✔
726
    n->pattern = std::move(p);
86 ✔
727
    n->text = pattern_identity();
86 ✔
728
    return e;
86 ✔
729
}
43 !
730
}  // namespace
731

732
Expr expr_str_pattern(
30 ✔
733
    const Expr& a,
734
    dftracer::utils::dstd::SharedPtr<const duql::CompiledPattern> p) {
735
    return pattern_node(ExprKind::StrPattern, a, std::move(p), 0);
30 !
736
}
15 ✔
737
Expr expr_str_extract(
26 ✔
738
    const Expr& a,
739
    dftracer::utils::dstd::SharedPtr<const duql::CompiledPattern> p,
740
    std::int64_t group) {
741
    return pattern_node(ExprKind::StrExtract, a, std::move(p), group);
26 !
742
}
13 ✔
743
Expr expr_str_extract_col(
10 ✔
744
    const Expr& a,
745
    dftracer::utils::dstd::SharedPtr<const duql::CompiledPattern> p,
746
    const Expr& group) {
747
    Expr e = pattern_node(ExprKind::StrExtractCol, a, std::move(p), 0);
10 !
748
    const_cast<ExprNode*>(e.node().get())->b = group.node();
10 ✔
749
    return e;
10 ✔
750
}
5 !
751
Expr expr_str_regex_replace(
20 ✔
752
    const Expr& a,
753
    dftracer::utils::dstd::SharedPtr<const duql::CompiledPattern> p,
754
    duql::Substitution sub) {
755
    Expr e = pattern_node(ExprKind::StrRegexReplace, a, std::move(p), 0);
20 !
756
    const_cast<ExprNode*>(e.node().get())->subst =
30 ✔
757
        dstd::make_shared<const duql::Substitution>(std::move(sub));
20 !
758
    return e;
20 ✔
759
}
10 !
760
Expr expr_convert(ConvertOp op, const Expr& a) {
508 ✔
761
    return make(ExprKind::Convert, static_cast<std::int32_t>(op), {}, a.node(),
762 !
762
                nullptr);
762 !
763
}
254 ✔
764
Expr expr_list_size(const Expr& a) {
110 ✔
765
    return make(ExprKind::ListLen, 0, {}, a.node(), nullptr);
165 !
766
}
55 ✔
767
Expr expr_list_get(const Expr& a, std::int64_t index) {
26 ✔
768
    dftu_scalar s{};
26 ✔
769
    s.kind = DFTU_SCALAR_TAG_I64;
26 ✔
770
    s.value.i = index;
26 ✔
771
    return make(ExprKind::ListGet, 0, s, a.node(), nullptr);
39 !
772
}
13 ✔
773
Expr expr_list_sum(const Expr& a) {
10 ✔
774
    return make(ExprKind::ListSum, 0, {}, a.node(), nullptr);
15 !
775
}
5 ✔
776
Expr expr_list_contains(const Expr& a, Scalar value) {
8 ✔
777
    Expr e = make(ExprKind::ListContains, 0, value, a.node(), nullptr);
12 !
778
    const dftu_scalar raw = value;
8 ✔
779
    if (raw.kind == DFTU_SCALAR_TAG_STR) {
8 ✔
780
        auto* n = const_cast<ExprNode*>(e.node().get());
4 !
781
        n->text.assign(raw.value.s != nullptr ? raw.value.s : "", raw.len);
6 !
782
        n->scalar.value.s = n->text.data();
4 ✔
783
        n->scalar.len = static_cast<std::uint32_t>(n->text.size());
4 ✔
784
    }
2 ✔
785
    return e;
8 ✔
786
}
4 !
787

788
bool expr_as_col_str_pred(const Expr& e, std::int32_t* col, StrPredOp* op,
308 ✔
789
                          dftracer::utils::dstd::StringView* pattern) {
790
    const auto& n = e.node();
308 ✔
791
    if (!n || n->kind != ExprKind::StrPred || !n->a ||
308 !
792
        n->a->kind != ExprKind::Col)
84 !
793
        return false;
112 ✔
794
    *col = n->a->i;
84 ✔
795
    *op = static_cast<StrPredOp>(n->i);
84 ✔
796
    *pattern = n->text;
84 ✔
797
    return true;
84 ✔
798
}
154 ✔
799

800
bool expr_as_col_is_in(const Expr& e, std::int32_t* col, Series* values) {
354 ✔
801
    const auto& n = e.node();
354 ✔
802
    if (!n || n->kind != ExprKind::IsIn || !n->a || n->a->kind != ExprKind::Col)
354 !
803
        return false;
139 ✔
804
    *col = n->a->i;
76 ✔
805
    *values = n->values.share();
76 !
806
    return true;
76 ✔
807
}
177 ✔
808

809
bool expr_as_col_is_null(const Expr& e, std::int32_t* col, bool* null) {
66 ✔
810
    const auto& n = e.node();
66 ✔
811
    if (!n || n->kind != ExprKind::IsNull || n->i > 1 || !n->a ||
66 !
812
        n->a->kind != ExprKind::Col)
16 !
813
        return false;
25 ✔
814
    *col = n->a->i;
16 ✔
815
    *null = n->i != 0;
16 ✔
816
    return true;
16 ✔
817
}
33 ✔
818

819
// ---- compiler: type inference + CSE + lowering to a slot program ----------
820

821
namespace {
822

823
// The (from, to) columns of StrFn::Translate's text operands: `text` is the
824
// keys, one codepoint each; `text2` is one entry per key, a codepoint L then
825
// the value's codepoints, L = 1 + their count, or L = 0 for a deletion. False
826
// when either does not parse.
827
bool decode_translate_table(dftracer::utils::dstd::StringView text,
64 ✔
828
                            dftracer::utils::dstd::StringView text2,
829
                            Series& from, Series& to) {
830
    const auto step = [](dftracer::utils::dstd::StringView s, std::size_t pos,
554 ✔
831
                         std::uint32_t& cp) -> std::size_t {
832
        const auto c = static_cast<unsigned char>(s[pos]);
490 ✔
833
        const std::size_t n = c < 0x80 ? 1 : c < 0xE0 ? 2 : c < 0xF0 ? 3 : 4;
490 ✔
834
        if (c >= 0x80 && c < 0xC0) return 0;
490 !
835
        if (pos + n > s.size()) return 0;
490 ✔
836
        cp = n == 1 ? c : c & (0x7F >> n);
490 ✔
837
        for (std::size_t k = 1; k < n; ++k)
554 ✔
838
            cp = (cp << 6) | (static_cast<unsigned char>(s[pos + k]) & 0x3F);
64 ✔
839
        return n;
245 ✔
840
    };
245 ✔
841
    dstd::Vector<std::int32_t> koff{0}, voff{0};
64 ✔
842
    dstd::Vector<std::uint8_t> valid;
64 ✔
843
    dstd::String vdata;
64 ✔
844
    std::size_t pos = 0;
64 ✔
845
    std::size_t vpos = 0;
64 ✔
846
    bool any_null = false;
64 ✔
847
    while (pos < text.size()) {
220 ✔
848
        std::uint32_t cp;
158 ✔
849
        const std::size_t n = step(text, pos, cp);
158 ✔
850
        if (n == 0) return false;
159 !
851
        pos += n;
158 ✔
852
        koff.push_back(static_cast<std::int32_t>(pos));
158 ✔
853
        std::uint32_t count;
158 ✔
854
        const std::size_t ln =
237 ✔
855
            vpos < text2.size() ? step(text2, vpos, count) : 0;
158 ✔
856
        if (ln == 0) return false;
158 ✔
857
        vpos += ln;
156 ✔
858
        const std::size_t row = koff.size() - 2;
156 ✔
859
        if (valid.size() * 8 <= row) valid.push_back(0);
156 ✔
860
        if (count == 0) {
156 ✔
861
            any_null = true;
26 ✔
862
        } else {
26 ✔
863
            valid[row >> 3] |= static_cast<std::uint8_t>(1u << (row & 7));
104 ✔
864
            const std::size_t begin = vpos;
104 ✔
865
            for (std::uint32_t k = 1; k < count; ++k) {
280 !
866
                std::uint32_t ignored;
176 ✔
867
                const std::size_t m =
264 !
868
                    vpos < text2.size() ? step(text2, vpos, ignored) : 0;
176 !
869
                if (m == 0) return false;
176 ✔
870
                vpos += m;
176 ✔
871
            }
88 !
872
            vdata.append(text2.substr(begin, vpos - begin));
104 ✔
873
        }
52 !
874
        voff.push_back(static_cast<std::int32_t>(vdata.size()));
156 ✔
875
    }
79 ✔
876
    if (vpos != text2.size()) return false;
62 ✔
877
    const auto rows = static_cast<std::int64_t>(koff.size() - 1);
62 ✔
878
    from = Series{dftu_series_new_string(DFTU_TYPE_STRING, koff.data(),
93 ✔
879
                                         text.data(), rows, nullptr)};
62 !
880
    to = Series{dftu_series_new_string(DFTU_TYPE_STRING, voff.data(),
119 ✔
881
                                       vdata.data(), rows,
62 ✔
882
                                       any_null ? valid.data() : nullptr)};
88 ✔
883
    return from.handle() != nullptr && to.handle() != nullptr;
62 !
884
}
64 ✔
885

886
// Slot-IR opcodes.
887
enum {
888
    OpLoad,
889
    OpAdd,
890
    OpSub,
891
    OpMul,
892
    OpDiv,
893
    OpAdds,
894
    OpSubs,
895
    OpMuls,
896
    OpDivs,
897
    OpPrim,
898
    OpUnary,
899
    OpClip,
900
    OpFillna,
901
    OpCmp,
902
    OpLogical,
903
    OpNot,
904
    OpCast,
905
    OpStrPred,
906
    OpStrMap,
907
    OpStrLen,
908
    OpStrFind,
909
    OpStrReplace,
910
    OpStrSlice,
911
    OpIsIn,
912
    OpUdf,     // the bound UDF over the columns in `udf_args`
913
    OpConst,   // a column of `param` type filled with `scalar`
914
    OpSelect,  // c ? a : b, with the mask in slot `c`
915
    OpIsNull,  // the null (1), valid (0), na (2) or notna (3) mask of slot `a`
916
    OpConstNull,
917
    OpToI64,   // Uint64 -> Int64, null past int64
918
    OpArith,
919
    OpNeg,
920
    OpCmpExpr,
921
    OpExtreme,
922
    OpConcat,
923
    OpRound,
924
    OpLog,
925
    OpPow,
926
    OpStrSubstr,
927
    OpStrPattern,
928
    OpStrExtract,
929
    OpStrRegexReplace,
930
    OpConvert,
931
    OpListLen,
932
    OpListGet,
933
    OpListSum,
934
    OpListContains,
935
    OpStrFn,  // param = StrFn; scalar/scalar2 = i0/i1; text/text2
936
    OpStrPredCol,
937
    OpStrReplaceCol,
938
    OpStrSubstrCol,
939
    OpRoundCol,
940
    OpStrExtractCol,
941
    OpDatePart,   // param = part code, scalar = ns per unit
942
    OpFormatTime  // text = format, scalar = ns per unit
943
};
944

945
struct SlotOp {
464,608 ✔
946
    int opcode = 0;
124,029 ✔
947
    int a = -1;
124,029 ✔
948
    int b = -1;
124,029 ✔
949
    int c = -1;
124,029 ✔
950
    std::int32_t param = 0;
124,029 ✔
951
    dftu_scalar scalar{};
124,029 ✔
952
    dftu_scalar scalar2{};  // clip hi / slice len
124,029 ✔
953
    // Borrowed from the ExprNode that emitted the op, which outlives the
954
    // program (eval_many holds the roots).
955
    dftracer::utils::dstd::StringView text;
956
    dftracer::utils::dstd::StringView text2;
957
    const dftu_series* values = nullptr;
124,029 ✔
958
    // OP_STR_PATTERN / OP_STR_EXTRACT, keyed by the node identity in `text`.
959
    const duql::CompiledPattern* pattern = nullptr;
124,029 ✔
960
    const duql::Substitution* subst = nullptr;
124,029 ✔
961
    // OpUdf: the bound UDF and the slot of each operand.
962
    const UdfBinding* udf = nullptr;
124,029 ✔
963
    dstd::Vector<int> udf_args;
964
};
965

966
const int COL_OP[4] = {OpAdd, OpSub, OpMul, OpDiv};
967
const int SCALAR_OP[4] = {OpAdds, OpSubs, OpMuls, OpDivs};
968

969
// A compiled subexpression: either a compile-time scalar or a column in slot
970
// `slot` of type `type`. `full` is the complete DataType: a bare column
971
// reference passes its input DataType through, every other node reports a
972
// scalar DataType (no kernel here can target a parameterized type).
973
struct Val {
42,886 ✔
974
    bool is_scalar;
975
    int slot;
976
    TypeId type;
977
    dftu_scalar scalar;
978
    DataType full;
979
};
980

981
bool is_float(const Val& v) {
84,726 ✔
982
    if (v.is_scalar) return v.scalar.kind == DFTU_SCALAR_TAG_F64;
84,726 ✔
983
    return v.type == TypeId::Float32 || v.type == TypeId::Float64;
71,119 ✔
984
}
42,364 ✔
985

986
bool is_unknown(const Val& v) { return v.full.id == TypeId::Unknown; }
180,015 ✔
987
Val unknown_val() {
13,366 ✔
988
    return {false, -1, TypeId::Unknown, {}, scalar(TypeId::Unknown)};
13,366 ✔
989
}
990

991
double scalar_to_double(dftu_scalar s) {
6,760 ✔
992
    if (s.kind == DFTU_SCALAR_TAG_I64) return static_cast<double>(s.value.i);
6,760 ✔
993
    if (s.kind == DFTU_SCALAR_TAG_U64) return static_cast<double>(s.value.u);
3,702 !
994
    return s.value.d;
3,702 ✔
995
}
3,380 ✔
996

997
dftu_scalar to_f64_scalar(dftu_scalar s) {
6,760 ✔
998
    dftu_scalar r{};
6,760 ✔
999
    r.kind = DFTU_SCALAR_TAG_F64;
6,760 ✔
1000
    r.value.d = scalar_to_double(s);
6,760 ✔
1001
    return r;
3,380 ✔
1002
}
3,380 ✔
1003

1004
bool is_int_type(TypeId t) {
25,382 ✔
1005
    switch (t) {
25,382 ✔
1006
        case TypeId::Int8:
1007
        case TypeId::Int16:
1008
        case TypeId::Int32:
1009
        case TypeId::Int64:
1010
        case TypeId::Uint8:
1011
        case TypeId::Uint16:
1012
        case TypeId::Uint32:
1013
        case TypeId::Uint64:
1014
            return true;
7,794 ✔
1015
        default:
4,896 ✔
1016
            return false;
9,793 ✔
1017
    }
1018
}
12,691 ✔
1019

1020
bool is_num_type(TypeId t) {
25,250 ✔
1021
    return is_int_type(t) || t == TypeId::Float32 || t == TypeId::Float64;
25,250 ✔
1022
}
1023

1024
bool is_text_type(TypeId t) {
3,282 ✔
1025
    return t == TypeId::String || t == TypeId::LargeString;
3,282 ✔
1026
}
1027

1028
// The type two numeric operands meet at: either float makes Float64, two
1029
// different integer types meet at Int64.
1030
TypeId promote(TypeId a, TypeId b) {
10,483 ✔
1031
    if (a == TypeId::Float64 || b == TypeId::Float64 || a == TypeId::Float32 ||
10,483 !
1032
        b == TypeId::Float32)
8,153 !
1033
        return TypeId::Float64;
1,166 ✔
1034
    return a == b && (a == TypeId::Int64 || a == TypeId::Uint64)
5,722 ✔
1035
               ? a
5,721 ✔
1036
               : TypeId::Int64;
1037
}
5,242 ✔
1038

1039
TypeId arith_type(std::int32_t op, TypeId a, TypeId b) {
10,540 ✔
1040
    return static_cast<ArithOp>(op) == ArithOp::Div ? TypeId::Float64
10,540 ✔
1041
           : promote(a, b) == TypeId::Float64       ? TypeId::Float64
10,386 ✔
1042
                                                    : TypeId::Int64;
5,269 ✔
1043
}
1044

1045
// Depends only on each input column's DataType, never its data, so the same
1046
// compile() drives eval() (Series::data_type()) and infer_type() (a schema
1047
// with no data) and the two can never disagree.
1048
class Compiler {
1049
   public:
1050
    explicit Compiler(dstd::Span<const DataType> input_types)
163,170 ✔
1051
        : input_types_(input_types) {}
163,170 ✔
1052

1053
    // A root that folded to a scalar, as a column of that value in every row.
1054
    Val column(const Val& v) {
83,518 ✔
1055
        if (!v.is_scalar) return v;
83,518 ✔
1056
        return broadcast(
3,909 ✔
1057
            v.scalar, v.scalar.kind == DFTU_SCALAR_TAG_F64   ? TypeId::Float64
2,606 ✔
1058
                      : v.scalar.kind == DFTU_SCALAR_TAG_U64 ? TypeId::Uint64
2,586 !
1059
                                                             : TypeId::Int64);
2,596 ✔
1060
    }
41,769 ✔
1061

1062
    // The first type error. compile() records it and returns an unknown value,
1063
    // so the rest of the walk is harmless; the caller reads error() after it.
1064
    bool failed() const { return !error_.empty(); }
212,774 ✔
1065
    const dstd::String& error() const { return error_; }
98 ✔
1066

1067
    Val compile(const ExprNode* n) {
289,419 ✔
1068
        if (failed()) return unknown_val();
289,419 ✔
1069
        switch (n->kind) {
289,415 ✔
1070
            case ExprKind::LitI64:
16,413 ✔
1071
            case ExprKind::LitF64:
16,413 ✔
1072
                return {true, -1, TypeId::Int64, n->scalar,
49,241 ✔
1073
                        scalar(TypeId::Int64)};
32,827 ✔
1074
            case ExprKind::Col: {
62,882 ✔
1075
                if (n->i < 0 ||
125,796 ✔
1076
                    static_cast<std::size_t>(n->i) >= input_types_.size())
125,795 ✔
1077
                    return fail("expr: column index out of range");
4 ✔
1078
                const DataType& dt =
188,703 ✔
1079
                    input_types_[static_cast<std::size_t>(n->i)];
125,792 ✔
1080
                if (dt.id == TypeId::Unknown)
125,792 ✔
1081
                    return {false, -1, TypeId::Unknown, {}, dt};
16,704 ✔
1082
                int slot = emit(OpLoad, -1, -1, n->i, {});
109,088 ✔
1083
                return {false, slot, dt.id, {}, dt};
109,089 ✔
1084
            }
62,911 ✔
1085
            case ExprKind::Binary:
33,164 ✔
1086
                return compile_binary(n);
66,328 ✔
1087
            case ExprKind::Prim: {
117 ✔
1088
                Val a0 = compile(n->a.get());
234 ✔
1089
                if (is_unknown(a0)) return unknown_val();
234 !
1090
                Val a = as_col(a0, "prim");
234 ✔
1091
                if (a.type != TypeId::Int64 && a.type != TypeId::Uint64)
234 !
UNCOV
1092
                    a = cast(a, TypeId::Int64);
×
1093
                return {false,
468 ✔
1094
                        emit(OpPrim, a.slot, -1, n->i, {}),
234 ✔
1095
                        TypeId::Int64,
1096
                        {},
117 ✔
1097
                        scalar(TypeId::Int64)};
234 ✔
1098
            }
234 ✔
1099
            case ExprKind::Unary: {
651 ✔
1100
                Val a0 = compile(n->a.get());
1,302 ✔
1101
                if (is_unknown(a0)) return unknown_val();
1,302 !
1102
                Val a = as_col(a0, "unary");
1,302 ✔
1103
                // is_nan/is_finite/is_infinite yield a Bool mask; log/sqrt/exp
1104
                // widen to Float64; the rest keep the input type (integer
1105
                // floor/ceil/round/trunc are identities).
1106
                const auto op = static_cast<UnaryOp>(n->i);
1,302 ✔
1107
                TypeId t;
1,302 ✔
1108
                switch (op) {
1,302 ✔
1109
                    case UnaryOp::IsNan:
1110
                    case UnaryOp::IsFinite:
1111
                    case UnaryOp::IsInfinite:
1112
                        t = TypeId::Bool;
30 ✔
1113
                        break;
30 ✔
1114
                    case UnaryOp::Log:
18 ✔
1115
                    case UnaryOp::Sqrt:
18 ✔
1116
                    case UnaryOp::Exp:
18 ✔
1117
                    case UnaryOp::Log1p:
18 ✔
1118
                    case UnaryOp::Expm1:
18 ✔
1119
                        t = TypeId::Float64;
36 ✔
1120
                        break;
36 ✔
1121
                    default:
603 ✔
1122
                        t = a.type;
1,206 ✔
1123
                        break;
1,206 ✔
1124
                }
1125
                return {false,
3,255 ✔
1126
                        emit(OpUnary, a.slot, -1, n->i, {}),
1,302 ✔
1127
                        t,
651 ✔
1128
                        {},
651 ✔
1129
                        scalar(t)};
1,302 ✔
1130
            }
1,302 ✔
1131
            case ExprKind::Clip: {
42 ✔
1132
                Val a0 = compile(n->a.get());
84 ✔
1133
                if (is_unknown(a0)) return unknown_val();
84 !
1134
                Val a = as_col(a0, "clip");
84 ✔
1135
                return {false,
210 ✔
1136
                        emit(OpClip, a.slot, -1, 0, n->scalar, n->scalar2),
84 ✔
1137
                        a.type,
84 ✔
1138
                        {},
42 ✔
1139
                        scalar(a.type)};
84 ✔
1140
            }
84 ✔
1141
            case ExprKind::Fillna: {
32 ✔
1142
                Val a0 = compile(n->a.get());
64 ✔
1143
                if (is_unknown(a0)) return unknown_val();
64 !
1144
                Val a = as_col(a0, "fillna");
64 ✔
1145
                const dftu_scalar fill = n->scalar;
64 ✔
1146
                if (is_text_type(a.type) ? fill.kind != DFTU_SCALAR_TAG_STR &&
91 ✔
1147
                                               fill.kind != DFTU_SCALAR_TAG_NULL
2 ✔
1148
                                         : fill.kind == DFTU_SCALAR_TAG_STR)
54 ✔
1149
                    return fail(dstd::fmt<"expr: fillna of {} takes {}">(
12 ✔
1150
                        type_name(a.type), is_text_type(a.type)
18 ✔
1151
                                               ? "a string fill"
1152
                                               : "a number fill"));
6 ✔
1153
                return {false,
156 ✔
1154
                        emit(OpFillna, a.slot, -1, n->i, n->scalar),
52 ✔
1155
                        a.type,
52 ✔
1156
                        {},
26 ✔
1157
                        scalar(a.type)};
58 ✔
1158
            }
64 ✔
1159
            case ExprKind::Cmp: {
3,906 ✔
1160
                Val a0 = compile(n->a.get());
7,811 ✔
1161
                if (is_unknown(a0)) return unknown_val();
7,811 ✔
1162
                Val a = as_col(a0, "compare");
7,729 ✔
1163
                return {false,
15,457 ✔
1164
                        emit(OpCmp, a.slot, -1, n->i, n->scalar),
7,729 ✔
1165
                        TypeId::Bool,
1166
                        {},
3,864 ✔
1167
                        scalar(TypeId::Bool)};
7,729 ✔
1168
            }
7,811 ✔
1169
            case ExprKind::Logical: {
558 ✔
1170
                Val a0 = compile(n->a.get());
1,116 ✔
1171
                Val b0 = compile(n->b.get());
1,116 ✔
1172
                if (is_unknown(a0) || is_unknown(b0)) return unknown_val();
1,116 ✔
1173
                Val a = as_col(a0, "logical");
1,036 ✔
1174
                Val b = as_col(b0, "logical");
1,036 ✔
1175
                return {false,
2,072 ✔
1176
                        emit(OpLogical, a.slot, b.slot, n->i, {}),
1,036 ✔
1177
                        TypeId::Bool,
1178
                        {},
518 ✔
1179
                        scalar(TypeId::Bool)};
1,036 ✔
1180
            }
1,634 ✔
1181
            case ExprKind::Not: {
258 ✔
1182
                Val a0 = compile(n->a.get());
516 ✔
1183
                if (is_unknown(a0)) return unknown_val();
516 ✔
1184
                Val a = as_col(a0, "not");
436 ✔
1185
                return {false,
872 ✔
1186
                        emit(OpNot, a.slot, -1, 0, {}),
436 ✔
1187
                        TypeId::Bool,
1188
                        {},
218 ✔
1189
                        scalar(TypeId::Bool)};
436 ✔
1190
            }
516 ✔
1191
            case ExprKind::Cast: {
7,312 ✔
1192
                Val a = as_col(compile(n->a.get()), "cast");
14,625 ✔
1193
                return cast(a, static_cast<TypeId>(n->i));
14,625 ✔
1194
            }
14,625 ✔
1195
            case ExprKind::StrPred: {
159 ✔
1196
                Val a0 = compile(n->a.get());
318 ✔
1197
                if (is_unknown(a0)) return unknown_val();
318 !
1198
                Val a = as_str(a0, "string predicate", true);
318 ✔
1199
                return {false,
636 ✔
1200
                        emit_text(OpStrPred, a.slot, n->i, n->text),
318 ✔
1201
                        TypeId::Bool,
1202
                        {},
159 ✔
1203
                        scalar(TypeId::Bool)};
318 ✔
1204
            }
318 ✔
1205
            case ExprKind::StrMap: {
545 ✔
1206
                Val a0 = compile(n->a.get());
1,090 ✔
1207
                if (is_unknown(a0)) return unknown_val();
1,090 ✔
1208
                Val a = as_str(a0, "string map", false);
1,088 ✔
1209
                return {false,
2,176 ✔
1210
                        emit(OpStrMap, a.slot, -1, n->i, {}),
1,088 ✔
1211
                        TypeId::String,
1212
                        {},
544 ✔
1213
                        scalar(TypeId::String)};
1,088 ✔
1214
            }
1,090 ✔
1215
            case ExprKind::StrLen: {
72 ✔
1216
                Val a0 = compile(n->a.get());
144 ✔
1217
                if (is_unknown(a0)) return unknown_val();
144 ✔
1218
                Val a = as_str(a0, "string length", true);
142 ✔
1219
                return {false,
284 ✔
1220
                        emit(OpStrLen, a.slot, -1, n->i, {}),
142 ✔
1221
                        TypeId::Int64,
1222
                        {},
71 ✔
1223
                        scalar(TypeId::Int64)};
142 ✔
1224
            }
144 ✔
1225
            case ExprKind::StrFind: {
41 ✔
1226
                Val a0 = compile(n->a.get());
82 ✔
1227
                if (is_unknown(a0)) return unknown_val();
82 !
1228
                Val a = as_str(a0, "string find", true);
82 ✔
1229
                return {false,
164 ✔
1230
                        emit_text(OpStrFind, a.slot, 0, n->text),
82 ✔
1231
                        TypeId::Int64,
1232
                        {},
41 ✔
1233
                        scalar(TypeId::Int64)};
82 ✔
1234
            }
82 ✔
1235
            case ExprKind::StrReplace: {
16 ✔
1236
                Val a0 = compile(n->a.get());
32 ✔
1237
                if (is_unknown(a0)) return unknown_val();
32 !
1238
                Val a = as_str(a0, "string replace", false);
32 ✔
1239
                return {
64 ✔
1240
                    false,
1241
                    emit_text(OpStrReplace, a.slot, n->i, n->text, n->text2),
32 ✔
1242
                    TypeId::String,
1243
                    {},
16 ✔
1244
                    scalar(TypeId::String)};
32 ✔
1245
            }
32 ✔
1246
            case ExprKind::DatePart:
521 ✔
1247
            case ExprKind::FormatTime: {
521 ✔
1248
                const bool fmt = n->kind == ExprKind::FormatTime;
1,042 ✔
1249
                Val a0 = compile(n->a.get());
1,042 ✔
1250
                if (is_unknown(a0)) return unknown_val();
1,042 !
1251
                if (!a0.is_scalar && !is_num_type(a0.type))
1,042 !
1252
                    return fail(
8 ✔
1253
                        dstd::fmt<
4 ✔
1254
                            "expr: {} needs a time or integer operand, got {}">(
8 ✔
1255
                            (fmt ? "format_time" : "date_part"),
8 ✔
1256
                            type_name(a0.type)));
12 ✔
1257
                Val a = num(a0, fmt ? "format_time" : "date_part");
1,479 ✔
1258
                SlotOp op;
1,034 ✔
1259
                op.opcode = fmt ? OpFormatTime : OpDatePart;
1,034 ✔
1260
                op.a = a.slot;
1,034 ✔
1261
                op.param = n->i;
1,034 ✔
1262
                op.scalar = n->scalar;
1,034 ✔
1263
                op.text = n->text;
1,034 ✔
1264
                return col_val(emit_op(op),
1,551 ✔
1265
                               fmt ? TypeId::String : TypeId::Int64);
1,479 ✔
1266
            }
1,559 ✔
1267
            case ExprKind::StrSlice: {
7 ✔
1268
                Val a0 = compile(n->a.get());
14 ✔
1269
                if (is_unknown(a0)) return unknown_val();
14 !
1270
                Val a = as_str(a0, "string slice", false);
14 ✔
1271
                return {false,
28 ✔
1272
                        emit(OpStrSlice, a.slot, -1, 0, n->scalar, n->scalar2),
14 ✔
1273
                        TypeId::String,
1274
                        {},
7 ✔
1275
                        scalar(TypeId::String)};
14 ✔
1276
            }
14 ✔
1277
            case ExprKind::IsIn: {
355 ✔
1278
                Val a0 = compile(n->a.get());
710 ✔
1279
                if (is_unknown(a0)) return unknown_val();
710 !
1280
                Val a = as_col(a0, "is_in");
710 ✔
1281
                if (!n->values.valid())
710 ✔
UNCOV
1282
                    return fail("expr: is_in needs a values column");
×
1283
                if (value_domain(a.type) != value_domain(n->values.type()))
710 ✔
1284
                    return fail(
4 ✔
1285
                        dstd::fmt<
2 ✔
1286
                            "expr: is_in over a {} column needs {} values, got "
1287
                            "{}">(type_name(a.type), type_name(a.type),
6 ✔
1288
                                  type_name(n->values.type())));
4 ✔
1289
                SlotOp op;
706 ✔
1290
                op.opcode = OpIsIn;
706 ✔
1291
                op.a = a.slot;
706 ✔
1292
                op.values = n->values.handle();
706 ✔
1293
                return {
1,412 ✔
1294
                    false, emit_op(op), TypeId::Bool, {}, scalar(TypeId::Bool)};
1,412 ✔
1295
            }
1,065 ✔
1296
            case ExprKind::Select:
845 ✔
1297
                return compile_select(n);
1,691 ✔
1298
            case ExprKind::LitStr: {
726 ✔
1299
                dftu_scalar s{};
1,452 ✔
1300
                s.kind = DFTU_SCALAR_TAG_STR;
1,452 ✔
1301
                s.value.s = n->text.data();
1,452 ✔
1302
                s.len = static_cast<std::uint32_t>(n->text.size());
1,452 ✔
1303
                return broadcast(s, TypeId::String);
1,452 ✔
1304
            }
726 ✔
1305
            case ExprKind::LitBool: {
858 ✔
1306
                dftu_scalar s{};
1,716 ✔
1307
                s.kind = DFTU_SCALAR_TAG_I64;
1,716 ✔
1308
                s.value.i = n->i;
1,716 ✔
1309
                return broadcast(s, TypeId::Bool);
1,716 ✔
1310
            }
858 ✔
1311
            case ExprKind::LitNull: {
532 ✔
1312
                const auto t = static_cast<TypeId>(n->i);
1,065 ✔
1313
                if (!is_num_type(t) && t != TypeId::Bool && t != TypeId::String)
1,065 ✔
1314
                    return fail(dstd::fmt<"expr: no null literal of type {}">(
3 ✔
1315
                        type_name(t)));
2 ✔
1316
                return col_val(emit(OpConstNull, -1, -1, n->i, {}), t);
1,063 ✔
1317
            }
533 ✔
1318
            case ExprKind::Arith: {
3,094 ✔
1319
                Val a0 = compile(n->a.get());
6,189 ✔
1320
                Val b0 = compile(n->b.get());
6,189 ✔
1321
                if (is_unknown(a0) || is_unknown(b0)) return unknown_val();
6,189 !
1322
                Val a = num(a0, "arithmetic");
6,189 ✔
1323
                Val b = num(b0, "arithmetic");
6,189 ✔
1324
                const TypeId t = arith_type(n->i, a.type, b.type);
6,189 ✔
1325
                return col_val(emit(OpArith, a.slot, b.slot, n->i, {}), t);
6,189 ✔
1326
            }
9,283 ✔
1327
            case ExprKind::Neg: {
41 ✔
1328
                Val a0 = compile(n->a.get());
82 ✔
1329
                if (is_unknown(a0)) return unknown_val();
82 !
1330
                Val a = num(a0, "negation");
82 ✔
1331
                const TypeId t =
164 ✔
1332
                    a.type == TypeId::Float64 ? TypeId::Float64 : TypeId::Int64;
82 ✔
1333
                return col_val(emit(OpNeg, a.slot, -1, 0, {}), t);
82 ✔
1334
            }
82 ✔
1335
            case ExprKind::CmpExpr: {
990 ✔
1336
                Val a0 = compile(n->a.get());
1,980 ✔
1337
                Val b0 = compile(n->b.get());
1,980 ✔
1338
                if (is_unknown(a0) || is_unknown(b0)) return unknown_val();
1,980 !
1339
                Val a = operand(a0, "compare");
1,900 ✔
1340
                Val b = operand(b0, "compare");
1,900 ✔
1341
                same_domain(a, b, "compare");
1,900 ✔
1342
                return col_val(emit(OpCmpExpr, a.slot, b.slot, n->i, {}),
1,900 ✔
1343
                               TypeId::Bool);
950 ✔
1344
            }
2,930 ✔
1345
            case ExprKind::Coalesce: {
217 ✔
1346
                Val a0 = compile(n->a.get());
434 ✔
1347
                Val b0 = compile(n->b.get());
434 ✔
1348
                if (is_unknown(a0) || is_unknown(b0)) return unknown_val();
434 !
1349
                Val a = operand(a0, "coalesce");
434 ✔
1350
                Val b = operand(b0, "coalesce");
434 ✔
1351
                const TypeId t = common_type(a, b, "coalesce");
434 ✔
1352
                // Presence is the operand's own: a value that does not fit
1353
                // `t` is a null result, not a reason to move on to `b`.
1354
                const int present = emit(OpIsNull, a.slot, -1, 0, {});
434 ✔
1355
                a = to_type(a, t);
434 ✔
1356
                b = to_type(b, t);
434 ✔
1357
                SlotOp op;
434 ✔
1358
                op.opcode = OpSelect;
434 ✔
1359
                op.a = a.slot;
434 ✔
1360
                op.b = b.slot;
434 ✔
1361
                op.c = present;
434 ✔
1362
                return col_val(emit_op(op), t);
434 ✔
1363
            }
651 ✔
1364
            case ExprKind::Extreme: {
17 ✔
1365
                Val a0 = compile(n->a.get());
34 ✔
1366
                Val b0 = compile(n->b.get());
34 ✔
1367
                if (is_unknown(a0) || is_unknown(b0)) return unknown_val();
34 !
1368
                Val a = operand(a0, "least/greatest");
34 ✔
1369
                Val b = operand(b0, "least/greatest");
34 ✔
1370
                same_domain(a, b, "least/greatest");
34 ✔
1371
                const TypeId t = common_type(a, b, "least/greatest");
34 ✔
1372
                return col_val(emit(OpExtreme, a.slot, b.slot, n->i, {}), t);
34 ✔
1373
            }
51 ✔
1374
            case ExprKind::Concat: {
535 ✔
1375
                Val a0 = compile(n->a.get());
1,070 ✔
1376
                Val b0 = compile(n->b.get());
1,070 ✔
1377
                if (is_unknown(a0) || is_unknown(b0)) return unknown_val();
1,070 !
1378
                Val a = as_str(a0, "concat", false);
1,070 ✔
1379
                Val b = as_str(b0, "concat", false);
1,070 ✔
1380
                return col_val(emit(OpConcat, a.slot, b.slot, 0, {}),
1,070 ✔
1381
                               TypeId::String);
535 ✔
1382
            }
1,605 ✔
1383
            case ExprKind::Round: {
42 ✔
1384
                Val a0 = compile(n->a.get());
84 ✔
1385
                if (is_unknown(a0)) return unknown_val();
84 !
1386
                const bool integer = a0.is_scalar
84 !
1387
                                         ? a0.scalar.kind != DFTU_SCALAR_TAG_F64
42 !
1388
                                         : is_int_type(a0.type);
84 ✔
1389
                if (integer && n->scalar.value.i >= 0) return a0;
84 ✔
1390
                Val a = num(a0, "round");
54 ✔
1391
                const TypeId t = integer ? TypeId::Int64 : TypeId::Float64;
54 ✔
1392
                return col_val(emit(OpRound, a.slot, -1, 0, n->scalar), t);
54 ✔
1393
            }
84 ✔
1394
            case ExprKind::Log: {
2 ✔
1395
                Val a0 = compile(n->a.get());
4 ✔
1396
                if (is_unknown(a0)) return unknown_val();
4 !
1397
                Val a = num(a0, "log");
4 ✔
1398
                return col_val(emit(OpLog, a.slot, -1, 0, {}), TypeId::Float64);
4 ✔
1399
            }
4 ✔
1400
            case ExprKind::Pow: {
3 ✔
1401
                Val a0 = compile(n->a.get());
6 ✔
1402
                Val b0 = compile(n->b.get());
6 ✔
1403
                if (is_unknown(a0) || is_unknown(b0)) return unknown_val();
6 !
1404
                Val a = num(a0, "pow");
6 ✔
1405
                Val b = num(b0, "pow");
6 ✔
1406
                return col_val(emit(OpPow, a.slot, b.slot, 0, {}),
6 ✔
1407
                               TypeId::Float64);
3 ✔
1408
            }
9 ✔
1409
            case ExprKind::StrSubstr: {
8 ✔
1410
                Val a0 = compile(n->a.get());
16 ✔
1411
                if (is_unknown(a0)) return unknown_val();
16 !
1412
                Val a = as_str(a0, "substr", false);
16 ✔
1413
                return col_val(
16 ✔
1414
                    emit(OpStrSubstr, a.slot, -1, 0, n->scalar, n->scalar2),
8 ✔
1415
                    TypeId::String);
8 ✔
1416
            }
16 ✔
1417
            case ExprKind::StrPredCol: {
56 ✔
1418
                Val a0 = compile(n->a.get());
112 ✔
1419
                Val b0 = compile(n->b.get());
112 ✔
1420
                if (is_unknown(a0) || is_unknown(b0)) return unknown_val();
112 !
1421
                Val a = as_str(a0, "string predicate", true);
112 ✔
1422
                Val b = as_str(b0, "string predicate", true);
112 ✔
1423
                return col_val(emit(OpStrPredCol, a.slot, b.slot, n->i, {}),
112 ✔
1424
                               TypeId::Bool);
56 ✔
1425
            }
168 ✔
1426
            case ExprKind::StrReplaceCol: {
17 ✔
1427
                Val a0 = compile(n->a.get());
34 ✔
1428
                Val b0 = compile(n->b.get());
34 ✔
1429
                Val c0 = compile(n->c.get());
34 ✔
1430
                if (is_unknown(a0) || is_unknown(b0) || is_unknown(c0))
34 !
UNCOV
1431
                    return unknown_val();
×
1432
                Val a = as_str(a0, "string replace", false);
34 ✔
1433
                Val b = as_str(b0, "string replace", false);
34 ✔
1434
                Val c = as_str(c0, "string replace", false);
34 ✔
1435
                SlotOp op;
34 ✔
1436
                op.opcode = OpStrReplaceCol;
34 ✔
1437
                op.a = a.slot;
34 ✔
1438
                op.b = b.slot;
34 ✔
1439
                op.c = c.slot;
34 ✔
1440
                return col_val(emit_op(op), TypeId::String);
34 ✔
1441
            }
51 ✔
1442
            case ExprKind::StrSubstrCol: {
17 ✔
1443
                Val a0 = compile(n->a.get());
34 ✔
1444
                Val b0 = compile(n->b.get());
34 ✔
1445
                Val c0 = n->c ? compile(n->c.get()) : Val{};
34 ✔
1446
                if (is_unknown(a0) || is_unknown(b0) ||
44 !
1447
                    (n->c && is_unknown(c0)))
34 !
UNCOV
1448
                    return unknown_val();
×
1449
                Val a = as_str(a0, "substr", false);
34 ✔
1450
                Val b = num(b0, "substr");
34 ✔
1451
                SlotOp op;
34 ✔
1452
                op.opcode = OpStrSubstrCol;
34 ✔
1453
                op.a = a.slot;
34 ✔
1454
                op.b = b.slot;
34 ✔
1455
                if (n->c) op.c = num(c0, "substr").slot;
34 ✔
1456
                return col_val(emit_op(op), TypeId::String);
34 ✔
1457
            }
51 ✔
1458
            case ExprKind::RoundCol: {
17 ✔
1459
                Val a0 = compile(n->a.get());
34 ✔
1460
                Val b0 = compile(n->b.get());
34 ✔
1461
                if (is_unknown(a0) || is_unknown(b0)) return unknown_val();
34 !
1462
                const bool integer = a0.is_scalar
34 ✔
1463
                                         ? a0.scalar.kind != DFTU_SCALAR_TAG_F64
20 ✔
1464
                                         : is_int_type(a0.type);
28 ✔
1465
                Val a = num(a0, "round");
34 ✔
1466
                Val b = num(b0, "round");
34 ✔
1467
                const bool unsigned_in =
68 ✔
1468
                    a0.is_scalar ? a0.scalar.kind == DFTU_SCALAR_TAG_U64
34 ✔
1469
                                 : a0.type == TypeId::Uint64;
28 ✔
1470
                return col_val(emit(OpRoundCol, a.slot, b.slot, 0, {}),
51 ✔
1471
                               unsigned_in ? TypeId::Uint64
17 ✔
1472
                               : integer   ? TypeId::Int64
30 ✔
1473
                                           : TypeId::Float64);
32 ✔
1474
            }
51 ✔
1475
            case ExprKind::StrPattern:
57 ✔
1476
            case ExprKind::StrExtract:
57 ✔
1477
            case ExprKind::StrExtractCol:
57 ✔
1478
            case ExprKind::StrRegexReplace:
57 ✔
1479
                return compile_pattern(n);
114 ✔
1480
            case ExprKind::Convert:
733 ✔
1481
                return compile_convert(n);
1,466 ✔
1482
            case ExprKind::ListLen: {
1,707 ✔
1483
                Val a0 = compile(n->a.get());
3,414 ✔
1484
                if (is_unknown(a0)) return unknown_val();
3,414 ✔
1485
                as_list(a0, "list_len");
3,394 ✔
1486
                return col_val(emit(OpListLen, a0.slot, -1, 0, {}),
3,394 ✔
1487
                               TypeId::Int64);
3,404 ✔
1488
            }
3,414 ✔
1489
            case ExprKind::ListGet: {
21 ✔
1490
                Val a0 = compile(n->a.get());
42 ✔
1491
                if (is_unknown(a0)) return unknown_val();
42 !
1492
                const DataType elem = as_list(a0, "list_get");
42 ✔
1493
                return {false,
105 ✔
1494
                        emit(OpListGet, a0.slot, -1, 0, n->scalar),
42 ✔
1495
                        elem.id,
42 ✔
1496
                        {},
21 ✔
1497
                        elem};
42 ✔
1498
            }
42 ✔
1499
            case ExprKind::ListSum: {
5 ✔
1500
                Val a0 = compile(n->a.get());
10 ✔
1501
                if (is_unknown(a0)) return unknown_val();
10 !
1502
                const TypeId e = as_list(a0, "list_sum").id;
10 ✔
1503
                const TypeId t = e == TypeId::Float32 || e == TypeId::Float64
15 !
1504
                                     ? TypeId::Float64
5 ✔
1505
                                     : TypeId::Int64;
1506
                return col_val(emit(OpListSum, a0.slot, -1, 0, {}), t);
15 ✔
1507
            }
10 ✔
1508
            case ExprKind::ListContains: {
4 ✔
1509
                Val a0 = compile(n->a.get());
8 ✔
1510
                if (is_unknown(a0)) return unknown_val();
8 !
1511
                as_list(a0, "list_contains");
8 ✔
1512
                return col_val(emit(OpListContains, a0.slot, -1, 0, n->scalar),
8 ✔
1513
                               TypeId::Bool);
8 ✔
1514
            }
8 ✔
1515
            case ExprKind::StrFn:
889 ✔
1516
                return compile_str_fn(n);
1,807 ✔
1517
            case ExprKind::Udf:
742 ✔
1518
                return compile_udf(n);
1,484 ✔
1519
            case ExprKind::IsNull: {
5,450 ✔
1520
                Val a0 = compile(n->a.get());
10,898 ✔
1521
                if (is_unknown(a0)) return unknown_val();
10,898 ✔
1522
                Val a = as_col(a0, "is_null");
10,738 ✔
1523
                return {false,
21,473 ✔
1524
                        emit(OpIsNull, a.slot, -1, n->i, {}),
10,737 ✔
1525
                        TypeId::Bool,
1526
                        {},
5,368 ✔
1527
                        scalar(TypeId::Bool)};
10,737 ✔
1528
            }
10,896 ✔
1529
        }
UNCOV
1530
        dstd::fatal("expr: unknown node kind");
×
1531
    }
144,739 ✔
1532

1533
    dstd::Vector<SlotOp> program;
1534
    dstd::Vector<dstd::SharedPtr<const UdfBinding>> bindings;
1535

1536
   private:
1537
    static Val col_val(int slot, TypeId t) {
20,260 ✔
1538
        return {false, slot, t, {}, scalar(t)};
17,897 ✔
1539
    }
10,142 ✔
1540

1541
    // A numeric operand as Int64, Uint64 or Float64, the three types the
1542
    // duql kernels read; a literal broadcasts.
1543
    Val num(Val v, dstd::StringView who) {
17,899 ✔
1544
        if (v.is_scalar)
17,899 ✔
1545
            return broadcast(v.scalar, v.scalar.kind == DFTU_SCALAR_TAG_F64
5,579 ✔
1546
                                           ? TypeId::Float64
1547
                                       : v.scalar.kind == DFTU_SCALAR_TAG_U64
2,646 ✔
1548
                                           ? TypeId::Uint64
2,647 !
1549
                                           : TypeId::Int64);
5,437 ✔
1550
        if (!is_num_type(v.type))
12,320 ✔
1551
            return fail(dstd::fmt<"expr: {} needs a numeric operand, got {}">(
6 ✔
1552
                who, type_name(v.type)));
4 ✔
1553
        if (v.type == TypeId::Int64 || v.type == TypeId::Uint64 ||
12,316 ✔
1554
            v.type == TypeId::Float64)
1,663 ✔
1555
            return v;
12,296 ✔
1556
        return cast(v, is_int_type(v.type) ? TypeId::Int64 : TypeId::Float64);
20 !
1557
    }
8,950 ✔
1558

1559
    // An operand of a comparison-like node: numeric ones as num() makes
1560
    // them, the rest as they are.
1561
    Val operand(Val v, dstd::StringView who) {
6,201 ✔
1562
        if (v.is_scalar || is_num_type(v.type)) return num(v, who);
6,201 ✔
1563
        return v;
1,996 ✔
1564
    }
3,100 ✔
1565

1566
    void same_domain(const Val& a, const Val& b, dstd::StringView who) {
1,934 ✔
1567
        const bool ok = (is_num_type(a.type) && is_num_type(b.type)) ||
1,937 ✔
1568
                        (is_text_type(a.type) && is_text_type(b.type)) ||
1,216 ✔
1569
                        (a.type == TypeId::Bool && b.type == TypeId::Bool);
5 ✔
1570
        if (!ok)
967 ✔
1571
            fail(dstd::fmt<"expr: {} of {} and {} has no ordering">(
6 ✔
1572
                who, type_name(a.type), type_name(b.type)));
9 ✔
1573
    }
1,934 ✔
1574

1575
    TypeId common_type(const Val& a, const Val& b, dstd::StringView who) {
467 ✔
1576
        if (is_num_type(a.type) && is_num_type(b.type))
467 ✔
1577
            return promote(a.type, b.type);
71 ✔
1578
        if (a.type != b.type) {
396 ✔
1579
            fail(dstd::fmt<"expr: {} needs one type, got {} and {}">(
2 ✔
1580
                who, type_name(a.type), type_name(b.type)));
2 ✔
1581
            return TypeId::Unknown;
2 ✔
1582
        }
1583
        return a.type;
197 ✔
1584
    }
233 ✔
1585

1586
    Val to_type(Val v, TypeId t) {
866 ✔
1587
        if (v.type == t) return v;
866 ✔
1588
        if (v.type == TypeId::Uint64 && t == TypeId::Int64)
16 ✔
1589
            return col_val(emit(OpToI64, v.slot, -1, 0, {}), t);
10 ✔
1590
        return cast(v, t);
6 ✔
1591
    }
432 ✔
1592

1593
    // The element type of a List operand, which must be known.
1594
    DataType as_list(const Val& v, dstd::StringView who) {
3,474 ✔
1595
        if (v.is_scalar || v.type != TypeId::List ||
3,474 !
1596
            v.full.fields.size() != 1) {
3,470 !
1597
            fail(dstd::fmt<"expr: {} needs a List column with a known element "
4 ✔
1598
                           "type, got {}">(
4 ✔
1599
                who, type_name(v.is_scalar ? TypeId::Int64 : v.type)));
4 ✔
1600
            return scalar(TypeId::Unknown);
4 ✔
1601
        }
1602
        return v.full.fields.front().type;
3,470 ✔
1603
    }
1,737 ✔
1604

1605
    Val compile_pattern(const ExprNode* n) {
114 ✔
1606
        Val a0 = compile(n->a.get());
114 ✔
1607
        if (is_unknown(a0)) return unknown_val();
114 !
1608
        const bool extract_col = n->kind == ExprKind::StrExtractCol;
114 ✔
1609
        const bool extract = n->kind == ExprKind::StrExtract || extract_col;
114 ✔
1610
        const bool replace = n->kind == ExprKind::StrRegexReplace;
114 ✔
1611
        const bool text_out = extract || replace;
114 ✔
1612
        Val a = as_str(a0,
228 ✔
1613
                       extract   ? "string extract"
57 ✔
1614
                       : replace ? "string regex replace"
64 ✔
1615
                                 : "string pattern",
1616
                       !text_out);
146 ✔
1617
        if (replace && !n->subst)
114 ✔
UNCOV
1618
            return fail("expr: a regex replace node needs a substitution");
×
1619
        if (!n->pattern) return fail("expr: a pattern node needs a pattern");
114 ✔
1620
        if (extract_col) {
108 ✔
1621
            Val g0 = compile(n->b.get());
8 ✔
1622
            if (is_unknown(g0)) return unknown_val();
8 !
1623
            SlotOp op;
8 ✔
1624
            op.opcode = OpStrExtractCol;
8 ✔
1625
            op.a = a.slot;
8 ✔
1626
            op.b = num(g0, "string extract").slot;
8 ✔
1627
            op.text = n->text;
8 ✔
1628
            op.pattern = n->pattern.get();
8 ✔
1629
            return col_val(emit_op(op), TypeId::String);
8 ✔
1630
        }
8 ✔
1631
        const std::int64_t group = n->scalar.value.i;
100 ✔
1632
        if (extract && (group < 0 || static_cast<std::uint64_t>(group) >
120 !
1633
                                         duql::capture_count(*n->pattern)))
40 ✔
1634
            return fail(
2 ✔
1635
                dstd::fmt<"expr: extract group {} is not in the pattern">(
3 ✔
1636
                    group));
1 ✔
1637
        SlotOp op;
98 ✔
1638
        op.opcode = extract   ? OpStrExtract
98 ✔
1639
                    : replace ? OpStrRegexReplace
30 ✔
1640
                              : OpStrPattern;
1641
        op.subst = n->subst.get();
98 ✔
1642
        op.a = a.slot;
98 ✔
1643
        op.scalar = n->scalar;
98 ✔
1644
        op.text = n->text;
98 ✔
1645
        op.pattern = n->pattern.get();
98 ✔
1646
        return col_val(emit_op(op), text_out ? TypeId::String : TypeId::Bool);
112 ✔
1647
    }
171 ✔
1648

1649
    Val compile_convert(const ExprNode* n) {
1,466 ✔
1650
        Val a0 = compile(n->a.get());
1,466 ✔
1651
        if (is_unknown(a0)) return unknown_val();
1,466 !
1652
        Val a = operand(a0, "convert");
1,466 ✔
1653
        if (!is_num_type(a.type) && !is_text_type(a.type) &&
1,466 ✔
1654
            a.type != TypeId::Bool)
5 ✔
1655
            return fail(
×
1656
                dstd::fmt<"expr: convert needs a scalar operand, got {}">(
×
UNCOV
1657
                    type_name(a.type)));
×
1658
        const auto op = static_cast<ConvertOp>(n->i);
1,466 ✔
1659
        if (op == ConvertOp::Int && a.type == TypeId::Int64) return a;
1,466 ✔
1660
        if (op == ConvertOp::String && a.type == TypeId::String) return a;
1,466 ✔
1661
        const TypeId t = op == ConvertOp::Int     ? TypeId::Int64
1,464 ✔
1662
                         : op == ConvertOp::Float ? TypeId::Float64
810 ✔
1663
                                                  : TypeId::String;
1664
        return col_val(emit(OpConvert, a.slot, -1, n->i, {}), t);
1,465 ✔
1665
    }
1,466 ✔
1666

1667
    int emit_str_fn(const ExprNode* n, int a, int b) {
1,787 ✔
1668
        SlotOp op;
1,787 ✔
1669
        op.opcode = OpStrFn;
1,787 ✔
1670
        op.a = a;
1,787 ✔
1671
        op.b = b;
1,787 ✔
1672
        op.param = n->i;
1,787 ✔
1673
        op.scalar = n->scalar;
1,787 ✔
1674
        op.scalar2 = n->scalar2;
1,787 ✔
1675
        op.text = n->text;
1,787 ✔
1676
        op.text2 = n->text2;
1,787 ✔
1677
        return emit_op(op);
1,787 ✔
1678
    }
1,791 ✔
1679

1680
    // The expression forms of the eager Series.str methods; the types are
1681
    // the eager results'.
1682
    Val compile_str_fn(const ExprNode* n) {
1,807 ✔
1683
        const auto fn = static_cast<StrFn>(n->i);
1,807 ✔
1684
        Val a0 = compile(n->a.get());
1,807 ✔
1685
        Val b0{};
1,809 ✔
1686
        if (fn == StrFn::Cat) {
1,809 ✔
1687
            if (!n->b)
14 ✔
1688
                return fail(
2 ✔
1689
                    "expr: cat needs another column; the one-column join is "
1 ✔
1690
                    "an aggregate (use Series.str.cat)");
1 ✔
1691
            b0 = compile(n->b.get());
12 ✔
1692
            if (is_unknown(b0)) return unknown_val();
12 !
1693
        }
6 ✔
1694
        if (is_unknown(a0)) return unknown_val();
1,807 !
1695
        const DataType list_str = list_of(scalar(TypeId::String));
1,807 ✔
1696
        if (fn == StrFn::Join) {
1,814 ✔
1697
            const DataType elem = as_list(a0, "join");
14 ✔
1698
            if (elem.id != TypeId::String)
14 ✔
1699
                return fail(
2 ✔
1700
                    dstd::fmt<
1 ✔
1701
                        "expr: join needs a List<String> column, got List<{}>">(
2 ✔
1702
                        type_name(elem.id)));
2 ✔
1703
            return col_val(emit_str_fn(n, a0.slot, -1), TypeId::String);
13 ✔
1704
        }
14 ✔
1705
        if (fn == StrFn::Get && !a0.is_scalar && a0.type == TypeId::List) {
1,800 !
1706
            const DataType elem = as_list(a0, "get");
6 ✔
1707
            return {false,
15 ✔
1708
                    emit(OpListGet, a0.slot, -1, 0, n->scalar),
6 ✔
1709
                    elem.id,
6 ✔
1710
                    {},
3 ✔
1711
                    elem};
6 ✔
1712
        }
6 ✔
1713
        Val a = as_str(a0, "string method", false);
1,794 ✔
1714
        switch (fn) {
1,793 ✔
1715
            case StrFn::IsAlnum:
60 ✔
1716
            case StrFn::IsAlpha:
60 ✔
1717
            case StrFn::IsDigit:
60 ✔
1718
            case StrFn::IsDecimal:
60 ✔
1719
            case StrFn::IsNumeric:
60 ✔
1720
            case StrFn::IsSpace:
60 ✔
1721
            case StrFn::IsLower:
60 ✔
1722
            case StrFn::IsUpper:
60 ✔
1723
            case StrFn::IsTitle:
60 ✔
1724
                return col_val(emit_str_fn(n, a.slot, -1), TypeId::Bool);
120 ✔
1725
            case StrFn::Split:
51 ✔
1726
            case StrFn::Partition:
51 ✔
1727
            case StrFn::RPartition:
51 ✔
1728
            case StrFn::Findall:
51 ✔
1729
                return {false,
255 ✔
1730
                        emit_str_fn(n, a.slot, -1),
102 ✔
1731
                        TypeId::List,
1732
                        {},
51 ✔
1733
                        list_str};
102 ✔
1734
            case StrFn::Rfind:
605 ✔
1735
            case StrFn::Index:
605 ✔
1736
            case StrFn::Rindex:
605 ✔
1737
                return col_val(emit_str_fn(n, a.slot, -1), TypeId::Int64);
1,231 ✔
1738
            case StrFn::Get:
11 ✔
1739
                if (n->scalar.value.i < 0)
22 ✔
1740
                    return fail(
4 ✔
1741
                        "expr: get with a negative position needs a List "
2 ✔
1742
                        "column; use slice");
2 ✔
1743
                return col_val(emit_str_fn(n, a.slot, -1), TypeId::String);
18 ✔
1744
            case StrFn::Cat: {
6 ✔
1745
                Val b = as_str(b0, "cat", false);
12 ✔
1746
                return col_val(emit_str_fn(n, a.slot, b.slot), TypeId::String);
12 ✔
1747
            }
12 ✔
1748
            case StrFn::Join:
1749
                break;
1750
            case StrFn::Normalize:
12 ✔
1751
                if (n->scalar.value.i < 0 || n->scalar.value.i > 3)
24 ✔
1752
                    return fail(
2 ✔
1753
                        "expr: normalize form must be NFC, NFKC, NFD or NFKD");
2 ✔
1754
                return col_val(emit_str_fn(n, a.slot, -1), TypeId::String);
22 ✔
1755
            case StrFn::Translate: {
18 ✔
1756
                Series from, to;
36 ✔
1757
                const Series probe = Series::nulls(TypeId::String, 1);
36 ✔
1758
                if (!decode_translate_table(n->text, n->text2, from, to) ||
36 ✔
1759
                    !Series{dftu_series_str_translate(
86 ✔
1760
                                probe.handle(), from.handle(), to.handle())}
34 ✔
1761
                         .handle())
34 ✔
1762
                    return fail(
4 ✔
1763
                        "expr: translate table is not one distinct codepoint "
2 ✔
1764
                        "per key");
2 ✔
1765
                return col_val(emit_str_fn(n, a.slot, -1), TypeId::String);
34 !
1766
            }
70 ✔
1767
            case StrFn::Wrap:
4 ✔
1768
                if (n->scalar.value.i < 1)
8 ✔
1769
                    return fail("expr: wrap width must be at least 1");
2 ✔
1770
                return col_val(emit_str_fn(n, a.slot, -1), TypeId::String);
6 ✔
1771
            default:
119 ✔
1772
                return col_val(emit_str_fn(n, a.slot, -1), TypeId::String);
1,003 ✔
1773
        }
UNCOV
1774
        dstd::fatal("expr: unknown string method");
×
1775
    }
2,690 ✔
1776

1777
    Val as_col(Val v, dstd::StringView who) {
45,537 ✔
1778
        if (v.is_scalar)
45,537 !
UNCOV
1779
            return fail(dstd::fmt<"expr: {} needs a column operand">(who));
×
1780
        return v;
45,537 ✔
1781
    }
22,783 ✔
1782

1783
    // A string operand: String always; Binary too when `binary_ok` (the
1784
    // predicate / length / find kernels read bytes, the maps produce text).
1785
    Val as_str(Val v, dstd::StringView who, bool binary_ok) {
6,101 ✔
1786
        Val a = as_col(v, who);
6,101 ✔
1787
        const bool ok =
9,139 ✔
1788
            a.type == TypeId::String || (binary_ok && a.type == TypeId::Binary);
6,095 !
1789
        if (!ok)
3,081 ✔
1790
            return fail(dstd::fmt<"expr: {} needs a String{} column, got {}">(
60 ✔
1791
                who, (binary_ok ? " or Binary" : ""), type_name(a.type)));
40 ✔
1792
        return a;
6,065 ✔
1793
    }
6,099 ✔
1794

1795
    Val cast(Val v, TypeId t) {
26,419 ✔
1796
        return {false,
66,049 ✔
1797
                emit(OpCast, v.slot, -1, static_cast<std::int32_t>(t), {}),
26,419 ✔
1798
                t,
13,210 ✔
1799
                {},
13,210 ✔
1800
                scalar(t)};
26,419 ✔
1801
    }
13,210 ✔
1802

1803
    Val compile_binary(const ExprNode* n) {
66,328 ✔
1804
        const int op = n->i;  // BinaryOp
66,328 ✔
1805
        Val a = compile(n->a.get());
66,328 ✔
1806
        Val b = compile(n->b.get());
66,328 ✔
1807
        if (is_unknown(a) || is_unknown(b)) return unknown_val();
66,328 ✔
1808
        if (a.is_scalar && b.is_scalar) return fold(op, a.scalar, b.scalar);
53,820 ✔
1809

1810
        const bool rf =
78,602 ✔
1811
            op == static_cast<int>(BinaryOp::Div) || is_float(a) || is_float(b);
53,820 ✔
1812
        TypeId out_type;
53,820 ✔
1813
        if (rf) {
53,820 ✔
1814
            promote_float(a);
21,596 ✔
1815
            promote_float(b);
21,596 ✔
1816
            out_type = TypeId::Float64;
21,596 ✔
1817
        } else if (!a.is_scalar && !b.is_scalar && a.type != b.type) {
43,022 ✔
1818
            a = cast(a, TypeId::Int64);
880 ✔
1819
            b = cast(b, TypeId::Int64);
880 ✔
1820
            out_type = TypeId::Int64;
880 ✔
1821
        } else {
440 ✔
1822
            out_type = a.is_scalar ? b.type : a.type;
31,344 ✔
1823
        }
1824

1825
        if (!a.is_scalar && !b.is_scalar)
53,820 ✔
1826
            return {false,
104,100 ✔
1827
                    emit(COL_OP[op], a.slot, b.slot, 0, {}),
34,700 ✔
1828
                    out_type,
17,350 ✔
1829
                    {},
17,350 ✔
1830
                    scalar(out_type)};
34,700 ✔
1831
        if (!a.is_scalar)  // col op scalar
19,120 ✔
1832
            return {false,
57,096 ✔
1833
                    emit(SCALAR_OP[op], a.slot, -1, 0, b.scalar),
19,032 ✔
1834
                    out_type,
9,516 ✔
1835
                    {},
9,516 ✔
1836
                    scalar(out_type)};
19,032 ✔
1837
        if (op == static_cast<int>(BinaryOp::Add) ||
88 ✔
1838
            op == static_cast<int>(BinaryOp::Mul))  // scalar op col commutes
87 ✔
1839
            return {false,
108 ✔
1840
                    emit(SCALAR_OP[op], b.slot, -1, 0, a.scalar),
36 ✔
1841
                    out_type,
18 ✔
1842
                    {},
18 ✔
1843
                    scalar(out_type)};
36 ✔
1844
        // scalar - col and scalar / col have no scalar-first kernel: broadcast
1845
        // the scalar to a column of the result type and run the column kernel.
1846
        const Val left = broadcast(a.scalar, out_type);
52 ✔
1847
        return {false,
130 ✔
1848
                emit(COL_OP[op], left.slot, b.slot, 0, {}),
52 ✔
1849
                out_type,
26 ✔
1850
                {},
26 ✔
1851
                scalar(out_type)};
52 ✔
1852
    }
66,328 ✔
1853

1854
    void promote_float(Val& v) {
43,192 ✔
1855
        if (v.is_scalar) {
43,192 ✔
1856
            v.scalar = to_f64_scalar(v.scalar);
6,640 ✔
1857
        } else if (v.type != TypeId::Float32 && v.type != TypeId::Float64) {
39,872 ✔
1858
            v = cast(v, TypeId::Float64);
9,998 ✔
1859
        }
4,999 ✔
1860
    }
43,192 ✔
1861

1862
    // A call of a registered UDF over its operands, which bind sees as types
1863
    // and, for a literal, as constants. The program holds the binding, which
1864
    // keeps the plugin library loaded while it runs.
1865
    Val compile_udf(const ExprNode* n) {
1,484 ✔
1866
        dstd::Vector<Val> vals;
1,484 ✔
1867
        dstd::Vector<DataType> types;
1,484 ✔
1868
        dstd::Vector<dftu_scalar> scalars(n->args.size());
1,484 ✔
1869
        dstd::Vector<const dftu_scalar*> consts(n->args.size(), nullptr);
1,484 ✔
1870
        for (std::size_t i = 0; i < n->args.size(); ++i) {
3,012 ✔
1871
            const ExprNode& arg = *n->args[i];
1,528 ✔
1872
            Val v = compile(&arg);
1,528 ✔
1873
            if (is_unknown(v)) return unknown_val();
1,528 !
1874
            if (arg.kind == ExprKind::LitI64 || arg.kind == ExprKind::LitF64 ||
1,528 ✔
1875
                arg.kind == ExprKind::LitStr || arg.kind == ExprKind::LitBool) {
1,526 !
1876
                scalars[i] = arg.scalar;
2 !
1877
                if (arg.kind == ExprKind::LitStr) {
2 !
1878
                    scalars[i].kind = DFTU_SCALAR_TAG_STR;
×
1879
                    scalars[i].value.s = arg.text.data();
×
1880
                    scalars[i].len =
×
UNCOV
1881
                        static_cast<std::uint32_t>(arg.text.size());
×
1882
                } else if (arg.kind == ExprKind::LitBool) {
2 ✔
1883
                    scalars[i].kind = DFTU_SCALAR_TAG_I64;
×
UNCOV
1884
                    scalars[i].value.i = arg.i;
×
1885
                }
1886
                consts[i] = &scalars[i];
2 ✔
1887
            }
1 ✔
1888
            v = column(v);
1,528 ✔
1889
            types.push_back(v.full);
1,528 ✔
1890
            vals.push_back(std::move(v));
1,528 ✔
1891
        }
1,528 !
1892
        auto bound = bind_udf(
3,706 !
1893
            n->udf, dstd::Span<const DataType>(types.data(), types.size()),
2,224 !
1894
            dstd::Span<const dftu_scalar* const>(consts.data(), consts.size()));
2,225 !
1895
        if (!bound) return fail(dstd::String(bound.error().message()));
1,483 ✔
1896
        bindings.push_back(
2,958 !
1897
            dstd::make_shared<const UdfBinding>(std::move(*bound)));
1,479 ✔
1898
        SlotOp op;
1,479 ✔
1899
        op.opcode = OpUdf;
1,479 ✔
1900
        op.udf = bindings.back().get();
1,479 ✔
1901
        for (const Val& v : vals) op.udf_args.push_back(v.slot);
3,002 ✔
1902
        const TypeId type = bindings.back()->result_type().id;
1,479 ✔
1903
        const int slot = static_cast<int>(program.size());
1,479 ✔
1904
        program.push_back(std::move(op));
1,479 ✔
1905
        return col_val(slot, type);
1,479 ✔
1906
    }
2,226 ✔
1907

1908
    // A column of `t` holding `s` in every row, for a scalar arm of a select.
1909
    Val broadcast(dftu_scalar s, TypeId t) {
12,412 ✔
1910
        return {false,
31,030 ✔
1911
                emit(OpConst, -1, -1, static_cast<std::int32_t>(t), s),
12,412 ✔
1912
                t,
6,206 ✔
1913
                {},
6,206 ✔
1914
                scalar(t)};
12,412 ✔
1915
    }
6,206 ✔
1916

1917
    // cond ? a : b. The arms promote as arithmetic does: either float makes
1918
    // both Float64 (Float32 stays Float32 against scalars and Float32), two
1919
    // different integer types meet at Int64; a scalar arm broadcasts into a
1920
    // column of the promoted type. A string arm needs a string on the other
1921
    // side too.
1922
    Val compile_select(const ExprNode* n) {
1,691 ✔
1923
        Val c0 = compile(n->a.get());
1,691 ✔
1924
        Val a = compile(n->b.get());
1,691 ✔
1925
        Val b = compile(n->c.get());
1,691 ✔
1926
        if (is_unknown(c0) || is_unknown(a) || is_unknown(b))
1,691 !
1927
            return unknown_val();
242 ✔
1928
        Val c = as_col(c0, "select");
1,449 ✔
1929
        if (c.type != TypeId::Bool)
1,449 ✔
1930
            return fail(
4 ✔
1931
                dstd::fmt<"expr: select needs a Bool condition, got {}">(
6 ✔
1932
                    type_name(c.type)));
4 ✔
1933
        if (a.is_scalar && b.is_scalar) {
1,445 ✔
1934
            const bool f = a.scalar.kind == DFTU_SCALAR_TAG_F64 ||
56 ✔
1935
                           b.scalar.kind == DFTU_SCALAR_TAG_F64;
52 !
1936
            const TypeId t = f ? TypeId::Float64 : TypeId::Int64;
58 ✔
1937
            if (f) {
30 ✔
1938
                a.scalar = to_f64_scalar(a.scalar);
4 ✔
1939
                b.scalar = to_f64_scalar(b.scalar);
4 ✔
1940
            }
2 ✔
1941
            a = broadcast(a.scalar, t);
56 ✔
1942
            b = broadcast(b.scalar, t);
56 ✔
1943
        } else {
56 ✔
1944
            const bool str_arm = (!a.is_scalar && a.type == TypeId::String) ||
2,061 ✔
1945
                                 (!b.is_scalar && b.type == TypeId::String);
1,343 !
1946
            if (str_arm) {
1,366 ✔
1947
                if (a.is_scalar || b.is_scalar || a.type != b.type)
46 !
UNCOV
1948
                    return fail(
×
1949
                        "expr: select needs two String columns for a "
1950
                        "String arm");
1951
            } else if (is_float(a) || is_float(b)) {
1,366 ✔
1952
                const bool a32 = !a.is_scalar && a.type == TypeId::Float32;
190 ✔
1953
                const bool b32 = !b.is_scalar && b.type == TypeId::Float32;
190 ✔
1954
                const bool narrow = (a32 || b32) && (a.is_scalar || a32) &&
194 ✔
1955
                                    (b.is_scalar || b32);
7 ✔
1956
                const TypeId ft = narrow ? TypeId::Float32 : TypeId::Float64;
98 ✔
1957
                if (a.is_scalar) {
190 ✔
1958
                    a = broadcast(to_f64_scalar(a.scalar), ft);
40 ✔
1959
                } else if (a.type != ft) {
170 ✔
1960
                    a = cast(a, ft);
4 ✔
1961
                }
2 ✔
1962
                if (b.is_scalar) {
190 ✔
1963
                    b = broadcast(to_f64_scalar(b.scalar), ft);
72 ✔
1964
                } else if (b.type != ft) {
154 ✔
1965
                    b = cast(b, ft);
2 ✔
1966
                }
1 ✔
1967
            } else {
95 ✔
1968
                const TypeId t = a.is_scalar        ? b.type
1,360 ✔
1969
                                 : b.is_scalar      ? a.type
599 ✔
1970
                                 : a.type == b.type ? a.type
370 ✔
1971
                                                    : TypeId::Int64;
1972
                if (!a.is_scalar && a.type != t) a = cast(a, t);
1,153 ✔
1973
                if (!b.is_scalar && b.type != t) b = cast(b, t);
1,153 ✔
1974
                if (a.is_scalar) a = broadcast(a.scalar, t);
1,153 ✔
1975
                if (b.is_scalar) b = broadcast(b.scalar, t);
1,153 ✔
1976
            }
577 ✔
1977
        }
695 !
1978
        SlotOp op;
1,445 ✔
1979
        op.opcode = OpSelect;
1,445 ✔
1980
        op.a = a.slot;
1,445 ✔
1981
        op.b = b.slot;
1,445 ✔
1982
        op.c = c.slot;
1,445 ✔
1983
        return {false, emit_op(op), a.type, {}, scalar(a.type)};
1,445 ✔
1984
    }
2,415 ✔
1985

1986
    Val fold(int op, dftu_scalar a, dftu_scalar b) {
×
1987
        const bool f = op == static_cast<int>(BinaryOp::Div) ||
×
1988
                       a.kind == DFTU_SCALAR_TAG_F64 ||
×
1989
                       b.kind == DFTU_SCALAR_TAG_F64;
×
1990
        dftu_scalar r{};
×
1991
        if (f) {
×
1992
            double x = scalar_to_double(a), y = scalar_to_double(b);
×
1993
            r.kind = DFTU_SCALAR_TAG_F64;
×
1994
            r.value.d = op == 0   ? x + y
×
1995
                        : op == 1 ? x - y
×
UNCOV
1996
                        : op == 2 ? x * y
×
1997
                                  : x / y;
1998
        } else {
1999
            std::int64_t x = a.value.i, y = b.value.i;
×
2000
            r.kind = DFTU_SCALAR_TAG_I64;
×
2001
            r.value.i = op == 0   ? x + y
×
2002
                        : op == 1 ? x - y
×
2003
                        : op == 2 ? x * y
×
UNCOV
2004
                                  : (y != 0 ? x / y : 0);
×
2005
        }
2006
        return {true, -1, TypeId::Int64, r,
×
UNCOV
2007
                scalar(f ? TypeId::Float64 : TypeId::Int64)};
×
2008
    }
2009

2010
    // Emit an op, hash-consing structurally identical ops to the same slot
2011
    // (common-subexpression elimination).
2012
    int emit(int opcode, int a, int b, std::int32_t param, dftu_scalar s,
240,520 ✔
2013
             dftu_scalar s2 = {}) {
2014
        SlotOp op;
240,520 ✔
2015
        op.opcode = opcode;
240,520 ✔
2016
        op.a = a;
240,520 ✔
2017
        op.b = b;
240,520 ✔
2018
        op.param = param;
240,520 ✔
2019
        op.scalar = s;
240,520 ✔
2020
        op.scalar2 = s2;
240,520 ✔
2021
        return emit_op(op);
240,520 ✔
2022
    }
240,522 ✔
2023

2024
    int emit_text(int opcode, int a, std::int32_t param,
432 ✔
2025
                  dftracer::utils::dstd::StringView text,
2026
                  dftracer::utils::dstd::StringView text2 = {}) {
2027
        SlotOp op;
432 ✔
2028
        op.opcode = opcode;
432 ✔
2029
        op.a = a;
432 ✔
2030
        op.param = param;
432 ✔
2031
        op.text = text;
432 ✔
2032
        op.text2 = text2;
432 ✔
2033
        return emit_op(op);
432 ✔
2034
    }
432 ✔
2035

2036
    int emit_op(const SlotOp& op) {
246,526 ✔
2037
        auto bits = [](dftu_scalar x) {
739,572 ✔
2038
            return x.kind == DFTU_SCALAR_TAG_F64
493,046 ✔
2039
                       ? std::bit_cast<std::int64_t>(x.value.d)
250,772 ✔
2040
                       : x.value.i;
242,274 ✔
2041
        };
2042
        // len is part of the key: a STR scalar's `bits` is its pointer, and
2043
        // two scalars can share a pointer with different lengths (a prefix),
2044
        // which would otherwise hash-cons to the same slot. A text operand is
2045
        // keyed by value, a values set by identity.
2046
        auto key = std::make_tuple(
369,815 ✔
2047
            op.opcode, op.a, op.b, op.c, static_cast<int>(op.param),
246,525 ✔
2048
            static_cast<int>(op.scalar.kind), bits(op.scalar), bits(op.scalar2),
369,761 ✔
2049
            op.scalar.len, op.scalar2.len, dstd::String(op.text),
369,765 ✔
2050
            dstd::String(op.text2),
369,765 ✔
2051
            reinterpret_cast<std::uintptr_t>(op.values));
369,774 ✔
2052
        auto it = memo_.find(key);
246,528 ✔
2053
        if (it != memo_.end()) return it->second;
246,530 ✔
2054
        int slot = static_cast<int>(program.size());
226,343 ✔
2055
        program.push_back(op);
226,343 ✔
2056
        memo_.emplace(key, slot);
226,345 ✔
2057
        return slot;
226,331 ✔
2058
    }
246,531 ✔
2059

2060
    Val fail(dstd::String message) {
106 ✔
2061
        if (error_.empty()) error_ = std::move(message);
106 ✔
2062
        return unknown_val();
106 ✔
2063
    }
53 ✔
2064

2065
    dstd::Span<const DataType> input_types_;
2066
    dstd::String error_;
2067
    dstd::Map<dftracer::utils::dstd::Tuple<
2068
                  int, int, int, int, int, int, std::int64_t, std::int64_t,
2069
                  std::uint32_t, std::uint32_t, dstd::String, dstd::String,
2070
                  std::uintptr_t>,
2071
              int>
2072
        memo_;
2073
};
2074

2075
// dftu_series_slice returns null for List and Struct; take()'s gather_column
2076
// handles those instead.
2077
Series load_slice(const Series& in, std::int64_t offset, std::int64_t len) {
71,960 ✔
2078
    if (dftu_series* v = dftu_series_slice(in.handle(), offset, len)) {
106,288 ✔
2079
        Series s{v};
68,618 ✔
2080
        if (s.encoding() != Encoding::Chunked) return s;
68,618 ✔
2081
        // An invalid column is the kernel refusing its input, which
2082
        // require_evaluated reports.
2083
        dstd::Result<Series> joined = join_chunks(s);
8 ✔
2084
        return joined ? std::move(*joined) : Series{};
12 !
2085
    }
68,626 ✔
2086
    dstd::Vector<std::int64_t> idx(static_cast<std::size_t>(len));
3,350 ✔
2087
    for (std::int64_t i = 0; i < len; ++i)
30,138 ✔
2088
        idx[static_cast<std::size_t>(i)] = offset + i;
26,788 ✔
2089
    return in.take(idx);
3,350 ✔
2090
}
37,678 ✔
2091

2092
// A failure a worker raises for the calling thread (index / rindex finding no
2093
// match); require_evaluated returns it, since a parallel worker cannot. One
2094
// per eval call, shared by its workers; the first message is kept.
2095
struct EvalError {
108,009 ✔
2096
    std::mutex mutex;
2097
    dstd::String message;
2098
    dstd::Condition condition = dstd::Condition::InvalidArgument;
27,022 ✔
2099

2100
    void set(dstd::String text,
1,225 ✔
2101
             dstd::Condition why = dstd::Condition::InvalidArgument) {
2102
        std::lock_guard<std::mutex> lock(mutex);
1,225 ✔
2103
        if (!message.empty()) return;
1,244 ✔
2104
        message = std::move(text);
1,242 ✔
2105
        condition = why;
1,231 ✔
2106
    }
1,249 !
2107
};
2108

2109
template <class T>
2110
Series const_fixed(TypeId t, const dftu_scalar& s, std::int64_t len) {
6,979 ✔
2111
    dstd::Vector<T> v(static_cast<std::size_t>(len), scalar_as<T>(s));
6,979 ✔
2112
    return Series::flat(t, v.data(), len);
6,979 ✔
2113
}
6,979 ✔
2114

2115
// A column of `len` rows of type `t`, every row holding `s` (a select arm
2116
// given as a literal). Refuses a type with no scalar form rather than build a
2117
// column whose contents would be a guess: the error goes to the calling thread
2118
// through `error` and the column is invalid.
2119
Series const_column(TypeId t, const dftu_scalar& s, std::int64_t len,
8,989 ✔
2120
                    EvalError& error) {
2121
    switch (t) {
8,989 !
2122
        case TypeId::Bool: {
378 ✔
2123
            const bool on = scalar_as<std::int64_t>(s) != 0;
756 ✔
2124
            dstd::Vector<std::uint8_t> bits(buffer_bytes(TypeId::Bool, len),
1,134 ✔
2125
                                            on ? 0xFF : 0x00);
865 ✔
2126
            return Series::flat(t, bits.data(), len);
756 ✔
2127
        }
756 ✔
2128
        case TypeId::Int8:
UNCOV
2129
            return const_fixed<std::int8_t>(t, s, len);
×
2130
        case TypeId::Int16:
UNCOV
2131
            return const_fixed<std::int16_t>(t, s, len);
×
2132
        case TypeId::Int32:
UNCOV
2133
            return const_fixed<std::int32_t>(t, s, len);
×
2134
        case TypeId::Int64:
2,772 ✔
2135
            return const_fixed<std::int64_t>(t, s, len);
5,545 ✔
2136
        case TypeId::Uint8:
UNCOV
2137
            return const_fixed<std::uint8_t>(t, s, len);
×
2138
        case TypeId::Uint16:
UNCOV
2139
            return const_fixed<std::uint16_t>(t, s, len);
×
2140
        case TypeId::Uint32:
UNCOV
2141
            return const_fixed<std::uint32_t>(t, s, len);
×
2142
        case TypeId::Uint64:
UNCOV
2143
            return const_fixed<std::uint64_t>(t, s, len);
×
2144
        case TypeId::Float32:
3 ✔
2145
            return const_fixed<float>(t, s, len);
6 ✔
2146
        case TypeId::Float64:
714 ✔
2147
            return const_fixed<double>(t, s, len);
1,428 ✔
2148
        case TypeId::String: {
627 ✔
2149
            const dftracer::utils::dstd::StringView v(
1,881 ✔
2150
                s.value.s ? s.value.s : "", s.len);
1,254 !
2151
            const dstd::Vector<dftracer::utils::dstd::StringView> rows(
1,881 ✔
2152
                static_cast<std::size_t>(len), v);
1,254 ✔
2153
            return Series::strings(
1,881 ✔
2154
                dftracer::utils::dstd::Span<
627 ✔
2155
                    const dftracer::utils::dstd::StringView>(rows));
627 ✔
2156
        }
1,254 ✔
2157
        case TypeId::Unknown:
2158
        case TypeId::Float16:
2159
        case TypeId::Binary:
2160
        case TypeId::List:
2161
        case TypeId::Struct:
2162
        case TypeId::Date32:
2163
        case TypeId::Date64:
2164
        case TypeId::Time32:
2165
        case TypeId::Time64:
2166
        case TypeId::Timestamp:
2167
        case TypeId::Duration:
2168
        case TypeId::Decimal128:
2169
        case TypeId::Decimal256:
2170
        case TypeId::FixedSizeBinary:
2171
        case TypeId::LargeString:
2172
        case TypeId::LargeBinary:
2173
        case TypeId::LargeList:
2174
        case TypeId::FixedSizeList:
2175
        case TypeId::Map:
2176
            break;
2177
    }
2178
    error.set(dstd::fmt<"expr: a literal cannot broadcast to a {} column">(
×
2179
        type_name(t)));
×
UNCOV
2180
    return {};
×
2181
}
4,495 ✔
2182

2183
// ---- duql kernels: flat loops over Int64 / Uint64 / Float64, String and Bool
2184
// columns; every unknown result is a null cell
2185
// ---------------------------------
2186

2187
Series flat_view(const Series& s) {
14,870 ✔
2188
    if (!s.valid() || s.encoding() == Encoding::Flat) return s.share();
22,304 !
2189
    return s.materialize();
34 ✔
2190
}
7,436 ✔
2191

2192
bool valid_at(const dftu_series* h, std::int64_t i) {
2,396,809 ✔
2193
    return !h->validity.block() ||
2,396,809 ✔
2194
           ((h->validity.data()[i >> 3] >> (i & 7)) & 1);
1,250,727 ✔
2195
}
2196

2197
bool bit_at(const dftu_series* h, std::int64_t i) {
50 ✔
2198
    return (h->data.data()[i >> 3] >> (i & 7)) & 1;
50 ✔
2199
}
2200

2201
template <class T>
2202
const T* values_of(const dftu_series* h) {
13,422 ✔
2203
    return h->data.block() ? reinterpret_cast<const T*>(h->data.data())
13,422 !
2204
                           : nullptr;
6,710 ✔
2205
}
2206

2207
struct TextCol {
2208
    const char* data = "";
695 ✔
2209
    const std::int32_t* off32 = nullptr;
695 ✔
2210
    const std::int64_t* off64 = nullptr;
695 ✔
2211

2212
    explicit TextCol(const dftu_series* h) {
2,085 ✔
2213
        if (h->data.block())
1,390 ✔
2214
            data = reinterpret_cast<const char*>(h->data.data());
1,390 ✔
2215
        if (h->offsets.block() && !h->wide_offsets())
1,390 !
2216
            off32 = reinterpret_cast<const std::int32_t*>(h->offsets.data());
1,390 ✔
2217
        if (h->offsets.block() && h->wide_offsets())
1,390 !
UNCOV
2218
            off64 = reinterpret_cast<const std::int64_t*>(h->offsets.data());
×
2219
    }
2,085 ✔
2220
    bool ok() const { return off32 || off64; }
875 !
2221
    dftracer::utils::dstd::StringView at(std::int64_t i) const {
565,450 ✔
2222
        if (off32)
565,450 !
2223
            return {data + off32[i],
848,175 ✔
2224
                    static_cast<std::size_t>(off32[i + 1] - off32[i])};
565,450 ✔
2225
        return {data + off64[i],
×
UNCOV
2226
                static_cast<std::size_t>(off64[i + 1] - off64[i])};
×
2227
    }
282,725 ✔
2228
};
2229

2230
dstd::Vector<std::uint8_t> bitmap(std::int64_t n) {
10,333 ✔
2231
    return dstd::Vector<std::uint8_t>(static_cast<std::size_t>((n + 7) / 8), 0);
10,333 ✔
2232
}
5,167 ✔
2233

2234
void set_bit(dstd::Vector<std::uint8_t>& bits, std::int64_t i) {
1,452,478 ✔
2235
    bits[static_cast<std::size_t>(i >> 3)] |=
1,452,478 ✔
2236
        static_cast<std::uint8_t>(1u << (i & 7));
1,452,478 ✔
2237
}
1,452,478 ✔
2238

2239
// Fixed-width output cells; a row never set is null.
2240
template <class T>
2241
class Cells {
2,875 ✔
2242
   public:
2243
    explicit Cells(std::int64_t n)
8,627 ✔
2244
        : vals_(static_cast<std::size_t>(n)), valid_(bitmap(n)) {}
11,503 ✔
2245
    void set(std::int64_t i, T v) {
626,858 ✔
2246
        vals_[static_cast<std::size_t>(i)] = v;
626,858 ✔
2247
        set_bit(valid_, i);
626,858 ✔
2248
        ++set_;
626,858 ✔
2249
    }
626,858 ✔
2250
    void set(std::int64_t i, dftracer::utils::dstd::Optional<T> v) {
345,561 !
2251
        if (v) set(i, *v);
691,044 !
2252
    }
345,522 ✔
2253
    Series finish(TypeId t) {
5,751 ✔
2254
        const auto n = static_cast<std::int64_t>(vals_.size());
5,751 ✔
2255
        const std::uint8_t* validity = set_ == n ? nullptr : valid_.data();
5,751 !
2256
        const T* data = vals_.data();
5,751 ✔
2257
        return Series::from_borrowed(t, data, n, std::move(vals_), validity);
5,751 ✔
2258
    }
2,876 ✔
2259

2260
   private:
2261
    dstd::Vector<T> vals_;
2262
    dstd::Vector<std::uint8_t> valid_;
2263
    std::int64_t set_ = 0;
2,876 ✔
2264
};
2265

2266
class BoolCells {
918 ✔
2267
   public:
2268
    explicit BoolCells(std::int64_t n)
2,754 ✔
2269
        : n_(n), bits_(bitmap(n)), valid_(bitmap(n)) {}
3,672 ✔
2270
    void set(std::int64_t i, bool v) {
293,501 ✔
2271
        if (v) set_bit(bits_, i);
293,501 ✔
2272
        set_bit(valid_, i);
293,501 ✔
2273
        ++set_;
293,501 ✔
2274
    }
293,501 ✔
2275
    Series finish() {
1,836 ✔
2276
        return Series::flat(TypeId::Bool, bits_.data(), n_,
2,754 ✔
2277
                            set_ == n_ ? nullptr : valid_.data());
1,836 ✔
2278
    }
918 ✔
2279

2280
   private:
2281
    std::int64_t n_;
2282
    dstd::Vector<std::uint8_t> bits_;
2283
    dstd::Vector<std::uint8_t> valid_;
2284
    std::int64_t set_ = 0;
918 ✔
2285
};
2286

2287
// String output rows, appended in row order.
2288
class TextCells {
2289
   public:
2290
    explicit TextCells(std::int64_t n) : n_(n), valid_(bitmap(n)) {
1,365 ✔
2291
        off_.reserve(static_cast<std::size_t>(n) + 1);
910 ✔
2292
        off_.push_back(0);
910 ✔
2293
    }
1,365 ✔
2294
    dftracer::utils::dstd::String& buf() { return data_; }
15,190 ✔
2295
    void end_row(bool valid) {
430,402 ✔
2296
        if (valid) {
430,402 ✔
2297
            set_bit(valid_, static_cast<std::int64_t>(off_.size()) - 1);
429,944 ✔
2298
            ++set_;
429,944 ✔
2299
        }
214,972 ✔
2300
        Series::check_string_bytes(data_.size());
430,402 ✔
2301
        off_.push_back(static_cast<std::int32_t>(data_.size()));
430,402 ✔
2302
    }
430,402 ✔
2303
    void add(dftracer::utils::dstd::StringView s) {
400,238 ✔
2304
        data_.append(s);
400,238 ✔
2305
        end_row(true);
400,238 ✔
2306
    }
400,238 ✔
2307
    Series finish() {
910 ✔
2308
        return Series{
910 ✔
2309
            dftu_series_new_string(DFTU_TYPE_STRING, off_.data(), data_.data(),
1,365 ✔
2310
                                   n_, set_ == n_ ? nullptr : valid_.data())};
910 ✔
2311
    }
455 ✔
2312

2313
   private:
2314
    std::int64_t n_;
2315
    dstd::Vector<std::int32_t> off_;
2316
    dftracer::utils::dstd::String data_;
2317
    dstd::Vector<std::uint8_t> valid_;
2318
    std::int64_t set_ = 0;
455 ✔
2319
};
2320

2321
// Calls fn with a value of the C++ type behind Int64, Uint64 or Float64.
2322
template <class Fn>
2323
void with_num(TypeId t, Fn&& fn) {
13,446 ✔
2324
    if (t == TypeId::Int64)
13,446 !
2325
        fn(std::int64_t{});
7,357 ✔
2326
    else if (t == TypeId::Uint64)
6,089 !
2327
        fn(std::uint64_t{});
3,466 ✔
2328
    else
2329
        fn(double{});
2,623 ✔
2330
}
13,446 ✔
2331

2332
template <class T>
2333
constexpr bool IS_DOUBLE = std::is_same_v<T, double>;
2334

2335
template <class T>
2336
int order(T a, T b) {
292,887 ✔
2337
    return a < b ? -1 : (b < a ? 1 : 0);
292,887 ✔
2338
}
2339

2340
// Exact comparison of an integer with a double, as the duql evaluator does
2341
// it: the integer is never rounded to a double.
2342
dftracer::utils::dstd::Optional<int> cmp_num(std::int64_t a, double d) {
8,126 ✔
2343
    constexpr double TWO_POW_63 = 9223372036854775808.0;
8,126 ✔
2344
    if (std::isnan(d)) return dftracer::utils::dstd::nullopt;
8,126 ✔
2345
    if (d >= TWO_POW_63) return -1;
8,120 ✔
2346
    if (d < -TWO_POW_63) return 1;
8,094 !
2347
    const double f = std::floor(d);
8,094 ✔
2348
    const auto fi = static_cast<std::int64_t>(f);
8,094 ✔
2349
    if (a != fi) return order(a, fi);
8,094 ✔
2350
    return d > f ? -1 : 0;
259 ✔
2351
}
4,063 ✔
2352

2353
dftracer::utils::dstd::Optional<int> cmp_num(std::uint64_t a, double d) {
17,132 ✔
2354
    constexpr double TWO_POW_64 = 18446744073709551616.0;
17,132 ✔
2355
    if (std::isnan(d)) return dftracer::utils::dstd::nullopt;
17,132 !
2356
    if (d < 0) return 1;
17,132 ✔
2357
    if (d >= TWO_POW_64) return -1;
17,130 ✔
2358
    const double f = std::floor(d);
17,128 ✔
2359
    const auto fu = static_cast<std::uint64_t>(f);
17,128 ✔
2360
    if (a != fu) return order(a, fu);
17,128 ✔
2361
    return d > f ? -1 : 0;
34 ✔
2362
}
8,566 ✔
2363

2364
dftracer::utils::dstd::Optional<int> cmp_num(std::int64_t a, std::uint64_t b) {
71,570 ✔
2365
    if (a < 0) return -1;
71,570 ✔
2366
    return order(static_cast<std::uint64_t>(a), b);
71,562 ✔
2367
}
35,785 ✔
2368

2369
dftracer::utils::dstd::Optional<int> flip(
79,616 ✔
2370
    dftracer::utils::dstd::Optional<int> c) {
2371
    if (c) return -*c;
79,616 ✔
2372
    return c;
2 ✔
2373
}
39,808 ✔
2374

2375
template <class A, class B>
2376
dftracer::utils::dstd::Optional<int> cmp_numbers(A a, B b) {
211,516 ✔
2377
    if constexpr (std::is_same_v<A, B>) {
2378
        if constexpr (IS_DOUBLE<A>)
2379
            if (std::isnan(a) || std::isnan(b))
51,038 !
2380
                return dftracer::utils::dstd::nullopt;
2 ✔
2381
        return order(a, b);
114,686 ✔
2382
    } else if constexpr (IS_DOUBLE<A>) {
2383
        return flip(cmp_num(b, a));
8,054 ✔
2384
    } else if constexpr (IS_DOUBLE<B>) {
2385
        return cmp_num(a, b);
17,204 ✔
2386
    } else if constexpr (std::is_same_v<A, std::int64_t>) {
2387
        return cmp_num(a, b);
8 ✔
2388
    } else {
2389
        return flip(cmp_num(b, a));
71,562 ✔
2390
    }
2391
}
105,746 ✔
2392

2393
bool apply_cmp(CmpOp op, int c) {
293,086 ✔
2394
    switch (op) {
293,086 ✔
2395
        case CmpOp::Gt:
59,773 ✔
2396
            return c > 0;
119,522 ✔
2397
        case CmpOp::Ge:
80 ✔
2398
            return c >= 0;
160 ✔
2399
        case CmpOp::Lt:
42,547 ✔
2400
            return c < 0;
85,094 ✔
2401
        case CmpOp::Le:
9 ✔
2402
            return c <= 0;
18 ✔
2403
        case CmpOp::Eq:
40,073 ✔
2404
            return c == 0;
80,146 ✔
2405
        case CmpOp::Ne:
4,073 ✔
2406
            return c != 0;
8,146 ✔
2407
    }
2408
    return false;
2409
}
146,531 ✔
2410

2411
// An integer as sign and magnitude, so int64 and uint64 mix without loss.
2412
struct Int {
2413
    bool neg = false;
2414
    std::uint64_t mag = 0;
2415
};
2416

2417
constexpr std::uint64_t U64_MAX = std::numeric_limits<std::uint64_t>::max();
2418
constexpr std::uint64_t I64_MIN_MAG = std::uint64_t{1} << 63;
2419

2420
Int int_of(std::int64_t v) {
1,006,130 ✔
2421
    if (v < 0) return {true, std::uint64_t{0} - static_cast<std::uint64_t>(v)};
1,006,130 ✔
2422
    return {false, static_cast<std::uint64_t>(v)};
663,116 ✔
2423
}
503,065 ✔
2424
Int int_of(std::uint64_t v) { return {false, v}; }
178,326 ✔
2425

2426
dftracer::utils::dstd::Optional<std::int64_t> i64_of(Int x) {
430,508 ✔
2427
    if (!x.neg) {
430,508 ✔
2428
        if (x.mag > static_cast<std::uint64_t>(
639,174 ✔
2429
                        std::numeric_limits<std::int64_t>::max()))
213,058 ✔
2430
            return dftracer::utils::dstd::nullopt;
28 ✔
2431
        return static_cast<std::int64_t>(x.mag);
426,088 ✔
2432
    }
2433
    if (x.mag > I64_MIN_MAG) return dftracer::utils::dstd::nullopt;
4,392 ✔
2434
    return static_cast<std::int64_t>(std::uint64_t{0} - x.mag);
4,388 ✔
2435
}
215,254 ✔
2436

2437
dftracer::utils::dstd::Optional<Int> int_add(Int a, Int b) {
110,134 ✔
2438
    if (a.neg == b.neg) {
110,134 ✔
2439
        if (a.mag > U64_MAX - b.mag) return dftracer::utils::dstd::nullopt;
83,162 !
2440
        return Int{a.neg, a.mag + b.mag};
83,162 ✔
2441
    }
2442
    if (a.mag >= b.mag) return Int{a.neg, a.mag - b.mag};
26,972 ✔
2443
    return Int{b.neg, b.mag - a.mag};
528 ✔
2444
}
55,067 ✔
2445

2446
dftracer::utils::dstd::Optional<std::int64_t> int_arith(ArithOp op, Int a,
590,130 ✔
2447
                                                        Int b) {
2448
    dftracer::utils::dstd::Optional<Int> out;
590,130 ✔
2449
    switch (op) {
590,130 !
2450
        case ArithOp::Add:
41,579 ✔
2451
            out = int_add(a, b);
83,158 ✔
2452
            break;
83,158 ✔
2453
        case ArithOp::Sub:
13,479 ✔
2454
            out = int_add(a, Int{!b.neg, b.mag});
26,958 ✔
2455
            break;
26,958 ✔
2456
        case ArithOp::Mul:
37,727 ✔
2457
            if (a.mag != 0 && b.mag > U64_MAX / a.mag)
75,454 ✔
2458
                return dftracer::utils::dstd::nullopt;
2 ✔
2459
            out = Int{a.neg != b.neg, a.mag * b.mag};
75,452 ✔
2460
            break;
75,452 ✔
2461
        case ArithOp::FloorDiv: {
180 ✔
2462
            if (b.mag == 0) return dftracer::utils::dstd::nullopt;
360 ✔
2463
            Int q{a.neg != b.neg, a.mag / b.mag};
352 ✔
2464
            if (q.neg && a.mag % b.mag != 0) ++q.mag;
352 ✔
2465
            out = q;
352 ✔
2466
            break;
176 ✔
2467
        }
176 ✔
2468
        case ArithOp::Mod: {
202,100 ✔
2469
            if (b.mag == 0) return dftracer::utils::dstd::nullopt;
404,200 ✔
2470
            std::uint64_t rem = a.mag % b.mag;
335,624 ✔
2471
            if (rem != 0 && a.neg != b.neg) rem = b.mag - rem;
335,624 ✔
2472
            out = Int{b.neg, rem};
335,624 ✔
2473
            break;
167,812 ✔
2474
        }
167,812 ✔
2475
        case ArithOp::Div:
UNCOV
2476
            return dftracer::utils::dstd::nullopt;
×
2477
    }
2478
    if (!out) return dftracer::utils::dstd::nullopt;
521,544 ✔
2479
    if (out->mag == 0) return 0;
521,544 ✔
2480
    return i64_of(*out);
366,988 ✔
2481
}
295,065 ✔
2482

2483
dftracer::utils::dstd::Optional<double> of_double(double d) {
36,696 ✔
2484
    if (std::isnan(d)) return dftracer::utils::dstd::nullopt;
36,696 ✔
2485
    return d;
36,688 ✔
2486
}
18,348 ✔
2487

2488
dftracer::utils::dstd::Optional<double> dbl_arith(ArithOp op, double a,
30,412 ✔
2489
                                                  double b) {
2490
    switch (op) {
30,412 ✔
2491
        case ArithOp::Add:
2,316 ✔
2492
            return of_double(a + b);
4,632 ✔
2493
        case ArithOp::Sub:
1,712 ✔
2494
            return of_double(a - b);
3,424 ✔
2495
        case ArithOp::Mul:
10,522 ✔
2496
            return of_double(a * b);
21,044 ✔
2497
        case ArithOp::Div:
322 ✔
2498
            if (b == 0) return dftracer::utils::dstd::nullopt;
644 ✔
2499
            return of_double(a / b);
636 ✔
2500
        case ArithOp::FloorDiv:
323 ✔
2501
            if (b == 0) return dftracer::utils::dstd::nullopt;
646 ✔
2502
            return of_double(std::floor(a / b));
642 ✔
2503
        case ArithOp::Mod: {
11 ✔
2504
            if (b == 0) return dftracer::utils::dstd::nullopt;
22 ✔
2505
            double rem = std::fmod(a, b);
18 ✔
2506
            if (rem != 0 && (rem < 0) != (b < 0)) rem += b;
18 ✔
2507
            return of_double(rem);
18 ✔
2508
        }
9 ✔
2509
    }
UNCOV
2510
    return dftracer::utils::dstd::nullopt;
×
2511
}
15,206 ✔
2512

2513
// A number as the output type R: past int64 is null, NaN is null.
2514
template <class R, class V>
2515
dftracer::utils::dstd::Optional<R> num_as(V v) {
59,748 ✔
2516
    if constexpr (IS_DOUBLE<R>) {
2517
        return of_double(static_cast<double>(v));
14 ✔
2518
    } else if constexpr (std::is_same_v<R, V>) {
2519
        return v;
58 ✔
2520
    } else if constexpr (std::is_same_v<R, std::int64_t> &&
2521
                         std::is_same_v<V, std::uint64_t>) {
2522
        return i64_of(Int{false, v});
59,676 ✔
2523
    } else {
UNCOV
2524
        return dftracer::utils::dstd::nullopt;
×
2525
    }
2526
}
29,874 ✔
2527

2528
// A double truncated to int64; null when it is not finite or out of range.
2529
dftracer::utils::dstd::Optional<std::int64_t> trunc_i64(double d) {
2,738 ✔
2530
    if (!std::isfinite(d)) return dftracer::utils::dstd::nullopt;
2,738 ✔
2531
    const double t = std::trunc(d);
2,732 ✔
2532
    if (t >= -9223372036854775808.0 && t < 9223372036854775808.0)
2,732 ✔
2533
        return static_cast<std::int64_t>(t);
1,958 ✔
2534
    return dftracer::utils::dstd::nullopt;
774 ✔
2535
}
1,369 ✔
2536

2537
bool same_rows(const dftu_series* a, const dftu_series* b) {
6,355 ✔
2538
    return a && b && a->length == b->length;
6,355 !
2539
}
2540

2541
Series arith_kernel(const Series& sa, const Series& sb, std::int32_t code) {
4,351 ✔
2542
    const Series fa = flat_view(sa);
4,351 ✔
2543
    const Series fb = flat_view(sb);
4,351 ✔
2544
    const dftu_series* a = fa.handle();
4,351 !
2545
    const dftu_series* b = fb.handle();
4,351 ✔
2546
    if (!same_rows(a, b)) return {};
4,351 !
2547
    const auto op = static_cast<ArithOp>(code);
4,351 ✔
2548
    const std::int64_t n = a->length;
4,351 ✔
2549
    const TypeId t = arith_type(code, a->type, b->type);
4,351 ✔
2550
    Series out;
4,351 ✔
2551
    with_num(a->type, [&](auto xa) {
8,702 ✔
2552
        with_num(b->type, [&](auto xb) {
1,317,595 ✔
2553
            using A = decltype(xa);
2554
            using B = decltype(xb);
2555
            const A* pa = values_of<A>(a);
6,526 ✔
2556
            const B* pb = values_of<B>(b);
4,351 ✔
2557
            if constexpr (!IS_DOUBLE<A>) {
2558
                if constexpr (!IS_DOUBLE<B>) {
2559
                    if (t == TypeId::Int64) {
5,811 ✔
2560
                        Cells<std::int64_t> c(n);
5,769 ✔
2561
                        for (std::int64_t i = 0; i < n; ++i)
650,956 ✔
2562
                            if (valid_at(a, i) && valid_at(b, i))
942,427 ✔
2563
                                c.set(i, int_arith(op, int_of(pa[i]),
887,370 ✔
2564
                                                   int_of(pb[i])));
590,130 !
2565
                        out = c.finish(TypeId::Int64);
5,769 !
2566
                        return;
1,797 ✔
2567
                    }
3,594 ✔
2568
                }
2569
            }
2570
            Cells<double> c(n);
757 ✔
2571
            for (std::int64_t i = 0; i < n; ++i)
33,009 !
2572
                if (valid_at(a, i) && valid_at(b, i))
47,458 !
2573
                    c.set(i, dbl_arith(op, static_cast<double>(pa[i]),
60,815 !
2574
                                       static_cast<double>(pb[i])));
30,412 ✔
2575
            out = c.finish(TypeId::Float64);
757 !
2576
        });
2,197 !
2577
    });
4,351 ✔
2578
    return out;
4,351 ✔
2579
}
6,526 !
2580

2581
Series neg_kernel(const Series& sa) {
30 ✔
2582
    const Series fa = flat_view(sa);
30 ✔
2583
    const dftu_series* a = fa.handle();
30 !
2584
    if (!a) return {};
30 ✔
2585
    const std::int64_t n = a->length;
30 ✔
2586
    Series out;
30 ✔
2587
    with_num(a->type, [&](auto xa) {
60 ✔
2588
        using A = decltype(xa);
2589
        const A* pa = values_of<A>(a);
1,960 ✔
2590
        if constexpr (IS_DOUBLE<A>) {
2591
            Cells<double> c(n);
1,961 ✔
2592
            for (std::int64_t i = 0; i < n; ++i)
4 ✔
2593
                if (valid_at(a, i)) c.set(i, of_double(-pa[i]));
3 !
2594
            out = c.finish(TypeId::Float64);
16 !
2595
        } else {
2 ✔
2596
            Cells<std::int64_t> c(n);
28 ✔
2597
            for (std::int64_t i = 0; i < n; ++i) {
3,886 ✔
2598
                if (!valid_at(a, i)) continue;
3,858 !
2599
                const Int x = int_of(pa[i]);
3,850 ✔
2600
                c.set(i, x.mag == 0
7,698 ✔
2601
                             ? dftracer::utils::dstd::Optional<std::int64_t>{0}
24 ✔
2602
                             : i64_of(Int{!x.neg, x.mag}));
3,826 ✔
2603
            }
1,925 ✔
2604
            out = c.finish(TypeId::Int64);
28 !
2605
        }
28 ✔
2606
    });
30 ✔
2607
    return out;
30 ✔
2608
}
30 !
2609

2610
bool is_num_col(const dftu_series* h) {
3,116 ✔
2611
    return h->type == TypeId::Int64 || h->type == TypeId::Uint64 ||
3,116 ✔
2612
           h->type == TypeId::Float64;
2,485 ✔
2613
}
2614

2615
// -1/0/1 of row i of `a` against row i of `b` (both present), per domain:
2616
// numbers exactly, strings bytewise, false before true; fn gets the order or
2617
// nullopt when the two do not compare (a NaN).
2618
template <class Fn>
2619
bool order_rows(const dftu_series* a, const dftu_series* b, Fn&& fn) {
1,772 ✔
2620
    const std::int64_t n = a->length;
1,772 ✔
2621
    if (is_num_col(a) && is_num_col(b)) {
1,772 !
2622
        with_num(a->type, [&](auto xa) {
3,255 ✔
2623
            with_num(b->type, [&](auto xb) {
428,035 ✔
2624
                using A = decltype(xa);
2625
                using B = decltype(xb);
2626
                const A* pa = values_of<A>(a);
1,302 ✔
2627
                const B* pb = values_of<B>(b);
1,302 ✔
2628
                for (std::int64_t i = 0; i < n; ++i)
213,805 !
2629
                    if (valid_at(a, i) && valid_at(b, i))
318,242 !
2630
                        fn(i, cmp_numbers(pa[i], pb[i]));
211,502 ✔
2631
            });
651 ✔
2632
        });
651 ✔
2633
        return true;
1,302 ✔
2634
    }
2635
    if (a->type == TypeId::Bool && b->type == TypeId::Bool) {
470 !
2636
        for (std::int64_t i = 0; i < n; ++i)
8 !
2637
            if (valid_at(a, i) && valid_at(b, i))
9 !
2638
                fn(i, dftracer::utils::dstd::Optional<int>(
9 ✔
2639
                          order(bit_at(a, i), bit_at(b, i))));
6 ✔
2640
        return true;
1 ✔
2641
    }
2642
    const TextCol ta(a), tb(b);
468 ✔
2643
    if (!is_text_type(a->type) || !is_text_type(b->type) || !ta.ok() ||
702 !
2644
        !tb.ok())
42,428 ✔
2645
        return false;
2646
    for (std::int64_t i = 0; i < n; ++i)
82,616 ✔
2647
        if (valid_at(a, i) && valid_at(b, i))
122,982 !
2648
            fn(i,
122,502 ✔
2649
               dftracer::utils::dstd::Optional<int>(order(ta.at(i), tb.at(i))));
81,668 ✔
2650
    return true;
234 ✔
2651
}
886 ✔
2652

2653
Series cmp_expr_kernel(const Series& sa, const Series& sb, std::int32_t code) {
1,744 ✔
2654
    const Series fa = flat_view(sa);
1,744 ✔
2655
    const Series fb = flat_view(sb);
1,744 ✔
2656
    const dftu_series* a = fa.handle();
1,744 !
2657
    const dftu_series* b = fb.handle();
1,744 ✔
2658
    if (!same_rows(a, b)) return {};
1,744 !
2659
    const auto op = static_cast<CmpOp>(code);
1,744 ✔
2660
    BoolCells c(a->length);
1,744 ✔
2661
    if (!order_rows(
2,616 !
2662
            a, b, [&](std::int64_t i, dftracer::utils::dstd::Optional<int> o) {
148,279 !
2663
                if (o) c.set(i, apply_cmp(op, *o));
293,093 ✔
2664
            }))
293,093 ✔
2665
        return {};
872 ✔
2666
    return c.finish();
1,744 ✔
2667
}
2,616 !
2668

2669
Series extreme_kernel(const Series& sa, const Series& sb, bool least) {
28 ✔
2670
    const Series fa = flat_view(sa);
28 ✔
2671
    const Series fb = flat_view(sb);
28 ✔
2672
    const dftu_series* a = fa.handle();
28 !
2673
    const dftu_series* b = fb.handle();
28 ✔
2674
    if (!same_rows(a, b)) return {};
42 !
2675
    const std::int64_t n = a->length;
28 ✔
2676
    const int want = least ? -1 : 1;
28 ✔
2677
    // Row i takes b only when b is strictly beyond a, as duql keeps the
2678
    // first of equal operands.
2679
    dstd::Vector<char> take_b(static_cast<std::size_t>(n), 0);
28 ✔
2680
    dstd::Vector<char> known(static_cast<std::size_t>(n), 0);
28 ✔
2681
    if (!order_rows(
42 !
2682
            b, a, [&](std::int64_t i, dftracer::utils::dstd::Optional<int> o) {
70 !
2683
                if (!o) return;
84 ✔
2684
                known[static_cast<std::size_t>(i)] = 1;
82 ✔
2685
                take_b[static_cast<std::size_t>(i)] = *o == want;
82 ✔
2686
            }))
83 ✔
UNCOV
2687
        return {};
×
2688
    auto pick = [&](std::int64_t i) {
110 ✔
2689
        return take_b[static_cast<std::size_t>(i)] != 0;
82 ✔
2690
    };
14 ✔
2691
    auto have = [&](std::int64_t i) {
130 ✔
2692
        return known[static_cast<std::size_t>(i)] != 0;
102 ✔
2693
    };
14 ✔
2694
    if (is_num_col(a)) {
28 ✔
2695
        Series out;
26 ✔
2696
        const TypeId t = promote(a->type, b->type);
26 ✔
2697
        with_num(t, [&](auto xr) {
52 ✔
2698
            with_num(a->type, [&](auto xa) {
78 ✔
2699
                with_num(b->type, [&](auto xb) {
101 ✔
2700
                    using R = decltype(xr);
2701
                    using A = decltype(xa);
2702
                    using B = decltype(xb);
2703
                    const A* pa = values_of<A>(a);
26 ✔
2704
                    const B* pb = values_of<B>(b);
26 ✔
2705
                    Cells<R> c(n);
39 ✔
2706
                    for (std::int64_t i = 0; i < n; ++i)
124 !
2707
                        if (have(i))
150 !
2708
                            c.set(i, pick(i) ? num_as<R>(pb[i])
130 !
2709
                                             : num_as<R>(pa[i]));
44 ✔
2710
                    out = c.finish(t);
39 !
2711
                });
26 ✔
2712
            });
13 ✔
2713
        });
26 ✔
2714
        return out;
26 ✔
2715
    }
26 !
2716
    if (a->type == TypeId::Bool) {
2 !
2717
        BoolCells c(n);
×
2718
        for (std::int64_t i = 0; i < n; ++i)
×
2719
            if (have(i)) c.set(i, pick(i) ? bit_at(b, i) : bit_at(a, i));
×
2720
        return c.finish();
×
UNCOV
2721
    }
×
2722
    const TextCol ta(a), tb(b);
2 ✔
2723
    TextCells c(n);
2 ✔
2724
    for (std::int64_t i = 0; i < n; ++i) {
6 ✔
2725
        if (have(i))
4 !
2726
            c.add(pick(i) ? tb.at(i) : ta.at(i));
4 ✔
2727
        else
UNCOV
2728
            c.end_row(false);
×
2729
    }
2 ✔
2730
    return c.finish();
2 ✔
2731
}
42 !
2732

2733
Series to_i64_kernel(const Series& sa) {
6 ✔
2734
    const Series fa = flat_view(sa);
6 ✔
2735
    const dftu_series* a = fa.handle();
6 !
2736
    if (!a || a->type != TypeId::Uint64) return {};
6 !
2737
    const auto* p = values_of<std::uint64_t>(a);
6 ✔
2738
    Cells<std::int64_t> c(a->length);
6 ✔
2739
    for (std::int64_t i = 0; i < a->length; ++i)
18 ✔
2740
        if (valid_at(a, i)) c.set(i, i64_of(Int{false, p[i]}));
16 ✔
2741
    return c.finish(TypeId::Int64);
6 ✔
2742
}
6 !
2743

2744
// Round half away from zero to `digits` decimals, as the duql evaluator
2745
// does; an integer operand comes back as Int64.
2746
Series round_kernel(const Series& sa, std::int64_t digits) {
50 ✔
2747
    const Series fa = flat_view(sa);
50 ✔
2748
    const dftu_series* a = fa.handle();
50 !
2749
    if (!a) return {};
50 ✔
2750
    const std::int64_t n = a->length;
50 ✔
2751
    const bool integer = a->type != TypeId::Float64;
50 ✔
2752
    const bool in_range = digits >= -308 && digits <= 308;
50 !
2753
    const double scale = std::pow(10.0, static_cast<double>(digits));
50 ✔
2754
    Series out;
50 ✔
2755
    with_num(a->type, [&](auto xa) {
100 ✔
2756
        using A = decltype(xa);
2757
        const A* pa = values_of<A>(a);
3,144 ✔
2758
        auto rounded = [&](std::int64_t i) {
6,226 ✔
2759
            return std::round(static_cast<double>(pa[i]) * scale) / scale;
6,201 ✔
2760
        };
2761
        if (integer) {
50 !
2762
            Cells<std::int64_t> c(n);
3,150 ✔
2763
            for (std::int64_t i = 0; i < n; ++i)
6 !
2764
                if (in_range && valid_at(a, i)) c.set(i, trunc_i64(rounded(i)));
6 !
2765
            out = c.finish(TypeId::Int64);
2 !
2766
        } else {
2 ✔
2767
            Cells<double> c(n);
48 ✔
2768
            for (std::int64_t i = 0; i < n; ++i)
6,242 !
2769
                if (in_range && valid_at(a, i)) c.set(i, of_double(rounded(i)));
9,280 !
2770
            out = c.finish(TypeId::Float64);
48 !
2771
        }
48 ✔
2772
    });
50 ✔
2773
    return out;
50 ✔
2774
}
50 !
2775

2776
Series log_kernel(const Series& sa) {
4 ✔
2777
    const Series fa = flat_view(sa);
4 ✔
2778
    const dftu_series* a = fa.handle();
4 !
2779
    if (!a) return {};
4 ✔
2780
    Cells<double> c(a->length);
4 ✔
2781
    with_num(a->type, [&](auto xa) {
8 ✔
2782
        using A = decltype(xa);
2783
        const A* pa = values_of<A>(a);
18 ✔
2784
        for (std::int64_t i = 0; i < a->length; ++i) {
28 !
2785
            const auto d = static_cast<double>(pa[i]);
24 ✔
2786
            if (valid_at(a, i) && d > 0) c.set(i, std::log(d));
24 !
2787
        }
12 ✔
2788
    });
4 ✔
2789
    return c.finish(TypeId::Float64);
4 ✔
2790
}
4 !
2791

2792
Series pow_kernel(const Series& sa, const Series& sb) {
6 ✔
2793
    const Series fa = flat_view(sa);
6 ✔
2794
    const Series fb = flat_view(sb);
6 ✔
2795
    const dftu_series* a = fa.handle();
6 !
2796
    const dftu_series* b = fb.handle();
6 ✔
2797
    if (!same_rows(a, b)) return {};
6 !
2798
    Cells<double> c(a->length);
6 ✔
2799
    with_num(a->type, [&](auto xa) {
12 ✔
2800
        with_num(b->type, [&](auto xb) {
55 ✔
2801
            using A = decltype(xa);
2802
            using B = decltype(xb);
2803
            const A* pa = values_of<A>(a);
9 ✔
2804
            const B* pb = values_of<B>(b);
6 ✔
2805
            for (std::int64_t i = 0; i < a->length; ++i)
30 !
2806
                if (valid_at(a, i) && valid_at(b, i))
35 !
2807
                    c.set(i, of_double(std::pow(static_cast<double>(pa[i]),
36 ✔
2808
                                                static_cast<double>(pb[i]))));
22 !
2809
        });
3 ✔
2810
    });
6 ✔
2811
    return c.finish(TypeId::Float64);
6 ✔
2812
}
9 !
2813

2814
bool utf8_continuation(char c) {
1,200,230 ✔
2815
    return (static_cast<unsigned char>(c) & 0xC0) == 0x80;
1,200,230 ✔
2816
}
2817

2818
// Byte offset of code point `n` in `s`, or s.size() past the end.
2819
std::size_t utf8_offset(dftracer::utils::dstd::StringView s, std::uint64_t n) {
800,212 ✔
2820
    std::size_t i = 0;
800,212 ✔
2821
    while (i < s.size() && n > 0) {
1,600,500 ✔
2822
        ++i;
800,288 ✔
2823
        while (i < s.size() && utf8_continuation(s[i])) ++i;
1,200,298 ✔
2824
        --n;
800,288 ✔
2825
    }
2826
    return i;
1,200,318 ✔
2827
}
400,106 ✔
2828

2829
Series substr_kernel(const Series& sa, std::int64_t start, std::int64_t len) {
22 ✔
2830
    const Series fa = flat_view(sa);
22 ✔
2831
    const dftu_series* a = fa.handle();
22 !
2832
    if (!a || !is_text_type(a->type)) return {};
22 !
2833
    const TextCol ta(a);
22 ✔
2834
    if (!ta.ok()) return {};
33 !
2835
    TextCells c(a->length);
22 ✔
2836
    for (std::int64_t i = 0; i < a->length; ++i) {
400,082 ✔
2837
        if (start < 0 || !valid_at(a, i)) {
400,060 ✔
2838
            c.end_row(false);
16 ✔
2839
            continue;
16 ✔
2840
        }
2841
        const dftracer::utils::dstd::StringView s = ta.at(i);
400,044 ✔
2842
        const dftracer::utils::dstd::StringView rest =
400,044 ✔
2843
            s.substr(utf8_offset(s, static_cast<std::uint64_t>(start)));
400,044 ✔
2844
        c.add(len < 0
600,057 ✔
2845
                  ? rest
9 ✔
2846
                  : rest.substr(
400,026 ✔
2847
                        0, utf8_offset(rest, static_cast<std::uint64_t>(len))));
200,013 ✔
2848
    }
200,022 ✔
2849
    return c.finish();
22 ✔
2850
}
22 ✔
2851

2852
// A time operand as whole units: a Float64 is floored, and a NaN, an infinity
2853
// or a value past int64 is null.
2854
template <class T>
2855
dftracer::utils::dstd::Optional<std::int64_t> time_units(T x) {
5,816 ✔
2856
    if constexpr (IS_DOUBLE<T>) {
2857
        return trunc_i64(std::floor(x));
2,700 ✔
2858
    } else if constexpr (std::is_same_v<T, std::uint64_t>) {
2859
        if (x > static_cast<std::uint64_t>(
60 ✔
2860
                    std::numeric_limits<std::int64_t>::max()))
20 ✔
2861
            return dftracer::utils::dstd::nullopt;
2 ✔
2862
        return static_cast<std::int64_t>(x);
38 ✔
2863
    } else {
2864
        return x;
3,076 ✔
2865
    }
2866
}
2,908 ✔
2867

2868
Series date_part_kernel(const Series& sa, std::int32_t part,
874 ✔
2869
                        std::int64_t ns_per_unit) {
2870
    const Series fa = flat_view(sa);
874 ✔
2871
    const dftu_series* a = fa.handle();
874 !
2872
    if (!a) return {};
874 ✔
2873
    Cells<std::int64_t> c(a->length);
874 ✔
2874
    with_num(a->type, [&](auto xa) {
1,748 ✔
2875
        using A = decltype(xa);
2876
        const A* pa = values_of<A>(a);
4,192 ✔
2877
        const auto p = static_cast<common::DatePart>(part);
874 ✔
2878
        for (std::int64_t i = 0; i < a->length; ++i) {
6,636 ✔
2879
            if (!valid_at(a, i)) continue;
5,762 ✔
2880
            if (const auto t = time_units<A>(pa[i]))
7,288 ✔
2881
                c.set(i, common::date_part(common::civil_time(*t, ns_per_unit),
6,612 ✔
2882
                                           p));
2,204 ✔
2883
        }
2,542 ✔
2884
    });
874 ✔
2885
    return c.finish(TypeId::Int64);
874 ✔
2886
}
874 !
2887

2888
Series format_time_kernel(const Series& sa,
138 ✔
2889
                          dftracer::utils::dstd::StringView fmt,
2890
                          std::int64_t ns_per_unit) {
2891
    const Series fa = flat_view(sa);
138 ✔
2892
    const dftu_series* a = fa.handle();
138 !
2893
    if (!a) return {};
207 !
2894
    TextCells c(a->length);
138 ✔
2895
    with_num(a->type, [&](auto xa) {
276 ✔
2896
        using A = decltype(xa);
2897
        const A* pa = values_of<A>(a);
624 ✔
2898
        for (std::int64_t i = 0; i < a->length; ++i) {
972 ✔
2899
            const auto t = valid_at(a, i) ? time_units<A>(pa[i])
834 !
2900
                                          : dftracer::utils::dstd::nullopt;
51 ✔
2901
            if (t)
834 !
2902
                common::format_time(c.buf(),
1,368 ✔
2903
                                    common::civil_time(*t, ns_per_unit), fmt);
951 ✔
2904
            c.end_row(t.has_value());
834 ✔
2905
        }
417 ✔
2906
    });
138 ✔
2907
    return c.finish();
138 ✔
2908
}
138 ✔
2909

2910
Series extract_kernel(const Series& sa, const duql::CompiledPattern& p,
24 ✔
2911
                      std::size_t group) {
2912
    const Series fa = flat_view(sa);
24 ✔
2913
    const dftu_series* a = fa.handle();
24 !
2914
    if (!a || !is_text_type(a->type)) return {};
24 !
2915
    const TextCol ta(a);
24 ✔
2916
    if (!ta.ok()) return {};
36 !
2917
    TextCells c(a->length);
24 ✔
2918
    for (std::int64_t i = 0; i < a->length; ++i) {
124 ✔
2919
        dftracer::utils::dstd::StringView m;
100 ✔
2920
        if (valid_at(a, i) &&
139 ✔
2921
            duql::extract(p, ta.at(i), group, m) == duql::MatchResult::Yes)
78 ✔
2922
            c.add(m);
46 ✔
2923
        else
2924
            c.end_row(false);
54 ✔
2925
    }
50 ✔
2926
    return c.finish();
24 ✔
2927
}
24 ✔
2928

2929
// An integer operand column as the scan evaluator reads one: a Float64 cell
2930
// is not an integer and reads as null.
2931
struct IntCol {
2932
    const dftu_series* h;
2933
    const void* p;
2934
    explicit IntCol(const dftu_series* s)
135 ✔
2935
        : h(s), p(s->data.block() ? s->data.data() : nullptr) {}
135 !
2936
    dftracer::utils::dstd::Optional<Int> at(std::int64_t i) const {
382 ✔
2937
        if (!valid_at(h, i)) return dftracer::utils::dstd::nullopt;
382 ✔
2938
        if (h->type == TypeId::Int64)
350 ✔
2939
            return int_of(static_cast<const std::int64_t*>(p)[i]);
328 ✔
2940
        if (h->type == TypeId::Uint64)
22 !
UNCOV
2941
            return int_of(static_cast<const std::uint64_t*>(p)[i]);
×
2942
        return dftracer::utils::dstd::nullopt;
22 ✔
2943
    }
191 ✔
2944
};
2945

2946
Series str_pred_col_kernel(const Series& sa, const Series& sb,
84 ✔
2947
                           std::int32_t code) {
2948
    const Series fa = flat_view(sa);
84 ✔
2949
    const Series fb = flat_view(sb);
84 ✔
2950
    const dftu_series* a = fa.handle();
84 !
2951
    const dftu_series* b = fb.handle();
84 ✔
2952
    if (!same_rows(a, b)) return {};
84 !
2953
    const TextCol ta(a);
84 ✔
2954
    const TextCol tb(b);
84 ✔
2955
    if (!ta.ok() || !tb.ok()) return {};
84 ✔
2956
    const auto op = static_cast<StrPredOp>(code);
84 ✔
2957
    BoolCells c(a->length);
84 ✔
2958
    for (std::int64_t i = 0; i < a->length; ++i) {
624 ✔
2959
        if (!valid_at(a, i) || !valid_at(b, i)) continue;
540 ✔
2960
        const dftracer::utils::dstd::StringView s = ta.at(i);
392 ✔
2961
        const dftracer::utils::dstd::StringView n = tb.at(i);
392 ✔
2962
        bool hit = false;
392 ✔
2963
        if (op == StrPredOp::StartsWith)
392 ✔
2964
            hit = s.starts_with(n);
180 ✔
2965
        else if (op == StrPredOp::EndsWith)
212 ✔
2966
            hit = s.ends_with(n);
78 ✔
2967
        else
2968
            hit = duql::detail::substr_find(s, n) >= 0;
134 ✔
2969
        c.set(i, hit);
392 ✔
2970
    }
196 ✔
2971
    return c.finish();
84 ✔
2972
}
126 !
2973

2974
Series str_replace_col_kernel(const Series& sa, const Series& sb,
32 ✔
2975
                              const Series& sc) {
2976
    const Series fa = flat_view(sa);
32 ✔
2977
    const Series fb = flat_view(sb);
32 ✔
2978
    const Series fc = flat_view(sc);
32 ✔
2979
    const dftu_series* a = fa.handle();
32 !
2980
    const dftu_series* b = fb.handle();
32 ✔
2981
    const dftu_series* d = fc.handle();
32 ✔
2982
    if (!same_rows(a, b) || !same_rows(a, d)) return {};
32 !
2983
    const TextCol ta(a);
32 ✔
2984
    const TextCol tb(b);
32 ✔
2985
    const TextCol td(d);
32 ✔
2986
    if (!ta.ok() || !tb.ok() || !td.ok()) return {};
48 !
2987
    TextCells c(a->length);
32 ✔
2988
    for (std::int64_t i = 0; i < a->length; ++i) {
256 ✔
2989
        if (!valid_at(a, i) || !valid_at(b, i) || !valid_at(d, i)) {
224 ✔
2990
            c.end_row(false);
60 ✔
2991
            continue;
60 ✔
2992
        }
2993
        const dftracer::utils::dstd::StringView s = ta.at(i);
164 ✔
2994
        const dftracer::utils::dstd::StringView from = tb.at(i);
164 ✔
2995
        const dftracer::utils::dstd::StringView to = td.at(i);
164 ✔
2996
        dftracer::utils::dstd::String& out = c.buf();
164 ✔
2997
        std::size_t pos = 0;
164 ✔
2998
        if (!from.empty()) {
164 ✔
2999
            for (std::size_t hit = s.find(from);
191 ✔
3000
                 hit != dftracer::utils::dstd::StringView::npos;
248 ✔
3001
                 hit = s.find(from, pos)) {
114 ✔
3002
                out.append(s.substr(pos, hit - pos));
114 ✔
3003
                out.append(to);
114 ✔
3004
                pos = hit + from.size();
114 ✔
3005
            }
57 ✔
3006
        }
67 ✔
3007
        out.append(s.substr(pos));
164 ✔
3008
        c.end_row(true);
164 ✔
3009
    }
82 ✔
3010
    return c.finish();
32 ✔
3011
}
64 !
3012

3013
Series substr_col_kernel(const Series& sa, const Series& sb, const Series* sc) {
28 ✔
3014
    const Series fa = flat_view(sa);
28 ✔
3015
    const Series fb = flat_view(sb);
28 ✔
3016
    const Series fc = sc ? flat_view(*sc) : Series{};
28 ✔
3017
    const dftu_series* a = fa.handle();
28 !
3018
    const dftu_series* b = fb.handle();
28 ✔
3019
    const dftu_series* d = fc.handle();
28 ✔
3020
    if (!same_rows(a, b) || (sc && !same_rows(a, d))) return {};
28 !
3021
    const TextCol ta(a);
28 ✔
3022
    if (!ta.ok()) return {};
42 !
3023
    const IntCol starts(b);
28 !
3024
    const IntCol lens(sc ? d : b);
28 ✔
3025
    TextCells c(a->length);
28 ✔
3026
    for (std::int64_t i = 0; i < a->length; ++i) {
182 ✔
3027
        const auto start =
154 ✔
3028
            valid_at(a, i) ? starts.at(i) : dftracer::utils::dstd::nullopt;
154 ✔
3029
        if (!start || start->neg) {
154 ✔
3030
            c.end_row(false);
62 ✔
3031
            continue;
79 ✔
3032
        }
3033
        const dftracer::utils::dstd::StringView s = ta.at(i);
92 ✔
3034
        const dftracer::utils::dstd::StringView rest =
92 ✔
3035
            s.substr(utf8_offset(s, start->mag));
92 ✔
3036
        if (!sc) {
92 ✔
3037
            c.add(rest);
34 ✔
3038
            continue;
34 ✔
3039
        }
3040
        const auto len = lens.at(i);
58 ✔
3041
        if (!len || len->neg)
58 ✔
3042
            c.end_row(false);
8 ✔
3043
        else
3044
            c.add(rest.substr(0, utf8_offset(rest, len->mag)));
50 ✔
3045
    }
77 !
3046
    return c.finish();
28 ✔
3047
}
56 !
3048

3049
Series round_col_kernel(const Series& sa, const Series& sb) {
26 ✔
3050
    const Series fa = flat_view(sa);
26 ✔
3051
    const Series fb = flat_view(sb);
26 ✔
3052
    const dftu_series* a = fa.handle();
26 !
3053
    const dftu_series* b = fb.handle();
26 ✔
3054
    if (!same_rows(a, b)) return {};
26 !
3055
    const std::int64_t n = a->length;
26 ✔
3056
    const IntCol digits(b);
26 !
3057
    constexpr double TWO_POW_63 = 9223372036854775808.0;
26 ✔
3058
    auto rounded = [](double x, const Int& d) {
102 ✔
3059
        const double scale = std::pow(10.0, d.neg ? -static_cast<double>(d.mag)
76 ✔
3060
                                                  : static_cast<double>(d.mag));
58 ✔
3061
        return std::round(x * scale) / scale;
114 ✔
3062
    };
38 ✔
3063
    Series out;
26 ✔
3064
    with_num(a->type, [&](auto xa) {
52 ✔
3065
        using A = decltype(xa);
3066
        const A* pa = values_of<A>(a);
102 ✔
3067
        if constexpr (IS_DOUBLE<A>) {
3068
            Cells<double> c(n);
109 ✔
3069
            for (std::int64_t i = 0; i < n; ++i) {
90 ✔
3070
                const auto d = valid_at(a, i) ? digits.at(i)
109 ✔
3071
                                              : dftracer::utils::dstd::nullopt;
3 ✔
3072
                if (d && d->mag <= 308) c.set(i, of_double(rounded(pa[i], *d)));
114 !
3073
            }
38 ✔
3074
            out = c.finish(TypeId::Float64);
20 !
3075
        } else if constexpr (std::is_same_v<A, std::uint64_t>) {
14 ✔
3076
            Cells<std::uint64_t> c(n);
4 ✔
3077
            for (std::int64_t i = 0; i < n; ++i) {
30 ✔
3078
                const auto d = valid_at(a, i) ? digits.at(i)
26 ✔
3079
                                              : dftracer::utils::dstd::nullopt;
2 ✔
3080
                if (!d) continue;
26 ✔
3081
                if (!d->neg) {
20 ✔
3082
                    c.set(i, pa[i]);
14 ✔
3083
                } else if (d->mag <= 308) {
13 ✔
3084
                    const double r = rounded(static_cast<double>(pa[i]), *d);
6 ✔
3085
                    if (r >= 0 && r < TWO_POW_63)
6 !
3086
                        c.set(i, static_cast<std::uint64_t>(r));
2 ✔
3087
                }
3 ✔
3088
            }
13 !
3089
            out = c.finish(TypeId::Uint64);
4 !
3090
        } else {
4 ✔
3091
            Cells<std::int64_t> c(n);
8 ✔
3092
            for (std::int64_t i = 0; i < n; ++i) {
58 ✔
3093
                const auto d = valid_at(a, i) ? digits.at(i)
50 ✔
3094
                                              : dftracer::utils::dstd::nullopt;
3 ✔
3095
                if (!d) continue;
50 ✔
3096
                if (!d->neg)
30 ✔
3097
                    c.set(i, pa[i]);
24 ✔
3098
                else if (d->mag <= 308)
6 ✔
3099
                    c.set(i,
12 !
3100
                          trunc_i64(rounded(static_cast<double>(pa[i]), *d)));
6 ✔
3101
            }
25 !
3102
            out = c.finish(TypeId::Int64);
8 !
3103
        }
8 ✔
3104
    });
26 ✔
3105
    return out;
26 ✔
3106
}
39 !
3107

3108
Series extract_col_kernel(const Series& sa, const Series& sb,
8 ✔
3109
                          const duql::CompiledPattern& p) {
3110
    const Series fa = flat_view(sa);
8 ✔
3111
    const Series fb = flat_view(sb);
8 ✔
3112
    const dftu_series* a = fa.handle();
8 !
3113
    const dftu_series* b = fb.handle();
8 ✔
3114
    if (!same_rows(a, b)) return {};
8 !
3115
    const TextCol ta(a);
8 ✔
3116
    if (!ta.ok()) return {};
12 !
3117
    const IntCol groups(b);
8 !
3118
    const std::uint64_t max_group = duql::capture_count(p);
8 ✔
3119
    TextCells c(a->length);
8 ✔
3120
    for (std::int64_t i = 0; i < a->length; ++i) {
68 ✔
3121
        const auto g =
60 ✔
3122
            valid_at(a, i) ? groups.at(i) : dftracer::utils::dstd::nullopt;
60 ✔
3123
        dftracer::utils::dstd::StringView m;
60 ✔
3124
        if (g && !g->neg && g->mag <= max_group &&
72 ✔
3125
            duql::extract(p, ta.at(i), static_cast<std::size_t>(g->mag), m) ==
24 ✔
3126
                duql::MatchResult::Yes)
3127
            c.add(m);
16 ✔
3128
        else
3129
            c.end_row(false);
44 ✔
3130
    }
30 ✔
3131
    return c.finish();
8 ✔
3132
}
12 !
3133

3134
template <class T>
3135
void append_number(dftracer::utils::dstd::String& out, T v) {
28,888 ✔
3136
    if constexpr (std::is_floating_point_v<T>) {
3137
        char buf[32];
20 ✔
3138
        if (char* end = dftracer::utils::dstd::to_chars_double(
80 !
3139
                buf, buf + sizeof(buf), v))
20 ✔
3140
            out.append(buf, end);
40 ✔
3141
    } else {
20 ✔
3142
        char buf[24];
14,424 ✔
3143
        const auto res =
14,424 ✔
3144
            dftracer::utils::dstd::to_chars(buf, buf + sizeof(buf), v);
28,848 ✔
3145
        out.append(buf, res.ptr);
28,848 ✔
3146
    }
14,424 ✔
3147
}
28,888 ✔
3148

3149
template <class V>
3150
dftracer::utils::dstd::Optional<V> parse_number(
584 ✔
3151
    dftracer::utils::dstd::StringView s) {
3152
    V out{};
584 ✔
3153
    std::from_chars_result res{};
584 ✔
3154
    if constexpr (std::is_same_v<V, double>)
3155
        res = dftracer::utils::dstd::from_chars_double(s, out);
18 ✔
3156
    else
3157
        res = dftracer::utils::dstd::from_chars(s, out);
566 ✔
3158
    if (res.ec != std::errc{} || res.ptr != s.data() + s.size())
584 !
3159
        return dftracer::utils::dstd::nullopt;
16 ✔
3160
    return out;
568 ✔
3161
}
292 ✔
3162

3163
dftracer::utils::dstd::Optional<std::int64_t> text_to_int(
566 ✔
3164
    dftracer::utils::dstd::StringView s) {
3165
    if (auto i = parse_number<std::int64_t>(s)) return i;
566 ✔
3166
    if (auto d = parse_number<double>(s)) return trunc_i64(*d);
10 ✔
3167
    return dftracer::utils::dstd::nullopt;
4 ✔
3168
}
283 ✔
3169

3170
// int(x) / float(x): numbers convert (a double truncates toward zero), Bool
3171
// is 0/1, a String parses; anything out of range or unparseable is null.
3172
template <class R>
3173
Series to_number_kernel(const dftu_series* a, TypeId t) {
368 ✔
3174
    const std::int64_t n = a->length;
368 ✔
3175
    Cells<R> c(n);
368 ✔
3176
    auto convert = [](auto v) -> dftracer::utils::dstd::Optional<R> {
59,892 ✔
3177
        if constexpr (IS_DOUBLE<R>) {
3178
            return of_double(static_cast<double>(v));
16 ✔
3179
        } else if constexpr (IS_DOUBLE<decltype(v)>) {
3180
            return trunc_i64(v);
22 ✔
3181
        } else {
3182
            return num_as<R>(v);
59,670 ✔
3183
        }
3184
    };
29,854 ✔
3185
    if (a->type == TypeId::Bool) {
368 ✔
3186
        for (std::int64_t i = 0; i < n; ++i)
12 ✔
3187
            if (valid_at(a, i)) c.set(i, static_cast<R>(bit_at(a, i)));
8 !
3188
    } else if (is_text_type(a->type)) {
366 ✔
3189
        const TextCol ta(a);
96 ✔
3190
        for (std::int64_t i = 0; i < n; ++i) {
672 ✔
3191
            if (!valid_at(a, i)) continue;
576 !
3192
            if constexpr (IS_DOUBLE<R>) {
3193
                const auto d = parse_number<double>(ta.at(i));
8 ✔
3194
                if (d) c.set(i, of_double(*d));
10 ✔
3195
            } else {
4 ✔
3196
                c.set(i, text_to_int(ta.at(i)));
846 ✔
3197
            }
3198
        }
287 ✔
3199
    } else {
48 ✔
3200
        with_num(a->type, [&](auto xa) {
90,372 ✔
3201
            using A = decltype(xa);
3202
            const A* pa = values_of<A>(a);
268 ✔
3203
            for (std::int64_t i = 0; i < n; ++i)
59,982 !
3204
                if (valid_at(a, i)) c.set(i, convert(pa[i]));
89,564 !
3205
        });
134 ✔
3206
    }
3207
    return c.finish(t);
368 ✔
3208
}
368 ✔
3209

3210
// string(x) and json(x): numbers in decimal or shortest round-trip form,
3211
// Bool as true/false; json quotes a string and writes a null (or NaN) as
3212
// null, string leaves them null.
3213
Series to_text_kernel(const dftu_series* a, bool json) {
656 ✔
3214
    const std::int64_t n = a->length;
656 ✔
3215
    TextCells c(n);
656 ✔
3216
    auto missing = [&]() {
682 ✔
3217
        if (json)
26 ✔
3218
            c.add("null");
12 ✔
3219
        else
3220
            c.end_row(false);
14 ✔
3221
    };
354 ✔
3222
    if (a->type == TypeId::Bool) {
656 ✔
3223
        for (std::int64_t i = 0; i < n; ++i) {
42 ✔
3224
            if (!valid_at(a, i))
36 ✔
3225
                missing();
4 ✔
3226
            else
3227
                c.add(bit_at(a, i) ? "true" : "false");
39 ✔
3228
        }
18 ✔
3229
    } else if (is_text_type(a->type)) {
653 ✔
3230
        const TextCol ta(a);
6 ✔
3231
        for (std::int64_t i = 0; i < n; ++i) {
30 ✔
3232
            if (!valid_at(a, i)) {
24 ✔
3233
                missing();
4 ✔
3234
            } else if (json) {
22 !
3235
                c.buf() += '"';
20 ✔
3236
                json::append_json_escaped(c.buf(), ta.at(i));
20 ✔
3237
                c.buf() += '"';
20 ✔
3238
                c.end_row(true);
20 ✔
3239
            } else {
10 ✔
UNCOV
3240
                c.add(ta.at(i));
×
3241
            }
3242
        }
12 ✔
3243
    } else {
3 ✔
3244
        with_num(a->type, [&](auto xa) {
1,288 ✔
3245
            using A = decltype(xa);
3246
            const A* pa = values_of<A>(a);
15,097 ✔
3247
            for (std::int64_t i = 0; i < n; ++i) {
29,550 ✔
3248
                bool nan = false;
28,906 ✔
3249
                if constexpr (IS_DOUBLE<A>) nan = std::isnan(pa[i]);
48 ✔
3250
                if (!valid_at(a, i) || nan) {
28,906 !
3251
                    missing();
18 ✔
3252
                } else {
9 ✔
3253
                    append_number(c.buf(), pa[i]);
28,888 ✔
3254
                    c.end_row(true);
28,888 ✔
3255
                }
3256
            }
14,453 ✔
3257
        });
644 ✔
3258
    }
3259
    return c.finish();
656 ✔
3260
}
656 ✔
3261

3262
Series convert_kernel(const Series& sa, std::int32_t code) {
1,024 ✔
3263
    const Series fa = flat_view(sa);
1,024 ✔
3264
    const dftu_series* a = fa.handle();
1,024 !
3265
    if (!a) return {};
1,024 ✔
3266
    switch (static_cast<ConvertOp>(code)) {
1,024 ✔
3267
        case ConvertOp::Int:
180 ✔
3268
            return to_number_kernel<std::int64_t>(a, TypeId::Int64);
360 ✔
3269
        case ConvertOp::Float:
4 ✔
3270
            return to_number_kernel<double>(a, TypeId::Float64);
8 ✔
3271
        case ConvertOp::String:
321 ✔
3272
            return to_text_kernel(a, false);
642 ✔
3273
        case ConvertOp::Json:
7 ✔
3274
            return to_text_kernel(a, true);
14 ✔
3275
    }
3276
    return {};
512 !
3277
}
1,024 ✔
3278

3279
// A List column's flat parts: its int32 offsets and its element column as
3280
// Int64 / Uint64 / Float64 when the elements are numeric.
3281
struct ListParts {
18 ✔
3282
    Series list;
3283
    Series elems;
3284
    const std::int32_t* off = nullptr;
9 ✔
3285
};
3286

3287
dftracer::utils::dstd::Optional<ListParts> list_parts(const Series& s) {
18 ✔
3288
    ListParts p;
18 ✔
3289
    p.list = flat_view(s);
18 !
3290
    const dftu_series* h = p.list.handle();
18 ✔
3291
    if (!h || h->type != TypeId::List || !h->offsets.block() || !h->child())
18 !
UNCOV
3292
        return dftracer::utils::dstd::nullopt;
×
3293
    p.off = reinterpret_cast<const std::int32_t*>(h->offsets.data());
18 ✔
3294
    Series child = flat_view(Series{dftu_series_share(h->child().get())});
18 !
3295
    const TypeId t = child.type();
18 ✔
3296
    if (is_num_type(t) && t != TypeId::Int64 && t != TypeId::Uint64 &&
18 !
3297
        t != TypeId::Float64)
1 ✔
3298
        child = Series{dftu_series_cast(
×
3299
            child.handle(),
×
UNCOV
3300
            static_cast<dftu_dtype>(is_int_type(t) ? TypeId::Int64
×
3301
                                                   : TypeId::Float64))};
3302
    if (!child.valid()) return dftracer::utils::dstd::nullopt;
18 ✔
3303
    p.elems = std::move(child);
18 !
3304
    return p;
18 !
3305
}
18 ✔
3306

3307
// Sum of each list's elements: integers exactly (past int64 is null),
3308
// doubles in order; a null or non-numeric element makes the row null.
3309
Series list_sum_kernel(const Series& s) {
10 ✔
3310
    auto parts = list_parts(s);
10 ✔
3311
    if (!parts) return {};
10 !
3312
    const dftu_series* h = parts->list.handle();
10 ✔
3313
    const dftu_series* e = parts->elems.handle();
10 ✔
3314
    const std::int32_t* off = parts->off;
10 ✔
3315
    const std::int64_t n = h->length;
10 ✔
3316
    if (!is_num_col(e)) {
10 ✔
3317
        Cells<std::int64_t> c(n);
2 ✔
3318
        for (std::int64_t i = 0; i < n; ++i)
6 ✔
3319
            if (valid_at(h, i) && off[i] == off[i + 1]) c.set(i, 0);
4 !
3320
        return c.finish(TypeId::Int64);
2 ✔
3321
    }
2 ✔
3322
    Series out;
8 ✔
3323
    with_num(e->type, [&](auto xe) {
16 ✔
3324
        using E = decltype(xe);
3325
        const E* pe = values_of<E>(e);
21 ✔
3326
        if constexpr (IS_DOUBLE<E>) {
3327
            Cells<double> c(n);
18 ✔
3328
            for (std::int64_t i = 0; i < n; ++i) {
6 ✔
3329
                if (!valid_at(h, i)) continue;
11 !
3330
                double total = 0;
4 ✔
3331
                bool ok = true;
4 ✔
3332
                for (std::int32_t k = off[i]; k < off[i + 1] && ok; ++k) {
16 ✔
3333
                    ok = valid_at(e, k);
6 ✔
3334
                    total += pe[k];
6 ✔
3335
                }
3 ✔
3336
                if (ok) c.set(i, of_double(total));
5 ✔
3337
            }
2 ✔
3338
            out = c.finish(TypeId::Float64);
5 !
3339
        } else {
2 ✔
3340
            Cells<std::int64_t> c(n);
6 ✔
3341
            for (std::int64_t i = 0; i < n; ++i) {
20 !
3342
                if (!valid_at(h, i)) continue;
14 !
3343
                dftracer::utils::dstd::Optional<Int> total = Int{};
12 ✔
3344
                for (std::int32_t k = off[i]; k < off[i + 1] && total; ++k)
32 !
3345
                    total = valid_at(e, k) ? int_add(*total, int_of(pe[k]))
20 !
3346
                                           : dftracer::utils::dstd::nullopt;
1 ✔
3347
                if (total)
12 !
3348
                    c.set(i,
19 ✔
3349
                          total->mag == 0
10 !
3350
                              ? dftracer::utils::dstd::Optional<std::int64_t>{0}
2 ✔
3351
                              : i64_of(*total));
8 ✔
3352
            }
6 ✔
3353
            out = c.finish(TypeId::Int64);
6 !
3354
        }
6 ✔
3355
    });
8 ✔
3356
    return out;
8 ✔
3357
}
14 !
3358

3359
// Whether an element of each list equals `v`: numbers exactly, strings
3360
// bytewise; an element of another domain never equals it.
3361
Series list_contains_kernel(const Series& s, const dftu_scalar& v) {
8 ✔
3362
    auto parts = list_parts(s);
8 ✔
3363
    if (!parts) return {};
8 !
3364
    const dftu_series* h = parts->list.handle();
8 ✔
3365
    const dftu_series* e = parts->elems.handle();
8 ✔
3366
    const std::int32_t* off = parts->off;
8 ✔
3367
    const std::int64_t n = h->length;
8 ✔
3368
    BoolCells c(n);
8 ✔
3369
    auto each_row = [&](auto&& equal) {
16 ✔
3370
        for (std::int64_t i = 0; i < n; ++i) {
36 !
3371
            if (!valid_at(h, i)) continue;
28 !
3372
            bool hit = false;
22 ✔
3373
            for (std::int32_t k = off[i]; k < off[i + 1] && !hit; ++k)
50 !
3374
                hit = valid_at(e, k) && equal(k);
33 !
3375
            c.set(i, hit);
22 ✔
3376
        }
11 ✔
3377
    };
12 ✔
3378
    if (v.kind == DFTU_SCALAR_TAG_STR && is_text_type(e->type)) {
8 ✔
3379
        const TextCol te(e);
2 ✔
3380
        const dftracer::utils::dstd::StringView want(v.value.s ? v.value.s : "",
2 !
3381
                                                     v.len);
2 !
3382
        each_row([&](std::int32_t k) { return te.at(k) == want; });
3 ✔
3383
    } else if (v.kind != DFTU_SCALAR_TAG_STR && is_num_col(e)) {
7 !
3384
        const TypeId vt = v.kind == DFTU_SCALAR_TAG_I64   ? TypeId::Int64
4 ✔
3385
                          : v.kind == DFTU_SCALAR_TAG_U64 ? TypeId::Uint64
2 !
3386
                                                          : TypeId::Float64;
3387
        with_num(e->type, [&](auto xe) {
8 ✔
3388
            with_num(vt, [&](auto xv) {
12 ✔
3389
                using E = decltype(xe);
3390
                using V = decltype(xv);
3391
                const E* pe = values_of<E>(e);
6 ✔
3392
                const V want = scalar_as<V>(v);
6 ✔
3393
                each_row([&](std::int32_t k) {
20 ✔
3394
                    const auto o = cmp_numbers(pe[k], want);
14 !
3395
                    return o && *o == 0;
14 !
3396
                });
7 ✔
3397
            });
2 ✔
3398
        });
4 ✔
3399
    } else {
2 ✔
3400
        each_row([](std::int32_t) { return false; });
6 ✔
3401
    }
3402
    return c.finish();
8 ✔
3403
}
8 !
3404

3405
Series str_const(dftracer::utils::dstd::StringView t, std::int64_t len,
34 ✔
3406
                 EvalError& error) {
3407
    dftu_scalar sc{};
34 ✔
3408
    sc.kind = DFTU_SCALAR_TAG_STR;
34 ✔
3409
    sc.value.s = t.data();
34 ✔
3410
    sc.len = static_cast<std::uint32_t>(t.size());
34 ✔
3411
    return const_column(TypeId::String, sc, len, error);
34 ✔
3412
}
17 ✔
3413

3414
// The OP_STR_FN runtime: the same C ABI kernels the eager Series.str calls, so
3415
// an expression gives the eager result.
3416
Series str_fn_eval(const SlotOp& op, const Series& a, const Series* b,
1,703 ✔
3417
                   std::int64_t len, EvalError& error) {
3418
    const dftu_series* h = a.handle();
1,703 ✔
3419
    const std::int64_t i0 = op.scalar.value.i;
1,703 ✔
3420
    const std::int64_t i1 = op.scalar2.value.i;
1,703 ✔
3421
    const char* t = op.text.data();
1,703 ✔
3422
    const auto tn = static_cast<std::int32_t>(op.text.size());
1,703 ✔
3423
    const char fill = op.text.empty() ? ' ' : op.text.front();
1,703 ✔
3424
    const auto fn = static_cast<StrFn>(op.param);
1,703 ✔
3425
    switch (fn) {
1,703 ✔
3426
        case StrFn::IsAlnum:
49 ✔
3427
        case StrFn::IsAlpha:
49 ✔
3428
        case StrFn::IsDigit:
49 ✔
3429
        case StrFn::IsDecimal:
49 ✔
3430
        case StrFn::IsNumeric:
49 ✔
3431
        case StrFn::IsSpace:
49 ✔
3432
        case StrFn::IsLower:
49 ✔
3433
        case StrFn::IsUpper:
49 ✔
3434
        case StrFn::IsTitle:
49 ✔
3435
            return Series{dftu_series_str_is(h, op.param)};
98 ✔
3436
        case StrFn::PadStart:
14 ✔
3437
            return Series{dftu_series_str_pad_start(h, i0, fill)};
28 ✔
3438
        case StrFn::PadEnd:
15 ✔
3439
            return Series{dftu_series_str_pad_end(h, i0, fill)};
30 ✔
3440
        case StrFn::Center:
8 ✔
3441
            return Series{dftu_series_str_center(h, i0, fill)};
16 ✔
3442
        case StrFn::Zfill:
6 ✔
3443
            return Series{dftu_series_str_zfill(h, i0)};
12 ✔
3444
        case StrFn::RemovePrefix:
8 ✔
3445
            return Series{dftu_series_str_remove_prefix(h, t, tn)};
16 ✔
3446
        case StrFn::RemoveSuffix:
6 ✔
3447
            return Series{dftu_series_str_remove_suffix(h, t, tn)};
12 ✔
3448
        case StrFn::Repeat:
6 ✔
3449
            return Series{dftu_series_str_repeat(h, i0)};
12 ✔
3450
        case StrFn::SliceReplace: {
11 ✔
3451
            Series head{dftu_series_str_slice(h, 0, i0)};
22 ✔
3452
            Series tail{
33 ✔
3453
                i1 == std::numeric_limits<std::int64_t>::min()
11 ✔
3454
                    ? dftu_series_str_slice(h, 0, 0)
10 ✔
3455
                    : dftu_series_str_slice(h, i1, std::int64_t{1} << 62)};
17 ✔
3456
            if (!head.handle() || !tail.handle()) return Series{};
22 !
3457
            const Series mid = str_const(op.text, len, error);
22 ✔
3458
            Series hm{dftu_series_str_cat(head.handle(), mid.handle())};
22 !
3459
            if (!hm.handle()) return Series{};
22 ✔
3460
            return Series{dftu_series_str_cat(hm.handle(), tail.handle())};
22 !
3461
        }
55 !
3462
        case StrFn::Split:
26 ✔
3463
            return Series{dftu_series_str_split(h, t, tn)};
52 ✔
3464
        case StrFn::Partition:
7 ✔
3465
            return Series{dftu_series_str_partition(h, t, tn, 0)};
14 ✔
3466
        case StrFn::RPartition:
6 ✔
3467
            return Series{dftu_series_str_partition(h, t, tn, 1)};
12 ✔
3468
        case StrFn::Findall:
6 ✔
3469
            return Series{dftu_series_str_findall(h, t, tn)};
12 ✔
3470
        case StrFn::Extract:
5 ✔
3471
            return Series{dftu_series_str_extract(h, t, tn, i0)};
10 ✔
3472
        case StrFn::RegexReplace:
29 ✔
3473
            return Series{dftu_series_str_regex_replace(
58 ✔
3474
                h, t, tn, op.text2.data(),
29 ✔
3475
                static_cast<std::int32_t>(op.text2.size()))};
58 ✔
3476
        case StrFn::Normalize:
10 ✔
3477
            return Series{
20 ✔
3478
                dftu_series_str_normalize(h, static_cast<std::int32_t>(i0))};
20 ✔
3479
        case StrFn::Translate: {
14 ✔
3480
            Series from, to;
28 ✔
3481
            if (!decode_translate_table(op.text, op.text2, from, to))
28 ✔
UNCOV
3482
                return Series{};
×
3483
            return Series{
28 ✔
3484
                dftu_series_str_translate(h, from.handle(), to.handle())};
28 !
3485
        }
42 !
3486
        case StrFn::Wrap:
2 ✔
3487
            return Series{
4 ✔
3488
                dftu_series_str_wrap(h, i0, static_cast<std::int32_t>(i1))};
4 ✔
3489
        case StrFn::Rfind:
8 ✔
3490
            return Series{dftu_series_str_rfind(h, t, tn)};
16 ✔
3491
        case StrFn::Index:
580 ✔
3492
        case StrFn::Rindex: {
580 ✔
3493
            Series r{fn == StrFn::Index ? dftu_series_str_find(h, t, tn)
1,188 ✔
3494
                                        : dftu_series_str_rfind(h, t, tn)};
587 ✔
3495
            if (!r.handle()) return Series{};
1,215 ✔
3496
            dftu_scalar minus_one{};
1,215 ✔
3497
            minus_one.kind = DFTU_SCALAR_TAG_I64;
1,215 ✔
3498
            minus_one.value.i = -1;
1,215 ✔
3499
            Series miss{
1,830 ✔
3500
                dftu_series_compare(r.handle(), DFTU_CMP_EQ, minus_one)};
1,215 !
3501
            if (miss.handle() && dftu_series_any(miss.handle()) != 0) {
1,215 !
3502
                error.set(
1,800 ✔
3503
                    dstd::fmt<"{}: substring '{}' not found in every row">(
1,792 ✔
3504
                        fn == StrFn::Index ? "index" : "rindex", op.text));
1,205 ✔
3505
                return Series{};
1,200 ✔
3506
            }
3507
            return r;
606 !
3508
        }
1,766 ✔
3509
        case StrFn::Join:
5 ✔
3510
            return Series{dftu_series_list_join(h, t, tn)};
10 ✔
3511
        case StrFn::Get: {
7 ✔
3512
            Series piece{dftu_series_str_slice(h, i0, 1)};
14 ✔
3513
            Series lens{dftu_series_str_len_bytes(h)};
14 !
3514
            if (!piece.handle() || !lens.handle()) return Series{};
14 !
3515
            dftu_scalar bound{};
14 ✔
3516
            bound.kind = DFTU_SCALAR_TAG_I64;
14 ✔
3517
            bound.value.i = i0;
14 ✔
3518
            Series cond{dftu_series_compare(lens.handle(), DFTU_CMP_GT, bound)};
14 ✔
3519
            const Series nulls = Series::nulls(TypeId::String, len);
14 ✔
3520
            if (!cond.handle()) return Series{};
14 ✔
3521
            return Series{dftu_series_where(cond.handle(), piece.handle(),
21 ✔
3522
                                            nulls.handle())};
14 !
3523
        }
35 !
3524
        case StrFn::Cat: {
6 ✔
3525
            if (b == nullptr) return Series{};
12 ✔
3526
            if (op.text.empty())
12 !
UNCOV
3527
                return Series{dftu_series_str_cat(h, b->handle())};
×
3528
            const Series sep = str_const(op.text, len, error);
12 ✔
3529
            Series ab{dftu_series_str_cat(h, sep.handle())};
12 !
3530
            if (!ab.handle()) return Series{};
12 ✔
3531
            return Series{dftu_series_str_cat(ab.handle(), b->handle())};
12 !
3532
        }
18 !
3533
    }
UNCOV
3534
    return Series{};
×
3535
}
869 ✔
3536

3537
// Evaluate the slot program over rows [offset, offset+len) and extract one
3538
// column per requested final slot (shared, so distinct outputs that resolved to
3539
// the same slot alias the one buffer).
3540
dstd::Vector<Series> eval_chunk(dstd::Span<const SlotOp> prog,
56,079 ✔
3541
                                dstd::Span<const Series> inputs,
3542
                                dstd::Span<const int> finals,
3543
                                std::int64_t offset, std::int64_t len,
3544
                                EvalError& error) {
3545
    dstd::Vector<Series> s(prog.size());
56,079 ✔
3546
    for (std::size_t k = 0; k < prog.size(); ++k) {
239,207 ✔
3547
        const SlotOp& op = prog[k];
183,725 !
3548
        auto A = [&]() { return s[static_cast<std::size_t>(op.a)].handle(); };
149,829 ✔
3549
        auto B = [&]() { return s[static_cast<std::size_t>(op.b)].handle(); };
211,562 ✔
3550
        auto SA = [&]() -> const Series& {
193,972 ✔
3551
            return s[static_cast<std::size_t>(op.a)];
9,099 ✔
3552
        };
91,821 ✔
3553
        auto SB = [&]() -> const Series& {
190,044 ✔
3554
            return s[static_cast<std::size_t>(op.b)];
3,196 ✔
3555
        };
91,821 ✔
3556
        switch (op.opcode) {
183,725 ✔
3557
            case OpUdf: {
861 ✔
3558
                dstd::Vector<const Series*> columns;
1,721 ✔
3559
                for (const int slot : op.udf_args)
3,480 ✔
3560
                    columns.push_back(&s[static_cast<std::size_t>(slot)]);
1,759 ✔
3561
                auto ran = op.udf->run(dstd::Span<const Series* const>(
3,441 ✔
3562
                                           columns.data(), columns.size()),
860 ✔
3563
                                       len);
1,721 ✔
3564
                if (!ran)
1,721 ✔
3565
                    error.set(
68 ✔
3566
                        dstd::String(ran.error().message()),
51 ✔
3567
                        ran.error().condition() == dstd::Condition::Cancelled
34 ✔
3568
                            ? dstd::Condition::Cancelled
3569
                            : dstd::Condition::InvalidArgument);
3570
                else
3571
                    s[k] = std::move(*ran);
1,687 ✔
3572
                break;
861 ✔
3573
            }
1,721 ✔
3574
            case OpLoad:
35,957 ✔
3575
                s[k] = load_slice(inputs[static_cast<std::size_t>(op.param)],
107,965 ✔
3576
                                  offset, len);
71,971 !
3577
                break;
71,972 ✔
3578
            case OpAdd:
4,677 ✔
3579
                s[k] = Series{dftu_series_add(A(), B())};
9,354 !
3580
                break;
9,354 ✔
3581
            case OpSub:
6,049 ✔
3582
                s[k] = Series{dftu_series_sub(A(), B())};
12,098 !
3583
                break;
12,098 ✔
3584
            case OpMul:
7 ✔
3585
                s[k] = Series{dftu_series_mul(A(), B())};
14 !
3586
                break;
14 ✔
3587
            case OpDiv:
1,027 ✔
3588
                s[k] = Series{dftu_series_div(A(), B())};
2,054 !
3589
                break;
2,054 ✔
3590
            case OpAdds:
2,389 ✔
3591
                s[k] = Series{dftu_series_add_scalar(A(), op.scalar)};
4,777 !
3592
                break;
4,777 ✔
3593
            case OpSubs:
777 ✔
3594
                s[k] = Series{dftu_series_sub_scalar(A(), op.scalar)};
1,554 !
3595
                break;
1,554 ✔
3596
            case OpMuls:
3,863 ✔
3597
                s[k] = Series{dftu_series_mul_scalar(A(), op.scalar)};
7,726 !
3598
                break;
7,726 ✔
3599
            case OpDivs:
1,071 ✔
3600
                s[k] = Series{dftu_series_div_scalar(A(), op.scalar)};
2,142 !
3601
                break;
2,142 ✔
3602
            case OpPrim:
109 ✔
3603
                s[k] = Series{
327 ✔
3604
                    dftu_series_prim(A(), static_cast<dftu_prim_op>(op.param))};
218 !
3605
                break;
218 ✔
3606
            case OpUnary: {
631 ✔
3607
                dftu_series* r = nullptr;
1,262 ✔
3608
                switch (static_cast<UnaryOp>(op.param)) {
1,262 !
3609
                    case UnaryOp::Abs:
28 ✔
3610
                        r = dftu_series_abs(A());
56 ✔
3611
                        break;
56 ✔
3612
                    case UnaryOp::Round:
7 ✔
3613
                        r = dftu_series_round(A());
14 ✔
3614
                        break;
14 ✔
3615
                    case UnaryOp::Floor:
534 ✔
3616
                        r = dftu_series_floor(A());
1,068 ✔
3617
                        break;
1,068 ✔
3618
                    case UnaryOp::Ceil:
3 ✔
3619
                        r = dftu_series_ceil(A());
6 ✔
3620
                        break;
6 ✔
3621
                    case UnaryOp::Log:
2 ✔
3622
                        r = dftu_series_log(A());
4 ✔
3623
                        break;
4 ✔
3624
                    case UnaryOp::Sqrt:
9 ✔
3625
                        r = dftu_series_sqrt(A());
18 ✔
3626
                        break;
18 ✔
3627
                    case UnaryOp::Exp:
3 ✔
3628
                        r = dftu_series_exp(A());
6 ✔
3629
                        break;
6 ✔
3630
                    case UnaryOp::Log1p:
1 ✔
3631
                        r = dftu_series_log1p(A());
2 ✔
3632
                        break;
2 ✔
3633
                    case UnaryOp::Expm1:
1 ✔
3634
                        r = dftu_series_expm1(A());
2 ✔
3635
                        break;
2 ✔
3636
                    case UnaryOp::Sign:
2 ✔
3637
                        r = dftu_series_sign(A());
4 ✔
3638
                        break;
4 ✔
3639
                    case UnaryOp::Negate:
18 ✔
3640
                        r = dftu_series_negate(A());
36 ✔
3641
                        break;
36 ✔
3642
                    case UnaryOp::Trunc:
2 ✔
3643
                        r = dftu_series_trunc(A());
4 ✔
3644
                        break;
4 ✔
3645
                    case UnaryOp::IsNan:
20 ✔
3646
                        r = dftu_series_is_nan(A());
40 ✔
3647
                        break;
40 ✔
3648
                    case UnaryOp::IsFinite:
1 ✔
3649
                        r = dftu_series_is_finite(A());
2 ✔
3650
                        break;
2 ✔
3651
                    case UnaryOp::IsInfinite:
3652
                        r = dftu_series_is_infinite(A());
×
UNCOV
3653
                        break;
×
3654
                }
3655
                s[k] = Series{r};
1,262 !
3656
                break;
631 ✔
3657
            }
631 ✔
3658
            case OpClip:
41 ✔
3659
                s[k] = Series{dftu_series_clip(A(), op.scalar, op.scalar2)};
82 !
3660
                break;
82 ✔
3661
            case OpFillna:
24 ✔
3662
                if (op.param) {
48 ✔
3663
                    const Series nan_free{dftu_series_fill_nan(A(), op.scalar)};
40 !
3664
                    s[k] = nan_free.handle()
60 !
3665
                               ? Series{dftu_series_fillna(nan_free.handle(),
80 !
3666
                                                           op.scalar)}
20 ✔
3667
                               : Series{};
20 !
3668
                } else {
40 ✔
3669
                    s[k] = Series{dftu_series_fillna(A(), op.scalar)};
8 !
3670
                }
3671
                break;
24 ✔
3672
            case OpCmp:
4,343 ✔
3673
                s[k] = Series{dftu_series_compare(
17,366 ✔
3674
                    A(), static_cast<dftu_cmp_op>(op.param), op.scalar)};
13,025 !
3675
                break;
8,684 ✔
3676
            case OpLogical:
464 ✔
3677
                s[k] = Series{dftu_series_logical(
1,392 ✔
3678
                    A(), B(), static_cast<dftu_logical_op>(op.param))};
928 !
3679
                break;
928 ✔
3680
            case OpNot:
195 ✔
3681
                s[k] = Series{dftu_series_logical_not(A())};
390 !
3682
                break;
390 ✔
3683
            case OpCast:
9,635 ✔
3684
                s[k] = Series{
28,907 ✔
3685
                    dftu_series_cast(A(), static_cast<dftu_dtype>(op.param))};
19,271 !
3686
                break;
19,271 ✔
3687
            case OpStrPred: {
172 ✔
3688
                const char* p = op.text.data();
344 !
3689
                const auto n = static_cast<std::int32_t>(op.text.size());
344 !
3690
                dftu_series* r = nullptr;
344 ✔
3691
                switch (static_cast<StrPredOp>(op.param)) {
344 ✔
3692
                    case StrPredOp::Contains:
62 ✔
3693
                        r = dftu_series_str_contains(A(), p, n);
124 ✔
3694
                        break;
124 ✔
3695
                    case StrPredOp::StartsWith:
22 ✔
3696
                        r = dftu_series_str_starts_with(A(), p, n);
44 ✔
3697
                        break;
44 ✔
3698
                    case StrPredOp::EndsWith:
13 ✔
3699
                        r = dftu_series_str_ends_with(A(), p, n);
26 ✔
3700
                        break;
26 ✔
3701
                    case StrPredOp::Like:
15 ✔
3702
                        r = dftu_series_str_like(A(), p, n);
30 ✔
3703
                        break;
30 ✔
3704
                    case StrPredOp::Matches:
6 ✔
3705
                        r = dftu_series_str_matches(A(), p, n);
12 ✔
3706
                        break;
12 ✔
3707
                    case StrPredOp::Search:
54 ✔
3708
                        r = dftu_series_str_search(A(), p, n);
108 ✔
3709
                        break;
108 ✔
3710
                }
3711
                s[k] = Series{r};
344 !
3712
                break;
172 ✔
3713
            }
172 ✔
3714
            case OpStrMap: {
531 ✔
3715
                dftu_series* r = nullptr;
1,062 ✔
3716
                switch (static_cast<StrMapOp>(op.param)) {
1,062 ✔
3717
                    case StrMapOp::Lower:
450 ✔
3718
                        r = dftu_series_to_lowercase(A());
900 ✔
3719
                        break;
900 ✔
3720
                    case StrMapOp::Upper:
41 ✔
3721
                        r = dftu_series_to_uppercase(A());
82 ✔
3722
                        break;
82 ✔
3723
                    case StrMapOp::Strip:
6 ✔
3724
                        r = dftu_series_str_strip(A());
12 ✔
3725
                        break;
12 ✔
3726
                    case StrMapOp::Lstrip:
3 ✔
3727
                        r = dftu_series_str_lstrip(A());
6 ✔
3728
                        break;
6 ✔
3729
                    case StrMapOp::Rstrip:
3 ✔
3730
                        r = dftu_series_str_rstrip(A());
6 ✔
3731
                        break;
6 ✔
3732
                    case StrMapOp::Capitalize:
9 ✔
3733
                        r = dftu_series_str_case(A(), 0);
18 ✔
3734
                        break;
18 ✔
3735
                    case StrMapOp::Title:
12 ✔
3736
                        r = dftu_series_str_case(A(), 1);
24 ✔
3737
                        break;
24 ✔
3738
                    case StrMapOp::Swapcase:
7 ✔
3739
                        r = dftu_series_str_case(A(), 2);
14 ✔
3740
                        break;
14 ✔
3741
                }
3742
                s[k] = Series{r};
1,062 !
3743
                break;
531 ✔
3744
            }
531 ✔
3745
            case OpStrLen:
89 ✔
3746
                s[k] = Series{op.param ? dftu_series_str_len_chars(A())
183 ✔
3747
                                       : dftu_series_str_len_bytes(A())};
94 !
3748
                break;
178 ✔
3749
            case OpStrFind:
21 ✔
3750
                s[k] = Series{dftu_series_str_find(
63 ✔
3751
                    A(), op.text.data(),
42 ✔
3752
                    static_cast<std::int32_t>(op.text.size()))};
42 !
3753
                break;
42 ✔
3754
            case OpStrReplace: {
15 ✔
3755
                const char* f = op.text.data();
30 ✔
3756
                const auto fn = static_cast<std::int32_t>(op.text.size());
30 ✔
3757
                const char* t = op.text2.data();
30 ✔
3758
                const auto tn = static_cast<std::int32_t>(op.text2.size());
30 ✔
3759
                s[k] = Series{
45 ✔
3760
                    op.param ? dftu_series_str_replace_all(A(), f, fn, t, tn)
30 ✔
3761
                             : dftu_series_str_replace(A(), f, fn, t, tn)};
19 !
3762
                break;
15 ✔
3763
            }
15 ✔
3764
            case OpStrSlice:
6 ✔
3765
                s[k] = Series{dftu_series_str_slice(A(), op.scalar.value.i,
18 ✔
3766
                                                    op.scalar2.value.i)};
12 !
3767
                break;
12 ✔
3768
            case OpIsIn:
356 ✔
3769
                s[k] = Series{dftu_series_is_in(A(), op.values)};
712 !
3770
                break;
712 ✔
3771
            case OpIsNull:
5,285 ✔
3772
                switch (op.param) {
10,571 ✔
3773
                    case 0:
5,097 ✔
3774
                        s[k] = Series{dftu_series_valid_mask(A())};
10,195 !
3775
                        break;
10,194 ✔
3776
                    case 1:
104 ✔
3777
                        s[k] = Series{dftu_series_null_mask(A())};
208 !
3778
                        break;
208 ✔
3779
                    case 2:
54 ✔
3780
                        s[k] = Series{dftu_series_na_mask(A())};
108 !
3781
                        break;
108 ✔
3782
                    default:
30 ✔
3783
                        s[k] = Series{dftu_series_notna_mask(A())};
60 !
3784
                        break;
60 ✔
3785
                }
3786
                break;
5,286 ✔
3787
            case OpConst:
4,477 ✔
3788
                s[k] = const_column(static_cast<TypeId>(op.param), op.scalar,
13,433 ✔
3789
                                    len, error);
8,955 !
3790
                break;
8,955 ✔
3791
            case OpSelect:
1,256 ✔
3792
                s[k] = Series{dftu_series_where(
3,770 ✔
3793
                    s[static_cast<std::size_t>(op.c)].handle(), A(), B())};
2,513 !
3794
                break;
2,513 ✔
3795
            case OpConstNull:
278 ✔
3796
                s[k] = Series::nulls(static_cast<TypeId>(op.param), len);
557 !
3797
                break;
557 ✔
3798
            case OpToI64:
3 ✔
3799
                s[k] = to_i64_kernel(SA());
6 !
3800
                break;
6 ✔
3801
            case OpArith:
2,175 ✔
3802
                s[k] = arith_kernel(SA(), SB(), op.param);
4,351 !
3803
                break;
4,351 ✔
3804
            case OpNeg:
15 ✔
3805
                s[k] = neg_kernel(SA());
30 !
3806
                break;
30 ✔
3807
            case OpCmpExpr:
872 ✔
3808
                s[k] = cmp_expr_kernel(SA(), SB(), op.param);
1,744 !
3809
                break;
1,744 ✔
3810
            case OpExtreme:
14 ✔
3811
                s[k] = extreme_kernel(SA(), SB(), op.param != 0);
28 !
3812
                break;
28 ✔
3813
            case OpConcat:
438 ✔
3814
                s[k] = Series{dftu_series_str_cat(A(), B())};
876 !
3815
                break;
876 ✔
3816
            case OpRound:
25 ✔
3817
                s[k] = round_kernel(SA(), op.scalar.value.i);
50 !
3818
                break;
50 ✔
3819
            case OpLog:
2 ✔
3820
                s[k] = log_kernel(SA());
4 !
3821
                break;
4 ✔
3822
            case OpPow:
3 ✔
3823
                s[k] = pow_kernel(SA(), SB());
6 !
3824
                break;
6 ✔
3825
            case OpStrSubstr:
11 ✔
3826
                s[k] =
22 ✔
3827
                    substr_kernel(SA(), op.scalar.value.i, op.scalar2.value.i);
22 !
3828
                break;
22 ✔
3829
            case OpStrPredCol:
42 ✔
3830
                s[k] = str_pred_col_kernel(SA(), SB(), op.param);
84 !
3831
                break;
84 ✔
3832
            case OpStrReplaceCol:
16 ✔
3833
                s[k] = str_replace_col_kernel(
48 ✔
3834
                    SA(), SB(), s[static_cast<std::size_t>(op.c)]);
32 !
3835
                break;
32 ✔
3836
            case OpStrSubstrCol:
14 ✔
3837
                s[k] = substr_col_kernel(
42 ✔
3838
                    SA(), SB(),
14 ✔
3839
                    op.c >= 0 ? &s[static_cast<std::size_t>(op.c)] : nullptr);
42 !
3840
                break;
28 ✔
3841
            case OpRoundCol:
13 ✔
3842
                s[k] = round_col_kernel(SA(), SB());
26 !
3843
                break;
26 ✔
3844
            case OpStrExtractCol:
4 ✔
3845
                s[k] = extract_col_kernel(SA(), SB(), *op.pattern);
8 !
3846
                break;
8 ✔
3847
            case OpDatePart:
437 ✔
3848
                s[k] = date_part_kernel(SA(), op.param, op.scalar.value.i);
874 !
3849
                break;
874 ✔
3850
            case OpFormatTime:
69 ✔
3851
                s[k] = format_time_kernel(SA(), op.text, op.scalar.value.i);
138 !
3852
                break;
138 ✔
3853
            case OpStrPattern:
14 ✔
3854
                s[k] = str_pattern(SA(), *op.pattern);
28 !
3855
                break;
28 ✔
3856
            case OpStrExtract:
12 ✔
3857
                s[k] =
36 ✔
3858
                    extract_kernel(SA(), *op.pattern,
36 ✔
3859
                                   static_cast<std::size_t>(op.scalar.value.i));
24 !
3860
                break;
24 ✔
3861
            case OpStrRegexReplace:
9 ✔
3862
                s[k] = str_regex_replace(SA(), *op.pattern, *op.subst);
18 !
3863
                break;
18 ✔
3864
            case OpConvert:
512 ✔
3865
                s[k] = convert_kernel(SA(), op.param);
1,024 !
3866
                break;
1,024 ✔
3867
            case OpListLen:
1,656 ✔
3868
                s[k] = Series{dftu_series_list_len(A())};
3,312 !
3869
                break;
3,312 ✔
3870
            case OpListGet:
15 ✔
3871
                s[k] = Series{dftu_series_list_get(A(), op.scalar.value.i)};
30 !
3872
                break;
30 ✔
3873
            case OpListSum:
5 ✔
3874
                s[k] = list_sum_kernel(SA());
10 !
3875
                break;
10 ✔
3876
            case OpListContains:
4 ✔
3877
                s[k] = list_contains_kernel(SA(), op.scalar);
8 !
3878
                break;
8 ✔
3879
            case OpStrFn:
835 ✔
3880
                s[k] = str_fn_eval(op, SA(), op.b >= 0 ? &SB() : nullptr, len,
1,704 ✔
3881
                                   error);
1,709 !
3882
                break;
1,715 ✔
3883
            default:
UNCOV
3884
                return {};
×
3885
        }
3886
        if (!s[k].handle()) return {};
183,746 ✔
3887
    }
91,904 ✔
3888
    dstd::Vector<Series> outs;
54,854 ✔
3889
    outs.reserve(finals.size());
54,854 ✔
3890
    for (int f : finals) outs.push_back(s[static_cast<std::size_t>(f)].share());
110,543 ✔
3891
    return outs;
54,854 ✔
3892
}
83,513 !
3893

3894
// eval_chunk returns no columns when a kernel does not take its input type;
3895
// reported here, on the calling thread, since the parallel workers cannot
3896
// return an error.
3897
dstd::Result<void> require_evaluated(dstd::Span<const Series> outs,
56,082 ✔
3898
                                     EvalError& error) {
3899
    if (outs.empty()) {
56,082 ✔
3900
        dstd::String message;
1,229 ✔
3901
        dstd::Condition condition;
1,229 ✔
3902
        {
603 ✔
3903
            std::lock_guard<std::mutex> lock(error.mutex);
1,229 ✔
3904
            message.swap(error.message);
1,241 ✔
3905
            condition = error.condition;
1,248 ✔
3906
        }
1,242 ✔
3907
        if (!message.empty())
1,242 ✔
3908
            return dstd::Unexpected(dstd::Error(condition, message));
1,238 ✔
3909
        return common::make_error(
8 ✔
3910
            common::ErrorCode::InvalidArgument,
3911
            "expr: an operation does not take its input column type");
4 ✔
3912
    }
1,224 ✔
3913
    return {};
54,853 ✔
3914
}
28,053 ✔
3915

3916
dstd::Vector<DataType> types_of(dstd::Span<const Series* const> inputs) {
53,716 ✔
3917
    dstd::Vector<DataType> out;
53,716 ✔
3918
    out.reserve(inputs.size());
53,716 ✔
3919
    for (const Series* s : inputs) out.push_back(s->data_type());
304,694 ✔
3920
    return out;
53,713 ✔
3921
}
26,867 !
3922

3923
// The roots compiled into one program, so hash-consing (CSE) spans all of
3924
// them. The ops borrow from the roots' nodes and from the compiler's UDF
3925
// bindings, so both live here, and a Program never moves.
3926
struct Program {
3927
    Program(dstd::Span<const Expr> r, dstd::Span<const Series* const> inputs)
107,440 ✔
3928
        : roots(r.begin(), r.end()),
53,704 ✔
3929
          input_types(types_of(inputs)),
53,722 ✔
3930
          c(input_types) {}
107,449 ✔
3931
    Program(const Program&) = delete;
3932
    Program& operator=(const Program&) = delete;
3933

3934
    dstd::Vector<Expr> roots;
3935
    dstd::Vector<DataType> input_types;
3936
    Compiler c;
3937
    dstd::Vector<Series> flat;  // the inputs the program loads, shared
3938
    dstd::Vector<int> finals;   // the slot of each root
3939
};
3940

3941
dstd::Result<dstd::UniquePtr<Program>> compile_program(
53,708 ✔
3942
    dstd::Span<const Expr> roots, dstd::Span<const Series* const> inputs) {
3943
    auto p = dstd::make_unique<Program>(roots, inputs);
53,708 ✔
3944
    p->finals.reserve(roots.size());
53,711 ✔
3945
    for (const Expr& root : p->roots) {
107,784 ✔
3946
        if (!root.valid())
54,124 ✔
UNCOV
3947
            return common::make_error(common::ErrorCode::InvalidArgument,
×
UNCOV
3948
                                      "expr: null expression");
×
3949
        p->finals.push_back(p->c.column(p->c.compile(root.node().get())).slot);
54,124 ✔
3950
        if (p->c.failed())
54,125 ✔
3951
            return common::make_error(common::ErrorCode::InvalidArgument,
188 ✔
3952
                                      p->c.error());
141 ✔
3953
    }
27,075 ✔
3954
    p->flat.resize(inputs.size());
53,611 ✔
3955
    for (const SlotOp& op : p->c.program)
227,609 ✔
3956
        if (op.opcode == OpLoad) {
174,001 ✔
3957
            const auto i = static_cast<std::size_t>(op.param);
67,994 ✔
3958
            if (!p->flat[i].valid()) p->flat[i] = inputs[i]->share();
67,994 !
3959
        }
87,037 ✔
3960
    return p;
53,608 ✔
3961
}
53,704 ✔
3962

3963
constexpr std::int64_t GRAIN = 1 << 16;
3964

3965
}  // namespace
3966

3967
dstd::Result<dstd::Vector<Series>> eval_many(
84,422 ✔
3968
    dstd::Span<const Expr> roots, dstd::Span<const Series* const> inputs) {
3969
    if (roots.empty())
84,422 !
UNCOV
3970
        return common::make_error(common::ErrorCode::InvalidArgument,
×
UNCOV
3971
                                  "expr: needs at least one expression");
×
3972
    if (inputs.empty())
84,422 !
UNCOV
3973
        return common::make_error(common::ErrorCode::InvalidArgument,
×
UNCOV
3974
                                  "expr: needs at least one input column");
×
3975

3976
    // Bare column references share the input; the evaluator would slice and
3977
    // concat a copy.
3978
    bool all_cols = true;
84,422 ✔
3979
    for (const Expr& root : roots) {
169,255 ✔
3980
        const std::int32_t i = root.valid() ? expr_col_index(root) : -1;
84,829 !
3981
        all_cols &= i >= 0 && static_cast<std::size_t>(i) < inputs.size();
84,833 !
3982
    }
42,431 ✔
3983
    if (all_cols) {
84,426 ✔
3984
        dstd::Vector<Series> outs;
30,758 ✔
3985
        outs.reserve(roots.size());
30,758 ✔
3986
        for (const Expr& root : roots) {
61,516 ✔
3987
            const Series& in =
46,137 ✔
3988
                *inputs[static_cast<std::size_t>(expr_col_index(root))];
30,758 ✔
3989
            outs.push_back(in.encoding() == Encoding::Flat ? in.share()
45,907 !
3990
                                                           : in.materialize());
230 ✔
3991
        }
15,379 ✔
3992
        return outs;
30,758 ✔
3993
    }
30,758 ✔
3994

3995
    dstd::Result<dstd::UniquePtr<Program>> compiled =
53,668 ✔
3996
        compile_program(roots, inputs);
53,668 ✔
3997
    if (!compiled) return compiled.error();
53,662 ✔
3998
    const Program& prog = **compiled;
53,567 ✔
3999
    const dstd::Span<const SlotOp> program(prog.c.program);
53,570 ✔
4000
    const dstd::Span<const Series> flat(prog.flat);
53,570 ✔
4001
    const dstd::Span<const int> finals(prog.finals);
53,570 ✔
4002
    // Inputs are read in place; each chunk's OP_LOAD slices its rows as a
4003
    // view of the input (a window that spans chunks of a CHUNKED input is
4004
    // joined there, in parallel).
4005
    dstd::Vector<bool> used(inputs.size(), false);
53,570 ✔
4006
    for (std::size_t i = 0; i < inputs.size(); ++i) used[i] = flat[i].valid();
304,340 ✔
4007
    EvalError error;
53,572 ✔
4008

4009
    const std::int64_t n = inputs.front()->length();
53,572 ✔
4010
    // Window starts: a CHUNKED input's own chunks when every chunked input
4011
    // shares them (each window reads its chunk in place and the results stay
4012
    // chunks), otherwise GRAIN-row windows.
4013
    dstd::Vector<std::int64_t> bounds;
53,575 ✔
4014
    for (std::size_t i = 0; i < inputs.size(); ++i) {
304,338 ✔
4015
        if (!used[i] || !inputs[i]->handle()->is_chunked()) continue;
250,760 ✔
4016
        const dftu_series& h = *inputs[i]->handle();
56 ✔
4017
        const auto* starts =
84 ✔
4018
            reinterpret_cast<const std::int64_t*>(h.data.data());
56 ✔
4019
        dstd::Vector<std::int64_t> own(starts, starts + h.nested.size() + 1);
56 ✔
4020
        if (bounds.empty()) {
56 ✔
4021
            bounds = std::move(own);
34 ✔
4022
        } else if (bounds != own) {
39 ✔
4023
            bounds.clear();
2 !
4024
            break;
2 ✔
4025
        }
4026
    }
56 ✔
4027
    const bool by_chunk = !bounds.empty();
53,579 ✔
4028
    if (!by_chunk) {
53,579 ✔
4029
        if (n <= GRAIN) {
53,547 ✔
4030
            dstd::Vector<Series> outs =
52,613 ✔
4031
                eval_chunk(program, flat, finals, 0, n, error);
52,613 ✔
4032
            if (auto ok = require_evaluated(outs, error); !ok)
53,239 ✔
4033
                return ok.error();
1,219 ✔
4034
            return outs;
51,391 ✔
4035
        }
52,629 ✔
4036
        for (std::int64_t lo = 0; lo < n; lo += GRAIN) bounds.push_back(lo);
3,786 ✔
4037
        bounds.push_back(n);
934 ✔
4038
    }
467 ✔
4039

4040
    const auto windows = static_cast<std::int64_t>(bounds.size() - 1);
966 ✔
4041
    dstd::Vector<dstd::Vector<Series>> parts(static_cast<std::size_t>(windows));
966 ✔
4042
    // One task per window: without a parallel backend parallel_for runs the
4043
    // whole range as one call, which must still fill every window.
4044
    const coro::CancelView cancel = udf_cancel();
966 ✔
4045
    parallel_for(windows, 1, [&](std::int64_t b, std::int64_t e) {
2,094 ✔
4046
        const UdfCancelScope cancel_scope(cancel);
2,256 ✔
4047
        for (std::int64_t k = b; k < e; ++k) {
5,290 ✔
4048
            const std::int64_t lo = bounds[static_cast<std::size_t>(k)];
3,034 ✔
4049
            const std::int64_t hi = bounds[static_cast<std::size_t>(k) + 1];
3,034 ✔
4050
            parts[static_cast<std::size_t>(k)] =
3,034 ✔
4051
                eval_chunk(program, flat, finals, lo, hi - lo, error);
4,551 ✔
4052
        }
1,517 ✔
4053
    });
2,256 ✔
4054
    for (const dstd::Vector<Series>& part : parts)
3,996 ✔
4055
        if (auto ok = require_evaluated(part, error); !ok) return ok.error();
4,546 ✔
4056
    dstd::Vector<Series> outs;
962 ✔
4057
    outs.reserve(finals.size());
962 ✔
4058
    for (std::size_t j = 0; j < finals.size(); ++j) {
1,972 !
4059
        if (by_chunk) {
1,010 ✔
4060
            dstd::Vector<Series> pieces;
62 ✔
4061
            pieces.reserve(parts.size());
62 ✔
4062
            for (const dstd::Vector<Series>& part : parts)
328 ✔
4063
                pieces.push_back(part[j].share());
266 !
4064
            dstd::Result<Series> chunked = chunked_column(std::move(pieces));
62 ✔
4065
            if (!chunked) return chunked.error();
62 ✔
4066
            outs.push_back(std::move(*chunked));
62 ✔
4067
            continue;
62 ✔
4068
        }
62 !
4069
        dstd::Vector<const Series*> ptrs;
948 ✔
4070
        ptrs.reserve(parts.size());
948 ✔
4071
        for (const dstd::Vector<Series>& part : parts) ptrs.push_back(&part[j]);
3,846 ✔
4072
        dstd::Result<Series> joined = concat_columns(ptrs);
948 ✔
4073
        if (!joined) return joined.error();
948 ✔
4074
        outs.push_back(std::move(*joined));
948 ✔
4075
    }
948 !
4076
    return outs;
962 ✔
4077
}
95,832 ✔
4078

4079
struct ExprWindows::Impl {
18 ✔
4080
    dstd::UniquePtr<Program> program;
4081
    coro::CancelView cancel;
4082
};
4083

4084
ExprWindows::ExprWindows(dstd::UniquePtr<Impl> impl) noexcept
54 ✔
4085
    : impl_(std::move(impl)) {}
54 ✔
4086
ExprWindows::ExprWindows(ExprWindows&&) noexcept = default;
162 ✔
UNCOV
4087
ExprWindows& ExprWindows::operator=(ExprWindows&&) noexcept = default;
×
4088
ExprWindows::~ExprWindows() = default;
216 ✔
4089

4090
dstd::Result<ExprWindows> ExprWindows::compile(
38 ✔
4091
    dstd::Span<const Expr> roots, dstd::Span<const Series* const> inputs) {
4092
    if (roots.empty())
38 !
UNCOV
4093
        return common::make_error(common::ErrorCode::InvalidArgument,
×
UNCOV
4094
                                  "expr: needs at least one expression");
×
4095
    if (inputs.empty())
38 !
UNCOV
4096
        return common::make_error(common::ErrorCode::InvalidArgument,
×
UNCOV
4097
                                  "expr: needs at least one input column");
×
4098
    dstd::Result<dstd::UniquePtr<Program>> compiled =
38 ✔
4099
        compile_program(roots, inputs);
38 ✔
4100
    if (!compiled) return compiled.error();
57 ✔
4101
    auto impl = dstd::make_unique<Impl>();
36 ✔
4102
    impl->program = std::move(*compiled);
36 ✔
4103
    impl->cancel = udf_cancel();
36 ✔
4104
    return ExprWindows(std::move(impl));
36 ✔
4105
}
37 ✔
4106

4107
dstd::Result<dstd::Vector<Series>> ExprWindows::eval(std::int64_t offset,
434 ✔
4108
                                                     std::int64_t len) const {
4109
    const UdfCancelScope cancel_scope(impl_->cancel);
434 ✔
4110
    const Program& p = *impl_->program;
434 ✔
4111
    EvalError error;
434 ✔
4112
    dstd::Vector<Series> outs =
434 ✔
4113
        eval_chunk(p.c.program, p.flat, p.finals, offset, len, error);
434 ✔
4114
    if (dstd::Result<void> ok = require_evaluated(outs, error); !ok)
434 !
UNCOV
4115
        return ok.error();
×
4116
    return outs;
434 ✔
4117
}
434 ✔
4118

4119
dstd::Result<Series> eval(const Expr& root,
83,952 ✔
4120
                          dstd::Span<const Series* const> inputs) {
4121
    if (!root.valid())
83,952 !
UNCOV
4122
        return common::make_error(common::ErrorCode::InvalidArgument,
×
UNCOV
4123
                                  "expr: null expression");
×
4124
    dstd::Result<dstd::Vector<Series>> outs =
83,952 ✔
4125
        eval_many(dstd::Span<const Expr>(&root, 1), inputs);
83,952 ✔
4126
    if (!outs) return outs.error();
83,958 ✔
4127
    return std::move(outs->front());
83,308 ✔
4128
}
83,975 ✔
4129

4130
dstd::Result<DataType> infer_type(const Expr& root,
27,862 ✔
4131
                                  dstd::Span<const DataType> input_types) {
4132
    if (!root.valid())
27,862 !
UNCOV
4133
        return common::make_error(common::ErrorCode::InvalidArgument,
×
UNCOV
4134
                                  "expr: null expression");
×
4135
    Compiler c(input_types);
27,862 ✔
4136
    DataType type = c.column(c.compile(root.node().get())).full;
27,862 ✔
4137
    if (c.failed())
27,862 ✔
4138
        return common::make_error(common::ErrorCode::InvalidArgument,
16 ✔
4139
                                  c.error());
12 ✔
4140
    return type;
27,858 ✔
4141
}
27,862 ✔
4142

4143
}  // namespace dftracer::utils::dataframe
4144

4145
// ---- C ABI ----------------------------------------------------------------
4146

4147
struct dftu_expr : dftracer::utils::dstd::HeapObject {
1,277 !
4148
    dftracer::utils::dataframe::Expr e;
4149
};
4150

4151
namespace dftracer::utils::dataframe {
4152
const Expr& expr_handle_unwrap(const dftu_expr* h) { return h->e; }
46 ✔
4153
dftu_expr* expr_handle_wrap(Expr e) { return new dftu_expr{{}, std::move(e)}; }
472 ✔
4154
}  // namespace dftracer::utils::dataframe
4155

4156
namespace {
4157
dftu_expr* wrap(dataframe::Expr e) { return new dftu_expr{{}, std::move(e)}; }
2,074 ✔
4158
const dataframe::Expr& unwrap(const dftu_expr* e) { return e->e; }
2,527 ✔
4159
}  // namespace
4160

4161
dftu_expr* dftu_expr_col(std::int32_t index) {
522 ✔
4162
    return wrap(dataframe::expr_col(index));
522 !
4163
}
4164
dftu_expr* dftu_expr_lit_i64(std::int64_t value) {
132 ✔
4165
    return wrap(dataframe::expr_lit(static_cast<std::int64_t>(value)));
132 !
4166
}
4167
dftu_expr* dftu_expr_lit_f64(double value) {
114 ✔
4168
    return wrap(dataframe::expr_lit(value));
114 !
4169
}
4170
dftu_expr* dftu_expr_binary(std::int32_t op, const dftu_expr* a,
386 ✔
4171
                            const dftu_expr* b) {
4172
    return wrap(dataframe::expr_binary(static_cast<dataframe::BinaryOp>(op),
579 !
4173
                                       unwrap(a), unwrap(b)));
386 ✔
4174
}
UNCOV
4175
dftu_expr* dftu_expr_prim(std::int32_t prim, const dftu_expr* a) {
×
UNCOV
4176
    return wrap(
×
UNCOV
4177
        dataframe::expr_prim(static_cast<dataframe::PrimOp>(prim), unwrap(a)));
×
4178
}
4179
dftu_expr* dftu_expr_unary(std::int32_t op, const dftu_expr* a) {
64 ✔
4180
    return wrap(
64 !
4181
        dataframe::expr_unary(static_cast<dataframe::UnaryOp>(op), unwrap(a)));
64 ✔
4182
}
4183
dftu_expr* dftu_expr_clip(const dftu_expr* a, dftu_scalar lo, dftu_scalar hi) {
64 ✔
4184
    return wrap(dataframe::expr_clip(unwrap(a), lo, hi));
64 !
4185
}
4186
std::int32_t dftu_expr_col_index(const dftu_expr* e) {
4 ✔
4187
    return e ? dataframe::expr_col_index(unwrap(e)) : -1;
4 !
4188
}
4189
std::int32_t dftu_expr_as_col_cmp(const dftu_expr* e, std::int32_t* col,
60 ✔
4190
                                  std::int32_t* cmp, dftu_scalar* rhs) {
4191
    if (!e || !col || !cmp || !rhs) return 0;
60 !
4192
    std::int32_t c = -1;
60 ✔
4193
    dataframe::CmpOp op{};
60 ✔
4194
    dataframe::Scalar r;
60 ✔
4195
    if (!dataframe::expr_as_col_cmp(unwrap(e), &c, &op, &r)) return 0;
60 ✔
4196
    *col = c;
50 ✔
4197
    *cmp = static_cast<std::int32_t>(op);
50 ✔
4198
    *rhs = r;
50 ✔
4199
    return 1;
50 ✔
4200
}
30 ✔
4201
std::int32_t dftu_expr_as_logical(const dftu_expr* e, std::int32_t* op,
10 ✔
4202
                                  dftu_expr** a, dftu_expr** b) {
4203
    if (!e || !op || !a || !b) return 0;
10 !
4204
    dataframe::LogicalOp lop{};
10 ✔
4205
    dataframe::Expr lhs, rhs;
10 ✔
4206
    if (!dataframe::expr_as_logical(unwrap(e), &lop, &lhs, &rhs)) return 0;
10 ✔
4207
    *op = static_cast<std::int32_t>(lop);
2 ✔
4208
    *a = wrap(std::move(lhs));
2 !
4209
    *b = wrap(std::move(rhs));
2 !
4210
    return 1;
2 ✔
4211
}
10 !
4212
std::int32_t dftu_expr_as_not(const dftu_expr* e, dftu_expr** a) {
10 ✔
4213
    if (!e || !a) return 0;
10 !
4214
    dataframe::Expr inner;
10 ✔
4215
    if (!dataframe::expr_as_not(unwrap(e), &inner)) return 0;
10 ✔
4216
    *a = wrap(std::move(inner));
2 !
4217
    return 1;
2 ✔
4218
}
10 ✔
4219
std::int32_t dftu_expr_as_col_str_pred(const dftu_expr* e, std::int32_t* col,
10 ✔
4220
                                       std::int32_t* op, const char** pattern,
4221
                                       std::int32_t* pattern_size) {
4222
    if (!e || !col || !op || !pattern || !pattern_size) return 0;
10 !
4223
    std::int32_t c = -1;
10 ✔
4224
    dataframe::StrPredOp sop{};
10 ✔
4225
    dftracer::utils::dstd::StringView pat;
10 ✔
4226
    if (!dataframe::expr_as_col_str_pred(unwrap(e), &c, &sop, &pat)) return 0;
10 ✔
4227
    *col = c;
2 ✔
4228
    *op = static_cast<std::int32_t>(sop);
2 ✔
4229
    *pattern = pat.data();
2 ✔
4230
    *pattern_size = static_cast<std::int32_t>(pat.size());
2 ✔
4231
    return 1;
2 ✔
4232
}
5 ✔
4233
std::int32_t dftu_expr_as_col_is_in(const dftu_expr* e, std::int32_t* col,
10 ✔
4234
                                    dftu_series** values) {
4235
    if (!e || !col || !values) return 0;
10 !
4236
    std::int32_t c = -1;
10 ✔
4237
    dataframe::Series v;
10 ✔
4238
    if (!dataframe::expr_as_col_is_in(unwrap(e), &c, &v)) return 0;
10 ✔
4239
    *col = c;
2 ✔
4240
    *values = v.release();
2 ✔
4241
    return 1;
2 ✔
4242
}
10 ✔
4243
dftu_expr* dftu_expr_cmp(std::int32_t cmp, const dftu_expr* a,
272 ✔
4244
                         dftu_scalar rhs) {
4245
    return wrap(dataframe::expr_cmp(static_cast<dataframe::CmpOp>(cmp),
544 !
4246
                                    unwrap(a), rhs));
408 ✔
4247
}
4248
dftu_expr* dftu_expr_logical(std::int32_t op, const dftu_expr* a,
76 ✔
4249
                             const dftu_expr* b) {
4250
    return wrap(dataframe::expr_logical(static_cast<dataframe::LogicalOp>(op),
114 !
4251
                                        unwrap(a), unwrap(b)));
76 ✔
4252
}
4253
dftu_expr* dftu_expr_not(const dftu_expr* a) {
18 ✔
4254
    return wrap(dataframe::expr_not(unwrap(a)));
18 !
4255
}
4256
dftu_expr* dftu_expr_cast(std::int32_t type, const dftu_expr* a) {
250 ✔
4257
    return wrap(
250 !
4258
        dataframe::expr_cast(static_cast<dataframe::TypeId>(type), unwrap(a)));
250 ✔
4259
}
UNCOV
4260
dftu_expr* dftu_expr_lower(const dftu_expr* a) {
×
UNCOV
4261
    return wrap(dataframe::expr_lower(unwrap(a)));
×
4262
}
4263
dftu_expr* dftu_expr_str_pred(std::int32_t op, const dftu_expr* a,
6 ✔
4264
                              const char* pattern, std::int32_t pattern_size) {
4265
    if (!a || (pattern_size > 0 && !pattern)) return nullptr;
6 !
4266
    return wrap(dataframe::expr_str_pred(
6 !
4267
        static_cast<dataframe::StrPredOp>(op), unwrap(a),
2 ✔
4268
        dftracer::utils::dstd::StringView(
2 ✔
4269
            pattern ? pattern : "", static_cast<std::size_t>(pattern_size))));
2 !
4270
}
3 ✔
4271
dftu_expr* dftu_expr_str_pred_col(std::int32_t op, const dftu_expr* a,
6 ✔
4272
                                  const dftu_expr* needle) {
4273
    if (!a || !needle) return nullptr;
6 ✔
4274
    if (op != static_cast<std::int32_t>(dataframe::StrPredOp::Contains) &&
4 ✔
4275
        op != static_cast<std::int32_t>(dataframe::StrPredOp::StartsWith) &&
3 !
4276
        op != static_cast<std::int32_t>(dataframe::StrPredOp::EndsWith))
1 ✔
4277
        return nullptr;
1 ✔
4278
    auto e = dataframe::expr_str_pred_col(static_cast<dataframe::StrPredOp>(op),
3 ✔
4279
                                          unwrap(a), unwrap(needle));
2 ✔
4280
    return e ? wrap(std::move(*e)) : nullptr;
4 !
4281
}
6 ✔
4282
dftu_expr* dftu_expr_str_replace_col(const dftu_expr* a, const dftu_expr* from,
4 ✔
4283
                                     const dftu_expr* to) {
4284
    if (!a || !from || !to) return nullptr;
4 !
4285
    return wrap(
2 !
4286
        dataframe::expr_str_replace_col(unwrap(a), unwrap(from), unwrap(to)));
3 ✔
4287
}
2 ✔
4288
dftu_expr* dftu_expr_str_substr_col(const dftu_expr* a, const dftu_expr* start,
8 ✔
4289
                                    const dftu_expr* len) {
4290
    if (!a || !start) return nullptr;
8 ✔
4291
    const dataframe::Expr l = len ? unwrap(len) : dataframe::Expr{};
4 !
4292
    return wrap(dataframe::expr_str_substr_col(unwrap(a), unwrap(start),
7 !
4293
                                               len ? &l : nullptr));
2 ✔
4294
}
8 ✔
4295
dftu_expr* dftu_expr_round_col(const dftu_expr* a, const dftu_expr* digits) {
4 ✔
4296
    if (!a || !digits) return nullptr;
4 ✔
4297
    return wrap(dataframe::expr_round_col(unwrap(a), unwrap(digits)));
2 !
4298
}
2 ✔
4299
dftu_expr* dftu_expr_str_map(std::int32_t op, const dftu_expr* a) {
2 ✔
4300
    if (!a) return nullptr;
2 !
4301
    return wrap(dataframe::expr_str_map(static_cast<dataframe::StrMapOp>(op),
3 !
4302
                                        unwrap(a)));
1 ✔
4303
}
1 ✔
4304
dftu_expr* dftu_expr_str_fn(std::int32_t fn, const dftu_expr* a,
4 ✔
4305
                            const dftu_expr* b, const char* text,
4306
                            std::int32_t text_size, const char* text2,
4307
                            std::int32_t text2_size, std::int64_t i0,
4308
                            std::int64_t i1) {
4309
    if (!a || fn < 0 || fn > DFTU_STR_FN_WRAP || (text_size > 0 && !text) ||
5 !
4310
        (text2_size > 0 && !text2))
2 !
4311
        return nullptr;
1 ✔
4312
    const dataframe::Expr other = b ? unwrap(b) : dataframe::Expr{};
2 !
4313
    return wrap(dataframe::expr_str_fn(
5 !
4314
        static_cast<dataframe::StrFn>(fn), unwrap(a), b ? &other : nullptr,
1 !
4315
        dftracer::utils::dstd::StringView(text ? text : "",
1 !
4316
                                          static_cast<std::size_t>(text_size)),
1 ✔
4317
        dftracer::utils::dstd::StringView(text2 ? text2 : "",
1 !
4318
                                          static_cast<std::size_t>(text2_size)),
1 ✔
4319
        i0, i1));
1 ✔
4320
}
4 ✔
4321
dftu_expr* dftu_expr_str_len(const dftu_expr* a, std::int32_t chars) {
2 ✔
4322
    if (!a) return nullptr;
2 !
4323
    return wrap(dataframe::expr_str_size(unwrap(a), chars != 0));
2 !
4324
}
1 ✔
4325
dftu_expr* dftu_expr_str_find(const dftu_expr* a, const char* needle,
2 ✔
4326
                              std::int32_t needle_size) {
4327
    if (!a || (needle_size > 0 && !needle)) return nullptr;
2 !
4328
    return wrap(dataframe::expr_str_find(
3 !
4329
        unwrap(a),
1 ✔
4330
        dftracer::utils::dstd::StringView(
1 ✔
4331
            needle ? needle : "", static_cast<std::size_t>(needle_size))));
1 !
4332
}
1 ✔
4333
dftu_expr* dftu_expr_str_replace(const dftu_expr* a, const char* from,
2 ✔
4334
                                 std::int32_t from_size, const char* to,
4335
                                 std::int32_t to_size, std::int32_t all) {
4336
    if (!a || (from_size > 0 && !from) || (to_size > 0 && !to)) return nullptr;
2 !
4337
    return wrap(dataframe::expr_str_replace(
4 !
4338
        unwrap(a),
1 ✔
4339
        dftracer::utils::dstd::StringView(from ? from : "",
1 !
4340
                                          static_cast<std::size_t>(from_size)),
1 ✔
4341
        dftracer::utils::dstd::StringView(to ? to : "",
1 !
4342
                                          static_cast<std::size_t>(to_size)),
1 ✔
4343
        all != 0));
1 ✔
4344
}
1 ✔
4345
dftu_expr* dftu_expr_date_part(const dftu_expr* a, std::int32_t part,
8 ✔
4346
                               std::int64_t ns_per_unit) {
4347
    if (!a || !dftracer::utils::common::is_date_part_code(part) ||
8 ✔
4348
        ns_per_unit <= 0)
2 ✔
4349
        return nullptr;
3 ✔
4350
    auto e = dataframe::expr_date_part(unwrap(a), part, ns_per_unit);
2 ✔
4351
    return e ? wrap(std::move(*e)) : nullptr;
4 !
4352
}
8 ✔
4353
dftu_expr* dftu_expr_format_time(const dftu_expr* a, const char* fmt,
12 ✔
4354
                                 std::int32_t fmt_size,
4355
                                 std::int64_t ns_per_unit) {
4356
    if (!a || fmt_size < 0 || (fmt_size > 0 && !fmt) || ns_per_unit <= 0)
12 ✔
4357
        return nullptr;
3 ✔
4358
    const dftracer::utils::dstd::StringView f(
9 ✔
4359
        fmt ? fmt : "", static_cast<std::size_t>(fmt_size));
6 ✔
4360
    if (!dftracer::utils::common::invalid_time_format(f).empty())
6 ✔
4361
        return nullptr;
2 ✔
4362
    auto e = dataframe::expr_format_time(unwrap(a), f, ns_per_unit);
2 ✔
4363
    return e ? wrap(std::move(*e)) : nullptr;
4 !
4364
}
12 ✔
4365
dftu_expr* dftu_expr_str_slice(const dftu_expr* a, std::int64_t start,
2 ✔
4366
                               std::int64_t len) {
4367
    if (!a) return nullptr;
2 !
4368
    return wrap(dataframe::expr_str_slice(unwrap(a), start, len));
2 !
4369
}
1 ✔
4370
dftu_expr* dftu_expr_is_in(const dftu_expr* a, const dftu_series* values) {
6 ✔
4371
    if (!a || !values) return nullptr;
6 ✔
4372
    return wrap(dataframe::expr_is_in(
4 !
4373
        unwrap(a), dataframe::Series{dftu_series_share(values)}));
6 ✔
4374
}
3 ✔
4375
dftu_expr* dftu_expr_select(const dftu_expr* cond, const dftu_expr* a,
36 ✔
4376
                            const dftu_expr* b) {
4377
    if (!cond || !a || !b) return nullptr;
36 !
4378
    return wrap(dataframe::expr_select(unwrap(cond), unwrap(a), unwrap(b)));
34 !
4379
}
18 ✔
4380
dftu_expr* dftu_expr_is_na(const dftu_expr* a, std::int32_t na) {
48 ✔
4381
    if (!a) return nullptr;
48 !
4382
    return wrap(dataframe::expr_is_na(unwrap(a), na != 0));
48 !
4383
}
24 ✔
4384

4385
dftu_expr* dftu_expr_is_null(const dftu_expr* a, std::int32_t null) {
6 ✔
4386
    if (!a) return nullptr;
6 ✔
4387
    return wrap(dataframe::expr_is_null(unwrap(a), null != 0));
4 !
4388
}
3 ✔
4389
dftu_expr* dftu_expr_lit_str(const char* value, std::int32_t len) {
4 ✔
4390
    if (len < 0 || (len > 0 && !value)) return nullptr;
4 !
4391
    return wrap(dataframe::expr_lit_str(dftracer::utils::dstd::StringView(
3 !
4392
        value ? value : "", static_cast<std::size_t>(len))));
1 !
4393
}
2 ✔
4394
dftu_expr* dftu_expr_lit_bool(std::int32_t value) {
×
4395
    return wrap(dataframe::expr_lit_bool(value != 0));
×
4396
}
4397
dftu_expr* dftu_expr_lit_null(std::int32_t type) {
×
4398
    return wrap(dataframe::expr_lit_null(static_cast<dataframe::TypeId>(type)));
×
4399
}
4400
dftu_expr* dftu_expr_arith(std::int32_t op, const dftu_expr* a,
22 ✔
4401
                           const dftu_expr* b) {
4402
    if (!a || !b) return nullptr;
22 ✔
4403
    return wrap(dataframe::expr_arith(static_cast<dataframe::ArithOp>(op),
30 !
4404
                                      unwrap(a), unwrap(b)));
10 ✔
4405
}
11 ✔
4406
dftu_expr* dftu_expr_neg(const dftu_expr* a) {
×
4407
    if (!a) return nullptr;
×
UNCOV
4408
    return wrap(dataframe::expr_neg(unwrap(a)));
×
4409
}
4410
dftu_expr* dftu_expr_cmp_expr(std::int32_t cmp, const dftu_expr* a,
16 ✔
4411
                              const dftu_expr* b) {
4412
    if (!a || !b) return nullptr;
16 !
4413
    return wrap(dataframe::expr_cmp_expr(static_cast<dataframe::CmpOp>(cmp),
24 !
4414
                                         unwrap(a), unwrap(b)));
8 ✔
4415
}
8 ✔
4416
namespace {
4417
bool expr_args(const dftu_expr* const* args, std::int32_t n,
20 ✔
4418
               dftracer::utils::dstd::Vector<dataframe::Expr>& out) {
4419
    if (!args || n <= 0) return false;
20 ✔
4420
    out.reserve(static_cast<std::size_t>(n));
18 ✔
4421
    for (std::int32_t i = 0; i < n; ++i) {
54 !
4422
        if (!args[i]) return false;
36 ✔
4423
        out.push_back(unwrap(args[i]));
36 ✔
4424
    }
18 ✔
4425
    return true;
9 ✔
4426
}
10 ✔
4427
}  // namespace
4428
dftu_expr* dftu_expr_coalesce(const dftu_expr* const* args, std::int32_t n) {
20 ✔
4429
    dftracer::utils::dstd::Vector<dataframe::Expr> v;
20 ✔
4430
    if (!expr_args(args, n, v)) return nullptr;
20 ✔
4431
    return wrap(dataframe::expr_coalesce(v));
18 !
4432
}
20 ✔
UNCOV
4433
dftu_expr* dftu_expr_extreme(const dftu_expr* const* args, std::int32_t n,
×
4434
                             std::int32_t least) {
UNCOV
4435
    dftracer::utils::dstd::Vector<dataframe::Expr> v;
×
UNCOV
4436
    if (!expr_args(args, n, v)) return nullptr;
×
UNCOV
4437
    return wrap(dataframe::expr_extreme(v, least != 0));
×
UNCOV
4438
}
×
UNCOV
4439
dftu_expr* dftu_expr_concat(const dftu_expr* const* args, std::int32_t n) {
×
UNCOV
4440
    dftracer::utils::dstd::Vector<dataframe::Expr> v;
×
UNCOV
4441
    if (!expr_args(args, n, v)) return nullptr;
×
UNCOV
4442
    return wrap(dataframe::expr_concat(v));
×
UNCOV
4443
}
×
UNCOV
4444
dftu_expr* dftu_expr_round(const dftu_expr* a, std::int64_t digits) {
×
UNCOV
4445
    if (!a) return nullptr;
×
UNCOV
4446
    return wrap(dataframe::expr_round(unwrap(a), digits));
×
4447
}
UNCOV
4448
dftu_expr* dftu_expr_log(const dftu_expr* a) {
×
UNCOV
4449
    if (!a) return nullptr;
×
UNCOV
4450
    return wrap(dataframe::expr_log(unwrap(a)));
×
4451
}
UNCOV
4452
dftu_expr* dftu_expr_pow(const dftu_expr* a, const dftu_expr* b) {
×
UNCOV
4453
    if (!a || !b) return nullptr;
×
UNCOV
4454
    return wrap(dataframe::expr_pow(unwrap(a), unwrap(b)));
×
4455
}
UNCOV
4456
dftu_expr* dftu_expr_str_substr(const dftu_expr* a, std::int64_t start,
×
4457
                                std::int64_t len) {
UNCOV
4458
    if (!a) return nullptr;
×
UNCOV
4459
    return wrap(dataframe::expr_str_substr(unwrap(a), start, len));
×
4460
}
4461
dftu_expr* dftu_expr_convert(std::int32_t op, const dftu_expr* a) {
2 ✔
4462
    if (!a) return nullptr;
2 !
4463
    return wrap(dataframe::expr_convert(static_cast<dataframe::ConvertOp>(op),
3 !
4464
                                        unwrap(a)));
1 ✔
4465
}
1 ✔
UNCOV
4466
dftu_expr* dftu_expr_list_len(const dftu_expr* a) {
×
UNCOV
4467
    if (!a) return nullptr;
×
UNCOV
4468
    return wrap(dataframe::expr_list_size(unwrap(a)));
×
4469
}
UNCOV
4470
dftu_expr* dftu_expr_list_get(const dftu_expr* a, std::int64_t index) {
×
UNCOV
4471
    if (!a) return nullptr;
×
UNCOV
4472
    return wrap(dataframe::expr_list_get(unwrap(a), index));
×
4473
}
UNCOV
4474
dftu_expr* dftu_expr_list_sum(const dftu_expr* a) {
×
UNCOV
4475
    if (!a) return nullptr;
×
UNCOV
4476
    return wrap(dataframe::expr_list_sum(unwrap(a)));
×
4477
}
UNCOV
4478
dftu_expr* dftu_expr_list_contains(const dftu_expr* a, dftu_scalar value) {
×
UNCOV
4479
    if (!a ||
×
UNCOV
4480
        (value.kind == DFTU_SCALAR_TAG_STR && value.len > 0 && !value.value.s))
×
4481
        return nullptr;
UNCOV
4482
    return wrap(dataframe::expr_list_contains(unwrap(a), value));
×
4483
}
4484
void dftu_expr_free(dftu_expr* e) { delete e; }
3,855 ✔
4485

4486
dftu_series* dftu_expr_eval(const dftu_expr* root,
152 ✔
4487
                            const dftu_series* const* inputs,
4488
                            std::int32_t n_inputs) {
4489
    if (!root) return nullptr;
152 !
4490
    dftracer::utils::dstd::Vector<dataframe::Series> owned;
152 ✔
4491
    dftracer::utils::dstd::Vector<const dataframe::Series*> cols;
152 ✔
4492
    owned.reserve(static_cast<std::size_t>(n_inputs));
152 ✔
4493
    cols.reserve(static_cast<std::size_t>(n_inputs));
152 ✔
4494
    for (std::int32_t i = 0; i < n_inputs; ++i) {
416 ✔
4495
        owned.emplace_back(const_cast<dftu_series*>(inputs[i]));
264 ✔
4496
        cols.push_back(&owned.back());
264 ✔
4497
    }
132 ✔
4498
    dftu_series* out = nullptr;
152 ✔
4499
    if (auto r = dataframe::eval(unwrap(root), cols)) out = r->release();
152 ✔
4500
    for (dataframe::Series& c : owned)
416 ✔
4501
        c.release();  // borrowed inputs, do not free
264 ✔
4502
    return out;
152 ✔
4503
}
152 ✔
4504

4505
std::int32_t dftu_expr_eval_many(const dftu_expr* const* roots,
116 ✔
4506
                                 std::int32_t n_roots,
4507
                                 const dftu_series* const* inputs,
4508
                                 std::int32_t n_inputs, dftu_series** out) {
4509
    if (!roots || n_roots <= 0) return -1;
116 !
4510
    dftracer::utils::dstd::Vector<dataframe::Expr> exprs;
116 ✔
4511
    exprs.reserve(static_cast<std::size_t>(n_roots));
116 ✔
4512
    for (std::int32_t i = 0; i < n_roots; ++i) {
492 !
4513
        if (!roots[i]) return -1;
376 ✔
4514
        exprs.push_back(unwrap(roots[i]));
376 ✔
4515
    }
188 ✔
4516
    dftracer::utils::dstd::Vector<dataframe::Series> owned;
116 ✔
4517
    dftracer::utils::dstd::Vector<const dataframe::Series*> cols;
116 ✔
4518
    owned.reserve(static_cast<std::size_t>(n_inputs));
116 ✔
4519
    cols.reserve(static_cast<std::size_t>(n_inputs));
116 ✔
4520
    for (std::int32_t i = 0; i < n_inputs; ++i) {
336 ✔
4521
        owned.emplace_back(const_cast<dftu_series*>(inputs[i]));
220 ✔
4522
        cols.push_back(&owned.back());
220 ✔
4523
    }
110 ✔
4524
    std::int32_t written = -1;
116 ✔
4525
    if (auto res = dataframe::eval_many(exprs, cols)) {
174 ✔
4526
        for (std::size_t i = 0; i < res->size(); ++i)
492 ✔
4527
            out[i] = (*res)[i].release();
376 ✔
4528
        written = static_cast<std::int32_t>(res->size());
116 ✔
4529
    }
116 ✔
4530
    for (dataframe::Series& c : owned)
336 ✔
4531
        c.release();  // borrowed inputs, do not free
220 ✔
4532
    return written;
116 ✔
4533
}
116 ✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc