Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Compatibility with jsonata-js

jlens targets the behaviour of jsonata-js 2.3.0, as specified by its official test suite. It copies that behaviour, quirks included, unless copying would cost precision, correctness or performance: a result made inexact by JavaScript’s rounding, a result that is wrong by the JSONata documentation or exposes a JavaScript internal, or a slower common path. This page records both kinds of decision:

  • Differences: where jlens behaves otherwise. A difference that affects the conformance suite is also an override there, with its reason.
  • Extensions: features of jlens alone, which do not change the meaning of valid expressions.
  • Quirks reproduced on purpose: jsonata-js behaviour that looks wrong, which jlens copies because its cost stays in unusual input or error paths, where users can expect the same answer from both engines.

jsonata-js 2.3.0 changed many results of 2.2.2, which its release notes list. jlens took those changes from jsonata-js’s main branch in 0.35 and 0.36, before the release, and its template strings in 0.37 (see the changelog), and gives what 2.3.0 gives, except for a $clone bound at the top level, below.

Differences

Most differences have one of four causes: Rust strings are UTF-8 where JavaScript’s are UTF-16; jlens never panics, overflows its stack or exhausts memory on user input, and reports a coded error instead; an evaluation never changes its input; and a result never depends on the machine, its time zone or JavaScript’s internals.

Strings and Unicode

Topicjsonata-jsjlens
String representationUTF-16, may contain lone surrogatesUTF-8 (String). A lone surrogate written as \uD800 becomes U+FFFD, and so does a digit of $formatNumber that would be one (a zero-digit just below U+D800)
\uXXXX surrogate pairsTwo code unitsCombined into one character, so "𝄞" is 𝄞
Error positionUTF-16 offsetThe same UTF-16 offset, plus a byte span

Two suite cases pass a lone surrogate to $encodeUrl / $encodeUrlComponent to provoke an error. jlens cannot represent that input, so it skips those two cases.

Parsing

  • Error recovery (parse_recover) produces the same codes and positions as jsonata-js on its recovery tests. It also recovers from lexer errors and post-processing errors, which jsonata-js throws even in recover mode.
  • An expression that starts right after a recovered error reuses that error. jsonata-js reports an extra S0211 with an undefined token in that situation.
  • Doc-comments (/** ... */) are parsed as audit annotations. Like any comment, they never change how an expression is parsed or evaluated.

Evaluation

Topicjsonata-jsjlens
Object key orderJavaScript order: integer-like keys first, ascending, then insertion orderInsertion order, always
Recursion limitThe JavaScript stack (RangeError)D1011 after Options::max_depth evaluation levels (50,000 by default; 500 in Wasm)
Step limitNoneU1006 once an evaluation has taken Options::max_steps steps, the same on every machine (ADR 0018); no limit by default
A limit reached by the text of $eval ($eval('$f(0)') with $f recursing forever)D3121, its message quoting the limit’s (D1011, D1012); the limit’s own error is kept in the field error, which jlens errors do not haveThe limit’s own code (D1011, D1012, U1001, U1003, U1006), located at the call of $eval as D3121 would be. The limits belong to the whole evaluation, not to the text: an application can tell them from an error in the text by the code, without reading the message. Other errors of the text are D3121 in both engines
Nesting limitThe JavaScript stack: about 2,000 terms in a chain such as 1 + 1 + … work, 5,000 raise a RangeErrorU1001 beyond 1,000 levels of syntax tree: nested subexpressions, and each operator of a chain (a chain of more than 1,000 terms is rejected)
Very long strings and arraysLimited by the JavaScript engine (a RangeError, or running out of memory)U1001 beyond Options::max_string_length (256 MiB) or Options::max_array_length (16,777,216 items)
A very large result, such as an object nested in itself many timesLimited by the JavaScript engine when the result is serializedU1001 beyond Options::max_result_size (256 MiB of JSON text)
Deeply nested values, in the input or built by a recursive functionThe JavaScript stack: 2,000 levels of arrays and objects work, 5,000 raise a RangeError when the result is returned, serialized ($string) or walked (**)U1001 beyond 1,000 levels where a value is converted to JSON (the result, a host function’s arguments), compared (=, $distinct), serialized ($string, $clone) or walked by **. The limit keeps the JSON returned safe to drop and print with recursive code. Lookups, *, $boolean, $keys and $spread walk nested arrays at any depth
A transform that makes an object contain itself (`$ ~>${‘self’: $}
A transform in an expression that binds $clone at the top level, outside any block ([$clone := function($v){$v}, $ ~> |a|{'y': 1}|])The transform copies with that $clone, bound in the frame of the host’s variables, so the one here changes the input. One bound in a block (($clone := function($v){ 'x' }; $ ~> |a|{'y': 1}|)) is not used, since pull request #871The built-in $clone or the host’s, wherever the expression binds one: a function bound as clone, or T2013 for a variable of the host’s that is no function. No transform changes its input
Several items of an array constructor, or values of an object constructor, failThe items are evaluated concurrently; the error raised first in the asynchronous schedule wins, which need not be the first item’sThe items are evaluated in order; the first failing item’s error is reported
A variable bound in an item of an array constructor, or a value of an object constructor, and read in a later one (($x := 1; [$x := 5, $x]))The items are evaluated concurrently, so that what the later item reads depends on its shape: a plain $x reads the value from before the binding, [5, 1], and 0 + $x the one after it, [5, 5]. The same in object constructorsThe items are evaluated in order, so that a later item always reads the binding: [5, 5]. The result depends on the expression, not on how many asynchronous steps its parts take, which are an internal of jsonata-js
A group-by or object constructor ({...}) over an empty array, of the input or of a value the expression holdsAdds an undefined item to that array, which the rest of the expression sees (($g := items{'k': 1}; $count(items)) gives 1 when items is []; jlens gives 0). An item of a value the expression built changes too: a sort key that makes an object reads each item, so ([1, []])^(({}; 1)) gives [1, [null]]The input and the values already built are never changed: [1, []]
A wildcard over an array of sequences ($map([1, 2], function($e){ items.$ }).*)Adds a true item after the items of each sequence: an internal flag of the sequence, which its wildcard enumeratesThe items only
A group-by on a call in tail position of a lambda (function() { $zip(items){'k': $} }), the last expression of its body, of a branch of a condition or of a block, or either side of ?? and ?:Not applied: the trampoline that runs tail calls makes the call alone, and the call’s result is the function’s ([[…], […]] from $zip, where $zip(items){'k': $} outside a lambda gives {"k": […]})Applied, as outside a lambda. A call with a group-by is not a tail call, as a call with a predicate is not one in both engines: a recursion through it nests, while the other calls of the function stay tail calls. The dropped group-by is wrong by the JSONata documentation, and the cost stays in unusual expressions
An order-by after a step that binds @, # or an ancestor (items@$o^(price)), when a filter, a group-by or another order-by follows itThe sort returns a plain array of the path’s internal tuples, so a filter, group-by or order-by after it takes the tuples for items: $ is a tuple such as {"@": …, "o": …}, and $o is gone (items@$o.{}^(1){'s': $o} gives {}; items#$i^(price)^(>$i) keeps the first order, as every key of the second is missing, and items#$i.price^($)^($) fails with T2008). With a single item, the tuples are keptThe tuple stream is kept: $ is the context, and the variables stay bound ({"s": [<each item>]}; the second order-by sorts by $i, or by the prices). The leak exposes an internal of jsonata-js, and the analysis of the fields an expression reads cannot follow it
A position (#$j) bound right after such an order-by (items#$i^(price)#$j)Never bound: the position is set only by a sort that starts the stream (items^(price)#$j), or through a stage (items#$i^(price)[true]#$j), so $j is missingBound to the item’s place in the sorted order, as in the other two forms. The missing variable is wrong by the JSONata documentation, and binding it costs nothing elsewhere
Without an input, a path whose first step is an array constructor with a wildcard ([*].price), or with $not(), which takes the context ([$not()].price)The constructor is evaluated on the internal sequence [undefined]: the wildcard gives [undefined, true], its flag included, and $not() gives true, as the sequence is not undefined; so the path goes on: undefined (and {[*].price: 1} gives {})The wildcard gives nothing, and $not() gives nothing, as $not(undefined) does in both engines; the path is [], as [$].price is in both engines (and {[*].price: 1} fails with T1003)
A JavaScript exception inside jsonata-js (Cannot read properties of undefined, comp is not a function)Thrown without an error codeA coded error, or a result
The left side of ?? and ?:Copied into a condition when parsing, and evaluated twice: once for the test, once for the result, so a binding there is made twice ($count($x := [$x, 1]) ?: 0 with $x bound to [1, 2, 3] gives 5). Each level of nesting doubles the tree (22 levels of ((a ?: 1) ?: 1)… take 12 seconds to parse); ?? calls whatever $exists is bound toEvaluated once; the tree grows with the source
A regular expression literal on the left of ?? or ?: ($match('abc', /b/) ?? 1)The parser copies the left side through JSON, which turns the regex into {}; $match and $split then loop until memory runs out, and the timeout cannot stop themEvaluated as written
The keys of an order-by (items^(price))Evaluated for both items at every comparison: about 2·n·log₂ n evaluations for n itemsEvaluated once per item, on first use, and kept. The keys are evaluated in the order jsonata-js first evaluates them, so results and the first error are the same; only a key with a side effect differs, such as one using $random, which draws once per item
Error position and token inside function callsOverwritten with the call siteFilled in only when the inner error has none, so it points at the real cause
Invalid regular expressionJavaScript SyntaxError without a codeS0302 with the engine’s reason in the detail message, and the pattern in value and flags; the error reads Invalid regular expression: /a/uv: the flags 'u' and 'v' cannot be given together
A function as the final resultThe function objectNone, like JSON.stringify
Very large integers in resultsPrinted in full up to 1e21serde_json numbers. Integers above 2^53 become floats (same value, possibly in exponent notation)
$toMillis of a date-time without an offsetLocal time (per Date.parse)UTC, so results never depend on the machine’s time zone
A regular expression applied to a value that is not a string (x ~> /re/)RegExp.prototype.exec converts the value with JavaScript’s String(): undefined is matched as “undefined”, so missing ~> /de/ finds de; an object becomes “[object Object]”, an array its items joined by commasUndefined, as for a function given a missing argument. The conversion exposes JavaScript’s String()
An option of $formatNumber that is a character (decimal-separator, grouping-separator, exponent-separator, percent, per-mille, zero-digit, digit, pattern-separator) given an empty string or several characters ({'decimal-separator': ''}, {'decimal-separator': 'xy'})The string is taken whole, and the picture is searched for it character by character, so it is never found: the picture fails (D3091 for an empty decimal separator, D3086 for 'xy', even in '#,##0xy00')The first character of the string, and the default for an empty one: $formatNumber(1234.5, '#,##0.00', {'decimal-separator': ''}) is “1,234.50”, and with 'xy' the picture '#,##0x00' gives “1,234x50”. No such option works in jsonata-js, so no result it gives is lost. The options that are strings, minus-sign, infinity and NaN, are taken whole in both engines, an empty one too: $formatNumber(-5, '0', {'minus-sign': ''}) is “5”
$substringBefore, $substringAfter when chars is undefinedSearch for the text “undefined”: $substringBefore('a-undefined-b', missing) is “a-”The string unchanged. The search exposes JavaScript’s String(undefined)
$replace when replacement is undefinedWith a string pattern, the text “undefined” in place of each occurrence: $replace('ab', 'b', missing) is “aundefined”. With a regex, a JavaScript TypeError (Cannot read properties of undefined)The occurrences removed, with either pattern: “a”. The text exposes JavaScript’s String(undefined), and the error has no JSONata code. It decides more than the call: $replace($, 'x', missing) ?: other keeps a text that jsonata-js finds non-empty
$replace with a string pattern and a function as the replacementThe JavaScript source of the closure that wraps the function (async function (...params) {…}) in place of each occurrence, or [object Object] when the call is in tail position of a lambdaThe occurrences removed, as for a replacement that is undefined. The text exposes JavaScript internals. A function is called only with a regex, whose matches give it its argument
$fromMillis with a name presentation for fractional seconds ('[fn]')A JavaScript TypeError without a codeD3133, as for the other components that have no names ('[Yn]')
Rounding a very large number to many decimals ($round(1e300, 20)), or any number to so many that the shift overflows ($round(3, 1e3))Shifting the decimal point overflows to Infinity, and shifting it back gives NaN: $round returns nullThe number unchanged: a number that large has no fractional digits. $formatNumber writes such a number in full in both engines
$formatBase of a number from 2^53 in a radix that is not a power of two ($formatBase(1e30, 3))Zeros for the digits below the number’s precisionEvery digit exact. A radix that is a power of two gives the same digits in both engines
A number that overflows to infinity (1e308 * 10, 1 / 0, $sum([1e308, 1e308]), $round(1.7e308, -308), $parseInteger of a 400-digit number)Infinity, which goes on: a result writes it as null in JSON, a function takes it ($string and a template string fail with D3001, $formatNumber writes “Infinity”), and the next operator, $boolean or $sort fails with D1001D1001 where the number overflows, as $power(10, 400) (D3061) and the literal 1e400 (S0102) fail in both engines. JSON has no infinity, so a result never becomes null without notice. $average of numbers whose sum overflows gives their mean (1e308 for [1e308, 1e308]). 0 / 0 is NaN in both engines
A date/time picture marker with an unknown component and a presentation ($fromMillis(0, '[Qx]'), '[,2]')The text “undefined” in the result. With no presentation ('[Q]') it fails with D3132D3132 in every case. The text exposes JavaScript’s undefined. $toMillis gives D3133 for both, as jsonata-js does
A date beyond JavaScript’s range, ±8.64e15 ms (100,000,000 days) around 1970, after the time zone of $fromMillis ($fromMillis(1e17), $fromMillis(8.64e15, '[Y]', '+0100'))Every component is NaN: “0NaN-NaN-NaNTNaN:NaN:NaN.NaNZ”, but names, words, roman numerals and letters, which are empty strings (“|” for '[Yw]|[FNn]'). In 2.2.2 they were NaN too, and words recursed until the stack overflowedD1001, as a number that overflows to infinity. Within the range every component is exact, also where it counts from a date beyond it: $fromMillis(-8.64e15, '[Y] [d] [W]') is “-271821 110 16”, where jsonata-js writes “-271821 NaN NaN”. $toMillis gives no date beyond the range in both engines, and jlens checks it after the time zone too, so $fromMillis takes every date it gives
$fromMillis given NaN, which $toMillis returns for a date that does not exist, in both engines ($fromMillis($toMillis('2024-13-01')), $fromMillis(0 / 0))Every component is NaN: “0NaN-NaN-NaNTNaN:NaN:NaN.NaNZ”D1001, as a date beyond the range. The text exposes JavaScript’s NaN; until 0.19 jlens wrote the epoch, “1970-01-01T00:00:00.000Z”, a wrong date that looks valid
$fromMillis or $now with a timezone that does not start with a number ($fromMillis(0, undefined, "two"), "")parseInt gives NaN, and every component is written as “NaN”: “0NaN-NaN-NaNTNaN:NaN:NaN.NaN0N:aN”D3150. The text exposes JavaScript’s NaN. A timezone that starts with a number is read as far as its digits go, as parseInt reads it in both engines ("+0530x" is +05:30)
Words or letters for NaN or infinity, which only a Source can give jlens: letters or words for infinity (in jsonata-js, $formatInteger(1e308 * 10, 'a'))Words recurse until the stack overflows (RangeError); letters loop foreverNothing (“”), as roman numerals and letters write for NaN in both engines; digits write “NaN”
A month or day name, or am and pm, that $toMillis reads in another case than its title case ($toMillis('27 APRIL 2008', '[D1] [MN] [Y0001]'), 'Pm' with [P])Not read: the name is missing, so the picture lacks a part (D3136), even where [MN] asks for upper case. Pull request #875, open, reads names in any caseRead in any case, as the timestamp is matched case-insensitively and as #875 reads them: 'APRIL' and 'april' are April. Before 0.36 jlens read such a name as January, a wrong date that looks valid, and ignored an unknown [P] word
Roman numerals in another case than the picture’s ($toMillis('mmxviii-12', '[YI]-[M01]'))Matched, as the timestamp is matched case-insensitively, but read as NaN: “0NaN-NaN-NaNTNaN:NaN:NaN.NaNZ” once writtenRead in any case: 2018, as names are. NaN would leak a JavaScript internal
$split(s, "")Splits into UTF-16 code unitsSplits into characters (astral characters stay whole)
$random, $shuffleMath.randomA per-evaluation xorshift generator seeded from the clock
The timestamp of $now and $millisThe clock when the evaluation startsThe clock when the evaluation first needs it, or the seed of $random; read once, so it stays fixed for the evaluation. An audited evaluation reads it when it starts
Regular expressionsJavaScript RegExpjlens-regress, a fork of regress 0.12.0 (ECMAScript syntax and semantics). Match positions are UTF-16 offsets. A pattern matches characters, not UTF-16 code units: $match('a𝄞', /[^a]/) matches 𝄞, where jsonata-js matches its first half, a lone surrogate. A pattern nested more than 256 levels deep is a syntax error (S0302)
A regular expression that backtracks catastrophically, such as /^(a+)+$/ on a long run of a followed by !Runs until the match ends, which can take years, and blocks the threadThe same without limits. With Options::timeout or a cancellation token, the match stops with D1012 or U1003, like any other step (ADR 0009); with Options::max_steps, with U1006, each 1,024 steps of backtracking spending one (ADR 0018)

The suite runner’s own guard raises U1001 for its timelimit/depth cases; jlens enforces the same limits through Options and reports D1011/D1012, which the conformance harness accepts in place of U1001.

The input in WebAssembly

jsonata-js evaluates the JavaScript object it is given. jlens-wasm evaluate reads that object as JSON.stringify does, one object or array at a time, when the expression reaches it (ADR 0010):

Topicjsonata-jsjlens
A Date, a boxed primitive (new Number(1)), an object with a toJSON methodThe object itselfWhat JSON.stringify writes: a Date is its ISO 8601 string
undefined, functions and symbols in the inputVisible to the expressionLeft out of objects, and null in arrays, as in JSON.stringify
A cycle or a BigIntRead as they areThe TypeError that JSON.stringify throws, when the expression reads the object or array that holds them. An object or array of more than 16 values is read whole, so the error comes when it is read, wherever it is inside
A host function that modifies the inputLater reads see the changeThe same for the parts not read yet; a part already read keeps what was read

Host functions

Functions provided by the application through the bindings (Bindings::function in Rust, functions in the bindings object or registerFunction in the WebAssembly package):

Topicjsonata-jsjlens
Arguments and resultThe JavaScript values themselves, which the function may modifyJSON copies: the function cannot change the values of the evaluation
A function as an argument ($f($g))An async function that applies it, with an arity propertyIn Rust, None among the arguments, and HostCall::function gives a Callable (ADR 0011). In WebAssembly, a function with an arity property, as in jsonata-js
Calling a function argumentReturns a promiseSynchronous: returns the result. In WebAssembly, await f(x) keeps working; f(x).then(...) does not
Calling a function argument after the host function returnsWorks: the function holds its environmentNot possible in Rust (the Callable borrows the call); in WebAssembly, it throws U1005
The result of a function called by the hostThe internal value: a sequence keeps its sequence flag, a function is an internal objectJSON: a sequence is an array or a single value, a function is None
A recursion through a host functionRuns until the heap is exhaustedD1011, as any recursion too deep
The context valuethis: the context value for a function in the bindings, {environment, input} for one registered with registerFunction. An input array arrives in its wrapperHostCall::input, the context value itself, an input array included. In WebAssembly, this is undefined: a signature with - passes the context value as an argument
A function that returns a promiseThe evaluation awaits itU1002, on purpose: see Not planned
An exception thrown by the functionRethrown, with the position and token of the callRethrown as is in WebAssembly; position and token are added when missing

Extensions

These features exist only in jlens. Except for the regex flags, they live in comments or in the host API, not in the language syntax, so that expressions that use them remain valid JSONata.

  • The regex flags u and v (Unicode text), which jsonata-js rejects with S0202. An expression without them gives the same result in both engines. They follow JavaScript: u with v is a syntax error (S0302), and so is a flag given twice, which jsonata-js also rejects, with a JavaScript SyntaxError.
  • Audit annotations and the warnings W0101–W0103.
  • Ast node ids and spans, and parse_recover diagnostics with severities.
  • Static warnings (W0201–W0215) and the language service.
  • Document, for evaluating many expressions against one converted document.

Quirks reproduced on purpose

Both engines behave as described here. Each row gives the reason for copying it.

Topicjsonata-js and jlensDecision
$formatInteger in letters ('a', 'A') of a number above 2^53Computed in floating point: value - 1 rounds to value, and the letters follow that roundingKept. The number is already a rounded double, so exact arithmetic on it gains no real precision, and letter numbering of such numbers is not ordinary input
A block or a grouped path whose path starts with an array constructor, followed by a step (([{'a': {'k': 'x', 'v': 1}}].a{k: $sum(v)}).x, and without the parentheses since jsonata-js#838)The block is evaluated once, on the whole input, as an array constructor that starts a path is, and the step after it reads its result as a sequence. The group-by gives an object, not an array, so the step reads nothing: the result is undefined, where the group-by alone gives {"x": 1}Kept (0.36). jsonata-js 2.3.0 gives it both ways, and giving the step the object only without the parentheses would make the two forms differ, while changing both would diverge from 2.3.0 where the parentheses are written. The input is rare: an array literal, a group-by and a step after it. $.(…) or a variable bound to the constructor gives the object to the step
$power(±1, e) with e undefinedD3061: JavaScript’s Math.pow gives NaN for 1^NaN, where IEEE pow gives 1Kept. Every base fails with D3061 when the exponent is undefined, ±1 included
$base64encode, $base64decodeTake the low byte of each UTF-16 code unit (Node’s Buffer), so $base64decode reads Ĵ (U+0134) as the digit 4, and text outside Latin-1 does not round-tripKept. Latin-1 text gives the same Base64 in both engines, which data exchanged between them relies on; encoding UTF-8 instead would change the result for any text outside ASCII
An order-by whose keys are NaN ($^(0 / 0), $^($parseInteger('x', 'w')))A NaN key is neither equal to nor less than another key, so the comparison asks for a swap both ways, and the order depends on the merge sort: [1, 2, 3, 4, 5]^(0 / 0) is [5, 4, 3, 2, 1], and descending keeps the order. A later term is never reachedKept (0.19). Treating NaN as equal to every key, as jlens did, is no more right: NaN has no place in the order. The cost stays in unusual input, and an expression gives the same order in both engines
A call that takes the context ($string(), $not()) in tail position of a lambda that a built-in function calls back ($map, $filter, $reduce, $replace…) or that ~> appliesThe context is null: jsonata-js wraps a function passed to a call in a closure that applies it with no input, so $map([5], function($v){ $string() }) is “null”, and so is 5 ~> function($x){ $string() }. A tail call passes its arguments as they are, and so does a partial application for those it binds: a lambda among them takes the input it was made in, the $ of its body, so on the input 1 $map([5], function($e){ $map([7], function($f){ $string() }) }) is ["1"]Kept (0.36). By the JSONata documentation the context is $ in every case, but following it would change the common $map(…, function($v){ $string() }), where both engines have always agreed. The cost is one bit per argument of a built-in call. Until 0.36 jlens took null in every case, and ~> passed no input, so 5 ~> function($x){ $not() } gave nothing where jsonata-js gives true