dentaku 4.1.0 → 4.2.1
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.
- checksums.yaml +4 -4
- data/.github/workflows/rspec.yml +1 -1
- data/.github/workflows/rubocop.yml +1 -1
- data/CHANGELOG.md +75 -0
- data/README.md +176 -11
- data/lib/dentaku/ast/access.rb +14 -11
- data/lib/dentaku/ast/arithmetic.rb +17 -1
- data/lib/dentaku/ast/array.rb +2 -0
- data/lib/dentaku/ast/bitwise.rb +16 -1
- data/lib/dentaku/ast/combinators.rb +83 -0
- data/lib/dentaku/ast/functions/directed_rounding.rb +37 -0
- data/lib/dentaku/ast/functions/mul.rb +2 -1
- data/lib/dentaku/ast/functions/rounddown.rb +2 -4
- data/lib/dentaku/ast/functions/roundup.rb +2 -4
- data/lib/dentaku/ast/member_access.rb +56 -0
- data/lib/dentaku/ast/negation.rb +4 -0
- data/lib/dentaku/ast/operation.rb +6 -0
- data/lib/dentaku/ast.rb +2 -0
- data/lib/dentaku/bulk_expression_solver.rb +40 -2
- data/lib/dentaku/calculator.rb +26 -3
- data/lib/dentaku/dependency_resolver.rb +12 -0
- data/lib/dentaku/humanize_visitor.rb +276 -0
- data/lib/dentaku/numeric_limits.rb +67 -0
- data/lib/dentaku/numeric_parser.rb +6 -3
- data/lib/dentaku/parser.rb +15 -2
- data/lib/dentaku/print_visitor.rb +38 -2
- data/lib/dentaku/token_scanner.rb +36 -12
- data/lib/dentaku/tokenizer.rb +6 -1
- data/lib/dentaku/version.rb +1 -1
- data/lib/dentaku/visitor/infix.rb +4 -0
- data/mise.toml +2 -0
- data/spec/ast/arithmetic_spec.rb +1 -1
- data/spec/ast/member_access_spec.rb +124 -0
- data/spec/builtin_functions_spec.rb +26 -0
- data/spec/bulk_expression_solver_spec.rb +71 -5
- data/spec/calculator_spec.rb +175 -1
- data/spec/humanize_visitor_spec.rb +217 -0
- data/spec/numeric_limits_spec.rb +59 -0
- data/spec/parser_spec.rb +8 -0
- data/spec/print_visitor_spec.rb +66 -0
- data/spec/tokenizer_spec.rb +19 -0
- data/spec/visitor_spec.rb +7 -0
- metadata +10 -2
- data/lib/dentaku/token_matchers.rb +0 -29
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 8c72201c74cc7bb734b0b339ed3c7b013c84ca168c9f2227012c8ac17036dd2b
|
|
4
|
+
data.tar.gz: 3449be5cfad83709a7ca74f18f4cf737f2dbbd5d7a64232aa8f5eb8afae1cd0c
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 2beb81c610525fb4507b4da06669ae9720a35f598d75ccfc3125212e077ef9bb0b1370b5217cb45bce113d6dcb3247c9a8650d49459b50b0994fa922ffbdaa35
|
|
7
|
+
data.tar.gz: 06d9128f3409ce278f5a8e909e30c256c1d741f474da3277bcf069e670c930accb84a606e1d742e1cb4955871d8d8593ce80e87784dede3a0d0bd0520e01feec
|
data/.github/workflows/rspec.yml
CHANGED
data/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,80 @@
|
|
|
1
1
|
# Change Log
|
|
2
2
|
|
|
3
|
+
## [v4.2.1] 2026-11-23
|
|
4
|
+
- `ROUNDUP` and `ROUNDDOWN` no longer hang on a very negative precision.
|
|
5
|
+
Since 4.2.0, `ROUNDUP(7, -1000000000)` built a billion-digit power of ten
|
|
6
|
+
in a single C call that `Timeout` can't interrupt, so one short formula
|
|
7
|
+
could tie up a thread. A precision past the number's digits now returns
|
|
8
|
+
`0` when rounding toward zero, and raises `Dentaku::ArgumentError` when
|
|
9
|
+
rounding away from zero would need more than 10,000 digits
|
|
10
|
+
- **behavior change:** numbers are limited to 10,000 digits
|
|
11
|
+
(`Dentaku::NumericLimits::MAX_DIGITS`). Ruby does bignum arithmetic in
|
|
12
|
+
single C calls that `Timeout` can't interrupt, so `7 ^ 100000000`,
|
|
13
|
+
`1 << 10000000000`, `ROUND(1e100000000)` or `LEFT("abc", 1e100000000)`
|
|
14
|
+
could tie up a thread for hours. `^` and `<<` are checked before they run,
|
|
15
|
+
arithmetic, bitwise and `MUL` results are checked after, and function
|
|
16
|
+
arguments are checked when coerced. Past the limit they raise
|
|
17
|
+
`Dentaku::ArgumentError` (`evaluate` returns `nil`)
|
|
18
|
+
|
|
19
|
+
## [v4.2.0] 2026-11-18
|
|
20
|
+
- `XOR` works as an operator, like `AND` and `OR`: `a XOR b` (#344). It
|
|
21
|
+
shares their precedence and treats `null` as false, as the function does
|
|
22
|
+
- `NOT` works as a prefix operator, aliased as `!`: `NOT a`, `!(a > 5)`
|
|
23
|
+
(#345). It binds looser than comparisons, so `NOT a > 5` is
|
|
24
|
+
`NOT (a > 5)`. `NOT(...)` and `NOT (...)` are still the function
|
|
25
|
+
- `AND (a, b)` and `OR (a, b)` with a space before the parenthesis call the
|
|
26
|
+
functions, as `XOR (a, b)` already did, instead of failing to parse
|
|
27
|
+
- `-` right after `CASE`, `WHEN`, `THEN` or `ELSE` is a negation:
|
|
28
|
+
`CASE x WHEN 1 THEN -1 END` failed to parse
|
|
29
|
+
- `ROUNDUP` and `ROUNDDOWN` round the number as written. They scaled by a
|
|
30
|
+
Float power of ten, so `ROUNDDOWN(x, 2)` with `x = 0.29` returned `0.28`
|
|
31
|
+
and `ROUNDUP(x, 2)` with `x = 0.07` returned `0.08`. Like `ROUND`, they now
|
|
32
|
+
return the input's type: a decimal literal gives a BigDecimal rather than a
|
|
33
|
+
Float (#172)
|
|
34
|
+
- `solve` and `solve!` accept arrays of hashes and nested arrays, e.g.
|
|
35
|
+
`percents: [{ percent: 75 }, { percent: "30 + bonus" }]`. They raised a
|
|
36
|
+
`TokenizerError` because each hash was parsed as a formula string (#208).
|
|
37
|
+
`evaluate` and `evaluate!` also take a hash, solving each of its values.
|
|
38
|
+
A formula still can't reference another element of its own array
|
|
39
|
+
- `PrintVisitor` keeps the parentheses an index needs, as #268 and #316 did
|
|
40
|
+
for operators: `(a + b)[0]` printed as `a + b[0]`, which indexes only `b`.
|
|
41
|
+
`HumanizeVisitor` also groups function calls before an index, so
|
|
42
|
+
`FILTER(...)[0]` no longer reads as `... greater than 20[0]`
|
|
43
|
+
- `PrintVisitor` prints array literals as written, e.g. `{a, 1 + 2}`.
|
|
44
|
+
It printed the evaluated Ruby array, so `{1, 2}` became `[1, 2]`, which does
|
|
45
|
+
not parse, and an array of variables raised `UnboundVariableError`
|
|
46
|
+
- `Calculator#store` skips nested-hash flattening when no value is a Hash,
|
|
47
|
+
and builds Symbol keys' names from `Symbol#name`. Storing a flat 124-key
|
|
48
|
+
hash drops from 51µs / 998 allocations to 16µs / 250 allocations
|
|
49
|
+
- `MUL` works: it was added in 3.2.0 (#158) but never loaded, so every call
|
|
50
|
+
raised "Undefined function mul". `MUL(2, 3, 4)` now returns `24`
|
|
51
|
+
- remove `lib/dentaku/token_matchers.rb`, unused since the 2015 parser
|
|
52
|
+
rewrite. `require 'dentaku'` never loaded it, so this only affects code that
|
|
53
|
+
required `dentaku/token_matchers` itself
|
|
54
|
+
- add `Calculator#humanize` and `HumanizeVisitor`, which render a formula as
|
|
55
|
+
plain English: `humanize('IF(tenure >= 2, base * 1.1, base)')` returns
|
|
56
|
+
`"if tenure is greater than or equal to 2 then base times 1.1 else base"`.
|
|
57
|
+
Values passed as the second argument replace their variables in the
|
|
58
|
+
output. Nodes without a phrase (e.g. custom functions) fall back to
|
|
59
|
+
`PrintVisitor` (#338)
|
|
60
|
+
- **behavior change:** when a key passed to `solve` / `solve!` is also stored
|
|
61
|
+
in the calculator's memory, other formulas now see the solved value, no
|
|
62
|
+
matter what order the keys are in. Previously they could read the stored
|
|
63
|
+
value instead, depending on hash order (#256). Stored values still break
|
|
64
|
+
cycles, so self-referential formulas such as `x: "x + 1"` work as before
|
|
65
|
+
- add member access: `.name` directly after `]`, `)` or another member
|
|
66
|
+
access reads a hash value by name, so `FILTER(users, u, u.age > 20)[0].name`
|
|
67
|
+
and `users[0].account.year` work (#208, #346). String and symbol keys are
|
|
68
|
+
accepted (case-insensitively unless `case_sensitive: true`); a missing key
|
|
69
|
+
or a non-hash operand raises `Dentaku::ArgumentError`. Member names must
|
|
70
|
+
look like identifiers, whitespace before the dot is not allowed, and dotted
|
|
71
|
+
identifiers such as `user.age` are unchanged. Custom visitors need a
|
|
72
|
+
`visit_member_access` method to walk formulas that use it
|
|
73
|
+
- **behavior change:** accessing into `NULL` now returns `NULL` instead of
|
|
74
|
+
raising, for both `a[0]` and `a.name`, so `FILTER(...)[0][0]` and
|
|
75
|
+
`FILTER(...)[0].name` are `NULL` when nothing matches. Indexing into other
|
|
76
|
+
non-indexable values (numbers, booleans) still raises
|
|
77
|
+
|
|
3
78
|
## [v4.1.0] 2026-10-14
|
|
4
79
|
- `NumericParser` compiles its regular expressions once instead of on every
|
|
5
80
|
call. `Comparator#cast` runs one per string operand of every comparison,
|
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
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
Math: `+`, `-`, `*`, `/`, `%`, `^`, `|`, `&`, `<<`, `>>`
|
|
202
|
+
LITERALS
|
|
203
|
+
--------
|
|
206
204
|
|
|
207
|
-
|
|
205
|
+
Literal keywords are case-insensitive, all following are valid: `null`, `TRUE`, `False`.
|
|
208
206
|
|
|
209
|
-
|
|
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
|
-
|
|
209
|
+
String literals don't support escape sequences.
|
|
212
210
|
|
|
213
|
-
|
|
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
|
-
|
|
220
|
+
BUILT-IN OPERATORS AND FUNCTIONS
|
|
221
|
+
---------------------------------
|
|
216
222
|
|
|
217
|
-
|
|
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
|
-
|
|
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
|
----------------------
|
data/lib/dentaku/ast/access.rb
CHANGED
|
@@ -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
|
-
|
|
29
|
+
return nil if structure.nil?
|
|
29
30
|
|
|
30
|
-
|
|
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
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
require_relative './operation'
|
|
2
2
|
require_relative '../date_arithmetic'
|
|
3
|
+
require_relative '../numeric_limits'
|
|
3
4
|
require 'bigdecimal'
|
|
4
5
|
require 'bigdecimal/util'
|
|
5
6
|
|
|
@@ -37,6 +38,7 @@ module Dentaku
|
|
|
37
38
|
def calculate(left_value, right_value)
|
|
38
39
|
l = cast(left_value)
|
|
39
40
|
r = cast(right_value)
|
|
41
|
+
check_operands!(l, r)
|
|
40
42
|
|
|
41
43
|
result = begin
|
|
42
44
|
l.public_send(operator, r)
|
|
@@ -65,6 +67,7 @@ module Dentaku
|
|
|
65
67
|
# as the same rejection newer Rubies raise -- otherwise Infinity leaks
|
|
66
68
|
# out of Calculator#evaluate, which promises nil on failure (#332).
|
|
67
69
|
def validate_result(result, l, r)
|
|
70
|
+
Dentaku::NumericLimits.check!(result)
|
|
68
71
|
return result unless nonfinite?(result)
|
|
69
72
|
return result if nonfinite?(l) || nonfinite?(r)
|
|
70
73
|
|
|
@@ -76,9 +79,16 @@ module Dentaku
|
|
|
76
79
|
val.is_a?(::Numeric) && val.respond_to?(:finite?) && !val.finite?
|
|
77
80
|
end
|
|
78
81
|
|
|
82
|
+
# Hook for operators that can build a huge number from small operands
|
|
83
|
+
def check_operands!(_l, _r); end
|
|
84
|
+
|
|
79
85
|
def cast(val)
|
|
80
86
|
validate_value(val)
|
|
81
|
-
|
|
87
|
+
# strings here already match the numeric format; ensure_numeric! also
|
|
88
|
+
# rejects numbers past NumericLimits::MAX_DIGITS
|
|
89
|
+
return Dentaku::NumericParser.ensure_numeric!(val) if val.is_a?(::Numeric) || val.is_a?(::String)
|
|
90
|
+
|
|
91
|
+
val
|
|
82
92
|
end
|
|
83
93
|
|
|
84
94
|
def decimal(val)
|
|
@@ -285,6 +295,12 @@ module Dentaku
|
|
|
285
295
|
def self.precedence
|
|
286
296
|
30
|
|
287
297
|
end
|
|
298
|
+
|
|
299
|
+
private
|
|
300
|
+
|
|
301
|
+
def check_operands!(l, r)
|
|
302
|
+
Dentaku::NumericLimits.check_power!(l, r)
|
|
303
|
+
end
|
|
288
304
|
end
|
|
289
305
|
end
|
|
290
306
|
end
|
data/lib/dentaku/ast/array.rb
CHANGED
data/lib/dentaku/ast/bitwise.rb
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
require_relative './operation'
|
|
2
|
+
require_relative '../numeric_limits'
|
|
2
3
|
|
|
3
4
|
module Dentaku
|
|
4
5
|
module AST
|
|
@@ -6,8 +7,11 @@ module Dentaku
|
|
|
6
7
|
def value(context = {})
|
|
7
8
|
left_value = left.value(context)
|
|
8
9
|
right_value = right.value(context)
|
|
10
|
+
Dentaku::NumericLimits.check!(left_value)
|
|
11
|
+
Dentaku::NumericLimits.check!(right_value)
|
|
12
|
+
check_operands!(left_value, right_value)
|
|
9
13
|
|
|
10
|
-
left_value.public_send(operator, right_value)
|
|
14
|
+
Dentaku::NumericLimits.check!(left_value.public_send(operator, right_value))
|
|
11
15
|
rescue NoMethodError
|
|
12
16
|
raise Dentaku::ArgumentError.for(:incompatible_type, actual: left_value, expected: Integer),
|
|
13
17
|
"#{self.class} requires integer operands, but got #{left_value.class}"
|
|
@@ -15,6 +19,11 @@ module Dentaku
|
|
|
15
19
|
raise Dentaku::ArgumentError.for(:incompatible_type, actual: right_value, expected: Integer),
|
|
16
20
|
"#{self.class} requires integer operands, but got #{right_value.class}"
|
|
17
21
|
end
|
|
22
|
+
|
|
23
|
+
private
|
|
24
|
+
|
|
25
|
+
# Hook for operators that can build a huge number from small operands
|
|
26
|
+
def check_operands!(_left_value, _right_value); end
|
|
18
27
|
end
|
|
19
28
|
|
|
20
29
|
class BitwiseOr < Bitwise
|
|
@@ -33,6 +42,12 @@ module Dentaku
|
|
|
33
42
|
def operator
|
|
34
43
|
:<<
|
|
35
44
|
end
|
|
45
|
+
|
|
46
|
+
private
|
|
47
|
+
|
|
48
|
+
def check_operands!(left_value, right_value)
|
|
49
|
+
Dentaku::NumericLimits.check_shift!(left_value, right_value)
|
|
50
|
+
end
|
|
36
51
|
end
|
|
37
52
|
|
|
38
53
|
class BitwiseShiftRight < Bitwise
|
|
@@ -111,5 +111,88 @@ module Dentaku
|
|
|
111
111
|
!!operand_value
|
|
112
112
|
end
|
|
113
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
|
|
114
197
|
end
|
|
115
198
|
end
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
require 'bigdecimal'
|
|
2
|
+
require_relative '../../numeric_limits'
|
|
3
|
+
require_relative '../../numeric_parser'
|
|
4
|
+
|
|
5
|
+
module Dentaku
|
|
6
|
+
# Shared by ROUNDUP (:ceil) and ROUNDDOWN (:floor).
|
|
7
|
+
module DirectedRounding
|
|
8
|
+
def self.call(numeric, precision, direction)
|
|
9
|
+
precision = NumericParser.ensure_numeric!(precision || 0).to_i
|
|
10
|
+
numeric = NumericParser.ensure_numeric!(numeric)
|
|
11
|
+
# Float#ceil(digits) works on the binary value, so 0.07.ceil(2) is 0.08;
|
|
12
|
+
# going through the shortest decimal form rounds the number as written
|
|
13
|
+
decimal = numeric.is_a?(Float) ? BigDecimal(numeric.to_s) : numeric
|
|
14
|
+
|
|
15
|
+
# Integer#ceil(-n) builds 10**n in one uninterruptible C call, even when
|
|
16
|
+
# the answer is 0, so a precision past the number's digits is answered here
|
|
17
|
+
if precision < 0 && -precision > BigDecimal(decimal).exponent
|
|
18
|
+
return beyond_digits(numeric, precision, direction)
|
|
19
|
+
end
|
|
20
|
+
|
|
21
|
+
result = decimal.public_send(direction, precision)
|
|
22
|
+
result = result.to_f if numeric.is_a?(Float)
|
|
23
|
+
precision <= 0 ? result.to_i : result
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
# |numeric| < 10**-precision, so the result is 0 or ±10**-precision
|
|
27
|
+
def self.beyond_digits(numeric, precision, direction)
|
|
28
|
+
away_from_zero = direction == :ceil ? numeric.positive? : numeric.negative?
|
|
29
|
+
return 0 unless away_from_zero
|
|
30
|
+
|
|
31
|
+
# 10**n has n + 1 digits
|
|
32
|
+
NumericLimits.check_digits!(1 - precision)
|
|
33
|
+
(numeric.positive? ? 1 : -1) * 10**-precision
|
|
34
|
+
end
|
|
35
|
+
private_class_method :beyond_digits
|
|
36
|
+
end
|
|
37
|
+
end
|
|
@@ -8,5 +8,6 @@ Dentaku::AST::Function.register(:mul, :numeric, ->(*args) {
|
|
|
8
8
|
)
|
|
9
9
|
end
|
|
10
10
|
|
|
11
|
-
args.flatten.map { |arg| Dentaku::NumericParser.ensure_numeric!(arg) }
|
|
11
|
+
args.flatten.map { |arg| Dentaku::NumericParser.ensure_numeric!(arg) }
|
|
12
|
+
.reduce(1) { |product, arg| Dentaku::NumericLimits.check!(product * arg) }
|
|
12
13
|
})
|
|
@@ -1,8 +1,6 @@
|
|
|
1
1
|
require_relative '../function'
|
|
2
|
+
require_relative './directed_rounding'
|
|
2
3
|
|
|
3
4
|
Dentaku::AST::Function.register(:rounddown, :numeric, lambda { |numeric, precision = 0|
|
|
4
|
-
|
|
5
|
-
tens = 10.0**precision
|
|
6
|
-
result = (Dentaku::NumericParser.ensure_numeric!(numeric) * tens).floor / tens
|
|
7
|
-
precision <= 0 ? result.to_i : result
|
|
5
|
+
Dentaku::DirectedRounding.call(numeric, precision, :floor)
|
|
8
6
|
})
|
|
@@ -1,8 +1,6 @@
|
|
|
1
1
|
require_relative '../function'
|
|
2
|
+
require_relative './directed_rounding'
|
|
2
3
|
|
|
3
4
|
Dentaku::AST::Function.register(:roundup, :numeric, lambda { |numeric, precision = 0|
|
|
4
|
-
|
|
5
|
-
tens = 10.0**precision
|
|
6
|
-
result = (Dentaku::NumericParser.ensure_numeric!(numeric) * tens).ceil / tens
|
|
7
|
-
precision <= 0 ? result.to_i : result
|
|
5
|
+
Dentaku::DirectedRounding.call(numeric, precision, :ceil)
|
|
8
6
|
})
|