dentaku 4.0.2 → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. checksums.yaml +4 -4
  2. data/.github/workflows/rspec.yml +1 -1
  3. data/.github/workflows/rubocop.yml +1 -1
  4. data/CHANGELOG.md +87 -0
  5. data/README.md +176 -11
  6. data/lib/dentaku/ast/access.rb +14 -11
  7. data/lib/dentaku/ast/array.rb +2 -0
  8. data/lib/dentaku/ast/combinators.rb +105 -4
  9. data/lib/dentaku/ast/functions/duration.rb +3 -3
  10. data/lib/dentaku/ast/functions/rounddown.rb +8 -2
  11. data/lib/dentaku/ast/functions/roundup.rb +8 -2
  12. data/lib/dentaku/ast/functions/xor.rb +6 -6
  13. data/lib/dentaku/ast/member_access.rb +56 -0
  14. data/lib/dentaku/ast/negation.rb +4 -0
  15. data/lib/dentaku/ast/operation.rb +6 -0
  16. data/lib/dentaku/ast.rb +2 -0
  17. data/lib/dentaku/bulk_expression_solver.rb +48 -7
  18. data/lib/dentaku/calculator.rb +26 -3
  19. data/lib/dentaku/dependency_resolver.rb +12 -0
  20. data/lib/dentaku/humanize_visitor.rb +276 -0
  21. data/lib/dentaku/numeric_parser.rb +7 -6
  22. data/lib/dentaku/parser.rb +15 -2
  23. data/lib/dentaku/print_visitor.rb +38 -2
  24. data/lib/dentaku/token_scanner.rb +37 -19
  25. data/lib/dentaku/tokenizer.rb +6 -2
  26. data/lib/dentaku/version.rb +1 -1
  27. data/lib/dentaku/visitor/infix.rb +4 -0
  28. data/mise.toml +2 -0
  29. data/spec/ast/member_access_spec.rb +124 -0
  30. data/spec/ast/xor_spec.rb +16 -3
  31. data/spec/builtin_functions_spec.rb +26 -0
  32. data/spec/bulk_expression_solver_spec.rb +88 -0
  33. data/spec/calculator_spec.rb +181 -1
  34. data/spec/case_sensitivity_spec.rb +54 -0
  35. data/spec/humanize_visitor_spec.rb +217 -0
  36. data/spec/parser_spec.rb +8 -0
  37. data/spec/print_visitor_spec.rb +66 -0
  38. data/spec/tokenizer_spec.rb +19 -0
  39. data/spec/visitor_spec.rb +7 -0
  40. metadata +9 -3
  41. data/lib/dentaku/token_matchers.rb +0 -29
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 498d10748b47ba3ab1930e2d3df6685d8d557e1e4f7b95a0887952507557325a
4
- data.tar.gz: a47a69280b8c298a299edbba9758b0dc132fdcceecb055eaa4008c0427d785de
3
+ metadata.gz: f3346a9667db13855bf31fd78573e74772517391158da77a4c240533f05eb8ca
4
+ data.tar.gz: 1e982004771efb2e0dfc1702ca475007ebaa1c8c7d0d10023694a5a66c694e05
5
5
  SHA512:
6
- metadata.gz: '0466598da5b7018075787a018873cc72f4185faa40eabe3596b1666646625d70d29c199a8ac91d5fe0c4436d5b960f5cc9c95efbfe6ff2ea91a4855928074288'
7
- data.tar.gz: '0440877441b431ffb55da23343fe1fff2271afd6ef4868f86a860927ba26f6e37ffa586514dee83a3c018cea4506615377e092ead2135b1cf39e440006a3a933'
6
+ metadata.gz: 0160a7b2170ff95648be302ce6feb40655f362a90d72ad06255913747ec59b02da69e02e070110ad39677c946faf2098419102d220c2f30c8ebc129c6096140d
7
+ data.tar.gz: 60ff9d3aa81fa35c31565ced324ca740af6c7c9e5d0aacc9f56c459bbe758fd9e6eda19594d1660d9d1e46ec7cd36d544eac4c5ec10f12b6ddf3a20b1e28eeb9
@@ -11,7 +11,7 @@ jobs:
11
11
  - '3.2' # minimum supported Ruby
12
12
  - '3.3'
13
13
  - '3.4'
14
- - '4.0' # future compatibility signal
14
+ - 'mise.toml' # the pinned dev Ruby (currently 4.0.7)
15
15
  fail-fast: false
16
16
  steps:
17
17
  - uses: actions/checkout@v4
@@ -7,8 +7,8 @@ jobs:
7
7
  runs-on: ubuntu-latest
8
8
  steps:
9
9
  - uses: actions/checkout@v4
10
+ # No ruby-version: setup-ruby reads it from mise.toml, same as local dev.
10
11
  - uses: ruby/setup-ruby@v1
11
12
  with:
12
- ruby-version: '3.2'
13
13
  bundler-cache: true
14
14
  - run: bundle exec rubocop
data/CHANGELOG.md CHANGED
@@ -1,5 +1,92 @@
1
1
  # Change Log
2
2
 
3
+ ## [v4.2.0] 2026-11-18
4
+ - `XOR` works as an operator, like `AND` and `OR`: `a XOR b` (#344). It
5
+ shares their precedence and treats `null` as false, as the function does
6
+ - `NOT` works as a prefix operator, aliased as `!`: `NOT a`, `!(a > 5)`
7
+ (#345). It binds looser than comparisons, so `NOT a > 5` is
8
+ `NOT (a > 5)`. `NOT(...)` and `NOT (...)` are still the function
9
+ - `AND (a, b)` and `OR (a, b)` with a space before the parenthesis call the
10
+ functions, as `XOR (a, b)` already did, instead of failing to parse
11
+ - `-` right after `CASE`, `WHEN`, `THEN` or `ELSE` is a negation:
12
+ `CASE x WHEN 1 THEN -1 END` failed to parse
13
+ - `ROUNDUP` and `ROUNDDOWN` round the number as written. They scaled by a
14
+ Float power of ten, so `ROUNDDOWN(x, 2)` with `x = 0.29` returned `0.28`
15
+ and `ROUNDUP(x, 2)` with `x = 0.07` returned `0.08`. Like `ROUND`, they now
16
+ return the input's type: a decimal literal gives a BigDecimal rather than a
17
+ Float (#172)
18
+ - `solve` and `solve!` accept arrays of hashes and nested arrays, e.g.
19
+ `percents: [{ percent: 75 }, { percent: "30 + bonus" }]`. They raised a
20
+ `TokenizerError` because each hash was parsed as a formula string (#208).
21
+ `evaluate` and `evaluate!` also take a hash, solving each of its values.
22
+ A formula still can't reference another element of its own array
23
+ - `PrintVisitor` keeps the parentheses an index needs, as #268 and #316 did
24
+ for operators: `(a + b)[0]` printed as `a + b[0]`, which indexes only `b`.
25
+ `HumanizeVisitor` also groups function calls before an index, so
26
+ `FILTER(...)[0]` no longer reads as `... greater than 20[0]`
27
+ - `PrintVisitor` prints array literals as written, e.g. `{a, 1 + 2}`.
28
+ It printed the evaluated Ruby array, so `{1, 2}` became `[1, 2]`, which does
29
+ not parse, and an array of variables raised `UnboundVariableError`
30
+ - `Calculator#store` skips nested-hash flattening when no value is a Hash,
31
+ and builds Symbol keys' names from `Symbol#name`. Storing a flat 124-key
32
+ hash drops from 51µs / 998 allocations to 16µs / 250 allocations
33
+ - `MUL` works: it was added in 3.2.0 (#158) but never loaded, so every call
34
+ raised "Undefined function mul". `MUL(2, 3, 4)` now returns `24`
35
+ - remove `lib/dentaku/token_matchers.rb`, unused since the 2015 parser
36
+ rewrite. `require 'dentaku'` never loaded it, so this only affects code that
37
+ required `dentaku/token_matchers` itself
38
+ - add `Calculator#humanize` and `HumanizeVisitor`, which render a formula as
39
+ plain English: `humanize('IF(tenure >= 2, base * 1.1, base)')` returns
40
+ `"if tenure is greater than or equal to 2 then base times 1.1 else base"`.
41
+ Values passed as the second argument replace their variables in the
42
+ output. Nodes without a phrase (e.g. custom functions) fall back to
43
+ `PrintVisitor` (#338)
44
+ - **behavior change:** when a key passed to `solve` / `solve!` is also stored
45
+ in the calculator's memory, other formulas now see the solved value, no
46
+ matter what order the keys are in. Previously they could read the stored
47
+ value instead, depending on hash order (#256). Stored values still break
48
+ cycles, so self-referential formulas such as `x: "x + 1"` work as before
49
+ - add member access: `.name` directly after `]`, `)` or another member
50
+ access reads a hash value by name, so `FILTER(users, u, u.age > 20)[0].name`
51
+ and `users[0].account.year` work (#208, #346). String and symbol keys are
52
+ accepted (case-insensitively unless `case_sensitive: true`); a missing key
53
+ or a non-hash operand raises `Dentaku::ArgumentError`. Member names must
54
+ look like identifiers, whitespace before the dot is not allowed, and dotted
55
+ identifiers such as `user.age` are unchanged. Custom visitors need a
56
+ `visit_member_access` method to walk formulas that use it
57
+ - **behavior change:** accessing into `NULL` now returns `NULL` instead of
58
+ raising, for both `a[0]` and `a.name`, so `FILTER(...)[0][0]` and
59
+ `FILTER(...)[0].name` are `NULL` when nothing matches. Indexing into other
60
+ non-indexable values (numbers, booleans) still raises
61
+
62
+ ## [v4.1.0] 2026-10-14
63
+ - `NumericParser` compiles its regular expressions once instead of on every
64
+ call. `Comparator#cast` runs one per string operand of every comparison,
65
+ which made the regex compilation the single largest cost of evaluating a
66
+ typical condition: `country = 'US'` evaluated 30k times drops from 0.47s
67
+ to 0.07s
68
+ - fix dependency analysis of `AND` / `OR` chains taking exponential time
69
+ when a short-circuit probe raises (e.g. a zero denominator), a 4.0.0
70
+ regression on the normal `evaluate!` path (#355)
71
+ - `duration()` only accepts exact unit names (`day`, `days`, `month`,
72
+ `months`, `year`, `years`); units merely containing one, such as
73
+ `dayofmonth`, are now rejected
74
+ - `case_sensitive` is no longer shared between calculator instances. The
75
+ tokenizer read the setting from a class-level variable that every
76
+ calculator overwrote, so calculators with different settings running in
77
+ parallel threads could silently fold identifiers to the wrong case and
78
+ return wrong results. Casing is now applied only by the calculator's own
79
+ parser; `Tokenizer#tokenize` keeps identifiers' source casing and
80
+ `TokenScanner.case_sensitive` is removed
81
+ - key the bulk-solver dependency-order cache by the resolved dependency graph,
82
+ so changing formulas or stored context cannot reuse an incompatible order
83
+ from another solve with the same variable names.
84
+ - **behavior change:** `XOR` with three or more arguments is now the
85
+ exclusive OR of all of them (true when an odd number are true), matching
86
+ Excel and `XOR(XOR(a, b), c)`. It previously returned true only when
87
+ exactly one argument was true, so `XOR(true, true, true)` changes from
88
+ `false` to `true`. Results with one or two arguments are unchanged (#349)
89
+
3
90
  ## [v4.0.2] 2026-08-02
4
91
  - the 4.0.1 guard against arithmetic that rejects a well-typed operand only
5
92
  worked on Ruby 3.4+. Ruby 3.2 and 3.3 do not raise for an oversized
data/README.md CHANGED
@@ -199,24 +199,189 @@ identifier on a branch that is not taken will not be reported; use
199
199
  Context keys prefixed with a double underscore (e.g. `__evaluation_mode`)
200
200
  are reserved for internal use.
201
201
 
202
- BUILT-IN OPERATORS AND FUNCTIONS
203
- ---------------------------------
204
-
205
- Math: `+`, `-`, `*`, `/`, `%`, `^`, `|`, `&`, `<<`, `>>`
202
+ LITERALS
203
+ --------
206
204
 
207
- Also, all functions from Ruby's Math module, including `SIN`, `COS`, `TAN`, etc.
205
+ Literal keywords are case-insensitive, all following are valid: `null`, `TRUE`, `False`.
208
206
 
209
- Comparison: `<`, `>`, `<=`, `>=`, `<>`, `!=`, `=`,
207
+ Date/time literals take an optional time (separated by a space, `T` or `|`), optional fractional seconds, and an optional timezone (`Z` or `±HH:MM`). Pass `raw_date_literals: false` to disable them.
210
208
 
211
- Logic: `IF`, `AND`, `OR`, `XOR`, `NOT`, `SWITCH`
209
+ String literals don't support escape sequences.
212
210
 
213
- Numeric: `MIN`, `MAX`, `SUM`, `AVG`, `COUNT`, `ROUND`, `ROUNDDOWN`, `ROUNDUP`, `ABS`, `INTERCEPT`
211
+ | Type | Syntax | Examples |
212
+ |-----------|---------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------|
213
+ | Number | Integer, decimal, scientific or hexadecimal | `42`<br>`3.14`<br>`1.5e3`<br>`.1`<br>`0xff` => `255` |
214
+ | String | Single or double quotes | `"hello"`<br>`'world'` |
215
+ | Boolean | `true` / `false` | `true`<br>`false` |
216
+ | Null | `null` — evaluates to Ruby `nil` | `null` |
217
+ | Date/time | ISO-style date with optional time and zone, on by default | `2020-01-01`<br>`20-1-1`<br>`2020-01-01T13:00:00`<br>`2020-01-01\|13:00:00Z`<br>`2020-01-01 13:00:00 +02:00` |
218
+ | Array | Braces, comma-separated (see Arrays and collection functions) | `{1, 2, 3}`<br>`{{1, 2}, {3, 4}}` |
214
219
 
215
- Selections: `CASE` (syntax see [spec](https://github.com/rubysolo/dentaku/blob/main/lib/dentaku/ast/case.rb))
220
+ BUILT-IN OPERATORS AND FUNCTIONS
221
+ ---------------------------------
216
222
 
217
- String: `LEFT`, `RIGHT`, `MID`, `LEN`, `FIND`, `SUBSTITUTE`, `CONCAT`, `CONTAINS`
223
+ Operator, function, and keyword names are case-insensitive, you can use `AND`, `and`, and `And`; `SUM`, `sum`, and `Sum`; `CASE`, `case`, and `Case`.
224
+
225
+ ### Math operators
226
+
227
+ | Operator | Description | Precedence | Examples |
228
+ |----------|---------------------|:----------:|-------------------------------------------------------------------------------------------|
229
+ | `+` | Addition | 10 | `1 + 2` => `3`<br>`{1} + {2}` => `[1, 2]`<br>`2022-02-24 + 3` => `2022-02-27` |
230
+ | `-` | Subtraction | 10 | `5 - 2` => `3`<br>`2022-02-24 - 3` => `2022-02-21`<br>`2026-02-24 - 2022-02-24` => `1461` |
231
+ | `-` | Unary negation | 40 | `-x` negates `x` |
232
+ | `*` | Multiplication | 20 | `4 * 3` => `12` |
233
+ | `/` | Division | 20 | `9 / 3` => `3.0`<br>`10 / 4` => `2.5` |
234
+ | `%` | Modulo | 20 | `7 % 3` => `1` |
235
+ | `%` | Percentage | 30 | `7 + 1%` => `7.01` |
236
+ | `^` | Exponentiation | 30 | `9 ^ 0.5` => `3.0`<br>`2 ^ 3 ^ 2` => `64` |
237
+ | `&` | Bitwise AND | 0 | `6 & 3` => `2` |
238
+ | `\|` | Bitwise OR | 0 | `5 \| 2` => `7` |
239
+ | `<<` | Bitwise shift left | 0 | `1 << 4` => `16` |
240
+ | `>>` | Bitwise shift right | 0 | `32 >> 2` => `8` |
241
+
242
+ ### Numeric functions
243
+
244
+ | Name | Description | Examples |
245
+ |-------------|-------------------------------------------------------------------------|-------------------------------------------------------------------------------------------|
246
+ | `ABS` | Absolute value | `ABS(-5)` => `5`<br>`ABS(5)` => `5` |
247
+ | `AVG` | Arithmetic mean of arguments | `AVG(1, 2)` => `1.5`<br>`AVG({1, 2})` => `1.5` |
248
+ | `COUNT` | Length of a single array/string argument, otherwise number of arguments | `COUNT(1, 2, 3)` => `3`<br>`COUNT({4, 5})` => `2`<br>`COUNT("foo")` => `3` |
249
+ | `INTERCEPT` | y-intercept of the linear regression of two equal-length arrays | `INTERCEPT({1, 2, 3, 4, 5}, {3, 4, 6, 7, 9})` => `1.3` |
250
+ | `MAX` | Largest argument | `MAX(3, 1, 2)` => `3`<br>`MAX({3, 1, 2})` => `3` |
251
+ | `MIN` | Smallest argument | `MIN(3, 1, 2)` => `1`<br>`MIN({3, 1, 2})` => `1` |
252
+ | `MUL` | Product of arguments | `MUL(2, 3, 4)` => `24`<br>`MUL({2, 3, 4})` => `24` |
253
+ | `ROUND` | Round to 0 or specified number of decimals | `ROUND(1.5)` => `2`<br>`ROUND(-1.5)` => `-2`<br>`ROUND(3.14159, 3)` => `3.142` |
254
+ | `ROUNDDOWN` | Round down to 0 or specified number of decimals | `ROUNDDOWN(1.5)` => `1`<br>`ROUNDDOWN(-1.5)` => `-2`<br>`ROUNDDOWN(0.9999, 3)` => `0.999` |
255
+ | `ROUNDUP` | Round up to 0 or specified number of decimals | `ROUNDUP(1.5)` => `2`<br>`ROUNDUP(-1.5)` => `-1`<br>`ROUNDUP(1.0001, 3)` => `1.001` |
256
+ | `SUM` | Sum of arguments | `SUM(1, 2, 3)` => `6`<br>`SUM({1, 2, 3})` => `6` |
257
+
258
+ ### Math functions
259
+
260
+ Every method from Ruby's `Math` module is available as a function. All angles are in radians.
261
+
262
+ | Name | Description | Examples |
263
+ |----------|-------------------------------------------------------|--------------------------------------------------|
264
+ | `ACOS` | Arc cosine | `ACOS(-1)` => `3.14159…` |
265
+ | `ACOSH` | Inverse hyperbolic cosine | `ACOSH(2)` => `1.31695…` |
266
+ | `ASIN` | Arc sine | `ASIN(1)` => `1.57079…` |
267
+ | `ASINH` | Inverse hyperbolic sine | `ASINH(1)` => `0.88137…` |
268
+ | `ATAN` | Arc tangent | `ATAN(1)` => `0.78539…` |
269
+ | `ATAN2` | Arc tangent of `y / x` | `ATAN2(1, 1)` => `0.78539…` |
270
+ | `ATANH` | Inverse hyperbolic tangent | `ATANH(0.5)` => `0.54930…` |
271
+ | `CBRT` | Cube root | `CBRT(8)` => `2.0` |
272
+ | `COS` | Cosine | `COS(1)` => `0.54030…` |
273
+ | `COSH` | Hyperbolic cosine | `COSH(1)` => `1.54308…` |
274
+ | `ERF` | Gauss error function | `ERF(1)` => `0.84270…` |
275
+ | `ERFC` | Complementary error function (`1 - ERF`) | `ERFC(1)` => `0.15729…` |
276
+ | `EXP` | e raised to the given power | `EXP(1)` => `2.71828…` |
277
+ | `FREXP` | Normalized signed float fraction and integer exponent | `FREXP(8)` => `[0.5, 4]` |
278
+ | `GAMMA` | Gamma function | `GAMMA(5)` => `24.0` |
279
+ | `HYPOT` | Hypotenuse (`√(x² + y²)`) | `HYPOT(3, 4)` => `5.0` |
280
+ | `LDEXP` | Inverse of `FREXP` | `LDEXP(0.5, 4)` => `8.0` |
281
+ | `LGAMMA` | Log gamma and its sign | `LGAMMA(1)` => `[0.0, 1]` |
282
+ | `LOG` | Natural logarithm, or to a given base | `LOG(81)` => `4.39444…`<br>`LOG(81, 3)` => `4.0` |
283
+ | `LOG2` | Base-2 logarithm | `LOG2(8)` => `3.0` |
284
+ | `LOG10` | Base-10 logarithm | `LOG10(1000)` => `3.0` |
285
+ | `SIN` | Sine | `SIN(1)` => `0.84147…` |
286
+ | `SINH` | Hyperbolic sine | `SINH(1)` => `1.17520…` |
287
+ | `SQRT` | Square root | `SQRT(16)` => `4.0` |
288
+ | `TAN` | Tangent | `TAN(1)` => `1.55740…` |
289
+ | `TANH` | Hyperbolic tangent | `TANH(1)` => `0.76159…` |
290
+
291
+ ### Comparison operators
292
+
293
+ | Operator | Description | Precedence | Examples |
294
+ |--------------|-----------------------|:----------:|-------------------------------------------|
295
+ | `<` | Less than | 5 | `1 < 2` => `true`<br>`2 < 2` => `false` |
296
+ | `>` | Greater than | 5 | `2 > 1` => `true`<br>`2 > 2` => `false` |
297
+ | `<=` | Less than or equal | 5 | `2 <= 2` => `true`<br>`3 <= 2` => `false` |
298
+ | `>=` | Greater than or equal | 5 | `2 >= 2` => `true`<br>`2 >= 3` => `false` |
299
+ | `<>` or `!=` | Not equal | 5 | `1 != 2` => `true`<br>`1 != 1` => `false` |
300
+ | `=` or `==` | Equal | 5 | `2 = 2` => `true`<br>`2 = 1` => `false` |
301
+
302
+ ### Logical operators and functions
303
+
304
+ `AND`, `OR`, `XOR` and `NOT` are available both as operators and functions. All arguments must be logical or `null`; `XOR` and `NOT` treat `null` as false.
305
+
306
+ | Name | Description | Precedence | Examples |
307
+ |----------------|-------------------------------------------|:----------:|------------------------------------------------------------------------------------------------------------------|
308
+ | `NOT` or `!` | Logical negation | 3 | `NOT true` => `false`<br>`!(1 > 2)` => `true`<br>`NOT(false)` => `true` |
309
+ | `AND` or `&&` | True when all operands/arguments are true | 0 | `true && true && false` => `false`<br>`AND(true, true, true)` => `true` |
310
+ | `OR` or `\|\|` | True when any operand/argument is true | 0 | `false \|\| false \|\| true` => `true`<br>`OR(false, false, false)` => `false` |
311
+ | `XOR` | True for an odd number of true arguments | 0 | `true XOR false` => `true`<br>`XOR(true, false, true)` => `false`<br>`XOR(true, true, true)` => `true` |
312
+
313
+ `NOT` binds looser than comparisons and tighter than `AND`, `OR` and `XOR`, so
314
+ `NOT a > 5 AND b` means `(NOT (a > 5)) AND b`. `AND`, `OR` and `XOR` share a
315
+ precedence and group left to right: `a OR b AND c` means `(a OR b) AND c`.
316
+ `NOT` directly followed by parentheses is the function, so `NOT (a) = b` means
317
+ `NOT(a) = b`; write `!(a) = b` for the operator.
318
+
319
+ ### Conditionals
320
+
321
+ `IF(condition, when_true, when_false)` returns one of two branches based on a boolean condition:
322
+
323
+ `IF(1 > 2, 123, 456)` => `456`
324
+
325
+ `IF(2 > 1, "big", "small")` => `"big"`
326
+
327
+ `SWITCH(value, candidate1, result1, candidate2, result2, ..., default)` compares `value` against each candidate and returns the matching result, or the trailing `default` (`nil` if omitted and nothing matches):
328
+
329
+ `SWITCH("banana", "apple", 1, "banana", 2, 3)` => `2`
330
+
331
+ `SWITCH(4, 1, "a", 2, "b", "c")` => `"c"`
332
+
333
+ `CASE` provides similar behaviour using keyword form. If no branch matches and there is no `ELSE`, it raises an error:
334
+
335
+ `CASE "banana" WHEN "apple" THEN 1 WHEN "banana" THEN 2 ELSE 3 END` => `2`
336
+
337
+ `CASE 4 WHEN 1 THEN "a" WHEN 2 THEN "b" ELSE "c" END` => `"c"`
338
+
339
+ ### String functions
340
+
341
+ `FIND` and `SUBSTITUTE` also accept a regular expression from a variable.
342
+
343
+ | Name | Description | Examples |
344
+ |--------------|-------------------------------------------------------|--------------------------------------------------------------------------------|
345
+ | `CONCAT` | Concatenates all arguments | `CONCAT("ABC", "DEF", "G", "HI")` => `"ABCDEFGHI"` |
346
+ | `CONTAINS` | True when the substring is in the string | `CONTAINS("app", "apple")` => `true`<br>`CONTAINS("app", "orange")` => `false` |
347
+ | `FIND` | 1-based position of the substring, or `nil` if absent | `FIND("DE", "ABCDEFG")` => `4`<br>`FIND("X", "ABCDEFG")` => `nil` |
348
+ | `LEFT` | First count characters | `LEFT("ABCDEFG", 4)` => `"ABCD"`<br>`LEFT("AB", 4)` => `"AB"` |
349
+ | `LEN` | Number of characters | `LEN("ABCDEFG")` => `7` |
350
+ | `MID` | Starting at 1-based offset take count characters | `MID("ABCDEFG", 4, 2)` => `"DE"` |
351
+ | `RIGHT` | Last count characters | `RIGHT("ABCDEFG", 4)` => `"DEFG"`<br>`RIGHT("AB", 4)` => `"AB"` |
352
+ | `SUBSTITUTE` | Replace the first occurrence of the substring | `SUBSTITUTE("ABCDEFG", "ABC", "x")` => `"xDEFG"` |
353
+
354
+ ### Date functions
355
+
356
+ | Name | Description | Examples |
357
+ |------------|---------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------|
358
+ | `DURATION` | Amount of days, months or years | `2022-02-24 + DURATION(3, days)` => `2022-02-27`<br>`2022-02-24 - DURATION(1, month)` => `2022-01-24`<br>`2022-02-24 + DURATION(4, years)` => `2026-02-24` |
359
+
360
+ ### Arrays and collection functions
361
+
362
+ | Name | Description | Examples |
363
+ |----------|---------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------|
364
+ | `{}` | Create array | `{10, 20, 30}` => `[10, 20, 30]`<br>`{"a", "b"}` => `["a", "b"]`<br>`{{1, 2}, {3, 4}}` => `[[1, 2], [3, 4]]` |
365
+ | `[]` | Get array element at index (0-based, negative - -1 based from the end) or hash at key | `{10, 20, 30}[0]` => `10`<br>`{10, 20, 30}[-1]` => `30`<br>`hash["b"]` => `42`<br>`hash[1]` => `"a"`<br>`hash` is `{1 => "a", "b" => 42}` |
366
+ | `.name` | Get hash value by name, after an index, function call or `)` (see below) | `hashes[0].a` => `30`<br>`FILTER(hashes, h, h.a > 35)[0].a` => `40` |
367
+ | `ALL` | True if the expression is true for every element | `ALL({1, 2, 3}, x, x > 0)` => `true` |
368
+ | `ANY` | True if the expression is true for any element | `ANY({1, 2, 3}, x, x > 2)` => `true` |
369
+ | `FILTER` | Get elements for which the expression is true | `FILTER({1, 2, 3, 4}, x, x % 2 = 0)` => `[2, 4]` |
370
+ | `MAP` | Apply the expression to every element | `MAP({1, 2, 3}, x, x ^ 3)` => `[1, 8, 27]` |
371
+ | `PLUCK` | Collect one key from an array of hashes with optional default | `PLUCK(hashes, a)` => `[30, 40]`<br>`PLUCK(hashes, b, -1)` => `[42, -1]`<br>`hashes` is `[{a: 30, b: 42}, {a: 40}]` |
372
+ | `REDUCE` | Fold elements into an accumulator with optional initial value | `REDUCE({1, 2, 3, 4}, acc, x, acc + x, 0)` => `10` |
373
+
374
+ #### Member access
375
+
376
+ Member access accepts string or symbol keys (case-insensitively unless the
377
+ calculator is case-sensitive), and raises if the key is missing or the value
378
+ is not a hash. Member names must look like identifiers, so a key such as
379
+ `'a.b'` or `'2fa'` needs brackets: `users[0]["a.b"]`. There is no whitespace
380
+ before the dot, and a dotted name on its own, such as `user.age`, is still a
381
+ single nested variable.
218
382
 
219
- Collection: `MAP`, `FILTER`, `ALL`, `ANY`, `PLUCK`
383
+ Both `[]` and `.name` are nil-safe: accessing into `NULL` gives `NULL`, so
384
+ `FILTER(users, u, u.age > 99)[0].name` returns `NULL` when nothing matches.
220
385
 
221
386
  RESOLVING DEPENDENCIES
222
387
  ----------------------
@@ -23,20 +23,12 @@ module Dentaku
23
23
  @index = index
24
24
  end
25
25
 
26
+ # nil-safe: accessing into NULL is NULL
26
27
  def value(context = {})
27
28
  structure = @structure.value(context)
28
- index = @index.value(context)
29
+ return nil if structure.nil?
29
30
 
30
- unless structure.respond_to?(:[]) && !structure.is_a?(::Numeric)
31
- raise Dentaku::ArgumentError.for(:incompatible_type, actual: structure),
32
- "#{self.class} requires an indexable structure, but got #{structure.class}"
33
- end
34
-
35
- begin
36
- structure[index]
37
- rescue ::TypeError => e
38
- raise Dentaku::ArgumentError.for(:incompatible_type, actual: index), e.message
39
- end
31
+ read(structure, @index.value(context))
40
32
  end
41
33
 
42
34
  def dependencies(context = {})
@@ -53,6 +45,17 @@ module Dentaku
53
45
 
54
46
  private
55
47
 
48
+ def read(structure, index)
49
+ unless structure.respond_to?(:[]) && !structure.is_a?(::Numeric)
50
+ raise Dentaku::ArgumentError.for(:incompatible_type, actual: structure),
51
+ "#{self.class} requires an indexable structure, but got #{structure.class}"
52
+ end
53
+
54
+ structure[index]
55
+ rescue ::TypeError => e
56
+ raise Dentaku::ArgumentError.for(:incompatible_type, actual: index), e.message
57
+ end
58
+
56
59
  def compute_pure?
57
60
  @structure.pure? && @index.pure?
58
61
  end
@@ -3,6 +3,8 @@ require_relative "./node"
3
3
  module Dentaku
4
4
  module AST
5
5
  class Array < Node
6
+ attr_reader :elements
7
+
6
8
  def self.arity
7
9
  end
8
10
 
@@ -21,17 +21,35 @@ module Dentaku
21
21
  :logical
22
22
  end
23
23
 
24
+ # A short-circuit probe that raises tells us nothing about which operands are
25
+ # referenced, so fall back to the union of both sides. It has to be the union we
26
+ # already computed rather than `super`: `super` re-derives it by walking both
27
+ # subtrees again, and because the probe raises at every level of a chain, each
28
+ # level would walk its subtree twice -- making analysis exponential in the
29
+ # length of the chain.
24
30
  def dependencies(context = {})
25
31
  return super if static_mode?(context)
26
32
 
27
33
  left_deps = left.dependencies(context)
28
34
  right_deps = right.dependencies(context)
29
- return [] if left_deps.empty? && left.pure? && decisive?(left.value(context))
30
- return [] if right_deps.empty? && right.pure? && decisive?(right.value(context))
35
+
36
+ if left_deps.empty? && left.pure?
37
+ begin
38
+ return [] if decisive?(left.value(context))
39
+ rescue Dentaku::Error
40
+ return (left_deps + right_deps).uniq
41
+ end
42
+ end
43
+
44
+ if right_deps.empty? && right.pure?
45
+ begin
46
+ return [] if decisive?(right.value(context))
47
+ rescue Dentaku::Error
48
+ return (left_deps + right_deps).uniq
49
+ end
50
+ end
31
51
 
32
52
  (left_deps + right_deps).uniq
33
- rescue Dentaku::Error
34
- super
35
53
  end
36
54
 
37
55
  def value(context = {})
@@ -93,5 +111,88 @@ module Dentaku
93
111
  !!operand_value
94
112
  end
95
113
  end
114
+
115
+ # the XOR operator; the XOR function is AST::Xor
116
+ class ExclusiveOr < Combinator
117
+ def operator
118
+ :xor
119
+ end
120
+
121
+ # both operands are always needed, so nothing short-circuits
122
+ def value(context = {})
123
+ logical(left.value(context)) ^ logical(right.value(context))
124
+ end
125
+
126
+ private
127
+
128
+ def decisive?(_operand_value)
129
+ false
130
+ end
131
+
132
+ # null counts as false, as in the XOR function
133
+ def logical(operand_value)
134
+ case operand_value
135
+ when true, false then operand_value
136
+ when nil then false
137
+ else
138
+ raise Dentaku::ArgumentError.for(:incompatible_type, actual: operand_value, expected: :logical),
139
+ "#{self.class} requires logical operands"
140
+ end
141
+ end
142
+ end
143
+
144
+ # the prefix NOT operator (or `!`); the NOT function is AST::Function::Not
145
+ class Not < Operation
146
+ def self.arity
147
+ 1
148
+ end
149
+
150
+ def self.prefix?
151
+ true
152
+ end
153
+
154
+ def self.right_associative?
155
+ true
156
+ end
157
+
158
+ # looser than comparisons, so `NOT a > 5` is `NOT (a > 5)`, and tighter
159
+ # than AND, OR and XOR, so `NOT a AND b` is `(NOT a) AND b`
160
+ def self.precedence
161
+ 3
162
+ end
163
+
164
+ def initialize(node)
165
+ @right = node
166
+
167
+ unless valid_node?(node)
168
+ raise NodeError.new(:logical, node.type, :node),
169
+ "#{self.class} requires a logical operand"
170
+ end
171
+ end
172
+
173
+ def operator
174
+ :not
175
+ end
176
+
177
+ def type
178
+ :logical
179
+ end
180
+
181
+ def value(context = {})
182
+ !right.value(context)
183
+ end
184
+
185
+ def dependencies(context = {})
186
+ right.dependencies(context)
187
+ end
188
+
189
+ private
190
+
191
+ # static dependency check: this runs at parse time, and evaluating
192
+ # short-circuit guards here would execute user functions (#197)
193
+ def valid_node?(node)
194
+ node && (node.dependencies(Node::STATIC_CONTEXT).any? || node.type == :logical)
195
+ end
196
+ end
96
197
  end
97
198
  end
@@ -21,9 +21,9 @@ module Dentaku
21
21
 
22
22
  def validate_unit(unit)
23
23
  case unit.downcase
24
- when /years?/ then :year
25
- when /months?/ then :month
26
- when /days?/ then :day
24
+ when /\Ayears?\z/ then :year
25
+ when /\Amonths?\z/ then :month
26
+ when /\Adays?\z/ then :day
27
27
  else
28
28
  raise Dentaku::ArgumentError.for(:incompatible_type, actual: unit, expected: Duration),
29
29
  "'#{unit || unit.class}' is not a valid duration unit"
@@ -2,7 +2,13 @@ require_relative '../function'
2
2
 
3
3
  Dentaku::AST::Function.register(:rounddown, :numeric, lambda { |numeric, precision = 0|
4
4
  precision = Dentaku::NumericParser.ensure_numeric!(precision || 0).to_i
5
- tens = 10.0**precision
6
- result = (Dentaku::NumericParser.ensure_numeric!(numeric) * tens).floor / tens
5
+ numeric = Dentaku::NumericParser.ensure_numeric!(numeric)
6
+ # Float#floor(digits) works on the binary value, so 0.07.ceil(2) is 0.08;
7
+ # going through the shortest decimal form rounds the number as written
8
+ result = if numeric.is_a?(Float)
9
+ BigDecimal(numeric.to_s).floor(precision).to_f
10
+ else
11
+ numeric.floor(precision)
12
+ end
7
13
  precision <= 0 ? result.to_i : result
8
14
  })
@@ -2,7 +2,13 @@ require_relative '../function'
2
2
 
3
3
  Dentaku::AST::Function.register(:roundup, :numeric, lambda { |numeric, precision = 0|
4
4
  precision = Dentaku::NumericParser.ensure_numeric!(precision || 0).to_i
5
- tens = 10.0**precision
6
- result = (Dentaku::NumericParser.ensure_numeric!(numeric) * tens).ceil / tens
5
+ numeric = Dentaku::NumericParser.ensure_numeric!(numeric)
6
+ # Float#ceil(digits) works on the binary value, so 0.07.ceil(2) is 0.08;
7
+ # going through the shortest decimal form rounds the number as written
8
+ result = if numeric.is_a?(Float)
9
+ BigDecimal(numeric.to_s).ceil(precision).to_f
10
+ else
11
+ numeric.ceil(precision)
12
+ end
7
13
  precision <= 0 ? result.to_i : result
8
14
  })
@@ -20,14 +20,14 @@ module Dentaku
20
20
  )
21
21
  end
22
22
 
23
- true_arg_count = 0
24
- @args.each do |arg|
23
+ # exclusive OR of all arguments: true when an odd number are true, so
24
+ # XOR(a, b, c) == XOR(XOR(a, b), c)
25
+ true_arg_count = @args.count do |arg|
25
26
  case arg.value(context)
26
27
  when TrueClass
27
- true_arg_count += 1
28
- break if true_arg_count > 1
28
+ true
29
29
  when FalseClass, nil
30
- next
30
+ false
31
31
  else
32
32
  raise Dentaku::ArgumentError.for(
33
33
  :incompatible_type,
@@ -35,7 +35,7 @@ module Dentaku
35
35
  )
36
36
  end
37
37
  end
38
- true_arg_count == 1
38
+ true_arg_count.odd?
39
39
  end
40
40
  end
41
41
  end
@@ -0,0 +1,56 @@
1
+ require_relative "../exceptions"
2
+ require_relative "../token"
3
+ require_relative "./access"
4
+ require_relative "./string"
5
+
6
+ module Dentaku
7
+ module AST
8
+ # `a[0].name`: reads a hash value by name; the name is the access index
9
+ class MemberAccess < Access
10
+ attr_reader :member, :case_sensitive
11
+
12
+ def initialize(structure, member, case_sensitive: false)
13
+ super(structure, AST::String.new(Token.new(:string, member, member)))
14
+ @member = member
15
+ @case_sensitive = case_sensitive
16
+ end
17
+
18
+ def accept(visitor)
19
+ visitor.visit_member_access(self)
20
+ end
21
+
22
+ private
23
+
24
+ def read(structure, _index)
25
+ unless structure.is_a?(::Hash)
26
+ raise Dentaku::ArgumentError.for(:incompatible_type, actual: structure),
27
+ "#{self.class} requires a hash, but got #{structure.class}"
28
+ end
29
+
30
+ key = find_key(structure)
31
+ return structure[key] unless key.nil?
32
+
33
+ raise Dentaku::ArgumentError.for(:invalid_value, actual: member), missing_key_message(structure)
34
+ end
35
+
36
+ # string and symbol keys are both accepted; outside case-sensitive mode
37
+ # an exact match wins over a case-insensitive one
38
+ def find_key(hash)
39
+ return member if hash.key?(member)
40
+ return member.to_sym if hash.key?(member.to_sym)
41
+ return nil if case_sensitive
42
+
43
+ hash.each_key.find { |key| key.to_s.casecmp?(member) }
44
+ end
45
+
46
+ def missing_key_message(hash)
47
+ message = "no key '#{member}' in #{hash.keys.inspect}"
48
+ dotted = hash.keys.find { |key| key.to_s.start_with?("#{member}.") }
49
+ return message if dotted.nil?
50
+
51
+ "#{message}; member access only reads keys that look like identifiers, " \
52
+ "use brackets for '#{dotted}'"
53
+ end
54
+ end
55
+ end
56
+ end