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

llnl-asr / dftracer-utils / 45996541911

27 Nov 2026 12:11PM UTC coverage: 77.548% (-0.04%) from 77.591%
45996541911

push

github

rayandrew
test(trace): bound the scan alone in the small-unit budget test

The memory budget bounds the scan, not the frame that collect returns,
so the test measured memory the budget never promised to bound. A filter
that the scan applies and that matches no row leaves the scan alone.

166775 of 258053 branches covered (64.63%)

Branch coverage included in aggregate %.

192744 of 205558 relevant lines covered (93.77%)

4613634.78 hits per line

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

79.06
/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/float_divmod.h>
12
#include <dftracer/utils/dataframe/internal/scalar.h>     // scalar_as
13
#include <dftracer/utils/dataframe/kernels/string_ops.h>  // str_pattern
14
#include <dftracer/utils/dataframe/parallel.h>
15
#include <dftracer/utils/dataframe/udf_registry.h>
16
#include <dftracer/utils/dstd/fatal.h>
17
#include <dftracer/utils/dstd/fmt.h>
18
#include <dftracer/utils/dstd/map.h>
19
#include <dftracer/utils/dstd/memory.h>
20
#include <dftracer/utils/dstd/optional.h>
21
#include <dftracer/utils/dstd/span.h>
22
#include <dftracer/utils/dstd/string.h>
23
#include <dftracer/utils/dstd/to_chars.h>
24
#include <dftracer/utils/dstd/tuple.h>
25
#include <dftracer/utils/dstd/vector.h>
26
#include <dftracer/utils/duql/pattern_engine.h>
27
#include <dftracer/utils/duql/substr_simd.h>
28
#include <dftracer/utils/json/json_escape.h>
29

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

46
using namespace dftracer::utils;
47

48
namespace dftracer::utils::dataframe {
49

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

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

132
namespace {
133

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

146
}  // namespace
147

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

156
namespace {
157

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

178
}  // namespace
179

180
std::uint64_t expr_fingerprint(const Expr& e) {
356 ✔
181
    detail::Fingerprint fp;
356 ✔
182
    fingerprint_node(fp, e.node().get());
356 ✔
183
    return fp.value();
534 ✔
184
}
178 ✔
185

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

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

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

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

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

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

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

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

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

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

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

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

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

396
}  // namespace
397

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

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

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

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

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

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

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

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

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

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

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

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

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

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

822
namespace {
823

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

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

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

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

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

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

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

992
dftu_scalar to_f64_scalar(dftu_scalar s) {
6,724 ✔
993
    dftu_scalar r{};
6,724 ✔
994
    r.kind = DFTU_SCALAR_TAG_F64;
6,724 ✔
995
    const bool numeric = s.kind == DFTU_SCALAR_TAG_I64 ||
8,572 ✔
996
                         s.kind == DFTU_SCALAR_TAG_U64 ||
5,210 !
997
                         s.kind == DFTU_SCALAR_TAG_F64;
1,848 ✔
998
    r.value.d = numeric ? scalar_as<double>(s) : s.value.d;
6,724 !
999
    return r;
3,362 ✔
1000
}
3,362 ✔
1001

1002
bool is_int_type(TypeId t) {
25,544 ✔
1003
    switch (t) {
25,544 ✔
1004
        case TypeId::Int8:
1005
        case TypeId::Int16:
1006
        case TypeId::Int32:
1007
        case TypeId::Int64:
1008
        case TypeId::Uint8:
1009
        case TypeId::Uint16:
1010
        case TypeId::Uint32:
1011
        case TypeId::Uint64:
1012
            return true;
7,850 ✔
1013
        default:
4,921 ✔
1014
            return false;
9,843 ✔
1015
    }
1016
}
12,772 ✔
1017

1018
bool is_num_type(TypeId t) {
25,412 ✔
1019
    return is_int_type(t) || t == TypeId::Float32 || t == TypeId::Float64;
25,412 ✔
1020
}
1021

1022
bool is_text_type(TypeId t) {
3,316 ✔
1023
    return t == TypeId::String || t == TypeId::LargeString;
3,316 ✔
1024
}
1025

1026
// The type two numeric operands meet at: either float makes Float64, two
1027
// different integer types meet at Int64.
1028
TypeId promote(TypeId a, TypeId b) {
10,488 ✔
1029
    if (a == TypeId::Float64 || b == TypeId::Float64 || a == TypeId::Float32 ||
10,488 !
1030
        b == TypeId::Float32)
8,154 !
1031
        return TypeId::Float64;
1,168 ✔
1032
    return a == b && (a == TypeId::Int64 || a == TypeId::Uint64)
5,723 ✔
1033
               ? a
5,722 ✔
1034
               : TypeId::Int64;
1035
}
5,245 ✔
1036

1037
TypeId arith_type(std::int32_t op, TypeId a, TypeId b) {
10,544 ✔
1038
    return static_cast<ArithOp>(op) == ArithOp::Div ? TypeId::Float64
10,544 ✔
1039
           : promote(a, b) == TypeId::Float64       ? TypeId::Float64
10,390 ✔
1040
                                                    : TypeId::Int64;
5,271 ✔
1041
}
1042

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

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

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

1065
    Val compile(const ExprNode* n) {
290,107 ✔
1066
        if (failed()) return unknown_val();
290,107 ✔
1067
        switch (n->kind) {
290,103 ✔
1068
            case ExprKind::LitI64:
16,397 ✔
1069
            case ExprKind::LitF64:
16,397 ✔
1070
                return {true, -1, TypeId::Int64, n->scalar,
49,191 ✔
1071
                        scalar(TypeId::Int64)};
32,794 ✔
1072
            case ExprKind::Col: {
63,066 ✔
1073
                if (n->i < 0 ||
126,152 ✔
1074
                    static_cast<std::size_t>(n->i) >= input_types_.size())
126,150 ✔
1075
                    return fail("expr: column index out of range");
6 ✔
1076
                const DataType& dt =
189,227 ✔
1077
                    input_types_[static_cast<std::size_t>(n->i)];
126,146 ✔
1078
                if (dt.id == TypeId::Unknown)
126,146 ✔
1079
                    return {false, -1, TypeId::Unknown, {}, dt};
16,704 ✔
1080
                int slot = emit(OpLoad, -1, -1, n->i, {});
109,442 ✔
1081
                return {false, slot, dt.id, {}, dt};
109,453 ✔
1082
            }
63,081 ✔
1083
            case ExprKind::Binary:
33,148 ✔
1084
                return compile_binary(n);
66,295 ✔
1085
            case ExprKind::Prim: {
117 ✔
1086
                Val a0 = compile(n->a.get());
234 ✔
1087
                if (is_unknown(a0)) return unknown_val();
234 !
1088
                Val a = as_col(a0, "prim");
234 ✔
1089
                if (a.type != TypeId::Int64 && a.type != TypeId::Uint64)
234 !
1090
                    a = cast(a, TypeId::Int64);
×
1091
                return {false,
468 ✔
1092
                        emit(OpPrim, a.slot, -1, n->i, {}),
234 ✔
1093
                        TypeId::Int64,
1094
                        {},
117 ✔
1095
                        scalar(TypeId::Int64)};
234 ✔
1096
            }
234 ✔
1097
            case ExprKind::Unary: {
641 ✔
1098
                Val a0 = compile(n->a.get());
1,282 ✔
1099
                if (is_unknown(a0)) return unknown_val();
1,282 !
1100
                Val a = as_col(a0, "unary");
1,282 ✔
1101
                // is_nan/is_finite/is_infinite yield a Bool mask; log/sqrt/exp
1102
                // widen to Float64; the rest keep the input type (integer
1103
                // floor/ceil/round/trunc are identities).
1104
                const auto op = static_cast<UnaryOp>(n->i);
1,282 ✔
1105
                TypeId t;
1,282 ✔
1106
                switch (op) {
1,282 ✔
1107
                    case UnaryOp::IsNan:
1108
                    case UnaryOp::IsFinite:
1109
                    case UnaryOp::IsInfinite:
1110
                        t = TypeId::Bool;
30 ✔
1111
                        break;
30 ✔
1112
                    case UnaryOp::Log:
18 ✔
1113
                    case UnaryOp::Sqrt:
18 ✔
1114
                    case UnaryOp::Exp:
18 ✔
1115
                    case UnaryOp::Log1p:
18 ✔
1116
                    case UnaryOp::Expm1:
18 ✔
1117
                        t = TypeId::Float64;
36 ✔
1118
                        break;
36 ✔
1119
                    default:
593 ✔
1120
                        t = a.type;
1,186 ✔
1121
                        break;
1,186 ✔
1122
                }
1123
                return {false,
3,205 ✔
1124
                        emit(OpUnary, a.slot, -1, n->i, {}),
1,282 ✔
1125
                        t,
641 ✔
1126
                        {},
641 ✔
1127
                        scalar(t)};
1,282 ✔
1128
            }
1,282 ✔
1129
            case ExprKind::Clip: {
42 ✔
1130
                Val a0 = compile(n->a.get());
84 ✔
1131
                if (is_unknown(a0)) return unknown_val();
84 !
1132
                Val a = as_col(a0, "clip");
84 ✔
1133
                return {false,
210 ✔
1134
                        emit(OpClip, a.slot, -1, 0, n->scalar, n->scalar2),
84 ✔
1135
                        a.type,
84 ✔
1136
                        {},
42 ✔
1137
                        scalar(a.type)};
84 ✔
1138
            }
84 ✔
1139
            case ExprKind::Fillna: {
33 ✔
1140
                Val a0 = compile(n->a.get());
66 ✔
1141
                if (is_unknown(a0)) return unknown_val();
66 !
1142
                Val a = as_col(a0, "fillna");
66 ✔
1143
                const dftu_scalar fill = n->scalar;
66 ✔
1144
                if (is_text_type(a.type) ? fill.kind != DFTU_SCALAR_TAG_STR &&
94 ✔
1145
                                               fill.kind != DFTU_SCALAR_TAG_NULL
2 ✔
1146
                                         : fill.kind == DFTU_SCALAR_TAG_STR)
56 ✔
1147
                    return fail(dstd::fmt<"expr: fillna of {} takes {}">(
12 ✔
1148
                        type_name(a.type), is_text_type(a.type)
18 ✔
1149
                                               ? "a string fill"
1150
                                               : "a number fill"));
6 ✔
1151
                return {false,
162 ✔
1152
                        emit(OpFillna, a.slot, -1, n->i, n->scalar),
54 ✔
1153
                        a.type,
54 ✔
1154
                        {},
27 ✔
1155
                        scalar(a.type)};
60 ✔
1156
            }
66 ✔
1157
            case ExprKind::Cmp: {
3,961 ✔
1158
                Val a0 = compile(n->a.get());
7,921 ✔
1159
                if (is_unknown(a0)) return unknown_val();
7,921 ✔
1160
                Val a = as_col(a0, "compare");
7,839 ✔
1161
                return {false,
15,677 ✔
1162
                        emit(OpCmp, a.slot, -1, n->i, n->scalar),
7,839 ✔
1163
                        TypeId::Bool,
1164
                        {},
3,919 ✔
1165
                        scalar(TypeId::Bool)};
7,839 ✔
1166
            }
7,921 ✔
1167
            case ExprKind::Logical: {
573 ✔
1168
                Val a0 = compile(n->a.get());
1,146 ✔
1169
                Val b0 = compile(n->b.get());
1,146 ✔
1170
                if (is_unknown(a0) || is_unknown(b0)) return unknown_val();
1,146 ✔
1171
                Val a = as_col(a0, "logical");
1,066 ✔
1172
                Val b = as_col(b0, "logical");
1,066 ✔
1173
                return {false,
2,132 ✔
1174
                        emit(OpLogical, a.slot, b.slot, n->i, {}),
1,066 ✔
1175
                        TypeId::Bool,
1176
                        {},
533 ✔
1177
                        scalar(TypeId::Bool)};
1,066 ✔
1178
            }
1,679 ✔
1179
            case ExprKind::Not: {
276 ✔
1180
                Val a0 = compile(n->a.get());
552 ✔
1181
                if (is_unknown(a0)) return unknown_val();
552 ✔
1182
                Val a = as_col(a0, "not");
472 ✔
1183
                return {false,
944 ✔
1184
                        emit(OpNot, a.slot, -1, 0, {}),
472 ✔
1185
                        TypeId::Bool,
1186
                        {},
236 ✔
1187
                        scalar(TypeId::Bool)};
472 ✔
1188
            }
552 ✔
1189
            case ExprKind::Cast: {
7,303 ✔
1190
                Val a = as_col(compile(n->a.get()), "cast");
14,605 ✔
1191
                return cast(a, static_cast<TypeId>(n->i));
14,605 ✔
1192
            }
14,605 ✔
1193
            case ExprKind::StrPred: {
170 ✔
1194
                Val a0 = compile(n->a.get());
340 ✔
1195
                if (is_unknown(a0)) return unknown_val();
340 !
1196
                Val a = as_str(a0, "string predicate", true);
340 ✔
1197
                return {false,
680 ✔
1198
                        emit_text(OpStrPred, a.slot, n->i, n->text),
340 ✔
1199
                        TypeId::Bool,
1200
                        {},
170 ✔
1201
                        scalar(TypeId::Bool)};
340 ✔
1202
            }
340 ✔
1203
            case ExprKind::StrMap: {
547 ✔
1204
                Val a0 = compile(n->a.get());
1,094 ✔
1205
                if (is_unknown(a0)) return unknown_val();
1,094 ✔
1206
                Val a = as_str(a0, "string map", false);
1,092 ✔
1207
                return {false,
2,184 ✔
1208
                        emit(OpStrMap, a.slot, -1, n->i, {}),
1,092 ✔
1209
                        TypeId::String,
1210
                        {},
546 ✔
1211
                        scalar(TypeId::String)};
1,092 ✔
1212
            }
1,094 ✔
1213
            case ExprKind::StrLen: {
72 ✔
1214
                Val a0 = compile(n->a.get());
144 ✔
1215
                if (is_unknown(a0)) return unknown_val();
144 ✔
1216
                Val a = as_str(a0, "string length", true);
142 ✔
1217
                return {false,
284 ✔
1218
                        emit(OpStrLen, a.slot, -1, n->i, {}),
142 ✔
1219
                        TypeId::Int64,
1220
                        {},
71 ✔
1221
                        scalar(TypeId::Int64)};
142 ✔
1222
            }
144 ✔
1223
            case ExprKind::StrFind: {
41 ✔
1224
                Val a0 = compile(n->a.get());
82 ✔
1225
                if (is_unknown(a0)) return unknown_val();
82 !
1226
                Val a = as_str(a0, "string find", true);
82 ✔
1227
                return {false,
164 ✔
1228
                        emit_text(OpStrFind, a.slot, 0, n->text),
82 ✔
1229
                        TypeId::Int64,
1230
                        {},
41 ✔
1231
                        scalar(TypeId::Int64)};
82 ✔
1232
            }
82 ✔
1233
            case ExprKind::StrReplace: {
16 ✔
1234
                Val a0 = compile(n->a.get());
32 ✔
1235
                if (is_unknown(a0)) return unknown_val();
32 !
1236
                Val a = as_str(a0, "string replace", false);
32 ✔
1237
                return {
64 ✔
1238
                    false,
1239
                    emit_text(OpStrReplace, a.slot, n->i, n->text, n->text2),
32 ✔
1240
                    TypeId::String,
1241
                    {},
16 ✔
1242
                    scalar(TypeId::String)};
32 ✔
1243
            }
32 ✔
1244
            case ExprKind::DatePart:
521 ✔
1245
            case ExprKind::FormatTime: {
521 ✔
1246
                const bool fmt = n->kind == ExprKind::FormatTime;
1,042 ✔
1247
                Val a0 = compile(n->a.get());
1,042 ✔
1248
                if (is_unknown(a0)) return unknown_val();
1,042 !
1249
                if (!a0.is_scalar && !is_num_type(a0.type))
1,042 !
1250
                    return fail(
8 ✔
1251
                        dstd::fmt<
4 ✔
1252
                            "expr: {} needs a time or integer operand, got {}">(
8 ✔
1253
                            (fmt ? "format_time" : "date_part"),
8 ✔
1254
                            type_name(a0.type)));
12 ✔
1255
                Val a = num(a0, fmt ? "format_time" : "date_part");
1,479 ✔
1256
                SlotOp op;
1,034 ✔
1257
                op.opcode = fmt ? OpFormatTime : OpDatePart;
1,034 ✔
1258
                op.a = a.slot;
1,034 ✔
1259
                op.param = n->i;
1,034 ✔
1260
                op.scalar = n->scalar;
1,034 ✔
1261
                op.text = n->text;
1,034 ✔
1262
                return col_val(emit_op(op),
1,551 ✔
1263
                               fmt ? TypeId::String : TypeId::Int64);
1,479 ✔
1264
            }
1,559 ✔
1265
            case ExprKind::StrSlice: {
7 ✔
1266
                Val a0 = compile(n->a.get());
14 ✔
1267
                if (is_unknown(a0)) return unknown_val();
14 !
1268
                Val a = as_str(a0, "string slice", false);
14 ✔
1269
                return {false,
28 ✔
1270
                        emit(OpStrSlice, a.slot, -1, 0, n->scalar, n->scalar2),
14 ✔
1271
                        TypeId::String,
1272
                        {},
7 ✔
1273
                        scalar(TypeId::String)};
14 ✔
1274
            }
14 ✔
1275
            case ExprKind::IsIn: {
386 ✔
1276
                Val a0 = compile(n->a.get());
772 ✔
1277
                if (is_unknown(a0)) return unknown_val();
772 !
1278
                Val a = as_col(a0, "is_in");
772 ✔
1279
                if (!n->values.valid())
772 ✔
1280
                    return fail("expr: is_in needs a values column");
×
1281
                // No value matches nothing, whatever type the empty list has.
1282
                if (n->values.length() > 0 &&
772 ✔
1283
                    value_domain(a.type) != value_domain(n->values.type()))
764 ✔
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;
768 ✔
1290
                op.opcode = OpIsIn;
768 ✔
1291
                op.a = a.slot;
768 ✔
1292
                op.values = n->values.handle();
768 ✔
1293
                return {
1,536 ✔
1294
                    false, emit_op(op), TypeId::Bool, {}, scalar(TypeId::Bool)};
1,536 ✔
1295
            }
1,158 ✔
1296
            case ExprKind::Select:
849 ✔
1297
                return compile_select(n);
1,699 ✔
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: {
533 ✔
1312
                const auto t = static_cast<TypeId>(n->i);
1,067 ✔
1313
                if (!is_num_type(t) && t != TypeId::Bool && t != TypeId::String)
1,067 ✔
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,065 ✔
1317
            }
534 ✔
1318
            case ExprKind::Arith: {
3,095 ✔
1319
                Val a0 = compile(n->a.get());
6,191 ✔
1320
                Val b0 = compile(n->b.get());
6,191 ✔
1321
                if (is_unknown(a0) || is_unknown(b0)) return unknown_val();
6,191 !
1322
                Val a = num(a0, "arithmetic");
6,191 ✔
1323
                Val b = num(b0, "arithmetic");
6,191 ✔
1324
                const TypeId t = arith_type(n->i, a.type, b.type);
6,191 ✔
1325
                return col_val(emit(OpArith, a.slot, b.slot, n->i, {}), t);
6,191 ✔
1326
            }
9,286 ✔
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: {
1,005 ✔
1336
                Val a0 = compile(n->a.get());
2,010 ✔
1337
                Val b0 = compile(n->b.get());
2,010 ✔
1338
                if (is_unknown(a0) || is_unknown(b0)) return unknown_val();
2,010 !
1339
                Val a = operand(a0, "compare");
1,930 ✔
1340
                Val b = operand(b0, "compare");
1,930 ✔
1341
                same_domain(a, b, "compare");
1,930 ✔
1342
                return col_val(emit(OpCmpExpr, a.slot, b.slot, n->i, {}),
1,930 ✔
1343
                               TypeId::Bool);
965 ✔
1344
            }
2,975 ✔
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 !
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 !
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:
58 ✔
1476
            case ExprKind::StrExtract:
58 ✔
1477
            case ExprKind::StrExtractCol:
58 ✔
1478
            case ExprKind::StrRegexReplace:
58 ✔
1479
                return compile_pattern(n);
116 ✔
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:
922 ✔
1516
                return compile_str_fn(n);
1,867 ✔
1517
            case ExprKind::Udf:
742 ✔
1518
                return compile_udf(n);
1,482 ✔
1519
            case ExprKind::IsNull: {
5,485 ✔
1520
                Val a0 = compile(n->a.get());
10,968 ✔
1521
                if (is_unknown(a0)) return unknown_val();
10,968 ✔
1522
                Val a = as_col(a0, "is_null");
10,808 ✔
1523
                return {false,
21,614 ✔
1524
                        emit(OpIsNull, a.slot, -1, n->i, {}),
10,808 ✔
1525
                        TypeId::Bool,
1526
                        {},
5,403 ✔
1527
                        scalar(TypeId::Bool)};
10,808 ✔
1528
            }
10,968 ✔
1529
        }
1530
        dstd::fatal("expr: unknown node kind");
×
1531
    }
145,069 ✔
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,294 ✔
1538
        return {false, slot, t, {}, scalar(t)};
17,927 ✔
1539
    }
10,155 ✔
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,947 ✔
1544
        if (v.is_scalar)
17,947 ✔
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,368 ✔
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,364 ✔
1554
            v.type == TypeId::Float64)
1,668 ✔
1555
            return v;
12,344 ✔
1556
        return cast(v, is_int_type(v.type) ? TypeId::Int64 : TypeId::Float64);
20 !
1557
    }
8,974 ✔
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,261 ✔
1562
        if (v.is_scalar || is_num_type(v.type)) return num(v, who);
6,261 ✔
1563
        return v;
2,012 ✔
1564
    }
3,130 ✔
1565

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

1575
    TypeId common_type(const Val& a, const Val& b, dstd::StringView who) {
466 ✔
1576
        if (is_num_type(a.type) && is_num_type(b.type))
466 ✔
1577
            return promote(a.type, b.type);
72 ✔
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
    }
234 ✔
1585

1586
    Val to_type(Val v, TypeId t) {
867 ✔
1587
        if (v.type == t) return v;
867 ✔
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
    }
433 ✔
1592

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

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

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

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

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

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

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

1797
    Val cast(Val v, TypeId t) {
26,367 ✔
1798
        return {false,
65,913 ✔
1799
                emit(OpCast, v.slot, -1, static_cast<std::int32_t>(t), {}),
26,367 ✔
1800
                t,
13,182 ✔
1801
                {},
13,182 ✔
1802
                scalar(t)};
26,367 ✔
1803
    }
13,182 ✔
1804

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

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

1827
        if (!a.is_scalar && !b.is_scalar)
53,786 ✔
1828
            return {false,
104,106 ✔
1829
                    emit(COL_OP[op], a.slot, b.slot, 0, {}),
34,702 ✔
1830
                    out_type,
17,351 ✔
1831
                    {},
17,351 ✔
1832
                    scalar(out_type)};
34,702 ✔
1833
        if (!a.is_scalar)  // col op scalar
19,084 ✔
1834
            return {false,
57,002 ✔
1835
                    emit(SCALAR_OP[op], a.slot, -1, 0, b.scalar),
19,002 ✔
1836
                    out_type,
9,500 ✔
1837
                    {},
9,500 ✔
1838
                    scalar(out_type)};
19,002 ✔
1839
        if (op == static_cast<int>(BinaryOp::Add) ||
82 ✔
1840
            op == static_cast<int>(BinaryOp::Mul))  // scalar op col commutes
81 ✔
1841
            return {false,
108 ✔
1842
                    emit(SCALAR_OP[op], b.slot, -1, 0, a.scalar),
36 ✔
1843
                    out_type,
18 ✔
1844
                    {},
18 ✔
1845
                    scalar(out_type)};
36 ✔
1846
        // scalar - col and scalar / col have no scalar-first kernel: broadcast
1847
        // the scalar to a column of the result type and run the column kernel.
1848
        const Val left = broadcast(a.scalar, out_type);
46 ✔
1849
        return {false,
115 ✔
1850
                emit(COL_OP[op], left.slot, b.slot, 0, {}),
46 ✔
1851
                out_type,
23 ✔
1852
                {},
23 ✔
1853
                scalar(out_type)};
46 ✔
1854
    }
66,294 ✔
1855

1856
    void promote_float(Val& v) {
43,097 ✔
1857
        if (v.is_scalar) {
43,097 ✔
1858
            v.scalar = to_f64_scalar(v.scalar);
6,603 ✔
1859
        } else if (v.type != TypeId::Float32 && v.type != TypeId::Float64) {
39,795 ✔
1860
            v = cast(v, TypeId::Float64);
9,967 ✔
1861
        }
4,983 ✔
1862
    }
43,097 ✔
1863

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

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

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

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

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

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

2038
    int emit_op(const SlotOp& op) {
247,232 ✔
2039
        auto bits = [](dftu_scalar x) {
741,676 ✔
2040
            return x.kind == DFTU_SCALAR_TAG_F64
494,444 ✔
2041
                       ? std::bit_cast<std::int64_t>(x.value.d)
251,501 ✔
2042
                       : x.value.i;
242,943 ✔
2043
        };
2044
        // len is part of the key: a STR scalar's `bits` is its pointer, and
2045
        // two scalars can share a pointer with different lengths (a prefix),
2046
        // which would otherwise hash-cons to the same slot. A text operand is
2047
        // keyed by value, a values set by identity.
2048
        auto key = std::make_tuple(
370,857 ✔
2049
            op.opcode, op.a, op.b, op.c, static_cast<int>(op.param),
247,234 ✔
2050
            static_cast<int>(op.scalar.kind), bits(op.scalar), bits(op.scalar2),
370,843 ✔
2051
            op.scalar.len, op.scalar2.len, dstd::String(op.text),
370,835 ✔
2052
            dstd::String(op.text2),
370,836 ✔
2053
            reinterpret_cast<std::uintptr_t>(op.values));
370,836 ✔
2054
        auto it = memo_.find(key);
247,229 ✔
2055
        if (it != memo_.end()) return it->second;
247,231 ✔
2056
        int slot = static_cast<int>(program.size());
227,041 ✔
2057
        program.push_back(op);
227,041 ✔
2058
        memo_.emplace(key, slot);
227,038 ✔
2059
        return slot;
227,038 ✔
2060
    }
247,226 ✔
2061

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

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

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

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

2102
    void set(dstd::String text,
1,234 ✔
2103
             dstd::Condition why = dstd::Condition::InvalidArgument) {
2104
        std::lock_guard<std::mutex> lock(mutex);
1,234 ✔
2105
        if (!message.empty()) return;
1,236 ✔
2106
        message = std::move(text);
1,234 ✔
2107
        condition = why;
1,235 ✔
2108
    }
1,245 !
2109
};
2110

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

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

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

2189
Series flat_view(const Series& s) {
14,934 ✔
2190
    if (!s.valid() || s.encoding() == Encoding::Flat) return s.share();
22,400 !
2191
    return s.materialize();
34 ✔
2192
}
7,468 ✔
2193

2194
bool valid_at(const dftu_series* h, std::int64_t i) {
2,397,083 ✔
2195
    return !h->validity.block() ||
2,397,083 ✔
2196
           ((h->validity.data()[i >> 3] >> (i & 7)) & 1);
1,250,751 ✔
2197
}
2198

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

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

2209
struct TextCol {
2210
    const char* data = "";
703 ✔
2211
    const std::int32_t* off32 = nullptr;
703 ✔
2212
    const std::int64_t* off64 = nullptr;
703 ✔
2213

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

2232
dstd::Vector<std::uint8_t> bitmap(std::int64_t n) {
10,395 ✔
2233
    return dstd::Vector<std::uint8_t>(static_cast<std::size_t>((n + 7) / 8), 0);
10,395 ✔
2234
}
5,198 ✔
2235

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

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

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

2268
class BoolCells {
933 ✔
2269
   public:
2270
    explicit BoolCells(std::int64_t n)
2,799 ✔
2271
        : n_(n), bits_(bitmap(n)), valid_(bitmap(n)) {}
3,732 ✔
2272
    void set(std::int64_t i, bool v) {
293,638 ✔
2273
        if (v) set_bit(bits_, i);
293,638 ✔
2274
        set_bit(valid_, i);
293,638 ✔
2275
        ++set_;
293,638 ✔
2276
    }
293,638 ✔
2277
    Series finish() {
1,866 ✔
2278
        return Series::flat(TypeId::Bool, bits_.data(), n_,
2,799 ✔
2279
                            set_ == n_ ? nullptr : valid_.data());
1,866 ✔
2280
    }
933 ✔
2281

2282
   private:
2283
    std::int64_t n_;
2284
    dstd::Vector<std::uint8_t> bits_;
2285
    dstd::Vector<std::uint8_t> valid_;
2286
    std::int64_t set_ = 0;
933 ✔
2287
};
2288

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

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

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

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

2337
template <class T>
2338
int order(T a, T b) {
293,022 ✔
2339
    return a < b ? -1 : (b < a ? 1 : 0);
293,022 ✔
2340
}
2341

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

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

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

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

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

2395
bool apply_cmp(CmpOp op, int c) {
293,224 ✔
2396
    switch (op) {
293,224 ✔
2397
        case CmpOp::Gt:
59,782 ✔
2398
            return c > 0;
119,564 ✔
2399
        case CmpOp::Ge:
85 ✔
2400
            return c >= 0;
170 ✔
2401
        case CmpOp::Lt:
42,560 ✔
2402
            return c < 0;
85,120 ✔
2403
        case CmpOp::Le:
14 ✔
2404
            return c <= 0;
28 ✔
2405
        case CmpOp::Eq:
40,093 ✔
2406
            return c == 0;
80,186 ✔
2407
        case CmpOp::Ne:
4,078 ✔
2408
            return c != 0;
8,156 ✔
2409
    }
2410
    return false;
2411
}
146,612 ✔
2412

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

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

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

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

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

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

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

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

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

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

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

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

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

2612
bool is_num_col(const dftu_series* h) {
3,168 ✔
2613
    return h->type == TypeId::Int64 || h->type == TypeId::Uint64 ||
3,168 ✔
2614
           h->type == TypeId::Float64;
2,519 ✔
2615
}
2616

2617
// -1/0/1 of row i of `a` against row i of `b` (both present), per domain:
2618
// numbers exactly, strings bytewise, false before true; fn gets the order or
2619
// nullopt when the two do not compare (a NaN).
2620
template <class Fn>
2621
bool order_rows(const dftu_series* a, const dftu_series* b, Fn&& fn) {
1,802 ✔
2622
    const std::int64_t n = a->length;
1,802 ✔
2623
    if (is_num_col(a) && is_num_col(b)) {
1,802 !
2624
        with_num(a->type, [&](auto xa) {
3,310 ✔
2625
            with_num(b->type, [&](auto xb) {
428,273 ✔
2626
                using A = decltype(xa);
2627
                using B = decltype(xb);
2628
                const A* pa = values_of<A>(a);
1,324 ✔
2629
                const B* pb = values_of<B>(b);
1,324 ✔
2630
                for (std::int64_t i = 0; i < n; ++i)
213,936 !
2631
                    if (valid_at(a, i) && valid_at(b, i))
318,418 !
2632
                        fn(i, cmp_numbers(pa[i], pb[i]));
211,612 ✔
2633
            });
662 ✔
2634
        });
662 ✔
2635
        return true;
1,324 ✔
2636
    }
2637
    if (a->type == TypeId::Bool && b->type == TypeId::Bool) {
478 !
2638
        for (std::int64_t i = 0; i < n; ++i)
8 !
2639
            if (valid_at(a, i) && valid_at(b, i))
9 !
2640
                fn(i, dftracer::utils::dstd::Optional<int>(
9 ✔
2641
                          order(bit_at(a, i), bit_at(b, i))));
6 ✔
2642
        return true;
1 ✔
2643
    }
2644
    const TextCol ta(a), tb(b);
476 ✔
2645
    if (!is_text_type(a->type) || !is_text_type(b->type) || !ta.ok() ||
714 !
2646
        !tb.ok())
42,465 ✔
2647
        return false;
2648
    for (std::int64_t i = 0; i < n; ++i)
82,652 ✔
2649
        if (valid_at(a, i) && valid_at(b, i))
123,024 !
2650
            fn(i,
122,544 ✔
2651
               dftracer::utils::dstd::Optional<int>(order(ta.at(i), tb.at(i))));
81,696 ✔
2652
    return true;
238 ✔
2653
}
901 ✔
2654

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3898
// eval_chunk returns no columns when a kernel does not take its input type;
3899
// reported here, on the calling thread, since the parallel workers cannot
3900
// return an error.
3901
dstd::Result<void> require_evaluated(dstd::Span<const Series> outs,
56,370 ✔
3902
                                     EvalError& error) {
3903
    if (outs.empty()) {
56,370 ✔
3904
        dstd::String message;
1,237 ✔
3905
        dstd::Condition condition;
1,237 ✔
3906
        {
612 ✔
3907
            std::lock_guard<std::mutex> lock(error.mutex);
1,237 ✔
3908
            message.swap(error.message);
1,231 ✔
3909
            condition = error.condition;
1,242 ✔
3910
        }
1,246 ✔
3911
        if (!message.empty())
1,246 ✔
3912
            return dstd::Unexpected(dstd::Error(condition, message));
1,242 ✔
3913
        return common::make_error(
8 ✔
3914
            common::ErrorCode::InvalidArgument,
3915
            "expr: an operation does not take its input column type");
4 ✔
3916
    }
1,231 ✔
3917
    return {};
55,133 ✔
3918
}
28,192 ✔
3919

3920
dstd::Vector<DataType> types_of(dstd::Span<const Series* const> inputs) {
53,998 ✔
3921
    dstd::Vector<DataType> out;
53,998 ✔
3922
    out.reserve(inputs.size());
53,998 ✔
3923
    for (const Series* s : inputs) out.push_back(s->data_type());
305,373 ✔
3924
    return out;
53,980 ✔
3925
}
26,996 !
3926

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

3938
    dstd::Vector<Expr> roots;
3939
    dstd::Vector<DataType> input_types;
3940
    Compiler c;
3941
    dstd::Vector<Series> flat;  // the inputs the program loads, shared
3942
    dstd::Vector<int> finals;   // the slot of each root
3943
};
3944

3945
dstd::Result<dstd::UniquePtr<Program>> compile_program(
53,994 ✔
3946
    dstd::Span<const Expr> roots, dstd::Span<const Series* const> inputs) {
3947
    auto p = dstd::make_unique<Program>(roots, inputs);
53,994 ✔
3948
    p->finals.reserve(roots.size());
53,989 ✔
3949
    for (const Expr& root : p->roots) {
108,350 ✔
3950
        if (!root.valid())
54,408 ✔
3951
            return common::make_error(common::ErrorCode::InvalidArgument,
×
3952
                                      "expr: null expression");
×
3953
        p->finals.push_back(p->c.column(p->c.compile(root.node().get())).slot);
54,408 ✔
3954
        if (p->c.failed())
54,409 ✔
3955
            return common::make_error(common::ErrorCode::InvalidArgument,
188 ✔
3956
                                      p->c.error());
141 ✔
3957
    }
27,212 ✔
3958
    p->flat.resize(inputs.size());
53,894 ✔
3959
    for (const SlotOp& op : p->c.program)
228,603 ✔
3960
        if (op.opcode == OpLoad) {
174,705 ✔
3961
            const auto i = static_cast<std::size_t>(op.param);
68,342 ✔
3962
            if (!p->flat[i].valid()) p->flat[i] = inputs[i]->share();
68,342 !
3963
        }
87,371 ✔
3964
    return p;
53,898 ✔
3965
}
53,993 ✔
3966

3967
constexpr std::int64_t GRAIN = 1 << 16;
3968

3969
}  // namespace
3970

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

3980
    // Bare column references share the input; the evaluator would slice and
3981
    // concat a copy.
3982
    bool all_cols = true;
84,722 ✔
3983
    for (const Expr& root : roots) {
169,846 ✔
3984
        const std::int32_t i = root.valid() ? expr_col_index(root) : -1;
85,123 !
3985
        all_cols &= i >= 0 && static_cast<std::size_t>(i) < inputs.size();
85,124 !
3986
    }
42,566 ✔
3987
    if (all_cols) {
84,723 ✔
3988
        dstd::Vector<Series> outs;
30,768 ✔
3989
        outs.reserve(roots.size());
30,768 ✔
3990
        for (const Expr& root : roots) {
61,536 ✔
3991
            const Series& in =
46,152 ✔
3992
                *inputs[static_cast<std::size_t>(expr_col_index(root))];
30,768 ✔
3993
            outs.push_back(in.encoding() == Encoding::Flat ? in.share()
45,922 !
3994
                                                           : in.materialize());
230 ✔
3995
        }
15,384 ✔
3996
        return outs;
30,768 ✔
3997
    }
30,768 ✔
3998

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

4013
    const std::int64_t n = inputs.front()->length();
53,859 ✔
4014
    // Window starts: a CHUNKED input's own chunks when every chunked input
4015
    // shares them (each window reads its chunk in place and the results stay
4016
    // chunks), otherwise GRAIN-row windows.
4017
    dstd::Vector<std::int64_t> bounds;
53,852 ✔
4018
    for (std::size_t i = 0; i < inputs.size(); ++i) {
305,024 ✔
4019
        if (!used[i] || !inputs[i]->handle()->is_chunked()) continue;
251,164 ✔
4020
        const dftu_series& h = *inputs[i]->handle();
56 ✔
4021
        const auto* starts =
84 ✔
4022
            reinterpret_cast<const std::int64_t*>(h.data.data());
56 ✔
4023
        dstd::Vector<std::int64_t> own(starts, starts + h.nested.size() + 1);
56 ✔
4024
        if (bounds.empty()) {
56 ✔
4025
            bounds = std::move(own);
34 ✔
4026
        } else if (bounds != own) {
39 ✔
4027
            bounds.clear();
2 !
4028
            break;
2 ✔
4029
        }
4030
    }
56 !
4031
    const bool by_chunk = !bounds.empty();
53,861 ✔
4032
    if (!by_chunk) {
53,861 ✔
4033
        if (n <= GRAIN) {
53,829 ✔
4034
            dstd::Vector<Series> outs =
52,895 ✔
4035
                eval_chunk(program, flat, finals, 0, n, error);
52,895 ✔
4036
            if (auto ok = require_evaluated(outs, error); !ok)
53,518 ✔
4037
                return ok.error();
1,227 ✔
4038
            return outs;
51,669 ✔
4039
        }
52,903 ✔
4040
        for (std::int64_t lo = 0; lo < n; lo += GRAIN) bounds.push_back(lo);
3,786 ✔
4041
        bounds.push_back(n);
934 ✔
4042
    }
467 ✔
4043

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

4083
struct ExprWindows::Impl {
18 ✔
4084
    dstd::UniquePtr<Program> program;
4085
    coro::CancelView cancel;
4086
};
4087

4088
ExprWindows::ExprWindows(dstd::UniquePtr<Impl> impl) noexcept
54 ✔
4089
    : impl_(std::move(impl)) {}
54 ✔
4090
ExprWindows::ExprWindows(ExprWindows&&) noexcept = default;
162 ✔
4091
ExprWindows& ExprWindows::operator=(ExprWindows&&) noexcept = default;
×
4092
ExprWindows::~ExprWindows() = default;
216 ✔
4093

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

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

4123
dstd::Result<Series> eval(const Expr& root,
84,254 ✔
4124
                          dstd::Span<const Series* const> inputs) {
4125
    if (!root.valid())
84,254 !
4126
        return common::make_error(common::ErrorCode::InvalidArgument,
×
4127
                                  "expr: null expression");
×
4128
    dstd::Result<dstd::Vector<Series>> outs =
84,254 ✔
4129
        eval_many(dstd::Span<const Expr>(&root, 1), inputs);
84,254 ✔
4130
    if (!outs) return outs.error();
84,265 ✔
4131
    return std::move(outs->front());
83,595 ✔
4132
}
84,266 ✔
4133

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

4147
}  // namespace dftracer::utils::dataframe
4148

4149
// ---- C ABI ----------------------------------------------------------------
4150

4151
struct dftu_expr : dftracer::utils::dstd::HeapObject {
1,277 !
4152
    dftracer::utils::dataframe::Expr e;
4153
};
4154

4155
namespace dftracer::utils::dataframe {
4156
const Expr& expr_handle_unwrap(const dftu_expr* h) { return h->e; }
46 ✔
4157
dftu_expr* expr_handle_wrap(Expr e) { return new dftu_expr{{}, std::move(e)}; }
472 ✔
4158
}  // namespace dftracer::utils::dataframe
4159

4160
namespace {
4161
dftu_expr* wrap(dataframe::Expr e) { return new dftu_expr{{}, std::move(e)}; }
2,066 ✔
4162
const dataframe::Expr& unwrap(const dftu_expr* e) { return e->e; }
2,519 ✔
4163
}  // namespace
4164

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

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

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

4509
std::int32_t dftu_expr_eval_many(const dftu_expr* const* roots,
115 ✔
4510
                                 std::int32_t n_roots,
4511
                                 const dftu_series* const* inputs,
4512
                                 std::int32_t n_inputs, dftu_series** out) {
4513
    if (!roots || n_roots <= 0) return -1;
115 !
4514
    dftracer::utils::dstd::Vector<dataframe::Expr> exprs;
115 ✔
4515
    exprs.reserve(static_cast<std::size_t>(n_roots));
115 ✔
4516
    for (std::int32_t i = 0; i < n_roots; ++i) {
488 !
4517
        if (!roots[i]) return -1;
373 ✔
4518
        exprs.push_back(unwrap(roots[i]));
373 ✔
4519
    }
185 ✔
4520
    dftracer::utils::dstd::Vector<dataframe::Series> owned;
115 ✔
4521
    dftracer::utils::dstd::Vector<const dataframe::Series*> cols;
115 ✔
4522
    owned.reserve(static_cast<std::size_t>(n_inputs));
115 ✔
4523
    cols.reserve(static_cast<std::size_t>(n_inputs));
115 ✔
4524
    for (std::int32_t i = 0; i < n_inputs; ++i) {
334 ✔
4525
        owned.emplace_back(const_cast<dftu_series*>(inputs[i]));
219 ✔
4526
        cols.push_back(&owned.back());
219 ✔
4527
    }
109 ✔
4528
    std::int32_t written = -1;
115 ✔
4529
    if (auto res = dataframe::eval_many(exprs, cols)) {
172 ✔
4530
        for (std::size_t i = 0; i < res->size(); ++i)
488 ✔
4531
            out[i] = (*res)[i].release();
373 ✔
4532
        written = static_cast<std::int32_t>(res->size());
115 ✔
4533
    }
115 ✔
4534
    for (dataframe::Series& c : owned)
333 ✔
4535
        c.release();  // borrowed inputs, do not free
218 ✔
4536
    return written;
115 ✔
4537
}
115 ✔
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