dentaku 4.1.0 → 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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 75997c319d555caca8df23e6b1e1995f5a99b1fbd041f25d1e876ac40b487b49
4
- data.tar.gz: ee629e3909f7b5040d9f39c1cad871f3d7599be8a76d6b2753652bcdbc9aefbc
3
+ metadata.gz: f3346a9667db13855bf31fd78573e74772517391158da77a4c240533f05eb8ca
4
+ data.tar.gz: 1e982004771efb2e0dfc1702ca475007ebaa1c8c7d0d10023694a5a66c694e05
5
5
  SHA512:
6
- metadata.gz: 4f7342cd68c9b1edbd2c992b01784a3b66caa6f13f0cc698a26447883a01eb6ffde1c6262790d9810ded42d5bdd6ac601ab2c7585e4c6d5f5467964cb6fe92ce
7
- data.tar.gz: 8b1c85908541da4fe4896b3fcb90741fe8ea907c29fc162fcb64eca9ae60bd043ecdece5fe428490c0452a6f1072174a52b090ab575f50d117cbe3f976ad0265
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,64 @@
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
+
3
62
  ## [v4.1.0] 2026-10-14
4
63
  - `NumericParser` compiles its regular expressions once instead of on every
5
64
  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
- 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
 
@@ -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
@@ -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
  })
@@ -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
@@ -32,6 +32,10 @@ module Dentaku
32
32
  true
33
33
  end
34
34
 
35
+ def self.prefix?
36
+ true
37
+ end
38
+
35
39
  def self.precedence
36
40
  40
37
41
  end
@@ -26,6 +26,12 @@ module Dentaku
26
26
  false
27
27
  end
28
28
 
29
+ # a prefix operator has no left operand, so it never folds the
30
+ # operators before it
31
+ def self.prefix?
32
+ false
33
+ end
34
+
29
35
  def accept(visitor)
30
36
  visitor.visit_operation(self)
31
37
  end
data/lib/dentaku/ast.rb CHANGED
@@ -11,6 +11,7 @@ require_relative './ast/negation'
11
11
  require_relative './ast/comparators'
12
12
  require_relative './ast/combinators'
13
13
  require_relative './ast/access'
14
+ require_relative './ast/member_access'
14
15
  require_relative './ast/array'
15
16
  require_relative './ast/grouping'
16
17
  require_relative './ast/case'
@@ -28,6 +29,7 @@ require_relative './ast/functions/intercept'
28
29
  require_relative './ast/functions/map'
29
30
  require_relative './ast/functions/max'
30
31
  require_relative './ast/functions/min'
32
+ require_relative './ast/functions/mul'
31
33
  require_relative './ast/functions/not'
32
34
  require_relative './ast/functions/or'
33
35
  require_relative './ast/functions/pluck'
@@ -90,7 +90,7 @@ module Dentaku
90
90
 
91
91
  evaluated_facts = facts.to_h.each_with_object({}) do |(var_name, ast), h|
92
92
  with_rescues(var_name, h, block) do
93
- h[var_name] = ast.is_a?(Array) ? ast.map(&:value) : ast.value
93
+ h[var_name] = fact_value(ast)
94
94
  end
95
95
  end
96
96
 
@@ -116,6 +116,15 @@ module Dentaku
116
116
  {}
117
117
  end
118
118
 
119
+ # facts can be arrays and hashes nested to any depth, e.g. [{ a: 1 }]
120
+ def fact_value(ast)
121
+ case ast
122
+ when Array then ast.map { |a| fact_value(a) }
123
+ when Hash then ast.transform_values { |a| fact_value(a) }
124
+ else ast.value
125
+ end
126
+ end
127
+
119
128
  def with_rescues(var_name, results, block)
120
129
  yield
121
130
  rescue Dentaku::UnboundVariableError, Dentaku::ZeroDivisionError, Dentaku::ArgumentError => ex
@@ -152,9 +161,38 @@ module Dentaku
152
161
  end
153
162
  end
154
163
 
164
+ # Stored memory can satisfy a formula's reference to another key being
165
+ # solved, which hides that edge from `dependencies`. Order those keys first
166
+ # anyway so the formula sees the solved value rather than the stored one,
167
+ # unless the edge would close a cycle -- then the stored value is what
168
+ # breaks it, as for self-referential formulas.
169
+ def resolve_order_graph
170
+ graph = dependencies
171
+ keys = expressions.keys.map { |k| normalized_name(k) }
172
+
173
+ hidden = expressions.to_h do |var, expr|
174
+ own = normalized_name(var)
175
+ visible = graph.fetch(var, []).map { |d| normalized_name(d) }
176
+ all = Array(calculator.dependencies(expr, nil)).map { |d| normalized_name(d) }
177
+ [var, (all & keys) - visible - [own]]
178
+ end
179
+ return graph if hidden.values.all?(&:empty?)
180
+
181
+ with_hidden = graph.merge(hidden) { |_, deps, extra| deps + extra }
182
+ cycle_of = {}
183
+ DependencyResolver.cycles(with_hidden, calculator.case_sensitive).each_with_index do |cycle, i|
184
+ cycle.each { |name| cycle_of[name] = i }
185
+ end
186
+
187
+ graph.merge(hidden) do |var, deps, extra|
188
+ cycle = cycle_of[normalized_name(var)]
189
+ deps + extra.reject { |e| cycle && cycle_of[e] == cycle }
190
+ end
191
+ end
192
+
155
193
  def variables_in_resolve_order
156
194
  @ordered_deps ||= begin
157
- dependency_graph = dependencies
195
+ dependency_graph = resolve_order_graph
158
196
  cache_key = [!!calculator.case_sensitive, dependency_graph]
159
197
  self.class.dependency_cache.fetch(cache_key) {
160
198
  DependencyResolver.find_resolve_order(dependency_graph, calculator.case_sensitive).tap do |d|