formualizer-eval 0.7.0

High-performance Arrow-backed Excel formula engine with dependency graph and incremental recalculation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
//! Byte-oriented text functions for non-DBCS locales.
//!
//! Excel's `*B` functions count bytes in double-byte character set locales. Formualizer's locale
//! layer is currently invariant/non-DBCS, so these functions delegate to their character-counting
//! counterparts.

use super::{FindFn, LeftFn, LenFn, MidFn, ReplaceFn, RightFn, SearchFn};
use crate::args::ArgSchema;
use crate::builtins::utils::ARG_ANY_ONE;
use crate::function::Function;
use crate::traits::{ArgumentHandle, FunctionContext};
use formualizer_common::ExcelError;
use formualizer_macros::func_caps;

/// Finds text within text using non-DBCS byte-compatible semantics.
///
/// In Formualizer's invariant locale, FINDB delegates to FIND and counts Unicode
/// scalar characters rather than double-byte locale bytes.
///
/// ```yaml,sandbox
/// title: "Find byte-compatible text"
/// formula: '=FINDB("CD","abcDEFCD")'
/// expected: 7
/// ```
///
/// ```yaml,docs
/// related:
///   - FIND
///   - SEARCHB
///   - LENB
/// faq:
///   - q: "Does FINDB use DBCS byte counts?"
///     a: "Not currently. In the invariant locale it delegates to FIND."
/// ```
#[derive(Debug)]
pub struct FindBFn;
/// [formualizer-docgen:schema:start]
/// Name: FINDB
/// Type: FindBFn
/// Min args: 2
/// Max args: variadic
/// Variadic: true
/// Signature: FINDB(arg1...: any@scalar)
/// Arg schema: arg1{kinds=any,required=true,shape=scalar,by_ref=false,coercion=None,max=None,repeating=None,default=false}
/// Caps: PURE
/// [formualizer-docgen:schema:end]
impl Function for FindBFn {
    func_caps!(PURE);
    fn name(&self) -> &'static str {
        "FINDB"
    }
    fn min_args(&self) -> usize {
        2
    }
    fn variadic(&self) -> bool {
        true
    }
    fn arg_schema(&self) -> &'static [ArgSchema] {
        &ARG_ANY_ONE[..]
    }
    fn eval<'a, 'b, 'c>(
        &self,
        args: &'c [ArgumentHandle<'a, 'b>],
        ctx: &dyn FunctionContext<'b>,
    ) -> Result<crate::traits::CalcValue<'b>, ExcelError> {
        FindFn.eval(args, ctx)
    }
}

/// Returns the leftmost characters using non-DBCS byte-compatible semantics.
///
/// In Formualizer's invariant locale, LEFTB delegates to LEFT.
///
/// ```yaml,sandbox
/// title: "Left byte-compatible characters"
/// formula: '=LEFTB("hello",2)'
/// expected: "he"
/// ```
///
/// ```yaml,docs
/// related:
///   - LEFT
///   - RIGHTB
///   - MIDB
/// faq:
///   - q: "Does LEFTB split UTF-8 bytes?"
///     a: "No. It follows the non-DBCS behavior and delegates to LEFT."
/// ```
#[derive(Debug)]
pub struct LeftBFn;
/// [formualizer-docgen:schema:start]
/// Name: LEFTB
/// Type: LeftBFn
/// Min args: 1
/// Max args: variadic
/// Variadic: true
/// Signature: LEFTB(arg1...: any@scalar)
/// Arg schema: arg1{kinds=any,required=true,shape=scalar,by_ref=false,coercion=None,max=None,repeating=None,default=false}
/// Caps: PURE
/// [formualizer-docgen:schema:end]
impl Function for LeftBFn {
    func_caps!(PURE);
    fn name(&self) -> &'static str {
        "LEFTB"
    }
    fn min_args(&self) -> usize {
        1
    }
    fn variadic(&self) -> bool {
        true
    }
    fn arg_schema(&self) -> &'static [ArgSchema] {
        &ARG_ANY_ONE[..]
    }
    fn eval<'a, 'b, 'c>(
        &self,
        args: &'c [ArgumentHandle<'a, 'b>],
        ctx: &dyn FunctionContext<'b>,
    ) -> Result<crate::traits::CalcValue<'b>, ExcelError> {
        LeftFn.eval(args, ctx)
    }
}

/// Returns text length using non-DBCS byte-compatible semantics.
///
/// In Formualizer's invariant locale, LENB delegates to LEN.
///
/// ```yaml,sandbox
/// title: "Length of text"
/// formula: '=LENB("abc")'
/// expected: 3
/// ```
///
/// ```yaml,docs
/// related:
///   - LEN
///   - LEFTB
///   - RIGHTB
/// faq:
///   - q: "Does LENB count UTF-8 bytes?"
///     a: "No. In the invariant locale it matches LEN."
/// ```
#[derive(Debug)]
pub struct LenBFn;
/// [formualizer-docgen:schema:start]
/// Name: LENB
/// Type: LenBFn
/// Min args: 1
/// Max args: 1
/// Variadic: false
/// Signature: LENB(arg1: any@scalar)
/// Arg schema: arg1{kinds=any,required=true,shape=scalar,by_ref=false,coercion=None,max=None,repeating=None,default=false}
/// Caps: PURE
/// [formualizer-docgen:schema:end]
impl Function for LenBFn {
    func_caps!(PURE);
    fn name(&self) -> &'static str {
        "LENB"
    }
    fn min_args(&self) -> usize {
        1
    }
    fn arg_schema(&self) -> &'static [ArgSchema] {
        &ARG_ANY_ONE[..]
    }
    fn eval<'a, 'b, 'c>(
        &self,
        args: &'c [ArgumentHandle<'a, 'b>],
        ctx: &dyn FunctionContext<'b>,
    ) -> Result<crate::traits::CalcValue<'b>, ExcelError> {
        LenFn.eval(args, ctx)
    }
}

/// Extracts text from the middle using non-DBCS byte-compatible semantics.
///
/// In Formualizer's invariant locale, MIDB delegates to MID.
///
/// ```yaml,sandbox
/// title: "Middle byte-compatible characters"
/// formula: '=MIDB("abcdef",2,3)'
/// expected: "bcd"
/// ```
///
/// ```yaml,docs
/// related:
///   - MID
///   - LEFTB
///   - RIGHTB
/// faq:
///   - q: "How are byte positions interpreted?"
///     a: "In the invariant locale, positions are character positions matching MID."
/// ```
#[derive(Debug)]
pub struct MidBFn;
/// [formualizer-docgen:schema:start]
/// Name: MIDB
/// Type: MidBFn
/// Min args: 3
/// Max args: 1
/// Variadic: false
/// Signature: MIDB(arg1: any@scalar)
/// Arg schema: arg1{kinds=any,required=true,shape=scalar,by_ref=false,coercion=None,max=None,repeating=None,default=false}
/// Caps: PURE
/// [formualizer-docgen:schema:end]
impl Function for MidBFn {
    func_caps!(PURE);
    fn name(&self) -> &'static str {
        "MIDB"
    }
    fn min_args(&self) -> usize {
        3
    }
    fn arg_schema(&self) -> &'static [ArgSchema] {
        &ARG_ANY_ONE[..]
    }
    fn eval<'a, 'b, 'c>(
        &self,
        args: &'c [ArgumentHandle<'a, 'b>],
        ctx: &dyn FunctionContext<'b>,
    ) -> Result<crate::traits::CalcValue<'b>, ExcelError> {
        MidFn.eval(args, ctx)
    }
}

/// Replaces text using non-DBCS byte-compatible semantics.
///
/// In Formualizer's invariant locale, REPLACEB delegates to REPLACE.
///
/// ```yaml,sandbox
/// title: "Replace byte-compatible text"
/// formula: '=REPLACEB("abcdef",3,2,"ZZ")'
/// expected: "abZZef"
/// ```
///
/// ```yaml,docs
/// related:
///   - REPLACE
///   - MIDB
///   - FINDB
/// faq:
///   - q: "Does REPLACEB operate on raw UTF-8 bytes?"
///     a: "No. In the invariant locale it delegates to REPLACE."
/// ```
#[derive(Debug)]
pub struct ReplaceBFn;
/// [formualizer-docgen:schema:start]
/// Name: REPLACEB
/// Type: ReplaceBFn
/// Min args: 4
/// Max args: 1
/// Variadic: false
/// Signature: REPLACEB(arg1: any@scalar)
/// Arg schema: arg1{kinds=any,required=true,shape=scalar,by_ref=false,coercion=None,max=None,repeating=None,default=false}
/// Caps: PURE
/// [formualizer-docgen:schema:end]
impl Function for ReplaceBFn {
    func_caps!(PURE);
    fn name(&self) -> &'static str {
        "REPLACEB"
    }
    fn min_args(&self) -> usize {
        4
    }
    fn arg_schema(&self) -> &'static [ArgSchema] {
        &ARG_ANY_ONE[..]
    }
    fn eval<'a, 'b, 'c>(
        &self,
        args: &'c [ArgumentHandle<'a, 'b>],
        ctx: &dyn FunctionContext<'b>,
    ) -> Result<crate::traits::CalcValue<'b>, ExcelError> {
        ReplaceFn.eval(args, ctx)
    }
}

/// Returns the rightmost characters using non-DBCS byte-compatible semantics.
///
/// In Formualizer's invariant locale, RIGHTB delegates to RIGHT.
///
/// ```yaml,sandbox
/// title: "Right byte-compatible characters"
/// formula: '=RIGHTB("hello",2)'
/// expected: "lo"
/// ```
///
/// ```yaml,docs
/// related:
///   - RIGHT
///   - LEFTB
///   - MIDB
/// faq:
///   - q: "Does RIGHTB count DBCS bytes?"
///     a: "Not currently. In the invariant locale it matches RIGHT."
/// ```
#[derive(Debug)]
pub struct RightBFn;
/// [formualizer-docgen:schema:start]
/// Name: RIGHTB
/// Type: RightBFn
/// Min args: 1
/// Max args: variadic
/// Variadic: true
/// Signature: RIGHTB(arg1...: any@scalar)
/// Arg schema: arg1{kinds=any,required=true,shape=scalar,by_ref=false,coercion=None,max=None,repeating=None,default=false}
/// Caps: PURE
/// [formualizer-docgen:schema:end]
impl Function for RightBFn {
    func_caps!(PURE);
    fn name(&self) -> &'static str {
        "RIGHTB"
    }
    fn min_args(&self) -> usize {
        1
    }
    fn variadic(&self) -> bool {
        true
    }
    fn arg_schema(&self) -> &'static [ArgSchema] {
        &ARG_ANY_ONE[..]
    }
    fn eval<'a, 'b, 'c>(
        &self,
        args: &'c [ArgumentHandle<'a, 'b>],
        ctx: &dyn FunctionContext<'b>,
    ) -> Result<crate::traits::CalcValue<'b>, ExcelError> {
        RightFn.eval(args, ctx)
    }
}

/// Searches text using non-DBCS byte-compatible semantics.
///
/// In Formualizer's invariant locale, SEARCHB delegates to SEARCH and supports
/// the same wildcard behavior.
///
/// ```yaml,sandbox
/// title: "Wildcard byte-compatible search"
/// formula: '=SEARCHB("d?f","abcDEF")'
/// expected: 4
/// ```
///
/// ```yaml,docs
/// related:
///   - SEARCH
///   - FINDB
///   - LENB
/// faq:
///   - q: "Is SEARCHB case-sensitive?"
///     a: "No. It follows SEARCH behavior in the invariant locale."
/// ```
#[derive(Debug)]
pub struct SearchBFn;
/// [formualizer-docgen:schema:start]
/// Name: SEARCHB
/// Type: SearchBFn
/// Min args: 2
/// Max args: variadic
/// Variadic: true
/// Signature: SEARCHB(arg1...: any@scalar)
/// Arg schema: arg1{kinds=any,required=true,shape=scalar,by_ref=false,coercion=None,max=None,repeating=None,default=false}
/// Caps: PURE
/// [formualizer-docgen:schema:end]
impl Function for SearchBFn {
    func_caps!(PURE);
    fn name(&self) -> &'static str {
        "SEARCHB"
    }
    fn min_args(&self) -> usize {
        2
    }
    fn variadic(&self) -> bool {
        true
    }
    fn arg_schema(&self) -> &'static [ArgSchema] {
        &ARG_ANY_ONE[..]
    }
    fn eval<'a, 'b, 'c>(
        &self,
        args: &'c [ArgumentHandle<'a, 'b>],
        ctx: &dyn FunctionContext<'b>,
    ) -> Result<crate::traits::CalcValue<'b>, ExcelError> {
        SearchFn.eval(args, ctx)
    }
}

pub fn register_builtins() {
    use crate::function_registry::register_function;
    use std::sync::Arc;

    register_function(Arc::new(FindBFn));
    register_function(Arc::new(LeftBFn));
    register_function(Arc::new(LenBFn));
    register_function(Arc::new(MidBFn));
    register_function(Arc::new(ReplaceBFn));
    register_function(Arc::new(RightBFn));
    register_function(Arc::new(SearchBFn));
}

#[cfg(test)]
mod tests {
    use crate::test_workbook::TestWorkbook;
    use formualizer_common::LiteralValue;
    use formualizer_parse::parser::parse;

    fn eval(formula: &str) -> LiteralValue {
        let wb = TestWorkbook::new()
            .with_function(std::sync::Arc::new(super::FindBFn))
            .with_function(std::sync::Arc::new(super::LeftBFn))
            .with_function(std::sync::Arc::new(super::LenBFn))
            .with_function(std::sync::Arc::new(super::MidBFn))
            .with_function(std::sync::Arc::new(super::ReplaceBFn))
            .with_function(std::sync::Arc::new(super::RightBFn))
            .with_function(std::sync::Arc::new(super::SearchBFn));
        let interp = wb.interpreter();
        let ast = parse(formula).expect("parse");
        interp.evaluate_ast(&ast).expect("eval").into_literal()
    }

    #[test]
    fn byte_functions_delegate_in_non_dbcs_locale() {
        assert_eq!(eval("=LENB(\"éx\")"), LiteralValue::Int(2));
        assert_eq!(eval("=LEFTB(\"hello\",2)"), LiteralValue::Text("he".into()));
        assert_eq!(
            eval("=RIGHTB(\"hello\",2)"),
            LiteralValue::Text("lo".into())
        );
        assert_eq!(
            eval("=MIDB(\"abcdef\",2,3)"),
            LiteralValue::Text("bcd".into())
        );
        assert_eq!(
            eval("=REPLACEB(\"abcdef\",3,2,\"ZZ\")"),
            LiteralValue::Text("abZZef".into())
        );
        assert_eq!(eval("=FINDB(\"CD\",\"abcDEFCD\")"), LiteralValue::Int(7));
        assert_eq!(eval("=SEARCHB(\"d?f\",\"abcDEF\")"), LiteralValue::Int(4));
    }
}