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

llnl-asr / dftracer-utils / 38350517275

13 Oct 2026 05:15AM UTC coverage: 63.708% (+1.1%) from 62.623%
38350517275

push

github

rayandrew
feat(python): fill the pandas api gaps and print frames like pandas

Adds normalize, translate, wrap and a sketch_quantile group aggregate as
engine kernels, and the rest as compositions of existing ops.

Merging stored sketches now skips every sketch whose accuracy is not the
default, in duql too: keeping the first accuracy seen made the result
depend on row order once a group was split across partial states.

128013 of 248204 branches covered (51.58%)

Branch coverage included in aggregate %.

652 of 696 new or added lines in 15 files covered. (93.68%)

376 existing lines in 32 files now uncovered.

106752 of 120300 relevant lines covered (88.74%)

3382973.47 hits per line

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

68.93
/src/dftracer/utils/dataframe/expr.cpp
1
#include <dftracer/utils/core/common/calendar.h>
2
#include <dftracer/utils/core/common/to_chars.h>
3
#include <dftracer/utils/dataframe/batch_ops.h>          // concat_columns
4
#include <dftracer/utils/dataframe/expr.h>
5
#include <dftracer/utils/dataframe/internal/cell_ops.h>  // cell_to_string
6
#include <dftracer/utils/dataframe/internal/column_data.h>
7
#include <dftracer/utils/dataframe/internal/expr_handle.h>
8
#include <dftracer/utils/dataframe/internal/fingerprint.h>
9
#include <dftracer/utils/dataframe/internal/scalar.h>     // scalar_as
10
#include <dftracer/utils/dataframe/kernels/string_ops.h>  // str_pattern
11
#include <dftracer/utils/dataframe/parallel.h>
12
#include <dftracer/utils/duql/pattern_engine.h>
13
#include <dftracer/utils/duql/substr_simd.h>
14
#include <dftracer/utils/json/json_escape.h>
15

16
#include <algorithm>
17
#include <array>
18
#include <atomic>
19
#include <bit>
20
#include <charconv>
21
#include <cmath>
22
#include <cstdint>
23
#include <limits>
24
#include <map>
25
#include <mutex>
26
#include <optional>
27
#include <random>
28
#include <span>
29
#include <stdexcept>
30
#include <string>
31
#include <string_view>
32
#include <tuple>
33
#include <type_traits>
34
#include <vector>
35

36
namespace dataframe = dftracer::utils::dataframe;
37
namespace duql = dftracer::utils::duql;
38

39
namespace dftracer::utils::dataframe {
40

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

94
struct ExprNode {
41,641 ✔
95
    ExprKind kind;
96
    std::int32_t i = 0;     // col index / prim / unary / cmp op / logical op /
41,641 ✔
97
                            // cast type / binary op / str op / chars / all
98
    dftu_scalar scalar{};   // literal value / cmp rhs / clip lo / slice start
41,641 ✔
99
    dftu_scalar scalar2{};  // clip hi / slice len
41,641 ✔
100
    // Owns the text of a STR-tagged `scalar`, which borrows it, or a string
101
    // op's pattern / needle / from. The node is built once and never copied
102
    // (it lives behind shared_ptr<const>), and eval_many holds the roots for
103
    // the whole evaluation, so the borrow is valid for as long as the
104
    // compiled program can read it.
105
    std::string text;
106
    std::string text2;                                     // str_replace `to`
107
    std::shared_ptr<const duql::CompiledPattern> pattern;  // text: identity
108
    std::shared_ptr<const duql::Substitution> subst;       // regex replace
109
    Series values;                                         // is_in set
110
    std::shared_ptr<const ExprNode> a;  // first child (select: cond)
111
    std::shared_ptr<const ExprNode> b;  // second child (select: then)
112
    std::shared_ptr<const ExprNode> c;  // select: otherwise
113
};
114

115
namespace {
116

117
Expr make(ExprKind k, std::int32_t i, dftu_scalar s,
77,346 ✔
118
          std::shared_ptr<const ExprNode> a,
119
          std::shared_ptr<const ExprNode> b) {
120
    auto n = std::make_shared<ExprNode>();
77,346 !
121
    n->kind = k;
77,346 ✔
122
    n->i = i;
77,346 ✔
123
    n->scalar = s;
77,346 ✔
124
    n->a = std::move(a);
77,346 ✔
125
    n->b = std::move(b);
77,346 ✔
126
    return Expr{std::move(n)};
116,019 !
127
}
77,346 ✔
128

129
}  // namespace
130

131
Expr expr_col(std::int32_t index) {
47,852 ✔
132
    return make(ExprKind::Col, index, {}, nullptr, nullptr);
47,852 !
133
}
134
std::int32_t expr_col_index(const Expr& e) {
203,380 ✔
135
    const auto& n = e.node();
203,380 ✔
136
    return n && n->kind == ExprKind::Col ? n->i : -1;
203,380 !
137
}
138

139
namespace {
140

141
void fingerprint_node(detail::Fingerprint& fp, const ExprNode* n) {
3,322 ✔
142
    if (!n) {
3,322 ✔
143
        fp.pod(std::int32_t{-1});
2,328 ✔
144
        return;
2,328 ✔
145
    }
146
    fp.pod(static_cast<std::int32_t>(n->kind));
994 ✔
147
    fp.pod(n->i);
994 ✔
148
    fp.scalar(n->scalar);
994 ✔
149
    fp.scalar(n->scalar2);
994 ✔
150
    fp.str(n->text);
994 ✔
151
    fp.str(n->text2);
994 ✔
152
    const dftu_series* vals = n->values.handle();
994 ✔
153
    fp.pod(vals && vals->data ? vals->data->data() : nullptr);
994 ✔
154
    fp.pod(vals ? n->values.length() : std::int64_t{0});
994 ✔
155
    fingerprint_node(fp, n->a.get());
994 ✔
156
    fingerprint_node(fp, n->b.get());
994 ✔
157
    fingerprint_node(fp, n->c.get());
994 ✔
158
}
1,661 ✔
159

160
}  // namespace
161

162
std::uint64_t expr_fingerprint(const Expr& e) {
340 ✔
163
    detail::Fingerprint fp;
340 ✔
164
    fingerprint_node(fp, e.node().get());
340 !
165
    return fp.value();
510 ✔
166
}
167

168
bool expr_as_col_cmp(const Expr& e, std::int32_t* col, CmpOp* op, Scalar* rhs) {
200 ✔
169
    const auto& n = e.node();
200 ✔
170
    if (!n || n->kind != ExprKind::Cmp || !n->a || n->a->kind != ExprKind::Col)
200 !
171
        return false;
100 ✔
172
    *col = n->a->i;
100 ✔
173
    *op = static_cast<CmpOp>(n->i);
100 ✔
174
    *rhs = n->scalar;
100 ✔
175
    return true;
100 ✔
176
}
100 ✔
177

178
bool expr_as_col_binary(const Expr& e, BinaryOp* op, std::int32_t* a,
16 ✔
179
                        std::int32_t* b) {
180
    const auto& n = e.node();
16 ✔
181
    if (!n || n->kind != ExprKind::Binary || !n->a || !n->b ||
24 !
182
        n->a->kind != ExprKind::Col || n->b->kind != ExprKind::Col)
24 !
183
        return false;
8 ✔
184
    *op = static_cast<BinaryOp>(n->i);
8 ✔
185
    *a = n->a->i;
8 ✔
186
    *b = n->b->i;
8 ✔
187
    return true;
8 ✔
188
}
8 ✔
189

190
bool expr_as_logical(const Expr& e, LogicalOp* op, Expr* a, Expr* b) {
268 ✔
191
    const auto& n = e.node();
268 ✔
192
    if (!n || n->kind != ExprKind::Logical || !n->a || !n->b) return false;
268 !
193
    *op = static_cast<LogicalOp>(n->i);
42 ✔
194
    *a = Expr{n->a};
42 !
195
    *b = Expr{n->b};
42 !
196
    return true;
42 ✔
197
}
134 ✔
198

199
bool expr_as_not(const Expr& e, Expr* a) {
226 ✔
200
    const auto& n = e.node();
226 ✔
201
    if (!n || n->kind != ExprKind::Not || !n->a) return false;
226 !
202
    *a = Expr{n->a};
14 !
203
    return true;
14 ✔
204
}
113 ✔
205

206
namespace {
207
bool node_references(const std::shared_ptr<const ExprNode>& n,
11,068 ✔
208
                     std::int32_t index) {
209
    if (!n) return false;
11,068 ✔
210
    if (n->kind == ExprKind::Col) return n->i == index;
7,082 ✔
211
    return node_references(n->a, index) || node_references(n->b, index) ||
4,895 ✔
212
           node_references(n->c, index);
4,075 !
213
}
5,534 ✔
214
}  // namespace
215

216
bool expr_references(const Expr& e, std::int32_t index) {
2,688 ✔
217
    return node_references(e.node(), index);
2,688 ✔
218
}
219

220
namespace {
221
std::int32_t node_max_col(const std::shared_ptr<const ExprNode>& n) {
1,590 ✔
222
    if (!n) return -1;
1,590 ✔
223
    if (n->kind == ExprKind::Col) return n->i;
806 ✔
224
    return std::max(
392 ✔
225
        {node_max_col(n->a), node_max_col(n->b), node_max_col(n->c)});
392 !
226
}
795 ✔
227
}  // namespace
228

229
std::int32_t expr_max_col(const Expr& e) { return node_max_col(e.node()); }
414 ✔
230

231
namespace {
232
// Series is move-only, so a node copy shares the values set explicitly.
233
std::shared_ptr<ExprNode> clone(const ExprNode& n) {
4,380 ✔
234
    auto c = std::make_shared<ExprNode>();
4,380 ✔
235
    c->kind = n.kind;
4,380 ✔
236
    c->i = n.i;
4,380 ✔
237
    c->scalar = n.scalar;
4,380 ✔
238
    c->scalar2 = n.scalar2;
4,380 ✔
239
    c->text = n.text;
4,380 !
240
    c->text2 = n.text2;
4,380 !
241
    c->pattern = n.pattern;
4,380 ✔
242
    c->subst = n.subst;
4,380 ✔
243
    if (n.scalar.kind == DFTU_SCALAR_TAG_STR) {
4,380 ✔
244
        c->scalar.value.s = c->text.data();
×
245
        c->scalar.len = static_cast<std::uint32_t>(c->text.size());
×
246
    }
247
    if (n.values.valid()) c->values = n.values.share();
4,380 ✔
248
    c->a = n.a;
4,380 ✔
249
    c->b = n.b;
4,380 ✔
250
    c->c = n.c;
4,380 ✔
251
    return c;
4,380 ✔
252
}
2,190 !
253

254
std::shared_ptr<const ExprNode> node_remap(
2,706 ✔
255
    const std::shared_ptr<const ExprNode>& n,
256
    const std::vector<std::int32_t>& old_to_new) {
257
    if (!n) return nullptr;
2,706 ✔
258
    if (n->kind == ExprKind::Col) {
1,452 ✔
259
        const bool in_range =
412 ✔
260
            n->i >= 0 && static_cast<std::size_t>(n->i) < old_to_new.size();
824 !
261
        auto c = clone(*n);
824 !
262
        c->i = in_range ? old_to_new[static_cast<std::size_t>(n->i)] : n->i;
824 !
263
        return c;
824 ✔
264
    }
824 ✔
265
    auto a = node_remap(n->a, old_to_new);
628 !
266
    auto b = node_remap(n->b, old_to_new);
628 !
267
    auto c3 = node_remap(n->c, old_to_new);
628 !
268
    if (a == n->a && b == n->b && c3 == n->c) return n;  // unchanged: share
628 !
269
    auto c = clone(*n);
414 !
270
    c->a = std::move(a);
414 ✔
271
    c->b = std::move(b);
414 ✔
272
    c->c = std::move(c3);
414 ✔
273
    return c;
414 ✔
274
}
1,667 ✔
275
std::shared_ptr<const ExprNode> node_rebind(
17,726 ✔
276
    const std::shared_ptr<const ExprNode>& n, const std::vector<Expr>& by) {
277
    if (!n) return nullptr;
17,726 ✔
278
    if (n->kind == ExprKind::Col) {
7,930 ✔
279
        const bool in_range =
1,590 ✔
280
            n->i >= 0 && static_cast<std::size_t>(n->i) < by.size();
3,180 !
281
        return in_range && by[static_cast<std::size_t>(n->i)].valid()
3,180 !
282
                   ? by[static_cast<std::size_t>(n->i)].node()
3,180 ✔
283
                   : n;
3,180 !
284
    }
285
    auto a = node_rebind(n->a, by);
4,750 !
286
    auto b = node_rebind(n->b, by);
4,750 !
287
    auto c3 = node_rebind(n->c, by);
4,750 !
288
    if (a == n->a && b == n->b && c3 == n->c) return n;
4,750 !
289
    auto c = clone(*n);
3,142 !
290
    c->a = std::move(a);
3,142 ✔
291
    c->b = std::move(b);
3,142 ✔
292
    c->c = std::move(c3);
3,142 ✔
293
    return c;
3,142 ✔
294
}
11,238 ✔
295

296
void canonical_scalar(std::string& out, const dftu_scalar& v) {
60 ✔
297
    out += std::to_string(v.kind);
60 !
298
    out += ':';
60 ✔
299
    if (v.kind == DFTU_SCALAR_TAG_STR) {
60 !
300
        const std::string_view s =
301
            v.value.s ? std::string_view(v.value.s, v.len) : std::string_view();
×
302
        out += std::to_string(s.size());
×
303
        out += ':';
×
304
        out += s;
×
305
    } else {
306
        out += std::to_string(v.value.u);
60 !
307
    }
308
}
60 ✔
309

310
void canonical_text(std::string& out, std::string_view s) {
60 ✔
311
    out += std::to_string(s.size());
60 !
312
    out += ':';
60 ✔
313
    out += s;
60 ✔
314
}
60 ✔
315

316
void canonical_node(std::string& out, const ExprNode* n) {
110 ✔
317
    if (!n) {
110 ✔
318
        out += '_';
80 ✔
319
        return;
80 ✔
320
    }
321
    out += '(';
30 ✔
322
    out += std::to_string(static_cast<int>(n->kind));
30 !
323
    out += ',';
30 ✔
324
    out += std::to_string(n->i);
30 !
325
    out += ',';
30 ✔
326
    canonical_scalar(out, n->scalar);
30 ✔
327
    out += ',';
30 ✔
328
    canonical_scalar(out, n->scalar2);
30 ✔
329
    out += ',';
30 ✔
330
    canonical_text(out, n->text);
30 ✔
331
    out += ',';
30 ✔
332
    canonical_text(out, n->text2);
30 ✔
333
    out += ',';
30 ✔
334
    if (n->values.valid()) {
30 ✔
335
        out += std::to_string(static_cast<int>(n->values.type()));
×
336
        for (std::int64_t r = 0; r < n->values.length(); ++r) {
×
337
            out += ',';
×
338
            canonical_text(out, cell_to_string(n->values, r));
×
339
        }
340
    }
341
    out += ',';
30 ✔
342
    canonical_node(out, n->a.get());
30 ✔
343
    out += ',';
30 ✔
344
    canonical_node(out, n->b.get());
30 ✔
345
    out += ',';
30 ✔
346
    canonical_node(out, n->c.get());
30 ✔
347
    out += ')';
30 ✔
348
}
55 ✔
349

350
}  // namespace
351

352
Expr expr_remap_cols(const Expr& e,
822 ✔
353
                     const std::vector<std::int32_t>& old_to_new) {
354
    return Expr{node_remap(e.node(), old_to_new)};
822 !
355
}
356

357
Expr expr_rebind_cols(const Expr& e, const std::vector<Expr>& by_index) {
3,476 ✔
358
    return Expr{node_rebind(e.node(), by_index)};
3,476 !
359
}
360

361
std::string expr_canonical(const Expr& e) {
20 ✔
362
    std::string out;
20 ✔
363
    canonical_node(out, e.node().get());
20 !
364
    return out;
20 ✔
365
}
10 !
366
Expr expr_lit(std::int64_t value) {
5,804 ✔
367
    dftu_scalar s{};
5,804 ✔
368
    s.kind = DFTU_SCALAR_TAG_I64;
5,804 ✔
369
    s.value.i = value;
5,804 ✔
370
    return make(ExprKind::LitI64, 0, s, nullptr, nullptr);
5,804 !
371
}
372
Expr expr_lit(double value) {
672 ✔
373
    dftu_scalar s{};
672 ✔
374
    s.kind = DFTU_SCALAR_TAG_F64;
672 ✔
375
    s.value.d = value;
672 ✔
376
    return make(ExprKind::LitF64, 0, s, nullptr, nullptr);
672 !
377
}
378
Expr expr_binary(BinaryOp op, const Expr& a, const Expr& b) {
7,118 ✔
379
    return make(ExprKind::Binary, static_cast<std::int32_t>(op), {}, a.node(),
7,118 !
380
                b.node());
7,118 !
381
}
382
Expr expr_prim(PrimOp prim, const Expr& a) {
46 ✔
383
    return make(ExprKind::Prim, static_cast<std::int32_t>(prim), {}, a.node(),
46 !
384
                nullptr);
46 !
385
}
386
Expr expr_unary(UnaryOp op, const Expr& a) {
520 ✔
387
    return make(ExprKind::Unary, static_cast<std::int32_t>(op), {}, a.node(),
520 !
388
                nullptr);
520 !
389
}
390
Expr expr_clip(const Expr& a, Scalar lo, Scalar hi) {
12 ✔
391
    auto n = std::make_shared<ExprNode>();
12 !
392
    n->kind = ExprKind::Clip;
12 ✔
393
    n->scalar = lo;
12 ✔
394
    n->scalar2 = hi;
12 ✔
395
    n->a = a.node();
12 ✔
396
    return Expr{std::move(n)};
18 !
397
}
12 ✔
398
Expr expr_fillna(const Expr& a, Scalar fill) {
20 ✔
399
    return make(ExprKind::Fillna, 0, fill, a.node(), nullptr);
20 !
400
}
401
Expr expr_cmp(CmpOp cmp, const Expr& a, Scalar rhs) {
2,166 ✔
402
    Expr e = make(ExprKind::Cmp, static_cast<std::int32_t>(cmp), rhs, a.node(),
2,166 !
403
                  nullptr);
3,249 !
404
    // A STR rhs only borrows its text, and the caller's buffer may die before
405
    // the Expr is evaluated. Take a copy the node owns and repoint at it.
406
    const dftu_scalar raw = rhs;
2,166 ✔
407
    if (raw.kind == DFTU_SCALAR_TAG_STR) {
2,166 ✔
408
        auto* n = const_cast<ExprNode*>(e.node().get());
46 ✔
409
        n->text.assign(raw.value.s != nullptr ? raw.value.s : "", raw.len);
46 !
410
        n->scalar.value.s = n->text.data();
46 ✔
411
        n->scalar.len = static_cast<std::uint32_t>(n->text.size());
46 ✔
412
    }
23 ✔
413
    return e;
3,249 ✔
414
}
1,083 !
415
Expr expr_logical(LogicalOp op, const Expr& a, const Expr& b) {
582 ✔
416
    return make(ExprKind::Logical, static_cast<std::int32_t>(op), {}, a.node(),
582 !
417
                b.node());
582 !
418
}
419
Expr expr_not(const Expr& a) {
142 ✔
420
    return make(ExprKind::Not, 0, {}, a.node(), nullptr);
142 !
421
}
422
Expr expr_cast(TypeId type, const Expr& a) {
2,100 ✔
423
    return make(ExprKind::Cast, static_cast<std::int32_t>(type), {}, a.node(),
2,100 !
424
                nullptr);
2,100 !
425
}
426
Expr expr_str_pred(StrPredOp op, const Expr& a, std::string_view pattern) {
226 ✔
427
    Expr e = make(ExprKind::StrPred, static_cast<std::int32_t>(op), {},
226 !
428
                  a.node(), nullptr);
339 !
429
    const_cast<ExprNode*>(e.node().get())->text.assign(pattern);
226 !
430
    return e;
226 ✔
431
}
113 !
432
Expr expr_str_map(StrMapOp op, const Expr& a) {
488 ✔
433
    return make(ExprKind::StrMap, static_cast<std::int32_t>(op), {}, a.node(),
488 !
434
                nullptr);
488 !
435
}
436
Expr expr_lower(const Expr& a) { return expr_str_map(StrMapOp::Lower, a); }
360 ✔
437
Expr expr_str_len(const Expr& a, bool chars) {
58 ✔
438
    return make(ExprKind::StrLen, chars ? 1 : 0, {}, a.node(), nullptr);
58 !
439
}
440
Expr expr_str_find(const Expr& a, std::string_view needle) {
8 ✔
441
    Expr e = make(ExprKind::StrFind, 0, {}, a.node(), nullptr);
12 !
442
    const_cast<ExprNode*>(e.node().get())->text.assign(needle);
8 !
443
    return e;
8 ✔
444
}
4 !
445
Expr expr_str_replace(const Expr& a, std::string_view from, std::string_view to,
28 ✔
446
                      bool all) {
447
    Expr e = make(ExprKind::StrReplace, all ? 1 : 0, {}, a.node(), nullptr);
42 !
448
    auto* n = const_cast<ExprNode*>(e.node().get());
28 ✔
449
    n->text.assign(from);
28 !
450
    n->text2.assign(to);
28 !
451
    return e;
28 ✔
452
}
14 !
453
namespace {
454
Expr make_time_node(ExprKind k, std::int32_t part, const Expr& a,
1,026 ✔
455
                    std::int64_t ns_per_unit, std::string_view fmt) {
456
    if (ns_per_unit <= 0)
1,026 ✔
457
        throw std::invalid_argument("expr: time unit must be positive");
4 !
458
    auto n = std::make_shared<ExprNode>();
1,022 !
459
    n->kind = k;
1,022 ✔
460
    n->i = part;
1,022 ✔
461
    n->scalar.kind = DFTU_SCALAR_TAG_I64;
1,022 ✔
462
    n->scalar.value.i = ns_per_unit;
1,022 ✔
463
    n->text.assign(fmt);
1,022 !
464
    n->a = a.node();
1,022 ✔
465
    return Expr{std::move(n)};
1,533 !
466
}
1,022 ✔
467
}  // namespace
468
Expr expr_date_part(const Expr& a, std::int32_t part,
886 ✔
469
                    std::int64_t ns_per_unit) {
470
    if (!is_date_part_code(part))
886 ✔
471
        throw std::invalid_argument("expr: unknown date part");
4 !
472
    return make_time_node(ExprKind::DatePart, part, a, ns_per_unit, {});
882 ✔
473
}
474
Expr expr_format_time(const Expr& a, std::string_view fmt,
148 ✔
475
                      std::int64_t ns_per_unit) {
476
    const std::string_view bad = invalid_time_format(fmt);
148 !
477
    if (!bad.empty())
148 ✔
478
        throw std::invalid_argument("expr: invalid time format directive '" +
8 !
479
                                    std::string(bad) + "'");
10 !
480
    return make_time_node(ExprKind::FormatTime, 0, a, ns_per_unit, fmt);
215 ✔
481
}
2 ✔
482
Expr expr_str_slice(const Expr& a, std::int64_t start, std::int64_t len) {
8 ✔
483
    auto n = std::make_shared<ExprNode>();
8 !
484
    n->kind = ExprKind::StrSlice;
8 ✔
485
    n->scalar.kind = DFTU_SCALAR_TAG_I64;
8 ✔
486
    n->scalar.value.i = start;
8 ✔
487
    n->scalar2.kind = DFTU_SCALAR_TAG_I64;
8 ✔
488
    n->scalar2.value.i = len;
8 ✔
489
    n->a = a.node();
8 ✔
490
    return Expr{std::move(n)};
12 !
491
}
8 ✔
492
Expr expr_str_fn(StrFn fn, const Expr& a, const Expr* b, std::string_view text,
498 ✔
493
                 std::string_view text2, std::int64_t i0, std::int64_t i1) {
494
    auto n = std::make_shared<ExprNode>();
498 !
495
    n->kind = ExprKind::StrFn;
498 ✔
496
    n->i = static_cast<std::int32_t>(fn);
498 ✔
497
    n->scalar.kind = DFTU_SCALAR_TAG_I64;
498 ✔
498
    n->scalar.value.i = i0;
498 ✔
499
    n->scalar2.kind = DFTU_SCALAR_TAG_I64;
498 ✔
500
    n->scalar2.value.i = i1;
498 ✔
501
    n->text.assign(text);
498 !
502
    n->text2.assign(text2);
498 !
503
    n->a = a.node();
498 ✔
504
    if (b != nullptr) n->b = b->node();
498 ✔
505
    return Expr{std::move(n)};
747 !
506
}
498 ✔
507
Expr expr_is_in(const Expr& a, Series values) {
148 ✔
508
    Expr e = make(ExprKind::IsIn, 0, {}, a.node(), nullptr);
222 !
509
    const_cast<ExprNode*>(e.node().get())->values = std::move(values);
148 ✔
510
    return e;
148 ✔
511
}
74 !
512
Expr expr_is_null(const Expr& a, bool null) {
1,350 ✔
513
    return make(ExprKind::IsNull, null ? 1 : 0, {}, a.node(), nullptr);
1,350 !
514
}
515
Expr expr_select(const Expr& cond, const Expr& a, const Expr& b) {
754 ✔
516
    Expr e = make(ExprKind::Select, 0, {}, cond.node(), a.node());
1,131 !
517
    const_cast<ExprNode*>(e.node().get())->c = b.node();
754 ✔
518
    return e;
754 ✔
519
}
377 !
520

521
Expr expr_lit_str(std::string_view value) {
1,086 ✔
522
    Expr e = make(ExprKind::LitStr, 0, {}, nullptr, nullptr);
1,629 !
523
    const_cast<ExprNode*>(e.node().get())->text.assign(value);
1,086 !
524
    return e;
1,086 ✔
525
}
543 !
526
Expr expr_lit_bool(bool value) {
388 ✔
527
    return make(ExprKind::LitBool, value ? 1 : 0, {}, nullptr, nullptr);
388 !
528
}
529
Expr expr_lit_null(TypeId type) {
634 ✔
530
    return make(ExprKind::LitNull, static_cast<std::int32_t>(type), {}, nullptr,
634 !
531
                nullptr);
634 !
532
}
533
Expr expr_arith(ArithOp op, const Expr& a, const Expr& b) {
2,508 ✔
534
    return make(ExprKind::Arith, static_cast<std::int32_t>(op), {}, a.node(),
2,508 !
535
                b.node());
2,508 !
536
}
537
Expr expr_neg(const Expr& a) {
30 ✔
538
    return make(ExprKind::Neg, 0, {}, a.node(), nullptr);
30 !
539
}
540
Expr expr_cmp_expr(CmpOp cmp, const Expr& a, const Expr& b) {
1,400 ✔
541
    return make(ExprKind::CmpExpr, static_cast<std::int32_t>(cmp), {}, a.node(),
1,400 !
542
                b.node());
1,400 !
543
}
544

545
namespace {
546
// An n-ary node as a right fold of binary nodes; every n-ary form here is
547
// associative.
548
Expr fold_args(ExprKind k, std::int32_t i, const std::vector<Expr>& args,
270 ✔
549
               const char* who) {
550
    if (args.empty())
270 ✔
551
        throw std::invalid_argument(std::string("expr: ") + who +
2 !
552
                                    " needs at least one operand");
2 ✔
553
    Expr out = args.back();
268 ✔
554
    for (auto it = args.rbegin() + 1; it != args.rend(); ++it)
644 !
555
        out = make(k, i, {}, it->node(), out.node());
376 !
556
    return out;
268 ✔
557
}
135 !
558
}  // namespace
559

560
Expr expr_coalesce(const std::vector<Expr>& args) {
138 ✔
561
    return fold_args(ExprKind::Coalesce, 0, args, "coalesce");
138 ✔
562
}
563
Expr expr_extreme(const std::vector<Expr>& args, bool least) {
26 ✔
564
    return fold_args(ExprKind::Extreme, least ? 1 : 0, args,
26 ✔
565
                     least ? "least" : "greatest");
26 ✔
566
}
567
Expr expr_concat(const std::vector<Expr>& args) {
106 ✔
568
    if (args.size() == 1)
106 ✔
569
        return make(ExprKind::Concat, 0, {}, args.front().node(),
×
570
                    expr_lit_str("").node());
×
571
    return fold_args(ExprKind::Concat, 0, args, "concat");
106 ✔
572
}
53 ✔
573
Expr expr_round(const Expr& a, std::int64_t digits) {
26 ✔
574
    dftu_scalar s{};
26 ✔
575
    s.kind = DFTU_SCALAR_TAG_I64;
26 ✔
576
    s.value.i = digits;
26 ✔
577
    return make(ExprKind::Round, 0, s, a.node(), nullptr);
26 !
578
}
579
Expr expr_log(const Expr& a) {
4 ✔
580
    return make(ExprKind::Log, 0, {}, a.node(), nullptr);
4 !
581
}
582
Expr expr_pow(const Expr& a, const Expr& b) {
6 ✔
583
    return make(ExprKind::Pow, 0, {}, a.node(), b.node());
6 !
584
}
585
Expr expr_str_pred_col(StrPredOp op, const Expr& a, const Expr& needle) {
88 ✔
586
    if (op != StrPredOp::Contains && op != StrPredOp::StartsWith &&
88 ✔
587
        op != StrPredOp::EndsWith)
8 ✔
588
        throw std::invalid_argument(
2 !
589
            "expr: a column needle takes contains, starts_with or ends_with");
2 ✔
590
    return make(ExprKind::StrPredCol, static_cast<std::int32_t>(op), {},
86 !
591
                a.node(), needle.node());
86 !
592
}
593
Expr expr_str_replace_col(const Expr& a, const Expr& from, const Expr& to) {
32 ✔
594
    Expr e = make(ExprKind::StrReplaceCol, 0, {}, a.node(), from.node());
48 !
595
    const_cast<ExprNode*>(e.node().get())->c = to.node();
32 ✔
596
    return e;
32 ✔
597
}
16 !
598
Expr expr_str_substr_col(const Expr& a, const Expr& start, const Expr* len) {
28 ✔
599
    Expr e = make(ExprKind::StrSubstrCol, 0, {}, a.node(), start.node());
42 !
600
    if (len != nullptr) const_cast<ExprNode*>(e.node().get())->c = len->node();
28 ✔
601
    return e;
28 ✔
602
}
14 !
603
Expr expr_round_col(const Expr& a, const Expr& digits) {
28 ✔
604
    return make(ExprKind::RoundCol, 0, {}, a.node(), digits.node());
28 !
605
}
606
Expr expr_str_substr(const Expr& a, std::int64_t start, std::int64_t len) {
16 ✔
607
    auto n = std::make_shared<ExprNode>();
16 !
608
    n->kind = ExprKind::StrSubstr;
16 ✔
609
    n->scalar.kind = DFTU_SCALAR_TAG_I64;
16 ✔
610
    n->scalar.value.i = start;
16 ✔
611
    n->scalar2.kind = DFTU_SCALAR_TAG_I64;
16 ✔
612
    n->scalar2.value.i = len;
16 ✔
613
    n->a = a.node();
16 ✔
614
    return Expr{std::move(n)};
24 !
615
}
16 ✔
616
namespace {
617
// A compiled pattern has no source text to persist, so each pattern node
618
// gets an identity no other node in any process shares: a persisted plan
619
// that holds one never matches another, where a shared text could match a
620
// different pattern.
621
std::string pattern_identity() {
86 ✔
622
    static const std::string seed = [] {
57 !
623
        std::random_device rd;
14 !
624
        return std::to_string(rd()) + '.' + std::to_string(rd()) + '.' +
28 !
625
               std::to_string(rd());
35 !
626
    }();
57 !
627
    static std::atomic<std::uint64_t> next{0};
628
    return "pattern:" + seed + ':' + std::to_string(next++);
129 !
629
}
630

631
Expr pattern_node(ExprKind k, const Expr& a,
86 ✔
632
                  std::shared_ptr<const duql::CompiledPattern> p,
633
                  std::int64_t group) {
634
    dftu_scalar s{};
86 ✔
635
    s.kind = DFTU_SCALAR_TAG_I64;
86 ✔
636
    s.value.i = group;
86 ✔
637
    Expr e = make(k, 0, s, a.node(), nullptr);
129 !
638
    auto* n = const_cast<ExprNode*>(e.node().get());
86 ✔
639
    n->pattern = std::move(p);
86 ✔
640
    n->text = pattern_identity();
86 !
641
    return e;
129 ✔
642
}
43 !
643
}  // namespace
644

645
Expr expr_str_pattern(const Expr& a,
30 ✔
646
                      std::shared_ptr<const duql::CompiledPattern> p) {
647
    return pattern_node(ExprKind::StrPattern, a, std::move(p), 0);
30 !
648
}
649
Expr expr_str_extract(const Expr& a,
26 ✔
650
                      std::shared_ptr<const duql::CompiledPattern> p,
651
                      std::int64_t group) {
652
    return pattern_node(ExprKind::StrExtract, a, std::move(p), group);
26 !
653
}
654
Expr expr_str_extract_col(const Expr& a,
10 ✔
655
                          std::shared_ptr<const duql::CompiledPattern> p,
656
                          const Expr& group) {
657
    Expr e = pattern_node(ExprKind::StrExtractCol, a, std::move(p), 0);
10 !
658
    const_cast<ExprNode*>(e.node().get())->b = group.node();
10 ✔
659
    return e;
10 ✔
660
}
5 !
661
Expr expr_str_regex_replace(const Expr& a,
20 ✔
662
                            std::shared_ptr<const duql::CompiledPattern> p,
663
                            duql::Substitution sub) {
664
    Expr e = pattern_node(ExprKind::StrRegexReplace, a, std::move(p), 0);
20 !
665
    const_cast<ExprNode*>(e.node().get())->subst =
20 ✔
666
        std::make_shared<const duql::Substitution>(std::move(sub));
30 !
667
    return e;
20 ✔
668
}
10 !
669
Expr expr_convert(ConvertOp op, const Expr& a) {
394 ✔
670
    return make(ExprKind::Convert, static_cast<std::int32_t>(op), {}, a.node(),
394 !
671
                nullptr);
394 !
672
}
673
Expr expr_list_len(const Expr& a) {
108 ✔
674
    return make(ExprKind::ListLen, 0, {}, a.node(), nullptr);
108 !
675
}
676
Expr expr_list_get(const Expr& a, std::int64_t index) {
26 ✔
677
    dftu_scalar s{};
26 ✔
678
    s.kind = DFTU_SCALAR_TAG_I64;
26 ✔
679
    s.value.i = index;
26 ✔
680
    return make(ExprKind::ListGet, 0, s, a.node(), nullptr);
26 !
681
}
682
Expr expr_list_sum(const Expr& a) {
10 ✔
683
    return make(ExprKind::ListSum, 0, {}, a.node(), nullptr);
10 !
684
}
685
Expr expr_list_contains(const Expr& a, Scalar value) {
8 ✔
686
    Expr e = make(ExprKind::ListContains, 0, value, a.node(), nullptr);
12 !
687
    const dftu_scalar raw = value;
8 ✔
688
    if (raw.kind == DFTU_SCALAR_TAG_STR) {
8 ✔
689
        auto* n = const_cast<ExprNode*>(e.node().get());
4 ✔
690
        n->text.assign(raw.value.s != nullptr ? raw.value.s : "", raw.len);
4 !
691
        n->scalar.value.s = n->text.data();
4 ✔
692
        n->scalar.len = static_cast<std::uint32_t>(n->text.size());
4 ✔
693
    }
2 ✔
694
    return e;
12 ✔
695
}
4 !
696

697
bool expr_as_col_str_pred(const Expr& e, std::int32_t* col, StrPredOp* op,
218 ✔
698
                          std::string_view* pattern) {
699
    const auto& n = e.node();
218 ✔
700
    if (!n || n->kind != ExprKind::StrPred || !n->a ||
237 !
701
        n->a->kind != ExprKind::Col)
38 !
702
        return false;
180 ✔
703
    *col = n->a->i;
38 ✔
704
    *op = static_cast<StrPredOp>(n->i);
38 ✔
705
    *pattern = n->text;
38 ✔
706
    return true;
38 ✔
707
}
109 ✔
708

709
bool expr_as_col_is_in(const Expr& e, std::int32_t* col, Series* values) {
188 ✔
710
    const auto& n = e.node();
188 ✔
711
    if (!n || n->kind != ExprKind::IsIn || !n->a || n->a->kind != ExprKind::Col)
188 !
712
        return false;
176 ✔
713
    *col = n->a->i;
12 ✔
714
    *values = n->values.share();
12 ✔
715
    return true;
12 ✔
716
}
94 ✔
717

718
// ---- compiler: type inference + CSE + lowering to a slot program ----------
719

720
namespace {
721

722
// The (from, to) columns of StrFn::Translate's text operands: `text` is the
723
// keys, one codepoint each; `text2` is one entry per key, a codepoint L then
724
// the value's codepoints, L = 1 + their count, or L = 0 for a deletion. False
725
// when either does not parse.
726
bool decode_translate_table(std::string_view text, std::string_view text2,
64 ✔
727
                            Series& from, Series& to) {
728
    const auto step = [](std::string_view s, std::size_t pos,
522 ✔
729
                         std::uint32_t& cp) -> std::size_t {
730
        const auto c = static_cast<unsigned char>(s[pos]);
490 ✔
731
        const std::size_t n = c < 0x80 ? 1 : c < 0xE0 ? 2 : c < 0xF0 ? 3 : 4;
490 ✔
732
        if (c >= 0x80 && c < 0xC0) return 0;
490 ✔
733
        if (pos + n > s.size()) return 0;
490 !
734
        cp = n == 1 ? c : c & (0x7F >> n);
490 ✔
735
        for (std::size_t k = 1; k < n; ++k)
554 ✔
736
            cp = (cp << 6) | (static_cast<unsigned char>(s[pos + k]) & 0x3F);
64 ✔
737
        return n;
490 ✔
738
    };
245 ✔
739
    std::vector<std::int32_t> koff{0}, voff{0};
96 !
740
    std::vector<std::uint8_t> valid;
64 ✔
741
    std::string vdata;
64 ✔
742
    std::size_t pos = 0;
64 ✔
743
    std::size_t vpos = 0;
64 ✔
744
    bool any_null = false;
64 ✔
745
    while (pos < text.size()) {
220 ✔
746
        std::uint32_t cp;
747
        const std::size_t n = step(text, pos, cp);
158 !
748
        if (n == 0) return false;
159 ✔
749
        pos += n;
158 ✔
750
        koff.push_back(static_cast<std::int32_t>(pos));
158 !
751
        std::uint32_t count;
752
        const std::size_t ln =
79 ✔
753
            vpos < text2.size() ? step(text2, vpos, count) : 0;
158 !
754
        if (ln == 0) return false;
158 ✔
755
        vpos += ln;
156 ✔
756
        const std::size_t row = koff.size() - 2;
156 ✔
757
        if (valid.size() * 8 <= row) valid.push_back(0);
156 !
758
        if (count == 0) {
156 ✔
759
            any_null = true;
52 ✔
760
        } else {
26 ✔
761
            valid[row >> 3] |= static_cast<std::uint8_t>(1u << (row & 7));
104 ✔
762
            const std::size_t begin = vpos;
104 ✔
763
            for (std::uint32_t k = 1; k < count; ++k) {
280 ✔
764
                std::uint32_t ignored;
765
                const std::size_t m =
88 ✔
766
                    vpos < text2.size() ? step(text2, vpos, ignored) : 0;
176 !
767
                if (m == 0) return false;
176 ✔
768
                vpos += m;
176 ✔
769
            }
88 ✔
770
            vdata.append(text2.substr(begin, vpos - begin));
104 !
771
        }
772
        voff.push_back(static_cast<std::int32_t>(vdata.size()));
156 !
773
    }
774
    if (vpos != text2.size()) return false;
62 ✔
775
    const auto rows = static_cast<std::int64_t>(koff.size() - 1);
62 ✔
776
    from = Series{dftu_series_new_string(DFTU_TYPE_STRING, koff.data(),
124 !
777
                                         text.data(), rows, nullptr)};
93 ✔
778
    to = Series{dftu_series_new_string(DFTU_TYPE_STRING, voff.data(),
155 !
779
                                       vdata.data(), rows,
62 ✔
780
                                       any_null ? valid.data() : nullptr)};
88 ✔
781
    return from.handle() != nullptr && to.handle() != nullptr;
62 !
782
}
64 ✔
783

784
// Slot-IR opcodes.
785
enum {
786
    OP_LOAD,
787
    OP_ADD,
788
    OP_SUB,
789
    OP_MUL,
790
    OP_DIV,
791
    OP_ADDS,
792
    OP_SUBS,
793
    OP_MULS,
794
    OP_DIVS,
795
    OP_PRIM,
796
    OP_UNARY,
797
    OP_CLIP,
798
    OP_FILLNA,
799
    OP_CMP,
800
    OP_LOGICAL,
801
    OP_NOT,
802
    OP_CAST,
803
    OP_STR_PRED,
804
    OP_STR_MAP,
805
    OP_STR_LEN,
806
    OP_STR_FIND,
807
    OP_STR_REPLACE,
808
    OP_STR_SLICE,
809
    OP_IS_IN,
810
    OP_CONST,    // a column of `param` type filled with `scalar`
811
    OP_SELECT,   // c ? a : b, with the mask in slot `c`
812
    OP_IS_NULL,  // the null mask of slot `a` (param 1) or the valid mask (0)
813
    OP_CONST_NULL,
814
    OP_TO_I64,   // Uint64 -> Int64, null past int64
815
    OP_ARITH,
816
    OP_NEG,
817
    OP_CMP_EXPR,
818
    OP_EXTREME,
819
    OP_CONCAT,
820
    OP_ROUND,
821
    OP_LOG,
822
    OP_POW,
823
    OP_STR_SUBSTR,
824
    OP_STR_PATTERN,
825
    OP_STR_EXTRACT,
826
    OP_STR_REGEX_REPLACE,
827
    OP_CONVERT,
828
    OP_LIST_LEN,
829
    OP_LIST_GET,
830
    OP_LIST_SUM,
831
    OP_LIST_CONTAINS,
832
    OP_STR_FN,  // param = StrFn; scalar/scalar2 = i0/i1; text/text2
833
    OP_STR_PRED_COL,
834
    OP_STR_REPLACE_COL,
835
    OP_STR_SUBSTR_COL,
836
    OP_ROUND_COL,
837
    OP_STR_EXTRACT_COL,
838
    OP_DATE_PART,   // param = part code, scalar = ns per unit
839
    OP_FORMAT_TIME  // text = format, scalar = ns per unit
840
};
841

842
struct SlotOp {
305,522 ✔
843
    int opcode = 0;
152,761 ✔
844
    int a = -1;
152,761 ✔
845
    int b = -1;
152,761 ✔
846
    int c = -1;
152,761 ✔
847
    std::int32_t param = 0;
152,761 ✔
848
    dftu_scalar scalar{};
152,761 ✔
849
    dftu_scalar scalar2{};  // clip hi / slice len
152,761 ✔
850
    // Borrowed from the ExprNode that emitted the op, which outlives the
851
    // program (eval_many holds the roots).
852
    std::string_view text;
853
    std::string_view text2;
854
    const dftu_series* values = nullptr;
152,761 ✔
855
    // OP_STR_PATTERN / OP_STR_EXTRACT, keyed by the node identity in `text`.
856
    const duql::CompiledPattern* pattern = nullptr;
152,761 ✔
857
    const duql::Substitution* subst = nullptr;
152,761 ✔
858
};
859

860
const int COL_OP[4] = {OP_ADD, OP_SUB, OP_MUL, OP_DIV};
861
const int SCALAR_OP[4] = {OP_ADDS, OP_SUBS, OP_MULS, OP_DIVS};
862

863
// A compiled subexpression: either a compile-time scalar or a column in slot
864
// `slot` of type `type`. `full` is the complete DataType: a bare column
865
// reference passes its input DataType through, every other node reports a
866
// scalar DataType (no kernel here can target a parameterized type).
867
struct Val {
868
    bool is_scalar;
869
    int slot;
870
    TypeId type;
871
    dftu_scalar scalar;
872
    DataType full;
873
};
874

875
bool is_float(const Val& v) {
115,848 ✔
876
    if (v.is_scalar) return v.scalar.kind == DFTU_SCALAR_TAG_F64;
115,848 ✔
877
    return v.type == TypeId::Float32 || v.type == TypeId::Float64;
96,746 ✔
878
}
57,924 ✔
879

880
bool is_unknown(const Val& v) { return v.full.id == TypeId::Unknown; }
226,534 ✔
881
Val unknown_val() {
14,688 ✔
882
    return {false, -1, TypeId::Unknown, {}, scalar(TypeId::Unknown)};
14,688 ✔
883
}
884

885
double scalar_to_double(dftu_scalar s) {
6,216 ✔
886
    if (s.kind == DFTU_SCALAR_TAG_I64) return static_cast<double>(s.value.i);
6,216 ✔
887
    if (s.kind == DFTU_SCALAR_TAG_U64) return static_cast<double>(s.value.u);
1,762 !
888
    return s.value.d;
1,762 ✔
889
}
3,108 ✔
890

891
dftu_scalar to_f64_scalar(dftu_scalar s) {
6,216 ✔
892
    dftu_scalar r{};
6,216 ✔
893
    r.kind = DFTU_SCALAR_TAG_F64;
6,216 ✔
894
    r.value.d = scalar_to_double(s);
6,216 ✔
895
    return r;
6,216 ✔
896
}
897

898
bool is_int_type(TypeId t) {
42,244 ✔
899
    switch (t) {
42,244 ✔
900
        case TypeId::Int8:
11,240 ✔
901
        case TypeId::Int16:
902
        case TypeId::Int32:
903
        case TypeId::Int64:
904
        case TypeId::Uint8:
905
        case TypeId::Uint16:
906
        case TypeId::Uint32:
907
        case TypeId::Uint64:
908
            return true;
22,480 ✔
909
        default:
9,882 ✔
910
            return false;
19,764 ✔
911
    }
912
}
21,122 ✔
913

914
bool is_num_type(TypeId t) {
42,112 ✔
915
    return is_int_type(t) || t == TypeId::Float32 || t == TypeId::Float64;
42,112 ✔
916
}
917

918
bool is_text_type(TypeId t) {
5,370 ✔
919
    return t == TypeId::String || t == TypeId::LargeString;
5,370 !
920
}
921

922
// The type two numeric operands meet at: either float makes Float64, two
923
// different integer types meet at Int64.
924
TypeId promote(TypeId a, TypeId b) {
20,172 ✔
925
    if (a == TypeId::Float64 || b == TypeId::Float64 || a == TypeId::Float32 ||
20,172 !
926
        b == TypeId::Float32)
7,630 ✔
927
        return TypeId::Float64;
4,912 ✔
928
    return a == b && (a == TypeId::Int64 || a == TypeId::Uint64)
11,707 !
929
               ? a
15,784 ✔
930
               : TypeId::Int64;
7,630 ✔
931
}
10,086 ✔
932

933
TypeId arith_type(std::int32_t op, TypeId a, TypeId b) {
20,234 ✔
934
    return static_cast<ArithOp>(op) == ArithOp::Div ? TypeId::Float64
30,279 ✔
935
           : promote(a, b) == TypeId::Float64       ? TypeId::Float64
20,090 ✔
936
                                                    : TypeId::Int64;
10,117 ✔
937
}
938

939
// Depends only on each input column's DataType, never its data, so the same
940
// compile() drives eval() (Series::data_type()) and infer_type() (a schema
941
// with no data) and the two can never disagree.
942
class Compiler {
943
   public:
944
    explicit Compiler(const std::vector<DataType>& input_types)
178,928 ✔
945
        : input_types_(input_types) {}
178,928 ✔
946

947
    // A root that folded to a scalar, as a column of that value in every row.
948
    Val column(const Val& v) {
89,550 ✔
949
        if (!v.is_scalar) return v;
89,550 ✔
950
        return broadcast(
2,390 ✔
951
            v.scalar, v.scalar.kind == DFTU_SCALAR_TAG_F64   ? TypeId::Float64
4,780 ✔
952
                      : v.scalar.kind == DFTU_SCALAR_TAG_U64 ? TypeId::Uint64
4,766 !
953
                                                             : TypeId::Int64);
4,773 ✔
954
    }
44,775 ✔
955

956
    Val compile(const ExprNode* n) {
347,180 ✔
957
        switch (n->kind) {
347,180 !
958
            case ExprKind::LitI64:
21,448 ✔
959
            case ExprKind::LitF64:
960
                return {true, -1, TypeId::Int64, n->scalar,
42,896 ✔
961
                        scalar(TypeId::Int64)};
42,896 ✔
962
            case ExprKind::Col: {
75,683 ✔
963
                if (n->i < 0 ||
227,049 ✔
964
                    static_cast<std::size_t>(n->i) >= input_types_.size())
151,365 ✔
965
                    throw std::invalid_argument(
18 !
966
                        "expr: column index out of range");
2 ✔
967
                const DataType& dt =
75,682 ✔
968
                    input_types_[static_cast<std::size_t>(n->i)];
151,364 ✔
969
                if (dt.id == TypeId::Unknown)
151,364 ✔
970
                    return {false, -1, TypeId::Unknown, {}, dt};
17,526 ✔
971
                int slot = emit(OP_LOAD, -1, -1, n->i, {});
133,838 ✔
972
                return {false, slot, dt.id, {}, dt};
133,838 ✔
973
            }
974
            case ExprKind::Binary:
43,817 ✔
975
                return compile_binary(n);
87,634 ✔
976
            case ExprKind::Prim: {
209 ✔
977
                Val a0 = compile(n->a.get());
418 !
978
                if (is_unknown(a0)) return unknown_val();
418 !
979
                Val a = as_col(a0, "prim");
418 !
980
                if (a.type != TypeId::Int64 && a.type != TypeId::Uint64)
418 !
981
                    a = cast(a, TypeId::Int64);
×
982
                return {false,
209 ✔
983
                        emit(OP_PRIM, a.slot, -1, n->i, {}),
627 !
984
                        TypeId::Int64,
985
                        {},
209 ✔
986
                        scalar(TypeId::Int64)};
418 !
987
            }
418 ✔
988
            case ExprKind::Unary: {
823 ✔
989
                Val a0 = compile(n->a.get());
1,646 !
990
                if (is_unknown(a0)) return unknown_val();
1,646 !
991
                Val a = as_col(a0, "unary");
740 !
992
                // is_nan/is_finite/is_infinite yield a Bool mask; log/sqrt/exp
993
                // widen to Float64; the rest keep the input type (integer
994
                // floor/ceil/round/trunc are identities).
995
                const auto op = static_cast<UnaryOp>(n->i);
740 ✔
996
                TypeId t;
997
                switch (op) {
370 ✔
998
                    case UnaryOp::IsNan:
30 ✔
999
                    case UnaryOp::IsFinite:
1000
                    case UnaryOp::IsInfinite:
1001
                        t = TypeId::Bool;
60 ✔
1002
                        break;
60 ✔
1003
                    case UnaryOp::Log:
16 ✔
1004
                    case UnaryOp::Sqrt:
1005
                    case UnaryOp::Exp:
1006
                        t = TypeId::Float64;
32 ✔
1007
                        break;
32 ✔
1008
                    default:
324 ✔
1009
                        t = a.type;
648 ✔
1010
                        break;
648 ✔
1011
                }
1012
                return {false,
370 ✔
1013
                        emit(OP_UNARY, a.slot, -1, n->i, {}),
1,110 !
1014
                        t,
370 ✔
1015
                        {},
370 ✔
1016
                        scalar(t)};
740 !
1017
            }
1,646 ✔
1018
            case ExprKind::Clip: {
6 ✔
1019
                Val a0 = compile(n->a.get());
12 !
1020
                if (is_unknown(a0)) return unknown_val();
12 !
1021
                Val a = as_col(a0, "clip");
12 !
1022
                return {false,
6 ✔
1023
                        emit(OP_CLIP, a.slot, -1, 0, n->scalar, n->scalar2),
18 !
1024
                        a.type,
12 ✔
1025
                        {},
6 ✔
1026
                        scalar(a.type)};
12 !
1027
            }
12 ✔
1028
            case ExprKind::Fillna: {
10 ✔
1029
                Val a0 = compile(n->a.get());
20 !
1030
                if (is_unknown(a0)) return unknown_val();
20 !
1031
                Val a = as_col(a0, "fillna");
20 !
1032
                return {false,
10 ✔
1033
                        emit(OP_FILLNA, a.slot, -1, 0, n->scalar),
30 !
1034
                        a.type,
20 ✔
1035
                        {},
10 ✔
1036
                        scalar(a.type)};
20 !
1037
            }
20 ✔
1038
            case ExprKind::Cmp: {
2,902 ✔
1039
                Val a0 = compile(n->a.get());
5,804 !
1040
                if (is_unknown(a0)) return unknown_val();
5,804 !
1041
                Val a = as_col(a0, "compare");
5,722 !
1042
                return {false,
2,861 ✔
1043
                        emit(OP_CMP, a.slot, -1, n->i, n->scalar),
8,583 !
1044
                        TypeId::Bool,
1045
                        {},
2,861 ✔
1046
                        scalar(TypeId::Bool)};
5,722 !
1047
            }
5,804 ✔
1048
            case ExprKind::Logical: {
1,080 ✔
1049
                Val a0 = compile(n->a.get());
2,160 !
1050
                Val b0 = compile(n->b.get());
2,160 !
1051
                if (is_unknown(a0) || is_unknown(b0)) return unknown_val();
2,160 !
1052
                Val a = as_col(a0, "logical");
2,080 !
1053
                Val b = as_col(b0, "logical");
2,080 !
1054
                return {false,
1,040 ✔
1055
                        emit(OP_LOGICAL, a.slot, b.slot, n->i, {}),
3,120 !
1056
                        TypeId::Bool,
1057
                        {},
1,040 ✔
1058
                        scalar(TypeId::Bool)};
2,080 !
1059
            }
2,160 ✔
1060
            case ExprKind::Not: {
309 ✔
1061
                Val a0 = compile(n->a.get());
618 !
1062
                if (is_unknown(a0)) return unknown_val();
618 !
1063
                Val a = as_col(a0, "not");
538 !
1064
                return {false,
269 ✔
1065
                        emit(OP_NOT, a.slot, -1, 0, {}),
807 !
1066
                        TypeId::Bool,
1067
                        {},
269 ✔
1068
                        scalar(TypeId::Bool)};
538 !
1069
            }
618 ✔
1070
            case ExprKind::Cast: {
9,195 ✔
1071
                Val a = as_col(compile(n->a.get()), "cast");
18,390 !
1072
                return cast(a, static_cast<TypeId>(n->i));
18,390 !
1073
            }
18,390 ✔
1074
            case ExprKind::StrPred: {
127 ✔
1075
                Val a0 = compile(n->a.get());
254 !
1076
                if (is_unknown(a0)) return unknown_val();
254 !
1077
                Val a = as_str(a0, "string predicate", true);
255 !
1078
                return {false,
126 ✔
1079
                        emit_text(OP_STR_PRED, a.slot, n->i, n->text),
252 !
1080
                        TypeId::Bool,
1081
                        {},
126 ✔
1082
                        scalar(TypeId::Bool)};
378 ✔
1083
            }
254 ✔
1084
            case ExprKind::StrMap: {
508 ✔
1085
                Val a0 = compile(n->a.get());
1,016 !
1086
                if (is_unknown(a0)) return unknown_val();
1,016 !
1087
                Val a = as_str(a0, "string map", false);
1,017 !
1088
                return {false,
504 ✔
1089
                        emit(OP_STR_MAP, a.slot, -1, n->i, {}),
1,512 !
1090
                        TypeId::String,
1091
                        {},
504 ✔
1092
                        scalar(TypeId::String)};
1,008 !
1093
            }
1,016 ✔
1094
            case ExprKind::StrLen: {
71 ✔
1095
                Val a0 = compile(n->a.get());
142 !
1096
                if (is_unknown(a0)) return unknown_val();
142 !
1097
                Val a = as_str(a0, "string length", true);
140 !
1098
                return {false,
70 ✔
1099
                        emit(OP_STR_LEN, a.slot, -1, n->i, {}),
210 !
1100
                        TypeId::Int64,
1101
                        {},
70 ✔
1102
                        scalar(TypeId::Int64)};
140 !
1103
            }
142 ✔
1104
            case ExprKind::StrFind: {
5 ✔
1105
                Val a0 = compile(n->a.get());
10 !
1106
                if (is_unknown(a0)) return unknown_val();
10 !
1107
                Val a = as_str(a0, "string find", true);
10 !
1108
                return {false,
5 ✔
1109
                        emit_text(OP_STR_FIND, a.slot, 0, n->text),
10 !
1110
                        TypeId::Int64,
1111
                        {},
5 ✔
1112
                        scalar(TypeId::Int64)};
15 ✔
1113
            }
10 ✔
1114
            case ExprKind::StrReplace: {
15 ✔
1115
                Val a0 = compile(n->a.get());
30 !
1116
                if (is_unknown(a0)) return unknown_val();
30 !
1117
                Val a = as_str(a0, "string replace", false);
30 !
1118
                return {
15 ✔
1119
                    false,
1120
                    emit_text(OP_STR_REPLACE, a.slot, n->i, n->text, n->text2),
30 !
1121
                    TypeId::String,
1122
                    {},
15 ✔
1123
                    scalar(TypeId::String)};
45 ✔
1124
            }
30 ✔
1125
            case ExprKind::DatePart:
519 ✔
1126
            case ExprKind::FormatTime: {
1127
                const bool fmt = n->kind == ExprKind::FormatTime;
1,038 ✔
1128
                Val a0 = compile(n->a.get());
1,038 !
1129
                if (is_unknown(a0)) return unknown_val();
1,038 !
1130
                if (!a0.is_scalar && !is_num_type(a0.type))
1,038 !
1131
                    throw std::invalid_argument(
6 !
1132
                        std::string("expr: ") +
6 !
1133
                        (fmt ? "format_time" : "date_part") +
6 !
1134
                        " needs a time or integer operand, got " +
8 !
1135
                        type_name(a0.type));
6 ✔
1136
                Val a = num(a0, fmt ? "format_time" : "date_part");
1,034 !
1137
                SlotOp op;
1,034 ✔
1138
                op.opcode = fmt ? OP_FORMAT_TIME : OP_DATE_PART;
1,034 ✔
1139
                op.a = a.slot;
1,034 ✔
1140
                op.param = n->i;
1,034 ✔
1141
                op.scalar = n->scalar;
1,034 ✔
1142
                op.text = n->text;
1,034 ✔
1143
                return col_val(emit_op(op),
517 !
1144
                               fmt ? TypeId::String : TypeId::Int64);
1,034 !
1145
            }
1,038 ✔
1146
            case ExprKind::StrSlice: {
5 ✔
1147
                Val a0 = compile(n->a.get());
10 !
1148
                if (is_unknown(a0)) return unknown_val();
10 !
1149
                Val a = as_str(a0, "string slice", false);
10 !
1150
                return {
5 ✔
1151
                    false,
1152
                    emit(OP_STR_SLICE, a.slot, -1, 0, n->scalar, n->scalar2),
15 !
1153
                    TypeId::String,
1154
                    {},
5 ✔
1155
                    scalar(TypeId::String)};
10 !
1156
            }
10 ✔
1157
            case ExprKind::IsIn: {
24 ✔
1158
                Val a0 = compile(n->a.get());
48 !
1159
                if (is_unknown(a0)) return unknown_val();
48 !
1160
                Val a = as_col(a0, "is_in");
48 !
1161
                if (!n->values.valid())
48 ✔
1162
                    throw std::invalid_argument(
×
1163
                        "expr: is_in needs a values column");
1164
                if (value_domain(a.type) != value_domain(n->values.type()))
48 ✔
1165
                    throw std::invalid_argument(
6 !
1166
                        std::string("expr: is_in over a ") + type_name(a.type) +
6 !
1167
                        " column needs " + type_name(a.type) + " values, got " +
8 !
1168
                        type_name(n->values.type()));
6 ✔
1169
                SlotOp op;
44 ✔
1170
                op.opcode = OP_IS_IN;
44 ✔
1171
                op.a = a.slot;
44 ✔
1172
                op.values = n->values.handle();
44 ✔
1173
                return {
22 ✔
1174
                    false, emit_op(op), TypeId::Bool, {}, scalar(TypeId::Bool)};
44 !
1175
            }
50 ✔
1176
            case ExprKind::Select:
800 ✔
1177
                return compile_select(n);
1,600 ✔
1178
            case ExprKind::LitStr: {
1,147 ✔
1179
                dftu_scalar s{};
2,294 ✔
1180
                s.kind = DFTU_SCALAR_TAG_STR;
2,294 ✔
1181
                s.value.s = n->text.data();
2,294 ✔
1182
                s.len = static_cast<std::uint32_t>(n->text.size());
2,294 ✔
1183
                return broadcast(s, TypeId::String);
2,294 !
1184
            }
1185
            case ExprKind::LitBool: {
1,228 ✔
1186
                dftu_scalar s{};
2,456 ✔
1187
                s.kind = DFTU_SCALAR_TAG_I64;
2,456 ✔
1188
                s.value.i = n->i;
2,456 ✔
1189
                return broadcast(s, TypeId::Bool);
2,456 !
1190
            }
1191
            case ExprKind::LitNull: {
547 ✔
1192
                const auto t = static_cast<TypeId>(n->i);
1,094 ✔
1193
                if (!is_num_type(t) && t != TypeId::Bool && t != TypeId::String)
1,094 ✔
1194
                    throw std::invalid_argument(
3 !
1195
                        std::string("expr: no null literal of type ") +
3 !
1196
                        type_name(t));
3 ✔
1197
                return col_val(emit(OP_CONST_NULL, -1, -1, n->i, {}), t);
1,092 ✔
1198
            }
1199
            case ExprKind::Arith: {
5,569 ✔
1200
                Val a0 = compile(n->a.get());
11,138 !
1201
                Val b0 = compile(n->b.get());
11,138 !
1202
                if (is_unknown(a0) || is_unknown(b0)) return unknown_val();
11,138 !
1203
                Val a = num(a0, "arithmetic");
11,139 !
1204
                Val b = num(b0, "arithmetic");
11,136 !
1205
                const TypeId t = arith_type(n->i, a.type, b.type);
11,136 !
1206
                return col_val(emit(OP_ARITH, a.slot, b.slot, n->i, {}), t);
11,136 !
1207
            }
11,139 ✔
1208
            case ExprKind::Neg: {
41 ✔
1209
                Val a0 = compile(n->a.get());
82 !
1210
                if (is_unknown(a0)) return unknown_val();
82 !
1211
                Val a = num(a0, "negation");
82 !
1212
                const TypeId t =
82 ✔
1213
                    a.type == TypeId::Float64 ? TypeId::Float64 : TypeId::Int64;
82 ✔
1214
                return col_val(emit(OP_NEG, a.slot, -1, 0, {}), t);
82 !
1215
            }
82 ✔
1216
            case ExprKind::CmpExpr: {
1,842 ✔
1217
                Val a0 = compile(n->a.get());
3,684 !
1218
                Val b0 = compile(n->b.get());
3,684 !
1219
                if (is_unknown(a0) || is_unknown(b0)) return unknown_val();
3,684 !
1220
                Val a = operand(a0, "compare");
3,604 !
1221
                Val b = operand(b0, "compare");
3,604 !
1222
                same_domain(a, b, "compare");
3,604 ✔
1223
                return col_val(emit(OP_CMP_EXPR, a.slot, b.slot, n->i, {}),
3,598 !
1224
                               TypeId::Bool);
1,799 !
1225
            }
3,693 ✔
1226
            case ExprKind::Coalesce: {
225 ✔
1227
                Val a0 = compile(n->a.get());
450 !
1228
                Val b0 = compile(n->b.get());
450 !
1229
                if (is_unknown(a0) || is_unknown(b0)) return unknown_val();
450 !
1230
                Val a = operand(a0, "coalesce");
450 !
1231
                Val b = operand(b0, "coalesce");
450 !
1232
                const TypeId t = common_type(a, b, "coalesce");
450 ✔
1233
                // Presence is the operand's own: a value that does not fit
1234
                // `t` is a null result, not a reason to move on to `b`.
1235
                const int present = emit(OP_IS_NULL, a.slot, -1, 0, {});
448 !
1236
                a = to_type(a, t);
448 !
1237
                b = to_type(b, t);
448 !
1238
                SlotOp op;
448 ✔
1239
                op.opcode = OP_SELECT;
448 ✔
1240
                op.a = a.slot;
448 ✔
1241
                op.b = b.slot;
448 ✔
1242
                op.c = present;
448 ✔
1243
                return col_val(emit_op(op), t);
448 !
1244
            }
453 ✔
1245
            case ExprKind::Extreme: {
17 ✔
1246
                Val a0 = compile(n->a.get());
34 !
1247
                Val b0 = compile(n->b.get());
34 !
1248
                if (is_unknown(a0) || is_unknown(b0)) return unknown_val();
34 !
1249
                Val a = operand(a0, "least/greatest");
34 !
1250
                Val b = operand(b0, "least/greatest");
34 !
1251
                same_domain(a, b, "least/greatest");
34 !
1252
                const TypeId t = common_type(a, b, "least/greatest");
34 !
1253
                return col_val(emit(OP_EXTREME, a.slot, b.slot, n->i, {}), t);
34 !
1254
            }
34 ✔
1255
            case ExprKind::Concat: {
951 ✔
1256
                Val a0 = compile(n->a.get());
1,902 !
1257
                Val b0 = compile(n->b.get());
1,902 !
1258
                if (is_unknown(a0) || is_unknown(b0)) return unknown_val();
1,902 !
1259
                Val a = as_str(a0, "concat", false);
1,902 !
1260
                Val b = as_str(b0, "concat", false);
1,903 !
1261
                return col_val(emit(OP_CONCAT, a.slot, b.slot, 0, {}),
950 !
1262
                               TypeId::String);
950 !
1263
            }
1,904 ✔
1264
            case ExprKind::Round: {
42 ✔
1265
                Val a0 = compile(n->a.get());
84 !
1266
                if (is_unknown(a0)) return unknown_val();
84 !
1267
                const bool integer = a0.is_scalar
126 !
1268
                                         ? a0.scalar.kind != DFTU_SCALAR_TAG_F64
42 !
1269
                                         : is_int_type(a0.type);
84 !
1270
                if (integer && n->scalar.value.i >= 0) return a0;
84 ✔
1271
                Val a = num(a0, "round");
54 !
1272
                const TypeId t = integer ? TypeId::Int64 : TypeId::Float64;
54 ✔
1273
                return col_val(emit(OP_ROUND, a.slot, -1, 0, n->scalar), t);
54 !
1274
            }
84 ✔
1275
            case ExprKind::Log: {
2 ✔
1276
                Val a0 = compile(n->a.get());
4 !
1277
                if (is_unknown(a0)) return unknown_val();
4 !
1278
                Val a = num(a0, "log");
4 !
1279
                return col_val(emit(OP_LOG, a.slot, -1, 0, {}),
2 !
1280
                               TypeId::Float64);
2 !
1281
            }
4 ✔
1282
            case ExprKind::Pow: {
3 ✔
1283
                Val a0 = compile(n->a.get());
6 !
1284
                Val b0 = compile(n->b.get());
6 !
1285
                if (is_unknown(a0) || is_unknown(b0)) return unknown_val();
6 !
1286
                Val a = num(a0, "pow");
6 !
1287
                Val b = num(b0, "pow");
6 !
1288
                return col_val(emit(OP_POW, a.slot, b.slot, 0, {}),
3 !
1289
                               TypeId::Float64);
3 !
1290
            }
6 ✔
1291
            case ExprKind::StrSubstr: {
8 ✔
1292
                Val a0 = compile(n->a.get());
16 !
1293
                if (is_unknown(a0)) return unknown_val();
16 !
1294
                Val a = as_str(a0, "substr", false);
16 !
1295
                return col_val(
8 !
1296
                    emit(OP_STR_SUBSTR, a.slot, -1, 0, n->scalar, n->scalar2),
8 !
1297
                    TypeId::String);
8 !
1298
            }
16 ✔
1299
            case ExprKind::StrPredCol: {
56 ✔
1300
                Val a0 = compile(n->a.get());
112 !
1301
                Val b0 = compile(n->b.get());
112 !
1302
                if (is_unknown(a0) || is_unknown(b0)) return unknown_val();
112 !
1303
                Val a = as_str(a0, "string predicate", true);
112 !
1304
                Val b = as_str(b0, "string predicate", true);
112 !
1305
                return col_val(emit(OP_STR_PRED_COL, a.slot, b.slot, n->i, {}),
112 !
1306
                               TypeId::Bool);
56 !
1307
            }
112 ✔
1308
            case ExprKind::StrReplaceCol: {
17 ✔
1309
                Val a0 = compile(n->a.get());
34 !
1310
                Val b0 = compile(n->b.get());
34 !
1311
                Val c0 = compile(n->c.get());
34 !
1312
                if (is_unknown(a0) || is_unknown(b0) || is_unknown(c0))
34 !
1313
                    return unknown_val();
×
1314
                Val a = as_str(a0, "string replace", false);
34 !
1315
                Val b = as_str(b0, "string replace", false);
34 !
1316
                Val c = as_str(c0, "string replace", false);
34 !
1317
                SlotOp op;
34 ✔
1318
                op.opcode = OP_STR_REPLACE_COL;
34 ✔
1319
                op.a = a.slot;
34 ✔
1320
                op.b = b.slot;
34 ✔
1321
                op.c = c.slot;
34 ✔
1322
                return col_val(emit_op(op), TypeId::String);
34 !
1323
            }
34 ✔
1324
            case ExprKind::StrSubstrCol: {
17 ✔
1325
                Val a0 = compile(n->a.get());
34 !
1326
                Val b0 = compile(n->b.get());
34 !
1327
                Val c0 = n->c ? compile(n->c.get()) : Val{};
34 !
1328
                if (is_unknown(a0) || is_unknown(b0) ||
71 !
1329
                    (n->c && is_unknown(c0)))
44 !
1330
                    return unknown_val();
10 !
1331
                Val a = as_str(a0, "substr", false);
24 !
1332
                Val b = num(b0, "substr");
34 !
1333
                SlotOp op;
34 ✔
1334
                op.opcode = OP_STR_SUBSTR_COL;
34 ✔
1335
                op.a = a.slot;
34 ✔
1336
                op.b = b.slot;
34 ✔
1337
                if (n->c) op.c = num(c0, "substr").slot;
34 !
1338
                return col_val(emit_op(op), TypeId::String);
34 !
1339
            }
34 ✔
1340
            case ExprKind::RoundCol: {
17 ✔
1341
                Val a0 = compile(n->a.get());
34 !
1342
                Val b0 = compile(n->b.get());
34 !
1343
                if (is_unknown(a0) || is_unknown(b0)) return unknown_val();
34 !
1344
                const bool integer = a0.is_scalar
48 ✔
1345
                                         ? a0.scalar.kind != DFTU_SCALAR_TAG_F64
20 ✔
1346
                                         : is_int_type(a0.type);
28 !
1347
                Val a = num(a0, "round");
34 !
1348
                Val b = num(b0, "round");
34 !
1349
                const bool unsigned_in =
34 ✔
1350
                    a0.is_scalar ? a0.scalar.kind == DFTU_SCALAR_TAG_U64
34 ✔
1351
                                 : a0.type == TypeId::Uint64;
28 ✔
1352
                return col_val(emit(OP_ROUND_COL, a.slot, b.slot, 0, {}),
34 !
1353
                               unsigned_in ? TypeId::Uint64
17 ✔
1354
                               : integer   ? TypeId::Int64
30 ✔
1355
                                           : TypeId::Float64);
32 !
1356
            }
34 ✔
1357
            case ExprKind::StrPattern:
57 ✔
1358
            case ExprKind::StrExtract:
1359
            case ExprKind::StrExtractCol:
1360
            case ExprKind::StrRegexReplace:
1361
                return compile_pattern(n);
114 ✔
1362
            case ExprKind::Convert:
942 ✔
1363
                return compile_convert(n);
1,884 ✔
1364
            case ExprKind::ListLen: {
1,897 ✔
1365
                Val a0 = compile(n->a.get());
3,794 !
1366
                if (is_unknown(a0)) return unknown_val();
3,794 !
1367
                as_list(a0, "list_len");
3,774 ✔
1368
                return col_val(emit(OP_LIST_LEN, a0.slot, -1, 0, {}),
1,886 !
1369
                               TypeId::Int64);
1,886 !
1370
            }
3,794 ✔
1371
            case ExprKind::ListGet: {
21 ✔
1372
                Val a0 = compile(n->a.get());
42 !
1373
                if (is_unknown(a0)) return unknown_val();
42 !
1374
                const DataType elem = as_list(a0, "list_get");
42 !
1375
                return {false,
21 ✔
1376
                        emit(OP_LIST_GET, a0.slot, -1, 0, n->scalar),
63 !
1377
                        elem.id,
42 ✔
1378
                        {},
21 ✔
1379
                        elem};
42 !
1380
            }
42 ✔
1381
            case ExprKind::ListSum: {
5 ✔
1382
                Val a0 = compile(n->a.get());
10 !
1383
                if (is_unknown(a0)) return unknown_val();
10 !
1384
                const TypeId e = as_list(a0, "list_sum").id;
10 !
1385
                const TypeId t = e == TypeId::Float32 || e == TypeId::Float64
10 ✔
1386
                                     ? TypeId::Float64
10 !
1387
                                     : TypeId::Int64;
1388
                return col_val(emit(OP_LIST_SUM, a0.slot, -1, 0, {}), t);
10 !
1389
            }
10 ✔
1390
            case ExprKind::ListContains: {
4 ✔
1391
                Val a0 = compile(n->a.get());
8 !
1392
                if (is_unknown(a0)) return unknown_val();
8 !
1393
                as_list(a0, "list_contains");
8 !
1394
                return col_val(
4 !
1395
                    emit(OP_LIST_CONTAINS, a0.slot, -1, 0, n->scalar),
4 !
1396
                    TypeId::Bool);
4 !
1397
            }
8 ✔
1398
            case ExprKind::StrFn:
287 ✔
1399
                return compile_str_fn(n);
574 ✔
1400
            case ExprKind::IsNull: {
1,092 ✔
1401
                Val a0 = compile(n->a.get());
2,184 !
1402
                if (is_unknown(a0)) return unknown_val();
2,184 !
1403
                Val a = as_col(a0, "is_null");
2,024 !
1404
                return {false,
1,012 ✔
1405
                        emit(OP_IS_NULL, a.slot, -1, n->i, {}),
3,036 !
1406
                        TypeId::Bool,
1407
                        {},
1,012 ✔
1408
                        scalar(TypeId::Bool)};
2,024 !
1409
            }
2,184 ✔
1410
        }
1411
        throw std::invalid_argument("expr: unknown node");
×
1412
    }
173,609 ✔
1413

1414
    std::vector<SlotOp> program;
1415

1416
   private:
1417
    static Val col_val(int slot, TypeId t) {
25,866 ✔
1418
        return {false, slot, t, {}, scalar(t)};
25,866 ✔
1419
    }
1420

1421
    // A numeric operand as Int64, Uint64 or Float64, the three types the
1422
    // duql kernels read; a literal broadcasts.
1423
    Val num(Val v, const char* who) {
30,836 ✔
1424
        if (v.is_scalar)
30,836 ✔
1425
            return broadcast(v.scalar, v.scalar.kind == DFTU_SCALAR_TAG_F64
8,710 ✔
1426
                                           ? TypeId::Float64
1427
                                       : v.scalar.kind == DFTU_SCALAR_TAG_U64
8,238 ✔
1428
                                           ? TypeId::Uint64
4,119 !
1429
                                           : TypeId::Int64);
8,474 ✔
1430
        if (!is_num_type(v.type))
22,126 ✔
1431
            throw std::invalid_argument(std::string("expr: ") + who +
5 !
1432
                                        " needs a numeric operand, got " +
4 !
1433
                                        type_name(v.type));
3 ✔
1434
        if (v.type == TypeId::Int64 || v.type == TypeId::Uint64 ||
22,124 ✔
1435
            v.type == TypeId::Float64)
7,140 ✔
1436
            return v;
22,104 ✔
1437
        return cast(v, is_int_type(v.type) ? TypeId::Int64 : TypeId::Float64);
20 !
1438
    }
15,418 ✔
1439

1440
    // An operand of a comparison-like node: numeric ones as num() makes
1441
    // them, the rest as they are.
1442
    Val operand(Val v, const char* who) {
10,060 ✔
1443
        if (v.is_scalar || is_num_type(v.type)) return num(v, who);
10,060 !
1444
        return v;
2,814 ✔
1445
    }
5,030 ✔
1446

1447
    static void same_domain(const Val& a, const Val& b, const char* who) {
3,638 ✔
1448
        const bool ok = (is_num_type(a.type) && is_num_type(b.type)) ||
5,900 ✔
1449
                        (is_text_type(a.type) && is_text_type(b.type)) ||
4,088 ✔
1450
                        (a.type == TypeId::Bool && b.type == TypeId::Bool);
8 !
1451
        if (!ok)
3,638 ✔
1452
            throw std::invalid_argument(std::string("expr: ") + who + " of " +
15 !
1453
                                        type_name(a.type) + " and " +
12 !
1454
                                        type_name(b.type) + " has no ordering");
15 !
1455
    }
3,635 ✔
1456

1457
    static TypeId common_type(const Val& a, const Val& b, const char* who) {
484 ✔
1458
        if (is_num_type(a.type) && is_num_type(b.type))
484 ✔
1459
            return promote(a.type, b.type);
56 ✔
1460
        if (a.type != b.type)
428 ✔
1461
            throw std::invalid_argument(
3 !
1462
                std::string("expr: ") + who + " needs one type, got " +
3 !
1463
                type_name(a.type) + " and " + type_name(b.type));
5 !
1464
        return a.type;
426 ✔
1465
    }
242 ✔
1466

1467
    Val to_type(Val v, TypeId t) {
896 ✔
1468
        if (v.type == t) return v;
896 ✔
1469
        if (v.type == TypeId::Uint64 && t == TypeId::Int64)
12 ✔
1470
            return col_val(emit(OP_TO_I64, v.slot, -1, 0, {}), t);
10 ✔
1471
        return cast(v, t);
2 !
1472
    }
448 ✔
1473

1474
    // The element type of a List operand, which must be known.
1475
    DataType as_list(const Val& v, const char* who) {
3,856 ✔
1476
        if (v.is_scalar || v.type != TypeId::List || v.full.fields.size() != 1)
3,856 !
1477
            throw std::invalid_argument(
6 !
1478
                std::string("expr: ") + who +
6 !
1479
                " needs a List column with a known element type, got " +
8 !
1480
                type_name(v.is_scalar ? TypeId::Int64 : v.type));
6 !
1481
        return v.full.fields.front().type;
3,852 ✔
1482
    }
2 ✔
1483

1484
    Val compile_pattern(const ExprNode* n) {
114 ✔
1485
        Val a0 = compile(n->a.get());
114 !
1486
        if (is_unknown(a0)) return unknown_val();
114 !
1487
        const bool extract_col = n->kind == ExprKind::StrExtractCol;
114 ✔
1488
        const bool extract = n->kind == ExprKind::StrExtract || extract_col;
114 ✔
1489
        const bool replace = n->kind == ExprKind::StrRegexReplace;
114 ✔
1490
        const bool text_out = extract || replace;
114 ✔
1491
        Val a = as_str(a0,
114 !
1492
                       extract   ? "string extract"
57 ✔
1493
                       : replace ? "string regex replace"
64 ✔
1494
                                 : "string pattern",
1495
                       !text_out);
146 !
1496
        if (replace && !n->subst)
114 !
1497
            throw std::invalid_argument(
×
1498
                "expr: a regex replace node needs a substitution");
1499
        if (!n->pattern)
114 ✔
1500
            throw std::invalid_argument("expr: a pattern node needs a pattern");
6 !
1501
        if (extract_col) {
108 ✔
1502
            Val g0 = compile(n->b.get());
8 !
1503
            if (is_unknown(g0)) return unknown_val();
8 !
1504
            SlotOp op;
8 ✔
1505
            op.opcode = OP_STR_EXTRACT_COL;
8 ✔
1506
            op.a = a.slot;
8 ✔
1507
            op.b = num(g0, "string extract").slot;
8 !
1508
            op.text = n->text;
8 ✔
1509
            op.pattern = n->pattern.get();
8 ✔
1510
            return col_val(emit_op(op), TypeId::String);
8 !
1511
        }
8 ✔
1512
        const std::int64_t group = n->scalar.value.i;
100 ✔
1513
        if (extract && (group < 0 || static_cast<std::uint64_t>(group) >
120 ✔
1514
                                         duql::capture_count(*n->pattern)))
40 !
1515
            throw std::invalid_argument("expr: extract group " +
4 !
1516
                                        std::to_string(group) +
5 !
1517
                                        " is not in the pattern");
2 ✔
1518
        SlotOp op;
98 ✔
1519
        op.opcode = extract   ? OP_STR_EXTRACT
98 ✔
1520
                    : replace ? OP_STR_REGEX_REPLACE
30 ✔
1521
                              : OP_STR_PATTERN;
1522
        op.subst = n->subst.get();
98 ✔
1523
        op.a = a.slot;
98 ✔
1524
        op.scalar = n->scalar;
98 ✔
1525
        op.text = n->text;
98 ✔
1526
        op.pattern = n->pattern.get();
98 ✔
1527
        return col_val(emit_op(op), text_out ? TypeId::String : TypeId::Bool);
98 !
1528
    }
119 ✔
1529

1530
    Val compile_convert(const ExprNode* n) {
1,884 ✔
1531
        Val a0 = compile(n->a.get());
1,884 !
1532
        if (is_unknown(a0)) return unknown_val();
1,884 !
1533
        Val a = operand(a0, "convert");
1,884 !
1534
        if (!is_num_type(a.type) && !is_text_type(a.type) &&
1,889 !
1535
            a.type != TypeId::Bool)
10 !
1536
            throw std::invalid_argument(
×
1537
                std::string("expr: convert needs a scalar operand, got ") +
×
1538
                type_name(a.type));
×
1539
        const auto op = static_cast<ConvertOp>(n->i);
1,884 ✔
1540
        if (op == ConvertOp::Int && a.type == TypeId::Int64) return a;
1,884 ✔
1541
        if (op == ConvertOp::String && a.type == TypeId::String) return a;
1,884 ✔
1542
        const TypeId t = op == ConvertOp::Int     ? TypeId::Int64
2,687 ✔
1543
                         : op == ConvertOp::Float ? TypeId::Float64
1,610 ✔
1544
                                                  : TypeId::String;
1545
        return col_val(emit(OP_CONVERT, a.slot, -1, n->i, {}), t);
1,882 !
1546
    }
1,884 ✔
1547

1548
    int emit_str_fn(const ExprNode* n, int a, int b) {
550 ✔
1549
        SlotOp op;
550 ✔
1550
        op.opcode = OP_STR_FN;
550 ✔
1551
        op.a = a;
550 ✔
1552
        op.b = b;
550 ✔
1553
        op.param = n->i;
550 ✔
1554
        op.scalar = n->scalar;
550 ✔
1555
        op.scalar2 = n->scalar2;
550 ✔
1556
        op.text = n->text;
550 ✔
1557
        op.text2 = n->text2;
550 ✔
1558
        return emit_op(op);
825 !
1559
    }
1560

1561
    // The expression forms of the eager Series.str methods; the types are
1562
    // the eager results'.
1563
    Val compile_str_fn(const ExprNode* n) {
574 ✔
1564
        const auto fn = static_cast<StrFn>(n->i);
574 ✔
1565
        Val a0 = compile(n->a.get());
574 !
1566
        Val b0{};
574 ✔
1567
        if (fn == StrFn::Cat) {
574 ✔
1568
            if (!n->b)
12 ✔
1569
                throw std::invalid_argument(
2 !
1570
                    "expr: cat needs another column; the one-column join is "
1571
                    "an aggregate (use Series.str.cat)");
2 ✔
1572
            b0 = compile(n->b.get());
10 !
1573
            if (is_unknown(b0)) return unknown_val();
10 !
1574
        }
5 ✔
1575
        if (is_unknown(a0)) return unknown_val();
572 !
1576
        const DataType list_str = list_of(scalar(TypeId::String));
858 !
1577
        if (fn == StrFn::Join) {
572 ✔
1578
            const DataType elem = as_list(a0, "join");
14 ✔
1579
            if (elem.id != TypeId::String)
12 ✔
1580
                throw std::invalid_argument(
×
1581
                    std::string("expr: join needs a List<String> column, got "
×
1582
                                "List<") +
×
1583
                    type_name(elem.id) + ">");
×
1584
            return col_val(emit_str_fn(n, a0.slot, -1), TypeId::String);
12 !
1585
        }
12 ✔
1586
        if (fn == StrFn::Get && !a0.is_scalar && a0.type == TypeId::List) {
558 !
1587
            const DataType elem = as_list(a0, "get");
6 !
1588
            return {false,
3 ✔
1589
                    emit(OP_LIST_GET, a0.slot, -1, 0, n->scalar),
9 !
1590
                    elem.id,
6 ✔
1591
                    {},
3 ✔
1592
                    elem};
6 !
1593
        }
6 ✔
1594
        Val a = as_str(a0, "string method", false);
553 !
1595
        switch (fn) {
550 ✔
1596
            case StrFn::IsAlnum:
58 ✔
1597
            case StrFn::IsAlpha:
1598
            case StrFn::IsDigit:
1599
            case StrFn::IsDecimal:
1600
            case StrFn::IsNumeric:
1601
            case StrFn::IsSpace:
1602
            case StrFn::IsLower:
1603
            case StrFn::IsUpper:
1604
            case StrFn::IsTitle:
1605
                return col_val(emit_str_fn(n, a.slot, -1), TypeId::Bool);
181 ✔
1606
            case StrFn::Split:
45 ✔
1607
            case StrFn::Partition:
1608
            case StrFn::RPartition:
1609
            case StrFn::Findall:
1610
                return {false,
1611
                        emit_str_fn(n, a.slot, -1),
90 ✔
1612
                        TypeId::List,
1613
                        {},
45 ✔
1614
                        list_str};
90 !
1615
            case StrFn::Rfind:
20 ✔
1616
            case StrFn::Index:
1617
            case StrFn::Rindex:
1618
                return col_val(emit_str_fn(n, a.slot, -1), TypeId::Int64);
20 ✔
1619
            case StrFn::Get:
10 ✔
1620
                if (n->scalar.value.i < 0)
20 ✔
1621
                    throw std::invalid_argument(
4 !
1622
                        "expr: get with a negative position needs a List "
1623
                        "column; use slice");
4 ✔
1624
                return col_val(emit_str_fn(n, a.slot, -1), TypeId::String);
16 !
1625
            case StrFn::Cat: {
5 ✔
1626
                Val b = as_str(b0, "cat", false);
10 !
1627
                return col_val(emit_str_fn(n, a.slot, b.slot), TypeId::String);
10 !
1628
            }
10 ✔
1629
            case StrFn::Join:
1630
                break;
×
1631
            case StrFn::Normalize:
11 ✔
1632
                if (n->scalar.value.i < 0 || n->scalar.value.i > 3)
22 ✔
1633
                    throw std::invalid_argument(
2 !
1634
                        "expr: normalize form must be NFC, NFKC, NFD or NFKD");
2 ✔
1635
                return col_val(emit_str_fn(n, a.slot, -1), TypeId::String);
20 !
1636
            case StrFn::Translate: {
18 ✔
1637
                Series from, to;
36 ✔
1638
                const Series probe = Series::nulls(TypeId::String, 1);
36 !
1639
                if (!decode_translate_table(n->text, n->text2, from, to) ||
70 !
1640
                    !Series{dftu_series_str_translate(
52 !
1641
                                probe.handle(), from.handle(), to.handle())}
34 ✔
1642
                         .handle())
34 ✔
1643
                    throw std::invalid_argument(
4 !
1644
                        "expr: translate table is not one distinct codepoint "
1645
                        "per key");
4 ✔
1646
                return col_val(emit_str_fn(n, a.slot, -1), TypeId::String);
32 !
1647
            }
40 ✔
1648
            case StrFn::Wrap:
3 ✔
1649
                if (n->scalar.value.i < 1)
6 ✔
1650
                    throw std::invalid_argument(
2 !
1651
                        "expr: wrap width must be at least 1");
2 ✔
1652
                return col_val(emit_str_fn(n, a.slot, -1), TypeId::String);
4 !
1653
            default:
105 ✔
1654
                return col_val(emit_str_fn(n, a.slot, -1), TypeId::String);
210 !
1655
        }
1656
        throw std::invalid_argument("expr: unknown string method");
×
1657
    }
729 ✔
1658

1659
    Val as_col(Val v, const char* who) {
39,746 ✔
1660
        if (v.is_scalar)
39,746 ✔
1661
            throw std::invalid_argument(std::string("expr: ") + who +
×
1662
                                        " needs a column operand");
1663
        return v;
39,746 ✔
1664
    }
1665

1666
    // A string operand: String always; Binary too when `binary_ok` (the
1667
    // predicate / length / find kernels read bytes, the maps produce text).
1668
    Val as_str(Val v, const char* who, bool binary_ok) {
6,314 ✔
1669
        Val a = as_col(v, who);
6,320 !
1670
        const bool ok =
6,314 ✔
1671
            a.type == TypeId::String || (binary_ok && a.type == TypeId::Binary);
6,314 !
1672
        if (!ok)
6,314 ✔
1673
            throw std::invalid_argument(std::string("expr: ") + who +
30 !
1674
                                        " needs a String" +
24 !
1675
                                        (binary_ok ? " or Binary" : "") +
18 !
1676
                                        " column, got " + type_name(a.type));
30 !
1677
        return a;
6,302 ✔
1678
    }
3,169 !
1679

1680
    Val cast(Val v, TypeId t) {
36,988 ✔
1681
        return {false,
92,470 ✔
1682
                emit(OP_CAST, v.slot, -1, static_cast<std::int32_t>(t), {}),
55,482 ✔
1683
                t,
18,494 ✔
1684
                {},
18,494 ✔
1685
                scalar(t)};
36,988 ✔
1686
    }
1687

1688
    Val compile_binary(const ExprNode* n) {
87,634 ✔
1689
        const int op = n->i;  // BinaryOp
87,634 ✔
1690
        Val a = compile(n->a.get());
87,634 !
1691
        Val b = compile(n->b.get());
87,634 !
1692
        if (is_unknown(a) || is_unknown(b)) return unknown_val();
87,634 !
1693
        if (a.is_scalar && b.is_scalar) return fold(op, a.scalar, b.scalar);
74,598 !
1694

1695
        const bool rf =
37,299 ✔
1696
            op == static_cast<int>(BinaryOp::Div) || is_float(a) || is_float(b);
74,598 !
1697
        TypeId out_type;
1698
        if (rf) {
74,598 ✔
1699
            promote_float(a);
30,422 !
1700
            promote_float(b);
30,422 !
1701
            out_type = TypeId::Float64;
30,422 ✔
1702
        } else if (!a.is_scalar && !b.is_scalar && a.type != b.type) {
59,387 ✔
1703
            a = cast(a, TypeId::Int64);
440 !
1704
            b = cast(b, TypeId::Int64);
440 !
1705
            out_type = TypeId::Int64;
440 ✔
1706
        } else {
220 ✔
1707
            out_type = a.is_scalar ? b.type : a.type;
43,736 ✔
1708
        }
1709

1710
        if (!a.is_scalar && !b.is_scalar)
74,598 ✔
1711
            return {false,
25,373 ✔
1712
                    emit(COL_OP[op], a.slot, b.slot, 0, {}),
76,119 !
1713
                    out_type,
25,373 ✔
1714
                    {},
25,373 ✔
1715
                    scalar(out_type)};
50,746 !
1716
        if (!a.is_scalar)  // col op scalar
23,852 ✔
1717
            return {false,
11,914 ✔
1718
                    emit(SCALAR_OP[op], a.slot, -1, 0, b.scalar),
35,742 !
1719
                    out_type,
11,914 ✔
1720
                    {},
11,914 ✔
1721
                    scalar(out_type)};
23,828 !
1722
        if (op == static_cast<int>(BinaryOp::Add) ||
24 ✔
1723
            op == static_cast<int>(BinaryOp::Mul))  // scalar op col commutes
11 ✔
1724
            return {false,
2 ✔
1725
                    emit(SCALAR_OP[op], b.slot, -1, 0, a.scalar),
6 !
1726
                    out_type,
2 ✔
1727
                    {},
2 ✔
1728
                    scalar(out_type)};
4 !
1729
        // scalar - col and scalar / col have no scalar-first kernel: broadcast
1730
        // the scalar to a column of the result type and run the column kernel.
1731
        const Val left = broadcast(a.scalar, out_type);
20 !
1732
        return {false,
10 ✔
1733
                emit(COL_OP[op], left.slot, b.slot, 0, {}),
30 !
1734
                out_type,
10 ✔
1735
                {},
10 ✔
1736
                scalar(out_type)};
20 !
1737
    }
87,634 ✔
1738

1739
    void promote_float(Val& v) {
61,068 ✔
1740
        if (v.is_scalar) {
61,068 ✔
1741
            v.scalar = to_f64_scalar(v.scalar);
6,208 ✔
1742
        } else if (v.type != TypeId::Float32 && v.type != TypeId::Float64) {
57,964 ✔
1743
            v = cast(v, TypeId::Float64);
17,692 !
1744
        }
8,846 ✔
1745
    }
61,068 ✔
1746

1747
    // A column of `t` holding `s` in every row, for a scalar arm of a select.
1748
    Val broadcast(dftu_scalar s, TypeId t) {
19,240 ✔
1749
        return {false,
48,100 ✔
1750
                emit(OP_CONST, -1, -1, static_cast<std::int32_t>(t), s),
28,860 ✔
1751
                t,
9,620 ✔
1752
                {},
9,620 ✔
1753
                scalar(t)};
19,240 ✔
1754
    }
1755

1756
    // cond ? a : b. The arms promote as arithmetic does: either float makes
1757
    // both Float64, two different integer types meet at Int64; a scalar arm
1758
    // broadcasts into a column of the promoted type. A string arm needs a
1759
    // string on the other side too.
1760
    Val compile_select(const ExprNode* n) {
1,600 ✔
1761
        Val c0 = compile(n->a.get());
1,600 !
1762
        Val a = compile(n->b.get());
1,600 !
1763
        Val b = compile(n->c.get());
1,600 !
1764
        if (is_unknown(c0) || is_unknown(a) || is_unknown(b))
1,600 !
1765
            return unknown_val();
240 ✔
1766
        Val c = as_col(c0, "select");
1,360 !
1767
        if (c.type != TypeId::Bool)
1,360 ✔
1768
            throw std::invalid_argument(
3 !
1769
                std::string("expr: select needs a Bool condition, got ") +
3 !
1770
                type_name(c.type));
3 ✔
1771
        if (a.is_scalar && b.is_scalar) {
1,358 ✔
1772
            const bool f = a.scalar.kind == DFTU_SCALAR_TAG_F64 ||
82 ✔
1773
                           b.scalar.kind == DFTU_SCALAR_TAG_F64;
52 !
1774
            const TypeId t = f ? TypeId::Float64 : TypeId::Int64;
56 ✔
1775
            if (f) {
56 ✔
1776
                a.scalar = to_f64_scalar(a.scalar);
4 ✔
1777
                b.scalar = to_f64_scalar(b.scalar);
4 ✔
1778
            }
2 ✔
1779
            a = broadcast(a.scalar, t);
56 !
1780
            b = broadcast(b.scalar, t);
56 !
1781
        } else {
56 ✔
1782
            const bool str_arm = (!a.is_scalar && a.type == TypeId::String) ||
2,558 ✔
1783
                                 (!b.is_scalar && b.type == TypeId::String);
1,256 !
1784
            if (str_arm) {
1,302 ✔
1785
                if (a.is_scalar || b.is_scalar || a.type != b.type)
46 !
1786
                    throw std::invalid_argument(
×
1787
                        "expr: select needs two String columns for a "
1788
                        "String arm");
1789
            } else if (is_float(a) || is_float(b)) {
1,279 ✔
1790
                promote_float(a);
112 !
1791
                promote_float(b);
112 !
1792
                if (a.is_scalar) a = broadcast(a.scalar, TypeId::Float64);
112 !
1793
                if (b.is_scalar) b = broadcast(b.scalar, TypeId::Float64);
112 !
1794
            } else {
56 ✔
1795
                const TypeId t = a.is_scalar        ? b.type
1,490 ✔
1796
                                 : b.is_scalar      ? a.type
664 ✔
1797
                                 : a.type == b.type ? a.type
318 ✔
1798
                                                    : TypeId::Int64;
1799
                if (!a.is_scalar && a.type != t) a = cast(a, t);
1,144 !
1800
                if (!b.is_scalar && b.type != t) b = cast(b, t);
1,144 !
1801
                if (a.is_scalar) a = broadcast(a.scalar, t);
1,144 !
1802
                if (b.is_scalar) b = broadcast(b.scalar, t);
1,144 !
1803
            }
1804
        }
1805
        SlotOp op;
1,358 ✔
1806
        op.opcode = OP_SELECT;
1,358 ✔
1807
        op.a = a.slot;
1,358 ✔
1808
        op.b = b.slot;
1,358 ✔
1809
        op.c = c.slot;
1,358 ✔
1810
        return {false, emit_op(op), a.type, {}, scalar(a.type)};
1,358 !
1811
    }
1,604 ✔
1812

1813
    Val fold(int op, dftu_scalar a, dftu_scalar b) {
×
1814
        const bool f = op == static_cast<int>(BinaryOp::Div) ||
×
1815
                       a.kind == DFTU_SCALAR_TAG_F64 ||
×
1816
                       b.kind == DFTU_SCALAR_TAG_F64;
×
1817
        dftu_scalar r{};
×
1818
        if (f) {
×
1819
            double x = scalar_to_double(a), y = scalar_to_double(b);
×
1820
            r.kind = DFTU_SCALAR_TAG_F64;
×
1821
            r.value.d = op == 0   ? x + y
×
1822
                        : op == 1 ? x - y
×
1823
                        : op == 2 ? x * y
×
1824
                                  : x / y;
1825
        } else {
1826
            std::int64_t x = a.value.i, y = b.value.i;
×
1827
            r.kind = DFTU_SCALAR_TAG_I64;
×
1828
            r.value.i = op == 0   ? x + y
×
1829
                        : op == 1 ? x - y
×
1830
                        : op == 2 ? x * y
×
1831
                                  : (y != 0 ? x / y : 0);
×
1832
        }
1833
        return {true, -1, TypeId::Int64, r,
1834
                scalar(f ? TypeId::Float64 : TypeId::Int64)};
×
1835
    }
1836

1837
    // Emit an op, hash-consing structurally identical ops to the same slot
1838
    // (common-subexpression elimination).
1839
    int emit(int opcode, int a, int b, std::int32_t param, dftu_scalar s,
301,622 ✔
1840
             dftu_scalar s2 = {}) {
1841
        SlotOp op;
301,622 ✔
1842
        op.opcode = opcode;
301,622 ✔
1843
        op.a = a;
301,622 ✔
1844
        op.b = b;
301,622 ✔
1845
        op.param = param;
301,622 ✔
1846
        op.scalar = s;
301,622 ✔
1847
        op.scalar2 = s2;
301,622 ✔
1848
        return emit_op(op);
452,433 !
1849
    }
1850

1851
    int emit_text(int opcode, int a, std::int32_t param, std::string_view text,
292 ✔
1852
                  std::string_view text2 = {}) {
1853
        SlotOp op;
292 ✔
1854
        op.opcode = opcode;
292 ✔
1855
        op.a = a;
292 ✔
1856
        op.param = param;
292 ✔
1857
        op.text = text;
292 ✔
1858
        op.text2 = text2;
292 ✔
1859
        return emit_op(op);
438 !
1860
    }
1861

1862
    int emit_op(const SlotOp& op) {
305,522 ✔
1863
        auto bits = [](dftu_scalar x) {
763,805 ✔
1864
            return x.kind == DFTU_SCALAR_TAG_F64
611,044 ✔
1865
                       ? std::bit_cast<std::int64_t>(x.value.d)
308,895 ✔
1866
                       : x.value.i;
607,671 ✔
1867
        };
1868
        // len is part of the key: a STR scalar's `bits` is its pointer, and
1869
        // two scalars can share a pointer with different lengths (a prefix),
1870
        // which would otherwise hash-cons to the same slot. A text operand is
1871
        // keyed by value, a values set by identity.
1872
        auto key = std::make_tuple(
152,761 !
1873
            op.opcode, op.a, op.b, op.c, static_cast<int>(op.param),
152,761 ✔
1874
            static_cast<int>(op.scalar.kind), bits(op.scalar), bits(op.scalar2),
458,283 ✔
1875
            op.scalar.len, op.scalar2.len, std::string(op.text),
458,283 !
1876
            std::string(op.text2), reinterpret_cast<std::uintptr_t>(op.values));
611,044 !
1877
        auto it = memo_.find(key);
305,522 !
1878
        if (it != memo_.end()) return it->second;
305,522 !
1879
        int slot = static_cast<int>(program.size());
279,570 ✔
1880
        program.push_back(op);
279,570 !
1881
        memo_.emplace(key, slot);
279,570 !
1882
        return slot;
279,570 ✔
1883
    }
305,522 ✔
1884

1885
    const std::vector<DataType>& input_types_;
1886
    std::map<std::tuple<int, int, int, int, int, int, std::int64_t,
1887
                        std::int64_t, std::uint32_t, std::uint32_t, std::string,
1888
                        std::string, std::uintptr_t>,
1889
             int>
1890
        memo_;
1891
};
1892

1893
// dftu_series_slice returns null for List and Struct; take()'s gather_column
1894
// handles those instead.
1895
Series load_slice(const Series& in, std::int64_t offset, std::int64_t len) {
89,451 ✔
1896
    if (dftu_series* v = dftu_series_slice(in.handle(), offset, len)) {
89,451 ✔
1897
        Series s{v};
85,721 ✔
1898
        return s.encoding() == Encoding::Chunked ? join_chunks(s)
85,717 !
1899
                                                 : std::move(s);
85,713 !
1900
    }
85,716 ✔
1901
    std::vector<std::int64_t> idx(static_cast<std::size_t>(len));
3,732 !
1902
    for (std::int64_t i = 0; i < len; ++i)
107,314 ✔
1903
        idx[static_cast<std::size_t>(i)] = offset + i;
103,582 ✔
1904
    return in.take(idx);
3,732 !
1905
}
46,593 ✔
1906

1907
template <class T>
1908
Series const_fixed(TypeId t, const dftu_scalar& s, std::int64_t len) {
10,888 ✔
1909
    std::vector<T> v(static_cast<std::size_t>(len), scalar_as<T>(s));
10,888 !
1910
    return Series::flat(t, v.data(), len);
16,332 !
1911
}
10,888 ✔
1912

1913
// A column of `len` rows of type `t`, every row holding `s` (a select arm
1914
// given as a literal). Refuses a type with no scalar form rather than build a
1915
// column whose contents would be a guess.
1916
Series const_column(TypeId t, const dftu_scalar& s, std::int64_t len) {
14,408 ✔
1917
    switch (t) {
14,408 !
1918
        case TypeId::Bool: {
714 ✔
1919
            const bool on = scalar_as<std::int64_t>(s) != 0;
1,428 ✔
1920
            std::vector<std::uint8_t> bits(buffer_bytes(TypeId::Bool, len),
1,428 ✔
1921
                                           on ? 0xFF : 0x00);
1,428 !
1922
            return Series::flat(t, bits.data(), len);
1,428 !
1923
        }
1,428 ✔
1924
        case TypeId::Int8:
1925
            return const_fixed<std::int8_t>(t, s, len);
×
1926
        case TypeId::Int16:
1927
            return const_fixed<std::int16_t>(t, s, len);
×
1928
        case TypeId::Int32:
1929
            return const_fixed<std::int32_t>(t, s, len);
×
1930
        case TypeId::Int64:
5,212 ✔
1931
            return const_fixed<std::int64_t>(t, s, len);
10,424 ✔
1932
        case TypeId::Uint8:
1933
            return const_fixed<std::uint8_t>(t, s, len);
×
1934
        case TypeId::Uint16:
1935
            return const_fixed<std::uint16_t>(t, s, len);
×
1936
        case TypeId::Uint32:
1937
            return const_fixed<std::uint32_t>(t, s, len);
×
1938
        case TypeId::Uint64:
1939
            return const_fixed<std::uint64_t>(t, s, len);
×
1940
        case TypeId::Float32:
1941
            return const_fixed<float>(t, s, len);
×
1942
        case TypeId::Float64:
232 ✔
1943
            return const_fixed<double>(t, s, len);
464 ✔
1944
        case TypeId::String: {
1,046 ✔
1945
            const std::string_view v(s.value.s ? s.value.s : "", s.len);
2,092 !
1946
            const std::vector<std::string_view> rows(
1,046 ✔
1947
                static_cast<std::size_t>(len), v);
2,092 !
1948
            return Series::strings(std::span<const std::string_view>(rows));
2,092 !
1949
        }
2,092 ✔
1950
        case TypeId::Unknown:
1951
        case TypeId::Float16:
1952
        case TypeId::Binary:
1953
        case TypeId::List:
1954
        case TypeId::Struct:
1955
        case TypeId::Date32:
1956
        case TypeId::Date64:
1957
        case TypeId::Time32:
1958
        case TypeId::Time64:
1959
        case TypeId::Timestamp:
1960
        case TypeId::Duration:
1961
        case TypeId::Decimal128:
1962
        case TypeId::Decimal256:
1963
        case TypeId::FixedSizeBinary:
1964
        case TypeId::LargeString:
1965
        case TypeId::LargeBinary:
1966
        case TypeId::LargeList:
1967
        case TypeId::FixedSizeList:
1968
        case TypeId::Map:
1969
            break;
×
1970
    }
1971
    throw std::invalid_argument(
×
1972
        std::string("expr: a literal cannot broadcast to a ") + type_name(t) +
×
1973
        " column");
1974
}
7,204 ✔
1975

1976
// ---- duql kernels: flat loops over Int64 / Uint64 / Float64, String and Bool
1977
// columns; every unknown result is a null cell
1978
// ---------------------------------
1979

1980
Series flat_view(const Series& s) {
28,368 ✔
1981
    if (!s.valid() || s.encoding() == Encoding::Flat) return s.share();
28,368 !
1982
    return s.materialize();
34 ✔
1983
}
14,184 ✔
1984

1985
bool valid_at(const dftu_series* h, std::int64_t i) {
3,688,164 ✔
1986
    return !h->validity || ((h->validity->data()[i >> 3] >> (i & 7)) & 1);
3,688,164 ✔
1987
}
1988

1989
bool bit_at(const dftu_series* h, std::int64_t i) {
50 ✔
1990
    return (h->data->data()[i >> 3] >> (i & 7)) & 1;
50 ✔
1991
}
1992

1993
template <class T>
1994
const T* values_of(const dftu_series* h) {
26,130 ✔
1995
    return h->data ? reinterpret_cast<const T*>(h->data->data()) : nullptr;
26,130 !
1996
}
1997

1998
struct TextCol {
1999
    const char* data = "";
1,090 ✔
2000
    const std::int32_t* off32 = nullptr;
1,090 ✔
2001
    const std::int64_t* off64 = nullptr;
1,090 ✔
2002

2003
    explicit TextCol(const dftu_series* h) {
3,270 ✔
2004
        if (h->data) data = reinterpret_cast<const char*>(h->data->data());
2,180 ✔
2005
        if (h->offsets && !h->wide_offsets())
2,180 !
2006
            off32 = reinterpret_cast<const std::int32_t*>(h->offsets->data());
2,180 ✔
2007
        if (h->offsets && h->wide_offsets())
2,180 !
2008
            off64 = reinterpret_cast<const std::int64_t*>(h->offsets->data());
×
2009
    }
3,270 ✔
2010
    bool ok() const { return off32 || off64; }
2,074 !
2011
    std::string_view at(std::int64_t i) const {
589,746 ✔
2012
        if (off32)
589,746 !
2013
            return {data + off32[i],
884,619 ✔
2014
                    static_cast<std::size_t>(off32[i + 1] - off32[i])};
589,746 ✔
2015
        return {data + off64[i],
×
2016
                static_cast<std::size_t>(off64[i + 1] - off64[i])};
×
2017
    }
294,873 ✔
2018
};
2019

2020
std::vector<std::uint8_t> bitmap(std::int64_t n) {
19,084 ✔
2021
    return std::vector<std::uint8_t>(static_cast<std::size_t>((n + 7) / 8), 0);
28,626 !
2022
}
2023

2024
void set_bit(std::vector<std::uint8_t>& bits, std::int64_t i) {
2,122,214 ✔
2025
    bits[static_cast<std::size_t>(i >> 3)] |=
2,122,214 ✔
2026
        static_cast<std::uint8_t>(1u << (i & 7));
2,122,214 ✔
2027
}
2,122,214 ✔
2028

2029
// Fixed-width output cells; a row never set is null.
2030
template <class T>
2031
class Cells {
2032
   public:
2033
    explicit Cells(std::int64_t n)
15,465 ✔
2034
        : vals_(static_cast<std::size_t>(n)), valid_(bitmap(n)) {}
15,465 !
2035
    void set(std::int64_t i, T v) {
1,037,086 ✔
2036
        vals_[static_cast<std::size_t>(i)] = v;
1,037,086 ✔
2037
        set_bit(valid_, i);
1,037,086 ✔
2038
        ++set_;
1,037,086 ✔
2039
    }
1,037,086 ✔
2040
    void set(std::int64_t i, std::optional<T> v) {
1,101,272 ✔
2041
        if (v) set(i, *v);
1,101,272 !
2042
    }
1,101,272 ✔
2043
    Series finish(TypeId t) {
10,310 ✔
2044
        const auto n = static_cast<std::int64_t>(vals_.size());
10,310 ✔
2045
        const std::uint8_t* validity = set_ == n ? nullptr : valid_.data();
10,310 !
2046
        const T* data = vals_.data();
10,310 ✔
2047
        return Series::from_borrowed(t, data, n, std::move(vals_), validity);
10,310 ✔
2048
    }
2049

2050
   private:
2051
    std::vector<T> vals_;
2052
    std::vector<std::uint8_t> valid_;
2053
    std::int64_t set_ = 0;
5,155 ✔
2054
};
2055

2056
class BoolCells {
2057
   public:
2058
    explicit BoolCells(std::int64_t n)
5,298 ✔
2059
        : n_(n), bits_(bitmap(n)), valid_(bitmap(n)) {}
5,298 !
2060
    void set(std::int64_t i, bool v) {
505,400 ✔
2061
        if (v) set_bit(bits_, i);
505,400 ✔
2062
        set_bit(valid_, i);
505,400 ✔
2063
        ++set_;
505,400 ✔
2064
    }
505,400 ✔
2065
    Series finish() {
3,532 ✔
2066
        return Series::flat(TypeId::Bool, bits_.data(), n_,
5,298 ✔
2067
                            set_ == n_ ? nullptr : valid_.data());
3,532 ✔
2068
    }
2069

2070
   private:
2071
    std::int64_t n_;
2072
    std::vector<std::uint8_t> bits_;
2073
    std::vector<std::uint8_t> valid_;
2074
    std::int64_t set_ = 0;
1,766 ✔
2075
};
2076

2077
// String output rows, appended in row order.
2078
class TextCells {
2079
   public:
2080
    explicit TextCells(std::int64_t n) : n_(n), valid_(bitmap(n)) {
2,565 !
2081
        off_.reserve(static_cast<std::size_t>(n) + 1);
1,710 !
2082
        off_.push_back(0);
1,710 !
2083
    }
2,565 ✔
2084
    std::string& buf() { return data_; }
87,346 ✔
2085
    void end_row(bool valid) {
488,002 ✔
2086
        if (valid) {
488,002 ✔
2087
            set_bit(valid_, static_cast<std::int64_t>(off_.size()) - 1);
487,544 ✔
2088
            ++set_;
487,544 ✔
2089
        }
243,772 ✔
2090
        Series::check_string_bytes(data_.size());
488,002 ✔
2091
        off_.push_back(static_cast<std::int32_t>(data_.size()));
488,002 !
2092
    }
488,002 ✔
2093
    void add(std::string_view s) {
400,238 ✔
2094
        data_.append(s);
400,238 ✔
2095
        end_row(true);
400,238 ✔
2096
    }
400,238 ✔
2097
    Series finish() {
1,710 ✔
2098
        return Series{
855 ✔
2099
            dftu_series_new_string(DFTU_TYPE_STRING, off_.data(), data_.data(),
2,565 ✔
2100
                                   n_, set_ == n_ ? nullptr : valid_.data())};
2,565 ✔
2101
    }
2102

2103
   private:
2104
    std::int64_t n_;
2105
    std::vector<std::int32_t> off_;
2106
    std::string data_;
2107
    std::vector<std::uint8_t> valid_;
2108
    std::int64_t set_ = 0;
855 ✔
2109
};
2110

2111
// Calls fn with a value of the C++ type behind Int64, Uint64 or Float64.
2112
template <class Fn>
2113
void with_num(TypeId t, Fn&& fn) {
26,154 ✔
2114
    if (t == TypeId::Int64)
26,154 !
2115
        fn(std::int64_t{});
12,034 ✔
2116
    else if (t == TypeId::Uint64)
14,120 !
2117
        fn(std::uint64_t{});
7,784 ✔
2118
    else
2119
        fn(double{});
6,336 ✔
2120
}
26,154 ✔
2121

2122
template <class T>
2123
constexpr bool IS_DOUBLE = std::is_same_v<T, double>;
2124

2125
template <class T>
2126
int order(T a, T b) {
504,704 ✔
2127
    return a < b ? -1 : (b < a ? 1 : 0);
504,704 ✔
2128
}
2129

2130
// Exact comparison of an integer with a double, as the duql evaluator does
2131
// it: the integer is never rounded to a double.
2132
std::optional<int> cmp_num(std::int64_t a, double d) {
12,606 ✔
2133
    constexpr double TWO_POW_63 = 9223372036854775808.0;
12,606 ✔
2134
    if (std::isnan(d)) return std::nullopt;
12,606 ✔
2135
    if (d >= TWO_POW_63) return -1;
12,600 ✔
2136
    if (d < -TWO_POW_63) return 1;
12,574 !
2137
    const double f = std::floor(d);
12,574 ✔
2138
    const auto fi = static_cast<std::int64_t>(f);
12,574 ✔
2139
    if (a != fi) return order(a, fi);
12,574 ✔
2140
    return d > f ? -1 : 0;
308 ✔
2141
}
6,303 ✔
2142

2143
std::optional<int> cmp_num(std::uint64_t a, double d) {
17,132 ✔
2144
    constexpr double TWO_POW_64 = 18446744073709551616.0;
17,132 ✔
2145
    if (std::isnan(d)) return std::nullopt;
17,132 !
2146
    if (d < 0) return 1;
17,132 ✔
2147
    if (d >= TWO_POW_64) return -1;
17,130 ✔
2148
    const double f = std::floor(d);
17,128 ✔
2149
    const auto fu = static_cast<std::uint64_t>(f);
17,128 ✔
2150
    if (a != fu) return order(a, fu);
17,128 ✔
2151
    return d > f ? -1 : 0;
32 ✔
2152
}
8,566 ✔
2153

2154
std::optional<int> cmp_num(std::int64_t a, std::uint64_t b) {
18,008 ✔
2155
    if (a < 0) return -1;
18,008 ✔
2156
    return order(static_cast<std::uint64_t>(a), b);
18,000 ✔
2157
}
9,004 ✔
2158

2159
std::optional<int> flip(std::optional<int> c) {
30,534 ✔
2160
    if (c) return -*c;
30,534 ✔
2161
    return c;
2 ✔
2162
}
15,267 ✔
2163

2164
template <class A, class B>
2165
std::optional<int> cmp_numbers(A a, B b) {
411,266 ✔
2166
    if constexpr (std::is_same_v<A, B>) {
2167
        if constexpr (IS_DOUBLE<A>)
2168
            if (std::isnan(a) || std::isnan(b)) return std::nullopt;
236,006 !
2169
        return order(a, b);
363,518 ✔
2170
    } else if constexpr (IS_DOUBLE<A>) {
2171
        return flip(cmp_num(b, a));
12,534 ✔
2172
    } else if constexpr (IS_DOUBLE<B>) {
2173
        return cmp_num(a, b);
17,204 ✔
2174
    } else if constexpr (std::is_same_v<A, std::int64_t>) {
2175
        return cmp_num(a, b);
8 ✔
2176
    } else {
2177
        return flip(cmp_num(b, a));
18,000 ✔
2178
    }
2179
}
118,003 ✔
2180

2181
bool apply_cmp(CmpOp op, int c) {
504,986 ✔
2182
    switch (op) {
504,986 ✔
2183
        case CmpOp::Gt:
45,436 ✔
2184
            return c > 0;
90,872 ✔
2185
        case CmpOp::Ge:
80 ✔
2186
            return c >= 0;
160 ✔
2187
        case CmpOp::Lt:
126,372 ✔
2188
            return c < 0;
252,744 ✔
2189
        case CmpOp::Le:
9 ✔
2190
            return c <= 0;
18 ✔
2191
        case CmpOp::Eq:
42,098 ✔
2192
            return c == 0;
84,196 ✔
2193
        case CmpOp::Ne:
38,498 ✔
2194
            return c != 0;
76,996 ✔
2195
    }
2196
    return false;
×
2197
}
252,493 ✔
2198

2199
// An integer as sign and magnitude, so int64 and uint64 mix without loss.
2200
struct Int {
2201
    bool neg = false;
2202
    std::uint64_t mag = 0;
2203
};
2204

2205
constexpr std::uint64_t U64_MAX = std::numeric_limits<std::uint64_t>::max();
2206
constexpr std::uint64_t I64_MIN_MAG = std::uint64_t{1} << 63;
2207

2208
Int int_of(std::int64_t v) {
1,509,510 ✔
2209
    if (v < 0) return {true, std::uint64_t{0} - static_cast<std::uint64_t>(v)};
1,509,510 ✔
2210
    return {false, static_cast<std::uint64_t>(v)};
1,166,496 ✔
2211
}
754,755 ✔
2212
Int int_of(std::uint64_t v) { return {false, v}; }
376,878 ✔
2213

2214
std::optional<std::int64_t> i64_of(Int x) {
780,924 ✔
2215
    if (!x.neg) {
780,924 ✔
2216
        if (x.mag > static_cast<std::uint64_t>(
1,116,198 ✔
2217
                        std::numeric_limits<std::int64_t>::max()))
744,132 ✔
2218
            return std::nullopt;
28 ✔
2219
        return static_cast<std::int64_t>(x.mag);
744,104 ✔
2220
    }
2221
    if (x.mag > I64_MIN_MAG) return std::nullopt;
36,792 ✔
2222
    return static_cast<std::int64_t>(std::uint64_t{0} - x.mag);
36,788 ✔
2223
}
390,462 ✔
2224

2225
std::optional<Int> int_add(Int a, Int b) {
395,526 ✔
2226
    if (a.neg == b.neg) {
395,526 ✔
2227
        if (a.mag > U64_MAX - b.mag) return std::nullopt;
349,354 !
2228
        return Int{a.neg, a.mag + b.mag};
349,354 ✔
2229
    }
2230
    if (a.mag >= b.mag) return Int{a.neg, a.mag - b.mag};
46,172 ✔
2231
    return Int{b.neg, b.mag - a.mag};
528 ✔
2232
}
197,763 ✔
2233

2234
std::optional<std::int64_t> int_arith(ArithOp op, Int a, Int b) {
924,896 ✔
2235
    std::optional<Int> out;
924,896 ✔
2236
    switch (op) {
924,896 !
2237
        case ArithOp::Add:
174,675 ✔
2238
            out = int_add(a, b);
349,350 ✔
2239
            break;
349,350 ✔
2240
        case ArithOp::Sub:
23,079 ✔
2241
            out = int_add(a, Int{!b.neg, b.mag});
46,158 ✔
2242
            break;
46,158 ✔
2243
        case ArithOp::Mul:
49,814 ✔
2244
            if (a.mag != 0 && b.mag > U64_MAX / a.mag) return std::nullopt;
99,628 ✔
2245
            out = Int{a.neg != b.neg, a.mag * b.mag};
99,626 ✔
2246
            break;
99,626 ✔
2247
        case ArithOp::FloorDiv: {
180 ✔
2248
            if (b.mag == 0) return std::nullopt;
360 ✔
2249
            Int q{a.neg != b.neg, a.mag / b.mag};
352 ✔
2250
            if (q.neg && a.mag % b.mag != 0) ++q.mag;
352 ✔
2251
            out = q;
352 ✔
2252
            break;
352 ✔
2253
        }
2254
        case ArithOp::Mod: {
214,700 ✔
2255
            if (b.mag == 0) return std::nullopt;
429,400 ✔
2256
            std::uint64_t rem = a.mag % b.mag;
360,824 ✔
2257
            if (rem != 0 && a.neg != b.neg) rem = b.mag - rem;
360,824 ✔
2258
            out = Int{b.neg, rem};
360,824 ✔
2259
            break;
360,824 ✔
2260
        }
2261
        case ArithOp::Div:
2262
            return std::nullopt;
×
2263
    }
2264
    if (!out) return std::nullopt;
856,310 ✔
2265
    if (out->mag == 0) return 0;
856,310 ✔
2266
    return i64_of(*out);
697,710 ✔
2267
}
462,448 ✔
2268

2269
std::optional<double> of_double(double d) {
92,468 ✔
2270
    if (std::isnan(d)) return std::nullopt;
92,468 ✔
2271
    return d;
92,460 ✔
2272
}
46,234 ✔
2273

2274
std::optional<double> dbl_arith(ArithOp op, double a, double b) {
86,184 ✔
2275
    switch (op) {
86,184 ✔
2276
        case ArithOp::Add:
5,796 ✔
2277
            return of_double(a + b);
11,592 ✔
2278
        case ArithOp::Sub:
5,192 ✔
2279
            return of_double(a - b);
10,384 ✔
2280
        case ArithOp::Mul:
31,450 ✔
2281
            return of_double(a * b);
62,900 ✔
2282
        case ArithOp::Div:
320 ✔
2283
            if (b == 0) return std::nullopt;
640 ✔
2284
            return of_double(a / b);
632 ✔
2285
        case ArithOp::FloorDiv:
323 ✔
2286
            if (b == 0) return std::nullopt;
646 ✔
2287
            return of_double(std::floor(a / b));
642 ✔
2288
        case ArithOp::Mod: {
11 ✔
2289
            if (b == 0) return std::nullopt;
22 ✔
2290
            double rem = std::fmod(a, b);
18 ✔
2291
            if (rem != 0 && (rem < 0) != (b < 0)) rem += b;
18 ✔
2292
            return of_double(rem);
18 ✔
2293
        }
2294
    }
2295
    return std::nullopt;
×
2296
}
43,092 ✔
2297

2298
// A number as the output type R: past int64 is null, NaN is null.
2299
template <class R, class V>
2300
std::optional<R> num_as(V v) {
47,042 ✔
2301
    if constexpr (IS_DOUBLE<R>) {
2302
        return of_double(static_cast<double>(v));
14 ✔
2303
    } else if constexpr (std::is_same_v<R, V>) {
2304
        return v;
58 ✔
2305
    } else if constexpr (std::is_same_v<R, std::int64_t> &&
2306
                         std::is_same_v<V, std::uint64_t>) {
2307
        return i64_of(Int{false, v});
46,970 ✔
2308
    } else {
2309
        return std::nullopt;
×
2310
    }
2311
}
2312

2313
// A double truncated to int64; null when it is not finite or out of range.
2314
std::optional<std::int64_t> trunc_i64(double d) {
2,738 ✔
2315
    if (!std::isfinite(d)) return std::nullopt;
2,738 ✔
2316
    const double t = std::trunc(d);
2,732 ✔
2317
    if (t >= -9223372036854775808.0 && t < 9223372036854775808.0)
2,732 ✔
2318
        return static_cast<std::int64_t>(t);
1,958 ✔
2319
    return std::nullopt;
774 ✔
2320
}
1,369 ✔
2321

2322
bool same_rows(const dftu_series* a, const dftu_series* b) {
12,798 ✔
2323
    return a && b && a->length == b->length;
12,798 !
2324
}
2325

2326
Series arith_kernel(const Series& sa, const Series& sb, std::int32_t code) {
9,098 ✔
2327
    const Series fa = flat_view(sa);
9,098 !
2328
    const Series fb = flat_view(sb);
9,098 !
2329
    const dftu_series* a = fa.handle();
9,098 ✔
2330
    const dftu_series* b = fb.handle();
9,098 ✔
2331
    if (!same_rows(a, b)) return {};
9,098 !
2332
    const auto op = static_cast<ArithOp>(code);
9,098 ✔
2333
    const std::int64_t n = a->length;
9,098 ✔
2334
    const TypeId t = arith_type(code, a->type, b->type);
9,098 !
2335
    Series out;
9,098 ✔
2336
    with_num(a->type, [&](auto xa) {
18,196 !
2337
        with_num(b->type, [&](auto xb) {
1,948,996 ✔
2338
            using A = decltype(xa);
2339
            using B = decltype(xb);
2340
            const A* pa = values_of<A>(a);
13,647 ✔
2341
            const B* pb = values_of<B>(b);
9,098 ✔
2342
            if constexpr (!IS_DOUBLE<A>) {
2343
                if constexpr (!IS_DOUBLE<B>) {
2344
                    if (t == TypeId::Int64) {
11,781 ✔
2345
                        Cells<std::int64_t> c(n);
11,743 !
2346
                        for (std::int64_t i = 0; i < n; ++i)
989,316 ✔
2347
                            if (valid_at(a, i) && valid_at(b, i))
1,444,570 !
2348
                                c.set(i, int_arith(op, int_of(pa[i]),
1,053,638 !
2349
                                                   int_of(pb[i])));
924,896 !
2350
                        out = c.finish(TypeId::Int64);
11,743 !
2351
                        return;
3,597 ✔
2352
                    }
7,194 ✔
2353
                }
2354
            }
2355
            Cells<double> c(n);
1,904 !
2356
            for (std::int64_t i = 0; i < n; ++i)
96,280 !
2357
                if (valid_at(a, i) && valid_at(b, i))
137,468 !
2358
                    c.set(i, dbl_arith(op, static_cast<double>(pa[i]),
129,276 !
2359
                                       static_cast<double>(pb[i])));
86,184 ✔
2360
            out = c.finish(TypeId::Float64);
1,904 !
2361
        });
5,501 ✔
2362
    });
9,098 ✔
2363
    return out;
9,098 ✔
2364
}
13,647 !
2365

2366
Series neg_kernel(const Series& sa) {
30 ✔
2367
    const Series fa = flat_view(sa);
30 !
2368
    const dftu_series* a = fa.handle();
30 ✔
2369
    if (!a) return {};
30 ✔
2370
    const std::int64_t n = a->length;
30 ✔
2371
    Series out;
30 ✔
2372
    with_num(a->type, [&](auto xa) {
60 !
2373
        using A = decltype(xa);
2374
        const A* pa = values_of<A>(a);
30 ✔
2375
        if constexpr (IS_DOUBLE<A>) {
2376
            Cells<double> c(n);
18,159 !
2377
            for (std::int64_t i = 0; i < n; ++i)
4 ✔
2378
                if (valid_at(a, i)) c.set(i, of_double(-pa[i]));
2 !
2379
            out = c.finish(TypeId::Float64);
16 !
2380
        } else {
2 ✔
2381
            Cells<std::int64_t> c(n);
28 !
2382
            for (std::int64_t i = 0; i < n; ++i) {
36,286 ✔
2383
                if (!valid_at(a, i)) continue;
36,258 !
2384
                const Int x = int_of(pa[i]);
36,250 ✔
2385
                c.set(i, x.mag == 0 ? std::optional<std::int64_t>{0}
72,476 !
2386
                                    : i64_of(Int{!x.neg, x.mag}));
36,226 !
2387
            }
18,125 ✔
2388
            out = c.finish(TypeId::Int64);
28 !
2389
        }
28 ✔
2390
    });
30 ✔
2391
    return out;
30 ✔
2392
}
45 !
2393

2394
bool is_num_col(const dftu_series* h) {
6,112 ✔
2395
    return h->type == TypeId::Int64 || h->type == TypeId::Uint64 ||
8,518 ✔
2396
           h->type == TypeId::Float64;
7,868 ✔
2397
}
2398

2399
// -1/0/1 of row i of `a` against row i of `b` (both present), per domain:
2400
// numbers exactly, strings bytewise, false before true; fn gets the order or
2401
// nullopt when the two do not compare (a NaN).
2402
template <class Fn>
2403
bool order_rows(const dftu_series* a, const dftu_series* b, Fn&& fn) {
3,468 ✔
2404
    const std::int64_t n = a->length;
3,468 ✔
2405
    if (is_num_col(a) && is_num_col(b)) {
3,468 !
2406
        with_num(a->type, [&](auto xa) {
6,505 !
2407
            with_num(b->type, [&](auto xb) {
835,560 !
2408
                using A = decltype(xa);
2409
                using B = decltype(xb);
2410
                const A* pa = values_of<A>(a);
2,602 ✔
2411
                const B* pb = values_of<B>(b);
2,602 ✔
2412
                for (std::int64_t i = 0; i < n; ++i)
417,726 !
2413
                    if (valid_at(a, i) && valid_at(b, i))
620,750 !
2414
                        fn(i, cmp_numbers(pa[i], pb[i]));
411,252 ✔
2415
            });
1,301 ✔
2416
        });
1,301 ✔
2417
        return true;
2,602 ✔
2418
    }
2419
    if (a->type == TypeId::Bool && b->type == TypeId::Bool) {
866 !
2420
        for (std::int64_t i = 0; i < n; ++i)
8 !
2421
            if (valid_at(a, i) && valid_at(b, i))
9 !
2422
                fn(i, std::optional<int>(order(bit_at(a, i), bit_at(b, i))));
6 ✔
2423
        return true;
2 ✔
2424
    }
2425
    const TextCol ta(a), tb(b);
864 ✔
2426
    if (!is_text_type(a->type) || !is_text_type(b->type) || !ta.ok() ||
1,296 !
2427
        !tb.ok())
864 !
2428
        return false;
×
2429
    for (std::int64_t i = 0; i < n; ++i)
95,162 ✔
2430
        if (valid_at(a, i) && valid_at(b, i))
141,207 !
2431
            fn(i, std::optional<int>(order(ta.at(i), tb.at(i))));
93,818 ✔
2432
    return true;
864 ✔
2433
}
1,734 ✔
2434

2435
Series cmp_expr_kernel(const Series& sa, const Series& sb, std::int32_t code) {
3,440 ✔
2436
    const Series fa = flat_view(sa);
3,440 !
2437
    const Series fb = flat_view(sb);
3,440 !
2438
    const dftu_series* a = fa.handle();
3,440 ✔
2439
    const dftu_series* b = fb.handle();
3,440 ✔
2440
    if (!same_rows(a, b)) return {};
3,440 ✔
2441
    const auto op = static_cast<CmpOp>(code);
3,440 ✔
2442
    BoolCells c(a->length);
3,440 !
2443
    if (!order_rows(a, b, [&](std::int64_t i, std::optional<int> o) {
255,936 !
2444
            if (o) c.set(i, apply_cmp(op, *o));
504,992 ✔
2445
        }))
504,992 ✔
2446
        return {};
×
2447
    return c.finish();
3,440 !
2448
}
3,440 ✔
2449

2450
Series extreme_kernel(const Series& sa, const Series& sb, bool least) {
28 ✔
2451
    const Series fa = flat_view(sa);
28 !
2452
    const Series fb = flat_view(sb);
28 !
2453
    const dftu_series* a = fa.handle();
28 ✔
2454
    const dftu_series* b = fb.handle();
28 ✔
2455
    if (!same_rows(a, b)) return {};
28 ✔
2456
    const std::int64_t n = a->length;
28 ✔
2457
    const int want = least ? -1 : 1;
28 ✔
2458
    // Row i takes b only when b is strictly beyond a, as duql keeps the
2459
    // first of equal operands.
2460
    std::vector<char> take_b(static_cast<std::size_t>(n), 0);
28 !
2461
    std::vector<char> known(static_cast<std::size_t>(n), 0);
28 !
2462
    if (!order_rows(b, a, [&](std::int64_t i, std::optional<int> o) {
70 !
2463
            if (!o) return;
84 ✔
2464
            known[static_cast<std::size_t>(i)] = 1;
82 ✔
2465
            take_b[static_cast<std::size_t>(i)] = *o == want;
82 ✔
2466
        }))
42 ✔
2467
        return {};
×
2468
    auto pick = [&](std::int64_t i) {
96 ✔
2469
        return take_b[static_cast<std::size_t>(i)] != 0;
82 ✔
2470
    };
14 ✔
2471
    auto have = [&](std::int64_t i) {
116 ✔
2472
        return known[static_cast<std::size_t>(i)] != 0;
102 ✔
2473
    };
14 ✔
2474
    if (is_num_col(a)) {
28 ✔
2475
        Series out;
26 ✔
2476
        const TypeId t = promote(a->type, b->type);
26 ✔
2477
        with_num(t, [&](auto xr) {
52 !
2478
            with_num(a->type, [&](auto xa) {
78 ✔
2479
                with_num(b->type, [&](auto xb) {
65 !
2480
                    using R = decltype(xr);
2481
                    using A = decltype(xa);
2482
                    using B = decltype(xb);
2483
                    const A* pa = values_of<A>(a);
26 ✔
2484
                    const B* pb = values_of<B>(b);
26 ✔
2485
                    Cells<R> c(n);
39 !
2486
                    for (std::int64_t i = 0; i < n; ++i)
124 !
2487
                        if (have(i))
150 !
2488
                            c.set(i, pick(i) ? num_as<R>(pb[i])
135 !
2489
                                             : num_as<R>(pa[i]));
44 !
2490
                    out = c.finish(t);
39 !
2491
                });
26 ✔
2492
            });
13 ✔
2493
        });
26 ✔
2494
        return out;
26 ✔
2495
    }
26 !
2496
    if (a->type == TypeId::Bool) {
2 !
2497
        BoolCells c(n);
×
2498
        for (std::int64_t i = 0; i < n; ++i)
×
2499
            if (have(i)) c.set(i, pick(i) ? bit_at(b, i) : bit_at(a, i));
×
2500
        return c.finish();
×
2501
    }
×
2502
    const TextCol ta(a), tb(b);
2 !
2503
    TextCells c(n);
2 !
2504
    for (std::int64_t i = 0; i < n; ++i) {
6 ✔
2505
        if (have(i))
4 !
2506
            c.add(pick(i) ? tb.at(i) : ta.at(i));
4 !
2507
        else
2508
            c.end_row(false);
×
2509
    }
2 ✔
2510
    return c.finish();
2 !
2511
}
28 ✔
2512

2513
Series to_i64_kernel(const Series& sa) {
6 ✔
2514
    const Series fa = flat_view(sa);
6 !
2515
    const dftu_series* a = fa.handle();
6 ✔
2516
    if (!a || a->type != TypeId::Uint64) return {};
6 !
2517
    const auto* p = values_of<std::uint64_t>(a);
6 !
2518
    Cells<std::int64_t> c(a->length);
6 !
2519
    for (std::int64_t i = 0; i < a->length; ++i)
18 ✔
2520
        if (valid_at(a, i)) c.set(i, i64_of(Int{false, p[i]}));
12 !
2521
    return c.finish(TypeId::Int64);
6 !
2522
}
6 ✔
2523

2524
// Round half away from zero to `digits` decimals, as the duql evaluator
2525
// does; an integer operand comes back as Int64.
2526
Series round_kernel(const Series& sa, std::int64_t digits) {
50 ✔
2527
    const Series fa = flat_view(sa);
50 !
2528
    const dftu_series* a = fa.handle();
50 ✔
2529
    if (!a) return {};
50 ✔
2530
    const std::int64_t n = a->length;
50 ✔
2531
    const bool integer = a->type != TypeId::Float64;
50 ✔
2532
    const bool in_range = digits >= -308 && digits <= 308;
50 ✔
2533
    const double scale = std::pow(10.0, static_cast<double>(digits));
50 ✔
2534
    Series out;
50 ✔
2535
    with_num(a->type, [&](auto xa) {
100 !
2536
        using A = decltype(xa);
2537
        const A* pa = values_of<A>(a);
50 ✔
2538
        auto rounded = [&](std::int64_t i) {
6,226 ✔
2539
            return std::round(static_cast<double>(pa[i]) * scale) / scale;
6,201 ✔
2540
        };
2541
        if (integer) {
50 !
2542
            Cells<std::int64_t> c(n);
2 !
2543
            for (std::int64_t i = 0; i < n; ++i)
6 !
2544
                if (in_range && valid_at(a, i)) c.set(i, trunc_i64(rounded(i)));
4 !
2545
            out = c.finish(TypeId::Int64);
2 !
2546
        } else {
2 ✔
2547
            Cells<double> c(n);
48 !
2548
            for (std::int64_t i = 0; i < n; ++i)
6,242 !
2549
                if (in_range && valid_at(a, i)) c.set(i, of_double(rounded(i)));
6,194 !
2550
            out = c.finish(TypeId::Float64);
48 !
2551
        }
48 ✔
2552
    });
50 ✔
2553
    return out;
50 ✔
2554
}
75 !
2555

2556
Series log_kernel(const Series& sa) {
4 ✔
2557
    const Series fa = flat_view(sa);
4 !
2558
    const dftu_series* a = fa.handle();
4 ✔
2559
    if (!a) return {};
4 ✔
2560
    Cells<double> c(a->length);
4 !
2561
    with_num(a->type, [&](auto xa) {
8 !
2562
        using A = decltype(xa);
2563
        const A* pa = values_of<A>(a);
4 ✔
2564
        for (std::int64_t i = 0; i < a->length; ++i) {
28 !
2565
            const auto d = static_cast<double>(pa[i]);
24 ✔
2566
            if (valid_at(a, i) && d > 0) c.set(i, std::log(d));
24 !
2567
        }
12 ✔
2568
    });
4 ✔
2569
    return c.finish(TypeId::Float64);
4 !
2570
}
4 ✔
2571

2572
Series pow_kernel(const Series& sa, const Series& sb) {
6 ✔
2573
    const Series fa = flat_view(sa);
6 !
2574
    const Series fb = flat_view(sb);
6 !
2575
    const dftu_series* a = fa.handle();
6 ✔
2576
    const dftu_series* b = fb.handle();
6 ✔
2577
    if (!same_rows(a, b)) return {};
6 ✔
2578
    Cells<double> c(a->length);
6 !
2579
    with_num(a->type, [&](auto xa) {
12 !
2580
        with_num(b->type, [&](auto xb) {
70 ✔
2581
            using A = decltype(xa);
2582
            using B = decltype(xb);
2583
            const A* pa = values_of<A>(a);
9 ✔
2584
            const B* pb = values_of<B>(b);
6 ✔
2585
            for (std::int64_t i = 0; i < a->length; ++i)
30 !
2586
                if (valid_at(a, i) && valid_at(b, i))
35 !
2587
                    c.set(i, of_double(std::pow(static_cast<double>(pa[i]),
36 !
2588
                                                static_cast<double>(pb[i]))));
22 ✔
2589
        });
3 ✔
2590
    });
6 ✔
2591
    return c.finish(TypeId::Float64);
6 !
2592
}
6 ✔
2593

2594
bool utf8_continuation(char c) {
1,200,230 ✔
2595
    return (static_cast<unsigned char>(c) & 0xC0) == 0x80;
1,200,230 ✔
2596
}
2597

2598
// Byte offset of code point `n` in `s`, or s.size() past the end.
2599
std::size_t utf8_offset(std::string_view s, std::uint64_t n) {
800,212 ✔
2600
    std::size_t i = 0;
800,212 ✔
2601
    while (i < s.size() && n > 0) {
1,600,500 ✔
2602
        ++i;
800,288 ✔
2603
        while (i < s.size() && utf8_continuation(s[i])) ++i;
1,200,298 ✔
2604
        --n;
800,288 ✔
2605
    }
2606
    return i;
800,212 ✔
2607
}
2608

2609
Series substr_kernel(const Series& sa, std::int64_t start, std::int64_t len) {
22 ✔
2610
    const Series fa = flat_view(sa);
22 !
2611
    const dftu_series* a = fa.handle();
22 ✔
2612
    if (!a || !is_text_type(a->type)) return {};
22 !
2613
    const TextCol ta(a);
22 !
2614
    if (!ta.ok()) return {};
22 ✔
2615
    TextCells c(a->length);
22 !
2616
    for (std::int64_t i = 0; i < a->length; ++i) {
400,082 ✔
2617
        if (start < 0 || !valid_at(a, i)) {
400,060 ✔
2618
            c.end_row(false);
16 !
2619
            continue;
16 ✔
2620
        }
2621
        const std::string_view s = ta.at(i);
400,044 ✔
2622
        const std::string_view rest =
2623
            s.substr(utf8_offset(s, static_cast<std::uint64_t>(start)));
400,044 !
2624
        c.add(len < 0
800,070 !
2625
                  ? rest
9 ✔
2626
                  : rest.substr(
400,026 !
2627
                        0, utf8_offset(rest, static_cast<std::uint64_t>(len))));
200,013 !
2628
    }
200,022 ✔
2629
    return c.finish();
22 !
2630
}
22 ✔
2631

2632
// A time operand as whole units: a Float64 is floored, and a NaN, an infinity
2633
// or a value past int64 is null.
2634
template <class T>
2635
std::optional<std::int64_t> time_units(T x) {
5,816 ✔
2636
    if constexpr (IS_DOUBLE<T>) {
2637
        return trunc_i64(std::floor(x));
2,700 ✔
2638
    } else if constexpr (std::is_same_v<T, std::uint64_t>) {
2639
        if (x > static_cast<std::uint64_t>(
60 ✔
2640
                    std::numeric_limits<std::int64_t>::max()))
40 ✔
2641
            return std::nullopt;
2 ✔
2642
        return static_cast<std::int64_t>(x);
38 ✔
2643
    } else {
2644
        return x;
3,076 ✔
2645
    }
2646
}
20 ✔
2647

2648
Series date_part_kernel(const Series& sa, std::int32_t part,
874 ✔
2649
                        std::int64_t ns_per_unit) {
2650
    const Series fa = flat_view(sa);
874 !
2651
    const dftu_series* a = fa.handle();
874 ✔
2652
    if (!a) return {};
874 ✔
2653
    Cells<std::int64_t> c(a->length);
874 !
2654
    with_num(a->type, [&](auto xa) {
1,748 !
2655
        using A = decltype(xa);
2656
        const A* pa = values_of<A>(a);
874 ✔
2657
        const auto p = static_cast<DatePart>(part);
874 ✔
2658
        for (std::int64_t i = 0; i < a->length; ++i) {
6,636 ✔
2659
            if (!valid_at(a, i)) continue;
5,762 ✔
2660
            if (const auto t = time_units<A>(pa[i]))
5,084 ✔
2661
                c.set(i, date_part(civil_time(*t, ns_per_unit), p));
4,408 ✔
2662
        }
2,542 ✔
2663
    });
874 ✔
2664
    return c.finish(TypeId::Int64);
874 !
2665
}
874 ✔
2666

2667
Series format_time_kernel(const Series& sa, std::string_view fmt,
138 ✔
2668
                          std::int64_t ns_per_unit) {
2669
    const Series fa = flat_view(sa);
138 !
2670
    const dftu_series* a = fa.handle();
138 ✔
2671
    if (!a) return {};
138 ✔
2672
    TextCells c(a->length);
138 !
2673
    with_num(a->type, [&](auto xa) {
276 !
2674
        using A = decltype(xa);
2675
        const A* pa = values_of<A>(a);
138 ✔
2676
        for (std::int64_t i = 0; i < a->length; ++i) {
972 ✔
2677
            const auto t = valid_at(a, i) ? time_units<A>(pa[i]) : std::nullopt;
834 !
2678
            if (t) format_time(c.buf(), civil_time(*t, ns_per_unit), fmt);
834 ✔
2679
            c.end_row(t.has_value());
834 !
2680
        }
417 ✔
2681
    });
138 ✔
2682
    return c.finish();
138 !
2683
}
138 ✔
2684

2685
Series extract_kernel(const Series& sa, const duql::CompiledPattern& p,
24 ✔
2686
                      std::size_t group) {
2687
    const Series fa = flat_view(sa);
24 !
2688
    const dftu_series* a = fa.handle();
24 ✔
2689
    if (!a || !is_text_type(a->type)) return {};
24 !
2690
    const TextCol ta(a);
24 !
2691
    if (!ta.ok()) return {};
24 ✔
2692
    TextCells c(a->length);
24 !
2693
    for (std::int64_t i = 0; i < a->length; ++i) {
124 ✔
2694
        std::string_view m;
100 ✔
2695
        if (valid_at(a, i) &&
178 ✔
2696
            duql::extract(p, ta.at(i), group, m) == duql::MatchResult::YES)
78 !
2697
            c.add(m);
46 !
2698
        else
2699
            c.end_row(false);
54 !
2700
    }
50 ✔
2701
    return c.finish();
24 !
2702
}
24 ✔
2703

2704
// An integer operand column as the scan evaluator reads one: a Float64 cell
2705
// is not an integer and reads as null.
2706
struct IntCol {
2707
    const dftu_series* h;
2708
    const void* p;
2709
    explicit IntCol(const dftu_series* s)
135 ✔
2710
        : h(s), p(s->data ? s->data->data() : nullptr) {}
135 !
2711
    std::optional<Int> at(std::int64_t i) const {
382 ✔
2712
        if (!valid_at(h, i)) return std::nullopt;
382 ✔
2713
        if (h->type == TypeId::Int64)
350 ✔
2714
            return int_of(static_cast<const std::int64_t*>(p)[i]);
328 ✔
2715
        if (h->type == TypeId::Uint64)
22 !
2716
            return int_of(static_cast<const std::uint64_t*>(p)[i]);
×
2717
        return std::nullopt;
22 ✔
2718
    }
191 ✔
2719
};
2720

2721
Series str_pred_col_kernel(const Series& sa, const Series& sb,
84 ✔
2722
                           std::int32_t code) {
2723
    const Series fa = flat_view(sa);
84 !
2724
    const Series fb = flat_view(sb);
84 !
2725
    const dftu_series* a = fa.handle();
84 ✔
2726
    const dftu_series* b = fb.handle();
84 ✔
2727
    if (!same_rows(a, b)) return {};
84 ✔
2728
    const TextCol ta(a);
84 !
2729
    const TextCol tb(b);
84 !
2730
    if (!ta.ok() || !tb.ok()) return {};
84 !
2731
    const auto op = static_cast<StrPredOp>(code);
84 ✔
2732
    BoolCells c(a->length);
84 !
2733
    for (std::int64_t i = 0; i < a->length; ++i) {
624 ✔
2734
        if (!valid_at(a, i) || !valid_at(b, i)) continue;
540 ✔
2735
        const std::string_view s = ta.at(i);
392 ✔
2736
        const std::string_view n = tb.at(i);
392 ✔
2737
        bool hit = false;
392 ✔
2738
        if (op == StrPredOp::StartsWith)
392 ✔
2739
            hit = s.starts_with(n);
180 ✔
2740
        else if (op == StrPredOp::EndsWith)
212 ✔
2741
            hit = s.ends_with(n);
78 ✔
2742
        else
2743
            hit = duql::detail::substr_find(
201 !
2744
                      s.data(), static_cast<std::int64_t>(s.size()), n.data(),
134 ✔
2745
                      static_cast<std::int64_t>(n.size())) >= 0;
134 ✔
2746
        c.set(i, hit);
392 ✔
2747
    }
196 ✔
2748
    return c.finish();
84 !
2749
}
84 ✔
2750

2751
Series str_replace_col_kernel(const Series& sa, const Series& sb,
32 ✔
2752
                              const Series& sc) {
2753
    const Series fa = flat_view(sa);
32 !
2754
    const Series fb = flat_view(sb);
32 !
2755
    const Series fc = flat_view(sc);
32 !
2756
    const dftu_series* a = fa.handle();
32 ✔
2757
    const dftu_series* b = fb.handle();
32 ✔
2758
    const dftu_series* d = fc.handle();
32 ✔
2759
    if (!same_rows(a, b) || !same_rows(a, d)) return {};
32 !
2760
    const TextCol ta(a);
32 !
2761
    const TextCol tb(b);
32 !
2762
    const TextCol td(d);
32 !
2763
    if (!ta.ok() || !tb.ok() || !td.ok()) return {};
32 !
2764
    TextCells c(a->length);
32 !
2765
    for (std::int64_t i = 0; i < a->length; ++i) {
256 ✔
2766
        if (!valid_at(a, i) || !valid_at(b, i) || !valid_at(d, i)) {
224 ✔
2767
            c.end_row(false);
60 !
2768
            continue;
60 ✔
2769
        }
2770
        const std::string_view s = ta.at(i);
164 ✔
2771
        const std::string_view from = tb.at(i);
164 ✔
2772
        const std::string_view to = td.at(i);
164 ✔
2773
        std::string& out = c.buf();
164 !
2774
        std::size_t pos = 0;
164 ✔
2775
        if (!from.empty()) {
164 ✔
2776
            for (std::size_t hit = s.find(from); hit != std::string_view::npos;
248 ✔
2777
                 hit = s.find(from, pos)) {
114 ✔
2778
                out.append(s.substr(pos, hit - pos));
114 !
2779
                out.append(to);
114 !
2780
                pos = hit + from.size();
114 ✔
2781
            }
57 ✔
2782
        }
67 ✔
2783
        out.append(s.substr(pos));
164 !
2784
        c.end_row(true);
164 !
2785
    }
82 ✔
2786
    return c.finish();
32 !
2787
}
32 ✔
2788

2789
Series substr_col_kernel(const Series& sa, const Series& sb, const Series* sc) {
28 ✔
2790
    const Series fa = flat_view(sa);
28 !
2791
    const Series fb = flat_view(sb);
28 !
2792
    const Series fc = sc ? flat_view(*sc) : Series{};
28 !
2793
    const dftu_series* a = fa.handle();
28 ✔
2794
    const dftu_series* b = fb.handle();
28 ✔
2795
    const dftu_series* d = fc.handle();
28 ✔
2796
    if (!same_rows(a, b) || (sc && !same_rows(a, d))) return {};
28 !
2797
    const TextCol ta(a);
28 !
2798
    if (!ta.ok()) return {};
28 ✔
2799
    const IntCol starts(b);
28 !
2800
    const IntCol lens(sc ? d : b);
28 !
2801
    TextCells c(a->length);
28 !
2802
    for (std::int64_t i = 0; i < a->length; ++i) {
182 ✔
2803
        const auto start = valid_at(a, i) ? starts.at(i) : std::nullopt;
154 !
2804
        if (!start || start->neg) {
154 ✔
2805
            c.end_row(false);
62 !
2806
            continue;
79 ✔
2807
        }
2808
        const std::string_view s = ta.at(i);
92 ✔
2809
        const std::string_view rest = s.substr(utf8_offset(s, start->mag));
92 !
2810
        if (!sc) {
92 ✔
2811
            c.add(rest);
34 !
2812
            continue;
34 ✔
2813
        }
2814
        const auto len = lens.at(i);
58 !
2815
        if (!len || len->neg)
58 ✔
2816
            c.end_row(false);
8 !
2817
        else
2818
            c.add(rest.substr(0, utf8_offset(rest, len->mag)));
50 !
2819
    }
29 ✔
2820
    return c.finish();
28 !
2821
}
28 ✔
2822

2823
Series round_col_kernel(const Series& sa, const Series& sb) {
26 ✔
2824
    const Series fa = flat_view(sa);
26 !
2825
    const Series fb = flat_view(sb);
26 !
2826
    const dftu_series* a = fa.handle();
26 ✔
2827
    const dftu_series* b = fb.handle();
26 ✔
2828
    if (!same_rows(a, b)) return {};
26 ✔
2829
    const std::int64_t n = a->length;
26 ✔
2830
    const IntCol digits(b);
26 !
2831
    constexpr double TWO_POW_63 = 9223372036854775808.0;
26 ✔
2832
    auto rounded = [](double x, const Int& d) {
89 ✔
2833
        const double scale = std::pow(10.0, d.neg ? -static_cast<double>(d.mag)
76 ✔
2834
                                                  : static_cast<double>(d.mag));
58 ✔
2835
        return std::round(x * scale) / scale;
76 ✔
2836
    };
2837
    Series out;
26 ✔
2838
    with_num(a->type, [&](auto xa) {
52 !
2839
        using A = decltype(xa);
2840
        const A* pa = values_of<A>(a);
26 ✔
2841
        if constexpr (IS_DOUBLE<A>) {
2842
            Cells<double> c(n);
64 !
2843
            for (std::int64_t i = 0; i < n; ++i) {
90 ✔
2844
                const auto d = valid_at(a, i) ? digits.at(i) : std::nullopt;
109 !
2845
                if (d && d->mag <= 308) c.set(i, of_double(rounded(pa[i], *d)));
82 !
2846
            }
38 ✔
2847
            out = c.finish(TypeId::Float64);
20 !
2848
        } else if constexpr (std::is_same_v<A, std::uint64_t>) {
14 ✔
2849
            Cells<std::uint64_t> c(n);
4 !
2850
            for (std::int64_t i = 0; i < n; ++i) {
30 ✔
2851
                const auto d = valid_at(a, i) ? digits.at(i) : std::nullopt;
26 !
2852
                if (!d) continue;
26 ✔
2853
                if (!d->neg) {
20 ✔
2854
                    c.set(i, pa[i]);
14 ✔
2855
                } else if (d->mag <= 308) {
13 ✔
2856
                    const double r = rounded(static_cast<double>(pa[i]), *d);
6 ✔
2857
                    if (r >= 0 && r < TWO_POW_63)
6 !
2858
                        c.set(i, static_cast<std::uint64_t>(r));
2 ✔
2859
                }
3 ✔
2860
            }
10 ✔
2861
            out = c.finish(TypeId::Uint64);
4 !
2862
        } else {
4 ✔
2863
            Cells<std::int64_t> c(n);
8 !
2864
            for (std::int64_t i = 0; i < n; ++i) {
58 ✔
2865
                const auto d = valid_at(a, i) ? digits.at(i) : std::nullopt;
50 !
2866
                if (!d) continue;
50 ✔
2867
                if (!d->neg)
30 ✔
2868
                    c.set(i, pa[i]);
24 !
2869
                else if (d->mag <= 308)
6 !
2870
                    c.set(i,
12 !
2871
                          trunc_i64(rounded(static_cast<double>(pa[i]), *d)));
6 !
2872
            }
15 ✔
2873
            out = c.finish(TypeId::Int64);
8 !
2874
        }
8 ✔
2875
    });
26 ✔
2876
    return out;
26 ✔
2877
}
39 !
2878

2879
Series extract_col_kernel(const Series& sa, const Series& sb,
8 ✔
2880
                          const duql::CompiledPattern& p) {
2881
    const Series fa = flat_view(sa);
8 !
2882
    const Series fb = flat_view(sb);
8 !
2883
    const dftu_series* a = fa.handle();
8 ✔
2884
    const dftu_series* b = fb.handle();
8 ✔
2885
    if (!same_rows(a, b)) return {};
8 ✔
2886
    const TextCol ta(a);
8 !
2887
    if (!ta.ok()) return {};
8 ✔
2888
    const IntCol groups(b);
8 !
2889
    const std::uint64_t max_group = duql::capture_count(p);
8 !
2890
    TextCells c(a->length);
8 !
2891
    for (std::int64_t i = 0; i < a->length; ++i) {
68 ✔
2892
        const auto g = valid_at(a, i) ? groups.at(i) : std::nullopt;
60 !
2893
        std::string_view m;
60 ✔
2894
        if (g && !g->neg && g->mag <= max_group &&
84 ✔
2895
            duql::extract(p, ta.at(i), static_cast<std::size_t>(g->mag), m) ==
24 !
2896
                duql::MatchResult::YES)
2897
            c.add(m);
16 !
2898
        else
2899
            c.end_row(false);
44 !
2900
    }
30 ✔
2901
    return c.finish();
8 !
2902
}
8 ✔
2903

2904
template <class T>
2905
void append_number(std::string& out, T v) {
86,488 ✔
2906
    if constexpr (std::is_floating_point_v<T>) {
2907
        char buf[32];
2908
        if (char* end = to_chars_double(buf, buf + sizeof(buf), v))
40 ✔
2909
            out.append(buf, end);
40 !
2910
    } else {
2911
        char buf[24];
2912
        const auto res = std::to_chars(buf, buf + sizeof(buf), v);
86,448 !
2913
        out.append(buf, res.ptr);
86,448 !
2914
    }
2915
}
86,488 ✔
2916

2917
template <class V>
2918
std::optional<V> parse_number(std::string_view s) {
580 ✔
2919
    V out{};
580 ✔
2920
    std::from_chars_result res{};
580 ✔
2921
    if constexpr (std::is_same_v<V, double>)
2922
        res = from_chars_double(s.data(), s.data() + s.size(), out);
18 ✔
2923
    else
2924
        res = std::from_chars(s.data(), s.data() + s.size(), out);
562 !
2925
    if (res.ec != std::errc{} || res.ptr != s.data() + s.size())
580 !
2926
        return std::nullopt;
16 ✔
2927
    return out;
564 ✔
2928
}
290 ✔
2929

2930
std::optional<std::int64_t> text_to_int(std::string_view s) {
562 ✔
2931
    if (auto i = parse_number<std::int64_t>(s)) return i;
562 ✔
2932
    if (auto d = parse_number<double>(s)) return trunc_i64(*d);
10 ✔
2933
    return std::nullopt;
4 ✔
2934
}
281 ✔
2935

2936
// int(x) / float(x): numbers convert (a double truncates toward zero), Bool
2937
// is 0/1, a String parses; anything out of range or unparseable is null.
2938
template <class R>
2939
Series to_number_kernel(const dftu_series* a, TypeId t) {
180 ✔
2940
    const std::int64_t n = a->length;
180 ✔
2941
    Cells<R> c(n);
180 !
2942
    auto convert = [](auto v) -> std::optional<R> {
47,092 ✔
2943
        if constexpr (IS_DOUBLE<R>) {
2944
            return of_double(static_cast<double>(v));
16 ✔
2945
        } else if constexpr (IS_DOUBLE<decltype(v)>) {
2946
            return trunc_i64(v);
22 ✔
2947
        } else {
2948
            return num_as<R>(v);
46,964 ✔
2949
        }
2950
    };
2951
    if (a->type == TypeId::Bool) {
180 ✔
2952
        for (std::int64_t i = 0; i < n; ++i)
12 ✔
2953
            if (valid_at(a, i)) c.set(i, static_cast<R>(bit_at(a, i)));
8 !
2954
    } else if (is_text_type(a->type)) {
178 ✔
2955
        const TextCol ta(a);
94 !
2956
        for (std::int64_t i = 0; i < n; ++i) {
666 ✔
2957
            if (!valid_at(a, i)) continue;
572 !
2958
            if constexpr (IS_DOUBLE<R>) {
2959
                const auto d = parse_number<double>(ta.at(i));
8 !
2960
                if (d) c.set(i, of_double(*d));
8 !
2961
            } else {
2962
                c.set(i, text_to_int(ta.at(i)));
562 !
2963
            }
2964
        }
285 ✔
2965
    } else {
47 ✔
2966
        with_num(a->type, [&](auto xa) {
70,755 !
2967
            using A = decltype(xa);
2968
            const A* pa = values_of<A>(a);
82 ✔
2969
            for (std::int64_t i = 0; i < n; ++i)
47,090 !
2970
                if (valid_at(a, i)) c.set(i, convert(pa[i]));
47,008 !
2971
        });
41 ✔
2972
    }
2973
    return c.finish(t);
270 !
2974
}
180 ✔
2975

2976
// string(x) and json(x): numbers in decimal or shortest round-trip form,
2977
// Bool as true/false; json quotes a string and writes a null (or NaN) as
2978
// null, string leaves them null.
2979
Series to_text_kernel(const dftu_series* a, bool json) {
1,456 ✔
2980
    const std::int64_t n = a->length;
1,456 ✔
2981
    TextCells c(n);
1,456 !
2982
    auto missing = [&]() {
754 ✔
2983
        if (json)
26 ✔
2984
            c.add("null");
12 !
2985
        else
2986
            c.end_row(false);
14 ✔
2987
    };
26 ✔
2988
    if (a->type == TypeId::Bool) {
1,456 ✔
2989
        for (std::int64_t i = 0; i < n; ++i) {
42 ✔
2990
            if (!valid_at(a, i))
36 ✔
2991
                missing();
4 !
2992
            else
2993
                c.add(bit_at(a, i) ? "true" : "false");
32 !
2994
        }
18 ✔
2995
    } else if (is_text_type(a->type)) {
1,453 ✔
2996
        const TextCol ta(a);
6 !
2997
        for (std::int64_t i = 0; i < n; ++i) {
30 ✔
2998
            if (!valid_at(a, i)) {
24 ✔
2999
                missing();
4 !
3000
            } else if (json) {
22 !
3001
                c.buf() += '"';
20 !
3002
                json::append_json_escaped(c.buf(), ta.at(i));
20 !
3003
                c.buf() += '"';
20 !
3004
                c.end_row(true);
20 !
3005
            } else {
10 ✔
3006
                c.add(ta.at(i));
×
3007
            }
3008
        }
12 ✔
3009
    } else {
3 ✔
3010
        with_num(a->type, [&](auto xa) {
2,888 !
3011
            using A = decltype(xa);
3012
            const A* pa = values_of<A>(a);
1,444 ✔
3013
            for (std::int64_t i = 0; i < n; ++i) {
87,950 ✔
3014
                bool nan = false;
86,506 ✔
3015
                if constexpr (IS_DOUBLE<A>) nan = std::isnan(pa[i]);
48 ✔
3016
                if (!valid_at(a, i) || nan) {
86,506 !
3017
                    missing();
18 ✔
3018
                } else {
9 ✔
3019
                    append_number(c.buf(), pa[i]);
86,488 ✔
3020
                    c.end_row(true);
86,488 ✔
3021
                }
3022
            }
43,253 ✔
3023
        });
1,444 ✔
3024
    }
3025
    return c.finish();
2,184 !
3026
}
1,456 ✔
3027

3028
Series convert_kernel(const Series& sa, std::int32_t code) {
1,636 ✔
3029
    const Series fa = flat_view(sa);
1,636 !
3030
    const dftu_series* a = fa.handle();
1,636 ✔
3031
    if (!a) return {};
1,636 ✔
3032
    switch (static_cast<ConvertOp>(code)) {
1,636 ✔
3033
        case ConvertOp::Int:
86 ✔
3034
            return to_number_kernel<std::int64_t>(a, TypeId::Int64);
172 !
3035
        case ConvertOp::Float:
4 ✔
3036
            return to_number_kernel<double>(a, TypeId::Float64);
8 !
3037
        case ConvertOp::String:
721 ✔
3038
            return to_text_kernel(a, false);
1,442 !
3039
        case ConvertOp::Json:
7 ✔
3040
            return to_text_kernel(a, true);
14 !
3041
    }
3042
    return {};
×
3043
}
1,636 ✔
3044

3045
// A List column's flat parts: its int32 offsets and its element column as
3046
// Int64 / Uint64 / Float64 when the elements are numeric.
3047
struct ListParts {
9 ✔
3048
    Series list;
3049
    Series elems;
3050
    const std::int32_t* off = nullptr;
9 ✔
3051
};
3052

3053
std::optional<ListParts> list_parts(const Series& s) {
18 ✔
3054
    ListParts p;
18 ✔
3055
    p.list = flat_view(s);
18 !
3056
    const dftu_series* h = p.list.handle();
18 ✔
3057
    if (!h || h->type != TypeId::List || !h->offsets || !h->child())
18 !
3058
        return std::nullopt;
×
3059
    p.off = reinterpret_cast<const std::int32_t*>(h->offsets->data());
18 ✔
3060
    Series child = flat_view(Series{dftu_series_share(h->child().get())});
18 !
3061
    const TypeId t = child.type();
18 ✔
3062
    if (is_num_type(t) && t != TypeId::Int64 && t != TypeId::Uint64 &&
18 !
3063
        t != TypeId::Float64)
1 ✔
3064
        child = Series{dftu_series_cast(
×
3065
            child.handle(),
×
3066
            static_cast<dftu_dtype>(is_int_type(t) ? TypeId::Int64
×
3067
                                                   : TypeId::Float64))};
3068
    if (!child.valid()) return std::nullopt;
18 ✔
3069
    p.elems = std::move(child);
18 ✔
3070
    return p;
18 !
3071
}
18 ✔
3072

3073
// Sum of each list's elements: integers exactly (past int64 is null),
3074
// doubles in order; a null or non-numeric element makes the row null.
3075
Series list_sum_kernel(const Series& s) {
10 ✔
3076
    auto parts = list_parts(s);
10 !
3077
    if (!parts) return {};
10 !
3078
    const dftu_series* h = parts->list.handle();
10 ✔
3079
    const dftu_series* e = parts->elems.handle();
10 ✔
3080
    const std::int32_t* off = parts->off;
10 ✔
3081
    const std::int64_t n = h->length;
10 ✔
3082
    if (!is_num_col(e)) {
10 ✔
3083
        Cells<std::int64_t> c(n);
2 !
3084
        for (std::int64_t i = 0; i < n; ++i)
6 ✔
3085
            if (valid_at(h, i) && off[i] == off[i + 1]) c.set(i, 0);
4 !
3086
        return c.finish(TypeId::Int64);
2 !
3087
    }
2 ✔
3088
    Series out;
8 ✔
3089
    with_num(e->type, [&](auto xe) {
16 !
3090
        using E = decltype(xe);
3091
        const E* pe = values_of<E>(e);
8 ✔
3092
        if constexpr (IS_DOUBLE<E>) {
3093
            Cells<double> c(n);
15 !
3094
            for (std::int64_t i = 0; i < n; ++i) {
6 ✔
3095
                if (!valid_at(h, i)) continue;
11 !
3096
                double total = 0;
4 ✔
3097
                bool ok = true;
4 ✔
3098
                for (std::int32_t k = off[i]; k < off[i + 1] && ok; ++k) {
32 ✔
3099
                    ok = valid_at(e, k);
6 ✔
3100
                    total += pe[k];
6 ✔
3101
                }
3 ✔
3102
                if (ok) c.set(i, of_double(total));
4 !
3103
            }
2 ✔
3104
            out = c.finish(TypeId::Float64);
5 !
3105
        } else {
2 ✔
3106
            Cells<std::int64_t> c(n);
6 !
3107
            for (std::int64_t i = 0; i < n; ++i) {
20 !
3108
                if (!valid_at(h, i)) continue;
14 !
3109
                std::optional<Int> total = Int{};
12 !
3110
                for (std::int32_t k = off[i]; k < off[i + 1] && total; ++k)
32 !
3111
                    total = valid_at(e, k) ? int_add(*total, int_of(pe[k]))
20 !
3112
                                           : std::nullopt;
1 ✔
3113
                if (total)
12 !
3114
                    c.set(i, total->mag == 0 ? std::optional<std::int64_t>{0}
18 !
3115
                                             : i64_of(*total));
8 !
3116
            }
6 ✔
3117
            out = c.finish(TypeId::Int64);
6 !
3118
        }
6 ✔
3119
    });
8 ✔
3120
    return out;
8 ✔
3121
}
14 !
3122

3123
// Whether an element of each list equals `v`: numbers exactly, strings
3124
// bytewise; an element of another domain never equals it.
3125
Series list_contains_kernel(const Series& s, const dftu_scalar& v) {
8 ✔
3126
    auto parts = list_parts(s);
8 !
3127
    if (!parts) return {};
8 !
3128
    const dftu_series* h = parts->list.handle();
8 ✔
3129
    const dftu_series* e = parts->elems.handle();
8 ✔
3130
    const std::int32_t* off = parts->off;
8 ✔
3131
    const std::int64_t n = h->length;
8 ✔
3132
    BoolCells c(n);
8 !
3133
    auto each_row = [&](auto&& equal) {
12 ✔
3134
        for (std::int64_t i = 0; i < n; ++i) {
36 !
3135
            if (!valid_at(h, i)) continue;
28 !
3136
            bool hit = false;
22 ✔
3137
            for (std::int32_t k = off[i]; k < off[i + 1] && !hit; ++k)
50 !
3138
                hit = valid_at(e, k) && equal(k);
28 !
3139
            c.set(i, hit);
22 ✔
3140
        }
11 ✔
3141
    };
12 ✔
3142
    if (v.kind == DFTU_SCALAR_TAG_STR && is_text_type(e->type)) {
8 ✔
3143
        const TextCol te(e);
2 !
3144
        const std::string_view want(v.value.s ? v.value.s : "", v.len);
2 !
3145
        each_row([&](std::int32_t k) { return te.at(k) == want; });
4 !
3146
    } else if (v.kind != DFTU_SCALAR_TAG_STR && is_num_col(e)) {
7 ✔
3147
        const TypeId vt = v.kind == DFTU_SCALAR_TAG_I64   ? TypeId::Int64
5 ✔
3148
                          : v.kind == DFTU_SCALAR_TAG_U64 ? TypeId::Uint64
2 !
3149
                                                          : TypeId::Float64;
3150
        with_num(e->type, [&](auto xe) {
8 !
3151
            with_num(vt, [&](auto xv) {
16 ✔
3152
                using E = decltype(xe);
3153
                using V = decltype(xv);
3154
                const E* pe = values_of<E>(e);
6 ✔
3155
                const V want = scalar_as<V>(v);
6 ✔
3156
                each_row([&](std::int32_t k) {
20 !
3157
                    const auto o = cmp_numbers(pe[k], want);
14 !
3158
                    return o && *o == 0;
14 !
3159
                });
3160
            });
2 ✔
3161
        });
4 ✔
3162
    } else {
2 ✔
3163
        each_row([](std::int32_t) { return false; });
10 !
3164
    }
3165
    return c.finish();
8 !
3166
}
8 ✔
3167

3168
// A failure a worker raises for the calling thread (index / rindex finding no
3169
// match); require_evaluated throws it, since a parallel worker cannot.
3170
std::mutex g_eval_error_mutex;
3171
std::string g_eval_error;
3172

3173
void set_eval_error(std::string message) {
8 ✔
3174
    std::lock_guard<std::mutex> lock(g_eval_error_mutex);
8 !
3175
    g_eval_error = std::move(message);
8 ✔
3176
}
8 ✔
3177

3178
Series str_const(std::string_view t, std::int64_t len) {
30 ✔
3179
    dftu_scalar sc{};
30 ✔
3180
    sc.kind = DFTU_SCALAR_TAG_STR;
30 ✔
3181
    sc.value.s = t.data();
30 ✔
3182
    sc.len = static_cast<std::uint32_t>(t.size());
30 ✔
3183
    return const_column(TypeId::String, sc, len);
45 !
3184
}
3185

3186
// The OP_STR_FN runtime: the same C ABI kernels the eager Series.str calls, so
3187
// an expression gives the eager result.
3188
Series str_fn_eval(const SlotOp& op, const Series& a, const Series* b,
482 ✔
3189
                   std::int64_t len) {
3190
    const dftu_series* h = a.handle();
482 ✔
3191
    const std::int64_t i0 = op.scalar.value.i;
482 ✔
3192
    const std::int64_t i1 = op.scalar2.value.i;
482 ✔
3193
    const char* t = op.text.data();
482 ✔
3194
    const auto tn = static_cast<std::int32_t>(op.text.size());
482 ✔
3195
    const char fill = op.text.empty() ? ' ' : op.text.front();
482 ✔
3196
    const auto fn = static_cast<StrFn>(op.param);
482 ✔
3197
    switch (fn) {
482 ✔
3198
        case StrFn::IsAlnum:
49 ✔
3199
        case StrFn::IsAlpha:
3200
        case StrFn::IsDigit:
3201
        case StrFn::IsDecimal:
3202
        case StrFn::IsNumeric:
3203
        case StrFn::IsSpace:
3204
        case StrFn::IsLower:
3205
        case StrFn::IsUpper:
3206
        case StrFn::IsTitle:
3207
            return Series{dftu_series_str_is(h, op.param)};
98 ✔
3208
        case StrFn::PadStart:
13 ✔
3209
            return Series{dftu_series_str_pad_start(h, i0, fill)};
26 ✔
3210
        case StrFn::PadEnd:
13 ✔
3211
            return Series{dftu_series_str_pad_end(h, i0, fill)};
26 ✔
3212
        case StrFn::Center:
7 ✔
3213
            return Series{dftu_series_str_center(h, i0, fill)};
14 ✔
3214
        case StrFn::Zfill:
6 ✔
3215
            return Series{dftu_series_str_zfill(h, i0)};
12 ✔
3216
        case StrFn::RemovePrefix:
7 ✔
3217
            return Series{dftu_series_str_remove_prefix(h, t, tn)};
14 ✔
3218
        case StrFn::RemoveSuffix:
5 ✔
3219
            return Series{dftu_series_str_remove_suffix(h, t, tn)};
10 ✔
3220
        case StrFn::Repeat:
5 ✔
3221
            return Series{dftu_series_str_repeat(h, i0)};
10 ✔
3222
        case StrFn::SliceReplace: {
10 ✔
3223
            Series head{dftu_series_str_slice(h, 0, i0)};
20 !
3224
            Series tail{
10 ✔
3225
                i1 == std::numeric_limits<std::int64_t>::min()
30 ✔
3226
                    ? dftu_series_str_slice(h, 0, 0)
10 !
3227
                    : dftu_series_str_slice(h, i1, std::int64_t{1} << 62)};
20 !
3228
            if (!head.handle() || !tail.handle()) return Series{};
20 !
3229
            const Series mid = str_const(op.text, len);
20 !
3230
            Series hm{dftu_series_str_cat(head.handle(), mid.handle())};
20 !
3231
            if (!hm.handle()) return Series{};
20 ✔
3232
            return Series{dftu_series_str_cat(hm.handle(), tail.handle())};
20 !
3233
        }
20 ✔
3234
        case StrFn::Split:
24 ✔
3235
            return Series{dftu_series_str_split(h, t, tn)};
48 ✔
3236
        case StrFn::Partition:
5 ✔
3237
            return Series{dftu_series_str_partition(h, t, tn, 0)};
10 ✔
3238
        case StrFn::RPartition:
5 ✔
3239
            return Series{dftu_series_str_partition(h, t, tn, 1)};
10 ✔
3240
        case StrFn::Findall:
5 ✔
3241
            return Series{dftu_series_str_findall(h, t, tn)};
10 ✔
3242
        case StrFn::Extract:
5 ✔
3243
            return Series{dftu_series_str_extract(h, t, tn, i0)};
10 ✔
3244
        case StrFn::RegexReplace:
25 ✔
3245
            return Series{dftu_series_str_regex_replace(
25 ✔
3246
                h, t, tn, op.text2.data(),
25 ✔
3247
                static_cast<std::int32_t>(op.text2.size()))};
50 ✔
3248
        case StrFn::Normalize:
9 ✔
3249
            return Series{
9 ✔
3250
                dftu_series_str_normalize(h, static_cast<std::int32_t>(i0))};
18 ✔
3251
        case StrFn::Translate: {
14 ✔
3252
            Series from, to;
28 ✔
3253
            if (!decode_translate_table(op.text, op.text2, from, to))
28 !
NEW
3254
                return Series{};
×
3255
            return Series{
14 ✔
3256
                dftu_series_str_translate(h, from.handle(), to.handle())};
28 !
3257
        }
28 ✔
3258
        case StrFn::Wrap:
1 ✔
3259
            return Series{
1 ✔
3260
                dftu_series_str_wrap(h, i0, static_cast<std::int32_t>(i1))};
2 ✔
3261
        case StrFn::Rfind:
7 ✔
3262
            return Series{dftu_series_str_rfind(h, t, tn)};
14 ✔
3263
        case StrFn::Index:
10 ✔
3264
        case StrFn::Rindex: {
3265
            Series r{fn == StrFn::Index ? dftu_series_str_find(h, t, tn)
17 ✔
3266
                                        : dftu_series_str_rfind(h, t, tn)};
20 !
3267
            if (!r.handle()) return Series{};
20 ✔
3268
            dftu_scalar minus_one{};
20 ✔
3269
            minus_one.kind = DFTU_SCALAR_TAG_I64;
20 ✔
3270
            minus_one.value.i = -1;
20 ✔
3271
            Series miss{
10 ✔
3272
                dftu_series_compare(r.handle(), DFTU_CMP_EQ, minus_one)};
20 !
3273
            if (miss.handle() && dftu_series_any(miss.handle()) != 0) {
20 !
3274
                set_eval_error(
8 !
3275
                    std::string(fn == StrFn::Index ? "index" : "rindex") +
12 !
3276
                    ": substring '" + std::string(op.text) +
20 !
3277
                    "' not found in every row");
3278
                return Series{};
8 ✔
3279
            }
3280
            return r;
12 ✔
3281
        }
20 ✔
3282
        case StrFn::Join:
5 ✔
3283
            return Series{dftu_series_list_join(h, t, tn)};
10 ✔
3284
        case StrFn::Get: {
6 ✔
3285
            Series piece{dftu_series_str_slice(h, i0, 1)};
12 !
3286
            Series lens{dftu_series_str_len_bytes(h)};
12 !
3287
            if (!piece.handle() || !lens.handle()) return Series{};
12 !
3288
            dftu_scalar bound{};
12 ✔
3289
            bound.kind = DFTU_SCALAR_TAG_I64;
12 ✔
3290
            bound.value.i = i0;
12 ✔
3291
            Series cond{dftu_series_compare(lens.handle(), DFTU_CMP_GT, bound)};
12 !
3292
            const Series nulls = Series::nulls(TypeId::String, len);
12 !
3293
            if (!cond.handle()) return Series{};
12 ✔
3294
            return Series{dftu_series_where(cond.handle(), piece.handle(),
18 !
3295
                                            nulls.handle())};
18 !
3296
        }
12 ✔
3297
        case StrFn::Cat: {
5 ✔
3298
            if (b == nullptr) return Series{};
10 ✔
3299
            if (op.text.empty())
10 !
3300
                return Series{dftu_series_str_cat(h, b->handle())};
×
3301
            const Series sep = str_const(op.text, len);
10 !
3302
            Series ab{dftu_series_str_cat(h, sep.handle())};
10 !
3303
            if (!ab.handle()) return Series{};
10 ✔
3304
            return Series{dftu_series_str_cat(ab.handle(), b->handle())};
10 !
3305
        }
10 ✔
3306
    }
3307
    return Series{};
×
3308
}
241 ✔
3309

3310
// Evaluate the slot program over rows [offset, offset+len) and extract one
3311
// column per requested final slot (shared, so distinct outputs that resolved to
3312
// the same slot alias the one buffer).
3313
std::vector<Series> eval_chunk(const std::vector<SlotOp>& prog,
63,196 ✔
3314
                               const std::vector<Series>& inputs,
3315
                               const std::vector<int>& finals,
3316
                               std::int64_t offset, std::int64_t len) {
3317
    std::vector<Series> s(prog.size());
63,196 !
3318
    for (std::size_t k = 0; k < prog.size(); ++k) {
293,270 ✔
3319
        const SlotOp& op = prog[k];
230,089 ✔
3320
        auto A = [&]() { return s[static_cast<std::size_t>(op.a)].handle(); };
224,681 ✔
3321
        auto B = [&]() { return s[static_cast<std::size_t>(op.b)].handle(); };
159,992 ✔
3322
        auto SA = [&]() -> const Series& {
131,128 ✔
3323
            return s[static_cast<std::size_t>(op.a)];
16,080 ✔
3324
        };
115,038 ✔
3325
        auto SB = [&]() -> const Series& {
127,808 ✔
3326
            return s[static_cast<std::size_t>(op.b)];
12,760 ✔
3327
        };
115,038 ✔
3328
        switch (op.opcode) {
230,086 !
3329
            case OP_LOAD:
44,728 ✔
3330
                s[k] = load_slice(inputs[static_cast<std::size_t>(op.param)],
178,911 ✔
3331
                                  offset, len);
89,451 ✔
3332
                break;
89,450 ✔
3333
            case OP_ADD:
7,542 ✔
3334
                s[k] = Series{dftu_series_add(A(), B())};
15,084 !
3335
                break;
15,084 ✔
3336
            case OP_SUB:
10,520 ✔
3337
                s[k] = Series{dftu_series_sub(A(), B())};
21,040 !
3338
                break;
21,040 ✔
3339
            case OP_MUL:
63 ✔
3340
                s[k] = Series{dftu_series_mul(A(), B())};
126 !
3341
                break;
126 ✔
3342
            case OP_DIV:
2,014 ✔
3343
                s[k] = Series{dftu_series_div(A(), B())};
4,028 !
3344
                break;
4,028 ✔
3345
            case OP_ADDS:
4,109 ✔
3346
                s[k] = Series{dftu_series_add_scalar(A(), op.scalar)};
8,218 !
3347
                break;
8,218 ✔
3348
            case OP_SUBS:
549 ✔
3349
                s[k] = Series{dftu_series_sub_scalar(A(), op.scalar)};
1,098 !
3350
                break;
1,098 ✔
3351
            case OP_MULS:
4,447 ✔
3352
                s[k] = Series{dftu_series_mul_scalar(A(), op.scalar)};
8,894 !
3353
                break;
8,894 ✔
3354
            case OP_DIVS:
1,146 ✔
3355
                s[k] = Series{dftu_series_div_scalar(A(), op.scalar)};
2,292 !
3356
                break;
2,292 ✔
3357
            case OP_PRIM:
201 ✔
3358
                s[k] = Series{
603 !
3359
                    dftu_series_prim(A(), static_cast<dftu_prim_op>(op.param))};
603 !
3360
                break;
402 ✔
3361
            case OP_UNARY: {
351 ✔
3362
                dftu_series* r = nullptr;
702 ✔
3363
                switch (static_cast<UnaryOp>(op.param)) {
702 !
3364
                    case UnaryOp::Abs:
12 ✔
3365
                        r = dftu_series_abs(A());
24 !
3366
                        break;
24 ✔
3367
                    case UnaryOp::Round:
7 ✔
3368
                        r = dftu_series_round(A());
14 !
3369
                        break;
14 ✔
3370
                    case UnaryOp::Floor:
232 ✔
3371
                        r = dftu_series_floor(A());
464 !
3372
                        break;
464 ✔
3373
                    case UnaryOp::Ceil:
59 ✔
3374
                        r = dftu_series_ceil(A());
118 !
3375
                        break;
118 ✔
3376
                    case UnaryOp::Log:
2 ✔
3377
                        r = dftu_series_log(A());
4 !
3378
                        break;
4 ✔
3379
                    case UnaryOp::Sqrt:
9 ✔
3380
                        r = dftu_series_sqrt(A());
18 !
3381
                        break;
18 ✔
3382
                    case UnaryOp::Exp:
3 ✔
3383
                        r = dftu_series_exp(A());
6 !
3384
                        break;
6 ✔
3385
                    case UnaryOp::Sign:
2 ✔
3386
                        r = dftu_series_sign(A());
4 !
3387
                        break;
4 ✔
3388
                    case UnaryOp::Negate:
2 ✔
3389
                        r = dftu_series_negate(A());
4 !
3390
                        break;
4 ✔
3391
                    case UnaryOp::Trunc:
2 ✔
3392
                        r = dftu_series_trunc(A());
4 !
3393
                        break;
4 ✔
3394
                    case UnaryOp::IsNan:
20 ✔
3395
                        r = dftu_series_is_nan(A());
40 !
3396
                        break;
40 ✔
3397
                    case UnaryOp::IsFinite:
1 ✔
3398
                        r = dftu_series_is_finite(A());
2 !
3399
                        break;
2 ✔
3400
                    case UnaryOp::IsInfinite:
3401
                        r = dftu_series_is_infinite(A());
×
3402
                        break;
×
3403
                }
3404
                s[k] = Series{r};
702 ✔
3405
                break;
702 ✔
3406
            }
3407
            case OP_CLIP:
5 ✔
3408
                s[k] = Series{dftu_series_clip(A(), op.scalar, op.scalar2)};
10 !
3409
                break;
10 ✔
3410
            case OP_FILLNA:
9 ✔
3411
                s[k] = Series{dftu_series_fillna(A(), op.scalar)};
18 !
3412
                break;
18 ✔
3413
            case OP_CMP:
2,736 ✔
3414
                s[k] = Series{dftu_series_compare(
8,208 ✔
3415
                    A(), static_cast<dftu_cmp_op>(op.param), op.scalar)};
8,208 ✔
3416
                break;
5,472 ✔
3417
            case OP_LOGICAL:
979 ✔
3418
                s[k] = Series{dftu_series_logical(
2,937 !
3419
                    A(), B(), static_cast<dftu_logical_op>(op.param))};
2,937 !
3420
                break;
1,958 ✔
3421
            case OP_NOT:
246 ✔
3422
                s[k] = Series{dftu_series_logical_not(A())};
492 !
3423
                break;
492 ✔
3424
            case OP_CAST:
15,138 ✔
3425
                s[k] = Series{
45,413 !
3426
                    dftu_series_cast(A(), static_cast<dftu_dtype>(op.param))};
45,414 !
3427
                break;
30,276 ✔
3428
            case OP_STR_PRED: {
142 ✔
3429
                const char* p = op.text.data();
284 ✔
3430
                const auto n = static_cast<std::int32_t>(op.text.size());
284 ✔
3431
                dftu_series* r = nullptr;
284 ✔
3432
                switch (static_cast<StrPredOp>(op.param)) {
284 !
3433
                    case StrPredOp::Contains:
69 ✔
3434
                        r = dftu_series_str_contains(A(), p, n);
138 !
3435
                        break;
138 ✔
3436
                    case StrPredOp::StartsWith:
17 ✔
3437
                        r = dftu_series_str_starts_with(A(), p, n);
34 !
3438
                        break;
34 ✔
3439
                    case StrPredOp::EndsWith:
8 ✔
3440
                        r = dftu_series_str_ends_with(A(), p, n);
16 !
3441
                        break;
16 ✔
3442
                    case StrPredOp::Like:
5 ✔
3443
                        r = dftu_series_str_like(A(), p, n);
10 !
3444
                        break;
10 ✔
3445
                    case StrPredOp::Matches:
5 ✔
3446
                        r = dftu_series_str_matches(A(), p, n);
10 !
3447
                        break;
10 ✔
3448
                    case StrPredOp::Search:
38 ✔
3449
                        r = dftu_series_str_search(A(), p, n);
76 !
3450
                        break;
76 ✔
3451
                }
3452
                s[k] = Series{r};
284 ✔
3453
                break;
284 ✔
3454
            }
3455
            case OP_STR_MAP: {
496 ✔
3456
                dftu_series* r = nullptr;
992 ✔
3457
                switch (static_cast<StrMapOp>(op.param)) {
992 !
3458
                    case StrMapOp::Lower:
419 ✔
3459
                        r = dftu_series_to_lowercase(A());
838 !
3460
                        break;
838 ✔
3461
                    case StrMapOp::Upper:
39 ✔
3462
                        r = dftu_series_to_uppercase(A());
78 !
3463
                        break;
78 ✔
3464
                    case StrMapOp::Strip:
6 ✔
3465
                        r = dftu_series_str_strip(A());
12 !
3466
                        break;
12 ✔
3467
                    case StrMapOp::Lstrip:
2 ✔
3468
                        r = dftu_series_str_lstrip(A());
4 !
3469
                        break;
4 ✔
3470
                    case StrMapOp::Rstrip:
2 ✔
3471
                        r = dftu_series_str_rstrip(A());
4 !
3472
                        break;
4 ✔
3473
                    case StrMapOp::Capitalize:
9 ✔
3474
                        r = dftu_series_str_case(A(), 0);
18 !
3475
                        break;
18 ✔
3476
                    case StrMapOp::Title:
12 ✔
3477
                        r = dftu_series_str_case(A(), 1);
24 !
3478
                        break;
24 ✔
3479
                    case StrMapOp::Swapcase:
7 ✔
3480
                        r = dftu_series_str_case(A(), 2);
14 !
3481
                        break;
14 ✔
3482
                }
3483
                s[k] = Series{r};
992 ✔
3484
                break;
992 ✔
3485
            }
3486
            case OP_STR_LEN:
89 ✔
3487
                s[k] = Series{op.param ? dftu_series_str_len_chars(A())
277 !
3488
                                       : dftu_series_str_len_bytes(A())};
99 !
3489
                break;
177 ✔
3490
            case OP_STR_FIND:
4 ✔
3491
                s[k] = Series{dftu_series_str_find(
16 !
3492
                    A(), op.text.data(),
8 !
3493
                    static_cast<std::int32_t>(op.text.size()))};
12 ✔
3494
                break;
8 ✔
3495
            case OP_STR_REPLACE: {
14 ✔
3496
                const char* f = op.text.data();
28 ✔
3497
                const auto fn = static_cast<std::int32_t>(op.text.size());
28 ✔
3498
                const char* t = op.text2.data();
28 ✔
3499
                const auto tn = static_cast<std::int32_t>(op.text2.size());
28 ✔
3500
                s[k] = Series{
42 ✔
3501
                    op.param ? dftu_series_str_replace_all(A(), f, fn, t, tn)
31 !
3502
                             : dftu_series_str_replace(A(), f, fn, t, tn)};
20 !
3503
                break;
28 ✔
3504
            }
3505
            case OP_STR_SLICE:
4 ✔
3506
                s[k] = Series{dftu_series_str_slice(A(), op.scalar.value.i,
12 !
3507
                                                    op.scalar2.value.i)};
12 ✔
3508
                break;
8 ✔
3509
            case OP_IS_IN:
21 ✔
3510
                s[k] = Series{dftu_series_is_in(A(), op.values)};
42 !
3511
                break;
42 ✔
3512
            case OP_IS_NULL:
776 ✔
3513
                s[k] = Series{op.param ? dftu_series_null_mask(A())
3,656 !
3514
                                       : dftu_series_valid_mask(A())};
2,104 !
3515
                break;
1,552 ✔
3516
            case OP_CONST:
7,189 ✔
3517
                s[k] =
14,378 ✔
3518
                    const_column(static_cast<TypeId>(op.param), op.scalar, len);
21,567 !
3519
                break;
14,378 ✔
3520
            case OP_SELECT:
500 ✔
3521
                s[k] = Series{dftu_series_where(
1,500 !
3522
                    s[static_cast<std::size_t>(op.c)].handle(), A(), B())};
1,500 !
3523
                break;
1,000 ✔
3524
            case OP_CONST_NULL:
271 ✔
3525
                s[k] = Series::nulls(static_cast<TypeId>(op.param), len);
542 !
3526
                break;
542 ✔
3527
            case OP_TO_I64:
3 ✔
3528
                s[k] = to_i64_kernel(SA());
6 !
3529
                break;
6 ✔
3530
            case OP_ARITH:
4,549 ✔
3531
                s[k] = arith_kernel(SA(), SB(), op.param);
9,098 !
3532
                break;
9,098 ✔
3533
            case OP_NEG:
15 ✔
3534
                s[k] = neg_kernel(SA());
30 !
3535
                break;
30 ✔
3536
            case OP_CMP_EXPR:
1,720 ✔
3537
                s[k] = cmp_expr_kernel(SA(), SB(), op.param);
3,440 !
3538
                break;
3,440 ✔
3539
            case OP_EXTREME:
14 ✔
3540
                s[k] = extreme_kernel(SA(), SB(), op.param != 0);
28 !
3541
                break;
28 ✔
3542
            case OP_CONCAT:
854 ✔
3543
                s[k] = Series{dftu_series_str_cat(A(), B())};
1,708 !
3544
                break;
1,708 ✔
3545
            case OP_ROUND:
25 ✔
3546
                s[k] = round_kernel(SA(), op.scalar.value.i);
50 !
3547
                break;
50 ✔
3548
            case OP_LOG:
2 ✔
3549
                s[k] = log_kernel(SA());
4 !
3550
                break;
4 ✔
3551
            case OP_POW:
3 ✔
3552
                s[k] = pow_kernel(SA(), SB());
6 !
3553
                break;
6 ✔
3554
            case OP_STR_SUBSTR:
11 ✔
3555
                s[k] =
22 ✔
3556
                    substr_kernel(SA(), op.scalar.value.i, op.scalar2.value.i);
33 !
3557
                break;
22 ✔
3558
            case OP_STR_PRED_COL:
42 ✔
3559
                s[k] = str_pred_col_kernel(SA(), SB(), op.param);
84 !
3560
                break;
84 ✔
3561
            case OP_STR_REPLACE_COL:
16 ✔
3562
                s[k] = str_replace_col_kernel(
48 !
3563
                    SA(), SB(), s[static_cast<std::size_t>(op.c)]);
48 !
3564
                break;
32 ✔
3565
            case OP_STR_SUBSTR_COL:
14 ✔
3566
                s[k] = substr_col_kernel(
42 !
3567
                    SA(), SB(),
14 !
3568
                    op.c >= 0 ? &s[static_cast<std::size_t>(op.c)] : nullptr);
42 ✔
3569
                break;
28 ✔
3570
            case OP_ROUND_COL:
13 ✔
3571
                s[k] = round_col_kernel(SA(), SB());
26 !
3572
                break;
26 ✔
3573
            case OP_STR_EXTRACT_COL:
4 ✔
3574
                s[k] = extract_col_kernel(SA(), SB(), *op.pattern);
8 !
3575
                break;
8 ✔
3576
            case OP_DATE_PART:
437 ✔
3577
                s[k] = date_part_kernel(SA(), op.param, op.scalar.value.i);
874 !
3578
                break;
874 ✔
3579
            case OP_FORMAT_TIME:
69 ✔
3580
                s[k] = format_time_kernel(SA(), op.text, op.scalar.value.i);
138 !
3581
                break;
138 ✔
3582
            case OP_STR_PATTERN:
14 ✔
3583
                s[k] = str_pattern(SA(), *op.pattern);
28 !
3584
                break;
28 ✔
3585
            case OP_STR_EXTRACT:
12 ✔
3586
                s[k] =
24 ✔
3587
                    extract_kernel(SA(), *op.pattern,
36 !
3588
                                   static_cast<std::size_t>(op.scalar.value.i));
36 ✔
3589
                break;
24 ✔
3590
            case OP_STR_REGEX_REPLACE:
9 ✔
3591
                s[k] = str_regex_replace(SA(), *op.pattern, *op.subst);
18 !
3592
                break;
18 ✔
3593
            case OP_CONVERT:
818 ✔
3594
                s[k] = convert_kernel(SA(), op.param);
1,636 !
3595
                break;
1,636 ✔
3596
            case OP_LIST_LEN:
1,847 ✔
3597
                s[k] = Series{dftu_series_list_len(A())};
3,694 !
3598
                break;
3,694 ✔
3599
            case OP_LIST_GET:
15 ✔
3600
                s[k] = Series{dftu_series_list_get(A(), op.scalar.value.i)};
30 !
3601
                break;
30 ✔
3602
            case OP_LIST_SUM:
5 ✔
3603
                s[k] = list_sum_kernel(SA());
10 !
3604
                break;
10 ✔
3605
            case OP_LIST_CONTAINS:
4 ✔
3606
                s[k] = list_contains_kernel(SA(), op.scalar);
8 !
3607
                break;
8 ✔
3608
            case OP_STR_FN:
241 ✔
3609
                s[k] = str_fn_eval(op, SA(), op.b >= 0 ? &SB() : nullptr, len);
482 !
3610
                break;
482 ✔
3611
            default:
3612
                return {};
2 ✔
3613
        }
3614
        if (!s[k].handle()) return {};
230,083 ✔
3615
    }
115,040 ✔
3616
    std::vector<Series> outs;
94,772 ✔
3617
    outs.reserve(finals.size());
63,183 !
3618
    for (int f : finals) outs.push_back(s[static_cast<std::size_t>(f)].share());
126,602 ✔
3619
    return outs;
63,184 ✔
3620
}
94,792 !
3621

3622
// eval_chunk returns no columns when a kernel does not take its input type;
3623
// raised here, on the calling thread, since the parallel workers cannot throw.
3624
void require_evaluated(const std::vector<Series>& outs) {
63,198 ✔
3625
    if (outs.empty()) {
63,198 ✔
3626
        std::string message;
12 ✔
3627
        {
3628
            std::lock_guard<std::mutex> lock(g_eval_error_mutex);
12 ✔
3629
            message.swap(g_eval_error);
12 ✔
3630
        }
12 ✔
3631
        if (!message.empty()) throw std::invalid_argument(message);
12 !
3632
        throw std::invalid_argument(
4 !
3633
            "expr: an operation does not take its input column type");
4 ✔
3634
    }
12 ✔
3635
}
63,192 ✔
3636

3637
constexpr std::int64_t GRAIN = 1 << 16;
3638

3639
}  // namespace
3640

3641
std::vector<Series> eval_many(const std::vector<Expr>& roots,
131,448 ✔
3642
                              const std::vector<const Series*>& inputs) {
3643
    if (roots.empty())
131,448 ✔
3644
        throw std::invalid_argument("expr: needs at least one expression");
35 !
3645
    if (inputs.empty())
131,448 ✔
3646
        throw std::invalid_argument("expr: needs at least one input column");
×
3647

3648
    // Bare column references share the input; the evaluator would slice and
3649
    // concat a copy.
3650
    bool all_cols = true;
131,448 ✔
3651
    for (const Expr& root : roots) {
263,044 ✔
3652
        const std::int32_t i = root.valid() ? expr_col_index(root) : -1;
131,596 !
3653
        all_cols &= i >= 0 && static_cast<std::size_t>(i) < inputs.size();
131,596 !
3654
    }
3655
    if (all_cols) {
131,448 ✔
3656
        std::vector<Series> outs;
68,386 ✔
3657
        outs.reserve(roots.size());
68,386 !
3658
        for (const Expr& root : roots) {
136,772 ✔
3659
            const Series& in =
34,193 ✔
3660
                *inputs[static_cast<std::size_t>(expr_col_index(root))];
68,386 !
3661
            outs.push_back(in.encoding() == Encoding::Flat ? in.share()
68,935 !
3662
                                                           : in.materialize());
549 !
3663
        }
3664
        return outs;
68,386 ✔
3665
    }
68,386 !
3666

3667
    // One compiler for all roots: hash-consing (CSE) spans the whole program.
3668
    std::vector<DataType> input_types;
63,062 ✔
3669
    input_types.reserve(inputs.size());
63,062 !
3670
    for (const Series* s : inputs) input_types.push_back(s->data_type());
462,592 !
3671
    Compiler c(input_types);
63,062 !
3672
    std::vector<int> finals;
63,062 ✔
3673
    finals.reserve(roots.size());
63,062 !
3674
    for (const Expr& root : roots) {
126,214 ✔
3675
        if (!root.valid()) throw std::invalid_argument("expr: null expression");
63,210 !
3676
        finals.push_back(c.column(c.compile(root.node().get())).slot);
63,210 ✔
3677
    }
3678

3679
    // Inputs are read in place; each chunk's OP_LOAD slices its rows as a
3680
    // view of the input (a window that spans chunks of a CHUNKED input is
3681
    // joined there, in parallel).
3682
    std::vector<bool> used(inputs.size(), false);
63,004 !
3683
    for (const SlotOp& op : c.program)
292,434 ✔
3684
        if (op.opcode == OP_LOAD)
229,430 ✔
3685
            used[static_cast<std::size_t>(op.param)] = true;
89,158 !
3686
    std::vector<Series> flat(inputs.size());
63,004 !
3687
    for (std::size_t i = 0; i < inputs.size(); ++i)
462,462 ✔
3688
        if (used[i]) flat[i] = inputs[i]->share();
399,458 !
3689

3690
    const std::int64_t n = inputs.front()->length();
63,004 ✔
3691
    // Window starts: a CHUNKED input's own chunks when every chunked input
3692
    // shares them (each window reads its chunk in place and the results stay
3693
    // chunks), otherwise GRAIN-row windows.
3694
    std::vector<std::int64_t> bounds;
63,004 ✔
3695
    for (std::size_t i = 0; i < inputs.size(); ++i) {
462,458 ✔
3696
        if (!used[i] || !inputs[i]->handle()->is_chunked()) continue;
399,456 !
3697
        const dftu_series& h = *inputs[i]->handle();
52 ✔
3698
        const auto* starts =
26 ✔
3699
            reinterpret_cast<const std::int64_t*>(h.data->data());
52 ✔
3700
        std::vector<std::int64_t> own(starts, starts + h.nested.size() + 1);
52 !
3701
        if (bounds.empty()) {
52 ✔
3702
            bounds = std::move(own);
30 ✔
3703
        } else if (bounds != own) {
37 !
3704
            bounds.clear();
2 ✔
3705
            break;
2 ✔
3706
        }
3707
    }
52 ✔
3708
    const bool by_chunk = !bounds.empty();
63,004 ✔
3709
    if (!by_chunk) {
63,004 ✔
3710
        if (n <= GRAIN) {
62,976 ✔
3711
            std::vector<Series> outs =
31,473 ✔
3712
                eval_chunk(c.program, flat, finals, 0, n);
62,946 !
3713
            require_evaluated(outs);
62,946 ✔
3714
            return outs;
62,936 ✔
3715
        }
62,946 !
3716
        for (std::int64_t lo = 0; lo < n; lo += GRAIN) bounds.push_back(lo);
116 ✔
3717
        bounds.push_back(n);
30 !
3718
    }
15 ✔
3719

3720
    const auto windows = static_cast<std::int64_t>(bounds.size() - 1);
58 ✔
3721
    std::vector<std::vector<Series>> parts(static_cast<std::size_t>(windows));
58 !
3722
    // One task per window: without a parallel backend parallel_for runs the
3723
    // whole range as one call, which must still fill every window.
3724
    parallel_for(windows, 1, [&](std::int64_t b, std::int64_t e) {
142 !
3725
        for (std::int64_t k = b; k < e; ++k) {
416 ✔
3726
            const std::int64_t lo = bounds[static_cast<std::size_t>(k)];
250 ✔
3727
            const std::int64_t hi = bounds[static_cast<std::size_t>(k) + 1];
249 ✔
3728
            parts[static_cast<std::size_t>(k)] =
248 ✔
3729
                eval_chunk(c.program, flat, finals, lo, hi - lo);
374 ✔
3730
        }
126 ✔
3731
    });
166 ✔
3732
    for (const std::vector<Series>& part : parts) require_evaluated(part);
308 ✔
3733
    std::vector<Series> outs;
56 ✔
3734
    outs.reserve(finals.size());
56 !
3735
    for (std::size_t j = 0; j < finals.size(); ++j) {
160 ✔
3736
        if (by_chunk) {
104 ✔
3737
            std::vector<Series> pieces;
58 ✔
3738
            pieces.reserve(parts.size());
58 ✔
3739
            for (const std::vector<Series>& part : parts)
308 ✔
3740
                pieces.push_back(part[j].share());
250 !
3741
            outs.push_back(chunked_column(std::move(pieces)));
58 !
3742
            continue;
29 ✔
3743
        }
58 ✔
3744
        std::vector<const Series*> ptrs;
46 ✔
3745
        ptrs.reserve(parts.size());
46 !
3746
        for (const std::vector<Series>& part : parts) ptrs.push_back(&part[j]);
182 ✔
3747
        outs.push_back(concat_columns(ptrs));
46 !
3748
    }
46 ✔
3749
    return outs;
56 ✔
3750
}
97,344 !
3751

3752
Series eval(const Expr& root, const std::vector<const Series*>& inputs) {
131,378 ✔
3753
    if (!root.valid()) throw std::invalid_argument("expr: null expression");
131,413 !
3754
    std::vector<Series> outs = eval_many({root}, inputs);
262,861 !
3755
    return std::move(outs.front());
196,962 ✔
3756
}
131,343 ✔
3757

3758
DataType infer_type(const Expr& root,
26,402 ✔
3759
                    const std::vector<DataType>& input_types) {
3760
    if (!root.valid()) throw std::invalid_argument("expr: null expression");
26,404 !
3761
    Compiler c(input_types);
26,402 ✔
3762
    return c.column(c.compile(root.node().get())).full;
39,601 !
3763
}
26,402 ✔
3764

3765
}  // namespace dftracer::utils::dataframe
3766

3767
// ---- C ABI ----------------------------------------------------------------
3768

3769
struct dftu_expr {
3770
    dftracer::utils::dataframe::Expr e;
3771
};
3772

3773
namespace dftracer::utils::dataframe {
3774
const Expr& expr_handle_unwrap(const dftu_expr* h) { return h->e; }
26 ✔
3775
dftu_expr* expr_handle_wrap(Expr e) { return new dftu_expr{std::move(e)}; }
64 ✔
3776
}  // namespace dftracer::utils::dataframe
3777

3778
namespace {
3779
dftu_expr* wrap(dataframe::Expr e) { return new dftu_expr{std::move(e)}; }
100 ✔
3780
const dataframe::Expr& unwrap(const dftu_expr* e) { return e->e; }
136 ✔
3781
}  // namespace
3782

3783
extern "C" {
3784

3785
dftu_expr* dftu_expr_col(int32_t index) {
36 ✔
3786
    return wrap(dataframe::expr_col(index));
36 !
3787
}
3788
dftu_expr* dftu_expr_lit_i64(int64_t value) {
4 ✔
3789
    return wrap(dataframe::expr_lit(static_cast<std::int64_t>(value)));
4 !
3790
}
3791
dftu_expr* dftu_expr_lit_f64(double value) {
×
3792
    return wrap(dataframe::expr_lit(value));
×
3793
}
3794
dftu_expr* dftu_expr_binary(int32_t op, const dftu_expr* a,
4 ✔
3795
                            const dftu_expr* b) {
3796
    return wrap(dataframe::expr_binary(static_cast<dataframe::BinaryOp>(op),
8 !
3797
                                       unwrap(a), unwrap(b)));
6 ✔
3798
}
3799
dftu_expr* dftu_expr_prim(int32_t prim, const dftu_expr* a) {
×
3800
    return wrap(
×
3801
        dataframe::expr_prim(static_cast<dataframe::PrimOp>(prim), unwrap(a)));
×
3802
}
3803
dftu_expr* dftu_expr_unary(int32_t op, const dftu_expr* a) {
×
3804
    return wrap(
×
3805
        dataframe::expr_unary(static_cast<dataframe::UnaryOp>(op), unwrap(a)));
×
3806
}
3807
dftu_expr* dftu_expr_clip(const dftu_expr* a, dftu_scalar lo, dftu_scalar hi) {
×
3808
    return wrap(dataframe::expr_clip(unwrap(a), lo, hi));
×
3809
}
3810
int32_t dftu_expr_col_index(const dftu_expr* e) {
×
3811
    return e ? dataframe::expr_col_index(unwrap(e)) : -1;
×
3812
}
3813
int32_t dftu_expr_as_col_cmp(const dftu_expr* e, int32_t* col, int32_t* cmp,
10 ✔
3814
                             dftu_scalar* rhs) {
3815
    if (!e || !col || !cmp || !rhs) return 0;
10 !
3816
    std::int32_t c = -1;
10 ✔
3817
    dataframe::CmpOp op{};
10 ✔
3818
    dataframe::Scalar r;
10 ✔
3819
    if (!dataframe::expr_as_col_cmp(unwrap(e), &c, &op, &r)) return 0;
10 !
3820
    *col = c;
10 ✔
3821
    *cmp = static_cast<int32_t>(op);
10 ✔
3822
    *rhs = r;
10 ✔
3823
    return 1;
10 ✔
3824
}
5 ✔
3825
int32_t dftu_expr_as_logical(const dftu_expr* e, int32_t* op, dftu_expr** a,
×
3826
                             dftu_expr** b) {
3827
    if (!e || !op || !a || !b) return 0;
×
3828
    dataframe::LogicalOp lop{};
×
3829
    dataframe::Expr lhs, rhs;
×
3830
    if (!dataframe::expr_as_logical(unwrap(e), &lop, &lhs, &rhs)) return 0;
×
3831
    *op = static_cast<int32_t>(lop);
×
3832
    *a = wrap(std::move(lhs));
×
3833
    *b = wrap(std::move(rhs));
×
3834
    return 1;
×
3835
}
×
3836
int32_t dftu_expr_as_not(const dftu_expr* e, dftu_expr** a) {
×
3837
    if (!e || !a) return 0;
×
3838
    dataframe::Expr inner;
×
3839
    if (!dataframe::expr_as_not(unwrap(e), &inner)) return 0;
×
3840
    *a = wrap(std::move(inner));
×
3841
    return 1;
×
3842
}
×
3843
int32_t dftu_expr_as_col_str_pred(const dftu_expr* e, int32_t* col, int32_t* op,
×
3844
                                  const char** pattern, int32_t* pattern_len) {
3845
    if (!e || !col || !op || !pattern || !pattern_len) return 0;
×
3846
    std::int32_t c = -1;
×
3847
    dataframe::StrPredOp sop{};
×
3848
    std::string_view pat;
×
3849
    if (!dataframe::expr_as_col_str_pred(unwrap(e), &c, &sop, &pat)) return 0;
×
3850
    *col = c;
×
3851
    *op = static_cast<int32_t>(sop);
×
3852
    *pattern = pat.data();
×
3853
    *pattern_len = static_cast<int32_t>(pat.size());
×
3854
    return 1;
×
3855
}
3856
int32_t dftu_expr_as_col_is_in(const dftu_expr* e, int32_t* col,
×
3857
                               dftu_series** values) {
3858
    if (!e || !col || !values) return 0;
×
3859
    std::int32_t c = -1;
×
3860
    dataframe::Series v;
×
3861
    if (!dataframe::expr_as_col_is_in(unwrap(e), &c, &v)) return 0;
×
3862
    *col = c;
×
3863
    *values = v.release();
×
3864
    return 1;
×
3865
}
×
3866
dftu_expr* dftu_expr_cmp(int32_t cmp, const dftu_expr* a, dftu_scalar rhs) {
12 ✔
3867
    return wrap(dataframe::expr_cmp(static_cast<dataframe::CmpOp>(cmp),
24 !
3868
                                    unwrap(a), rhs));
18 ✔
3869
}
3870
dftu_expr* dftu_expr_logical(int32_t op, const dftu_expr* a,
×
3871
                             const dftu_expr* b) {
3872
    return wrap(dataframe::expr_logical(static_cast<dataframe::LogicalOp>(op),
×
3873
                                        unwrap(a), unwrap(b)));
×
3874
}
3875
dftu_expr* dftu_expr_not(const dftu_expr* a) {
×
3876
    return wrap(dataframe::expr_not(unwrap(a)));
×
3877
}
3878
dftu_expr* dftu_expr_cast(int32_t type, const dftu_expr* a) {
×
3879
    return wrap(
×
3880
        dataframe::expr_cast(static_cast<dataframe::TypeId>(type), unwrap(a)));
×
3881
}
3882
dftu_expr* dftu_expr_lower(const dftu_expr* a) {
×
3883
    return wrap(dataframe::expr_lower(unwrap(a)));
×
3884
}
3885
dftu_expr* dftu_expr_str_pred(int32_t op, const dftu_expr* a,
4 ✔
3886
                              const char* pattern, int32_t pattern_len) {
3887
    if (!a || (pattern_len > 0 && !pattern)) return nullptr;
4 !
3888
    return wrap(dataframe::expr_str_pred(
3 !
3889
        static_cast<dataframe::StrPredOp>(op), unwrap(a),
1 ✔
3890
        std::string_view(pattern ? pattern : "",
1 !
3891
                         static_cast<std::size_t>(pattern_len))));
2 ✔
3892
}
2 ✔
3893
dftu_expr* dftu_expr_str_pred_col(int32_t op, const dftu_expr* a,
6 ✔
3894
                                  const dftu_expr* needle) {
3895
    if (!a || !needle) return nullptr;
6 !
3896
    if (op != static_cast<int32_t>(dataframe::StrPredOp::Contains) &&
4 !
3897
        op != static_cast<int32_t>(dataframe::StrPredOp::StartsWith) &&
2 !
3898
        op != static_cast<int32_t>(dataframe::StrPredOp::EndsWith))
1 ✔
3899
        return nullptr;
2 ✔
3900
    return wrap(dataframe::expr_str_pred_col(
3 !
3901
        static_cast<dataframe::StrPredOp>(op), unwrap(a), unwrap(needle)));
2 ✔
3902
}
3 ✔
3903
dftu_expr* dftu_expr_str_replace_col(const dftu_expr* a, const dftu_expr* from,
4 ✔
3904
                                     const dftu_expr* to) {
3905
    if (!a || !from || !to) return nullptr;
4 !
3906
    return wrap(
2 !
3907
        dataframe::expr_str_replace_col(unwrap(a), unwrap(from), unwrap(to)));
3 ✔
3908
}
2 ✔
3909
dftu_expr* dftu_expr_str_substr_col(const dftu_expr* a, const dftu_expr* start,
8 ✔
3910
                                    const dftu_expr* len) {
3911
    if (!a || !start) return nullptr;
8 ✔
3912
    const dataframe::Expr l = len ? unwrap(len) : dataframe::Expr{};
4 ✔
3913
    return wrap(dataframe::expr_str_substr_col(unwrap(a), unwrap(start),
8 !
3914
                                               len ? &l : nullptr));
4 ✔
3915
}
6 ✔
3916
dftu_expr* dftu_expr_round_col(const dftu_expr* a, const dftu_expr* digits) {
4 ✔
3917
    if (!a || !digits) return nullptr;
4 !
3918
    return wrap(dataframe::expr_round_col(unwrap(a), unwrap(digits)));
2 !
3919
}
2 ✔
3920
dftu_expr* dftu_expr_str_map(int32_t op, const dftu_expr* a) {
2 ✔
3921
    if (!a) return nullptr;
2 ✔
3922
    return wrap(dataframe::expr_str_map(static_cast<dataframe::StrMapOp>(op),
4 !
3923
                                        unwrap(a)));
2 ✔
3924
}
1 ✔
3925
dftu_expr* dftu_expr_str_fn(int32_t fn, const dftu_expr* a, const dftu_expr* b,
4 ✔
3926
                            const char* text, int32_t text_len,
3927
                            const char* text2, int32_t text2_len, int64_t i0,
3928
                            int64_t i1) {
3929
    if (!a || fn < 0 || fn > DFTU_STR_FN_WRAP || (text_len > 0 && !text) ||
5 !
3930
        (text2_len > 0 && !text2))
2 ✔
3931
        return nullptr;
2 ✔
3932
    const dataframe::Expr other = b ? unwrap(b) : dataframe::Expr{};
2 !
3933
    return wrap(dataframe::expr_str_fn(
3 !
3934
        static_cast<dataframe::StrFn>(fn), unwrap(a), b ? &other : nullptr,
1 !
3935
        std::string_view(text ? text : "", static_cast<std::size_t>(text_len)),
1 !
3936
        std::string_view(text2 ? text2 : "",
1 !
3937
                         static_cast<std::size_t>(text2_len)),
1 ✔
3938
        i0, i1));
2 ✔
3939
}
3 ✔
3940
dftu_expr* dftu_expr_str_len(const dftu_expr* a, int32_t chars) {
2 ✔
3941
    if (!a) return nullptr;
2 ✔
3942
    return wrap(dataframe::expr_str_len(unwrap(a), chars != 0));
2 !
3943
}
1 ✔
3944
dftu_expr* dftu_expr_str_find(const dftu_expr* a, const char* needle,
2 ✔
3945
                              int32_t needle_len) {
3946
    if (!a || (needle_len > 0 && !needle)) return nullptr;
2 !
3947
    return wrap(dataframe::expr_str_find(
3 !
3948
        unwrap(a), std::string_view(needle ? needle : "",
1 !
3949
                                    static_cast<std::size_t>(needle_len))));
2 ✔
3950
}
1 ✔
3951
dftu_expr* dftu_expr_str_replace(const dftu_expr* a, const char* from,
2 ✔
3952
                                 int32_t from_len, const char* to,
3953
                                 int32_t to_len, int32_t all) {
3954
    if (!a || (from_len > 0 && !from) || (to_len > 0 && !to)) return nullptr;
2 !
3955
    return wrap(dataframe::expr_str_replace(
3 !
3956
        unwrap(a),
1 ✔
3957
        std::string_view(from ? from : "", static_cast<std::size_t>(from_len)),
1 !
3958
        std::string_view(to ? to : "", static_cast<std::size_t>(to_len)),
1 !
3959
        all != 0));
2 ✔
3960
}
1 ✔
3961
dftu_expr* dftu_expr_date_part(const dftu_expr* a, int32_t part,
8 ✔
3962
                               int64_t ns_per_unit) {
3963
    if (!a || !dftracer::utils::is_date_part_code(part) || ns_per_unit <= 0)
8 ✔
3964
        return nullptr;
6 ✔
3965
    return wrap(dataframe::expr_date_part(unwrap(a), part, ns_per_unit));
2 !
3966
}
4 ✔
3967
dftu_expr* dftu_expr_format_time(const dftu_expr* a, const char* fmt,
12 ✔
3968
                                 int32_t fmt_len, int64_t ns_per_unit) {
3969
    if (!a || fmt_len < 0 || (fmt_len > 0 && !fmt) || ns_per_unit <= 0)
12 !
3970
        return nullptr;
6 ✔
3971
    const std::string_view f(fmt ? fmt : "", static_cast<std::size_t>(fmt_len));
6 !
3972
    if (!dftracer::utils::invalid_time_format(f).empty()) return nullptr;
6 ✔
3973
    return wrap(dataframe::expr_format_time(unwrap(a), f, ns_per_unit));
2 !
3974
}
6 ✔
3975
dftu_expr* dftu_expr_str_slice(const dftu_expr* a, int64_t start, int64_t len) {
2 ✔
3976
    if (!a) return nullptr;
2 ✔
3977
    return wrap(dataframe::expr_str_slice(unwrap(a), start, len));
2 !
3978
}
1 ✔
3979
dftu_expr* dftu_expr_is_in(const dftu_expr* a, const dftu_series* values) {
4 ✔
3980
    if (!a || !values) return nullptr;
4 !
3981
    return wrap(dataframe::expr_is_in(
3 !
3982
        unwrap(a), dataframe::Series{dftu_series_share(values)}));
4 ✔
3983
}
2 ✔
3984
dftu_expr* dftu_expr_select(const dftu_expr* cond, const dftu_expr* a,
4 ✔
3985
                            const dftu_expr* b) {
3986
    if (!cond || !a || !b) return nullptr;
4 !
3987
    return wrap(dataframe::expr_select(unwrap(cond), unwrap(a), unwrap(b)));
2 !
3988
}
2 ✔
3989
dftu_expr* dftu_expr_is_null(const dftu_expr* a, int32_t null) {
6 ✔
3990
    if (!a) return nullptr;
6 ✔
3991
    return wrap(dataframe::expr_is_null(unwrap(a), null != 0));
4 !
3992
}
3 ✔
3993
dftu_expr* dftu_expr_lit_str(const char* value, int32_t len) {
4 ✔
3994
    if (len < 0 || (len > 0 && !value)) return nullptr;
4 !
3995
    return wrap(dataframe::expr_lit_str(
3 !
3996
        std::string_view(value ? value : "", static_cast<std::size_t>(len))));
2 !
3997
}
2 ✔
3998
dftu_expr* dftu_expr_lit_bool(int32_t value) {
×
3999
    return wrap(dataframe::expr_lit_bool(value != 0));
×
4000
}
4001
dftu_expr* dftu_expr_lit_null(int32_t type) {
×
4002
    return wrap(dataframe::expr_lit_null(static_cast<dataframe::TypeId>(type)));
×
4003
}
4004
dftu_expr* dftu_expr_arith(int32_t op, const dftu_expr* a, const dftu_expr* b) {
4 ✔
4005
    if (!a || !b) return nullptr;
4 !
4006
    return wrap(dataframe::expr_arith(static_cast<dataframe::ArithOp>(op),
4 !
4007
                                      unwrap(a), unwrap(b)));
2 ✔
4008
}
2 ✔
4009
dftu_expr* dftu_expr_neg(const dftu_expr* a) {
×
4010
    if (!a) return nullptr;
×
4011
    return wrap(dataframe::expr_neg(unwrap(a)));
×
4012
}
4013
dftu_expr* dftu_expr_cmp_expr(int32_t cmp, const dftu_expr* a,
×
4014
                              const dftu_expr* b) {
4015
    if (!a || !b) return nullptr;
×
4016
    return wrap(dataframe::expr_cmp_expr(static_cast<dataframe::CmpOp>(cmp),
×
4017
                                         unwrap(a), unwrap(b)));
×
4018
}
4019
namespace {
4020
bool expr_args(const dftu_expr* const* args, int32_t n,
4 ✔
4021
               std::vector<dataframe::Expr>& out) {
4022
    if (!args || n <= 0) return false;
4 !
4023
    out.reserve(static_cast<std::size_t>(n));
2 ✔
4024
    for (int32_t i = 0; i < n; ++i) {
6 ✔
4025
        if (!args[i]) return false;
4 !
4026
        out.push_back(unwrap(args[i]));
4 ✔
4027
    }
2 ✔
4028
    return true;
2 ✔
4029
}
2 ✔
4030
}  // namespace
4031
dftu_expr* dftu_expr_coalesce(const dftu_expr* const* args, int32_t n) {
4 ✔
4032
    std::vector<dataframe::Expr> v;
4 ✔
4033
    if (!expr_args(args, n, v)) return nullptr;
4 !
4034
    return wrap(dataframe::expr_coalesce(v));
2 !
4035
}
4 ✔
4036
dftu_expr* dftu_expr_extreme(const dftu_expr* const* args, int32_t n,
×
4037
                             int32_t least) {
4038
    std::vector<dataframe::Expr> v;
×
4039
    if (!expr_args(args, n, v)) return nullptr;
×
4040
    return wrap(dataframe::expr_extreme(v, least != 0));
×
4041
}
×
4042
dftu_expr* dftu_expr_concat(const dftu_expr* const* args, int32_t n) {
×
4043
    std::vector<dataframe::Expr> v;
×
4044
    if (!expr_args(args, n, v)) return nullptr;
×
4045
    return wrap(dataframe::expr_concat(v));
×
4046
}
×
4047
dftu_expr* dftu_expr_round(const dftu_expr* a, int64_t digits) {
×
4048
    if (!a) return nullptr;
×
4049
    return wrap(dataframe::expr_round(unwrap(a), digits));
×
4050
}
4051
dftu_expr* dftu_expr_log(const dftu_expr* a) {
×
4052
    if (!a) return nullptr;
×
4053
    return wrap(dataframe::expr_log(unwrap(a)));
×
4054
}
4055
dftu_expr* dftu_expr_pow(const dftu_expr* a, const dftu_expr* b) {
×
4056
    if (!a || !b) return nullptr;
×
4057
    return wrap(dataframe::expr_pow(unwrap(a), unwrap(b)));
×
4058
}
4059
dftu_expr* dftu_expr_str_substr(const dftu_expr* a, int64_t start,
×
4060
                                int64_t len) {
4061
    if (!a) return nullptr;
×
4062
    return wrap(dataframe::expr_str_substr(unwrap(a), start, len));
×
4063
}
4064
dftu_expr* dftu_expr_convert(int32_t op, const dftu_expr* a) {
2 ✔
4065
    if (!a) return nullptr;
2 ✔
4066
    return wrap(dataframe::expr_convert(static_cast<dataframe::ConvertOp>(op),
4 !
4067
                                        unwrap(a)));
2 ✔
4068
}
1 ✔
4069
dftu_expr* dftu_expr_list_len(const dftu_expr* a) {
×
4070
    if (!a) return nullptr;
×
4071
    return wrap(dataframe::expr_list_len(unwrap(a)));
×
4072
}
4073
dftu_expr* dftu_expr_list_get(const dftu_expr* a, int64_t index) {
×
4074
    if (!a) return nullptr;
×
4075
    return wrap(dataframe::expr_list_get(unwrap(a), index));
×
4076
}
4077
dftu_expr* dftu_expr_list_sum(const dftu_expr* a) {
×
4078
    if (!a) return nullptr;
×
4079
    return wrap(dataframe::expr_list_sum(unwrap(a)));
×
4080
}
4081
dftu_expr* dftu_expr_list_contains(const dftu_expr* a, dftu_scalar value) {
×
4082
    if (!a ||
×
4083
        (value.kind == DFTU_SCALAR_TAG_STR && value.len > 0 && !value.value.s))
×
4084
        return nullptr;
×
4085
    return wrap(dataframe::expr_list_contains(unwrap(a), value));
×
4086
}
4087
void dftu_expr_free(dftu_expr* e) { delete e; }
164 ✔
4088

4089
dftu_series* dftu_expr_eval(const dftu_expr* root,
42 ✔
4090
                            const dftu_series* const* inputs,
4091
                            int32_t n_inputs) {
4092
    if (!root) return nullptr;
42 ✔
4093
    std::vector<dataframe::Series> owned;
42 ✔
4094
    std::vector<const dataframe::Series*> cols;
42 ✔
4095
    owned.reserve(static_cast<std::size_t>(n_inputs));
42 !
4096
    cols.reserve(static_cast<std::size_t>(n_inputs));
42 !
4097
    for (int32_t i = 0; i < n_inputs; ++i) {
100 ✔
4098
        owned.emplace_back(const_cast<dftu_series*>(inputs[i]));
58 !
4099
        cols.push_back(&owned.back());
58 !
4100
    }
29 ✔
4101
    dftu_series* out = nullptr;
42 ✔
4102
    try {
4103
        out = dataframe::eval(unwrap(root), cols).release();
42 !
4104
    } catch (const std::exception&) {
21 !
4105
        out = nullptr;
×
4106
    }
×
4107
    for (dataframe::Series& c : owned)
100 ✔
4108
        c.release();  // borrowed inputs, do not free
58 ✔
4109
    return out;
42 ✔
4110
}
42 ✔
4111

4112
int32_t dftu_expr_eval_many(const dftu_expr* const* roots, int32_t n_roots,
×
4113
                            const dftu_series* const* inputs, int32_t n_inputs,
4114
                            dftu_series** out) {
4115
    if (!roots || n_roots <= 0) return -1;
×
4116
    std::vector<dataframe::Expr> exprs;
×
4117
    exprs.reserve(static_cast<std::size_t>(n_roots));
×
4118
    for (int32_t i = 0; i < n_roots; ++i) {
×
4119
        if (!roots[i]) return -1;
×
4120
        exprs.push_back(unwrap(roots[i]));
×
4121
    }
4122
    std::vector<dataframe::Series> owned;
×
4123
    std::vector<const dataframe::Series*> cols;
×
4124
    owned.reserve(static_cast<std::size_t>(n_inputs));
×
4125
    cols.reserve(static_cast<std::size_t>(n_inputs));
×
4126
    for (int32_t i = 0; i < n_inputs; ++i) {
×
4127
        owned.emplace_back(const_cast<dftu_series*>(inputs[i]));
×
4128
        cols.push_back(&owned.back());
×
4129
    }
4130
    int32_t written = -1;
×
4131
    try {
4132
        std::vector<dataframe::Series> res = dataframe::eval_many(exprs, cols);
×
4133
        for (std::size_t i = 0; i < res.size(); ++i) out[i] = res[i].release();
×
4134
        written = static_cast<int32_t>(res.size());
×
4135
    } catch (const std::exception&) {
×
4136
        written = -1;
×
4137
    }
×
4138
    for (dataframe::Series& c : owned)
×
4139
        c.release();  // borrowed inputs, do not free
×
4140
    return written;
×
4141
}
×
4142
}
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